IT

Learning Unity Physics.pdf

DownLoad Book

Published: 2018-04-09 Author:Bieber 22 Browses


Tags: unity physics

默认图片

Extracting password:eeea466368e78fcc


Learning Unity Physics
Learn to implement Physics in interactive development
using the powerful components of Unity3D
K. Aava Rani
BIRMINGHAM - MUMBAI
Learning Unity Physics
Copyright © 2014 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: October 2014
Production reference: 1221014
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78355-369-3
www.packtpub.com
Credits
Author
K. Aava Rani
Reviewers
Subbu (L BalaSubbaiah)
Bryan Wai-ching CHUNG
Thuan Do The
Jacob Williams
Commissioning Editor
Akram Hussain
Acquisition Editor
Llewellyn Rozario
Content Development Editor
Prachi Bisht
Technical Editors
Pankaj Kadam
Nikhil Potdukhe
Copy Editors
Deepa Nambiar
Rashmi Sawant
Project Coordinator
Sageer Parkar
Proofreaders
Maria Gould
Ameesha Green
Paul Hindle
Indexers
Mariammal Chettiyar
Tejal Soni
Graphics
Disha Haria
Production Coordinators
Arvindkumar Gupta
Conidon Miranda
Cover Work
Conidon Miranda
About the Author
K. Aava Rani is a cofounder of CulpzLab Pvt Ltd—a software company with
10 years of experience in game technologies. She is a successful blogger and
technologist. She switched her focus to game development in 2004. Since then,
she has produced a number of game titles and has provided art and programming
solutions to Unity developers across the globe. She is based in New Delhi, India.
Aava Rani has been the recipient of several prestigious awards, including Game
Technology Expert (2012) from Adobe and recognition from SmartFoxServer for
her articles. She has experience in different technologies.
Aava has also reviewed the book, Creating E-Learning Games with Unity, David
Horachek, Packt Publishing.
I would like to extend my appreciation to the people at Packt
Publishing for their wholehearted support in producing my book.
My thanks go to Prachi Bisht, the content development editor,
for making the revision process work like a well-oiled machine;
Llewellyn Rosario, the acquisition editor, for his advice on shaping
the book. I want to thank the board of advisors who contributed
with their feedback throughout the process.
I specically want to thank Anil Kumar Sah for providing support
and guidance; Dr. Sunil Kumar Sah, a Computer Science lecturer
at TM University, who taught me how to love technology; Shova
Saha, who is a teacher and has a Master's degree in Computer
Applications, for supporting me throughout my book; Vinod Gupta,
my husband, who supported me; and my newly born son's love and
twinkling eyes, which give me energy and dedication.
Finally, I would like to express my greatest gratitude to my father,
RK Rajanjan, who has helped and supported me throughout my life
to be a better person and achieve great heights in my career.
About the Reviewers
Subbu has 5 years of experience in Unity3D. He has developed Physics games,
puzzle games, challenge games, ghting games, and so on. His games can be found
on iOS, Android, Facebook, and the Web.
He has been working at Credencys Solutions Inc. since September 2013 as a game
tech lead. He is very happy to work there since all his team members are very good
supporters and the work environment too is awesome.
Subbu has also written blogs on Unity3D tutorials.
I would like to thank Nihal Rama for her support, help, and valuable
suggestions while I was reviewing this book.
Bryan Wai-ching CHUNG is an interactive media artist and design consultant.
His artworks have been exhibited at World Wide Video Festival, Multimedia Art
Asia Pacic, Stuttgarter Filmwinter festival, Microwave International New Media
Arts Festival, and China Media Art Festival. In World Expo 2010 Shanghai, he
provided interactive design consultancy to various industry leaders in Hong Kong
and China. Chung studied Computer Science in Hong Kong, Interactive Multimedia
in London, and Software Art in Melbourne. He also develops software libraries for
the popular open source programming language, Processing. He is the author of the
book, Multimedia Programming with Pure Data, Packt Publishing. Currently, he is an
assistant professor at the Academy of Visual Arts, Hong Kong Baptist University,
where he teaches subjects on Interactive Arts, Computer Graphics, and Multimedia.
His website is http://www.magicandlove.com.
Thuan Do The is a passionate self-taught senior Flash developer who fell in
love with programming in the age of MS-DOS and Turbo Pascal. He inadvertently
discovered the beauty and power of Flash, started to learn 2D animation and
ActionScript, and then got his rst professional job in 2007.
During his career, he has built numerous interactive websites, media players,
galleries, and rich Internet applications and started several open source projects
on
http://github.com/thienhaflash.
Thuan started to play with Unity when Unity 2.6 was released and never looked
back. Being attracted by the power of the Unity platform, he stopped working on
Flash to completely focus on Unity games. Right now, besides being a Unity team
leader at his full-time job, Thuan is also an Asset Store author with some best-selling
editor extensions such as Hierarchy2, Inspector2, and NGUI Depth.
I would like to give a special thanks to my wife, Toky, for supporting
me so much in all my life.
Jacob Williams is a freelance software developer who has specialized in game
development. He has been a Unity developer for over 6 years and has been a very
active part of the independent game development community. He lives with his wife
and two kids in rural Alabama and can usually be found in the middle of the night
in front of his computer, working on personal projects and tech demos. You can read
more about Jacob at his personal blog, cheapdevotion.com.
www.PacktPub.com
Support les, eBooks, discount offers,
and more
You might want to visit www.PacktPub.com for support les and downloads related to
your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub
les available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
TM
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib
today and view nine entirely free books. Simply use your login credentials for immediate access.
Table of Contents
Preface 1
Chapter 1: Introduction to Physics in Unity3D 7
The most common component of Physics used in
interactive development 9
Use of Physics in simulation and frame rate 9
Basic components of Physics for interactive development 10
Integration 10
Collision detection 11
Collision resolution 11
Physical simulation in Unity 12
Built-in Physics in Unity3D 12
Built-in Physics components in Unity3D 12
Rigidbodies 13
Kinematic motion and Rigidbodies 13
Colliders 14
Triggers 16
Joints 17
Character controllers 17
Scripting based on collision 18
Frictionless Physic Materials 18
Summary 19
Chapter 2: Using Different Colliders for Interaction 21
Primitive colliders 21
Types of primitive colliders 22
Box Collider 3D 22
Box Collider 2D 24
Sphere Collider 3D 24
Circle Collider 2D 26
Capsule Collider 3D 26
Mesh Collider 28
Table of Contents
[ ii ]
Polygon Collider 2D 32
Edge Collider 2D 33
Nonprimitive colliders 33
Types of nonprimitive colliders 34
Wheel Collider 34
Static collider 37
Rigidbody Collider 37
Kinematic Rigidbody Collider 37
Trigger Collider 37
Compound colliders 39
Example – implementation of compound colliders 40
Summary 41
Chapter 3: Overview of Collision Matrix 43
Collision Matrix 3D 44
Trigger Matrix 45
Matrix for 2D Objects 47
Layers and Collision Matrix 49
An example of a layer-based Collision Matrix 49
Collision Matrix and a script 54
An example of a script-based Collision Matrix 55
Summary 55
Chapter 4: Rigidbody Types and Their Properties 57
Types of Rigidbody components 57
Physics Rigidbody 58
An example of creating a Physics Rigidbody 58
Kinematic Rigidbody 60
Properties of Rigidbody components 60
Example using a Rigidbody 62
Summary 66
Chapter 5: Joint Types and Their Properties 67
Types of joints 68
Fixed joint 68
Spring joint 72
Hinge joint 74
Character joints 77
Congurable joints 82
Handling movement/rotation restriction 83
Handling movement/rotation acceleration 84
Summary 85
Table of Contents
[ iii ]
Chapter 6: Animation and Unity3D Physics 87
Developing simple and complex animations 87
Interpolate and Extrapolate 88
The Cloth component 89
Important points while using the Cloth component 91
ConstantForce 92
An example of animation using ConstantForce 93
An example of animation using AddForce 94
An example of animation using AddTorque 96
An example of rope animation using different joints 97
Summary 100
Chapter 7: Optimizing Application's Performance
Using Physics in Unity3D 101
Developing an optimized application and game 102
Checking performance 102
Moving static colliders 102
Mesh Colliders 103
The complex collider shape 103
Rigidbodies 104
Joints 104
The Cloth component 104
Lower timestep 104
Precalculation 104
Optimizing graphics 105
Script call optimization for an iOS build 106
Pros of performance optimization 107
Summary 107
Index 109
Preface
In order to understand what it means to implement a Physics component of
Unity3D successfully in games and applications, a developer must have a better
understanding of the key elements of Physics and their behavior in the engine.
I wrote this book to provide a detailed description with examples for learning a
Physics component of Unity3D in a way that emphasizes the uniqueness of each
component and their implementation.
The successful implementation of Physics in game or application development
starts with a strong understanding of each component. When we look at game
and application development in Unity3D, it is easy to see that Physics is the most
important component. I have provided the conceptual foundation of a Physics
component and introduced these using examples for a better understanding.
I had three main goals while writing this book:
Accuracy: This book is the result of years of experience and research. This book
focuses on the Physics components of Unity3D and their implementations.
Implementation: My experience as a developer has taught me two things
about examples: they need to be detailed, and they must help developers do
their work. As a result, users of my book will always nd abundant examples
with every step carefully laid out and explained wherever necessary so that
the reader can follow. To describe and explain the Physics of Unity3D, this
book uses realistic examples to help developers get inside of what Physics is
really like. In addition to the examples, I have provided detailed screenshots
and gures for a better understanding. These examples will help developers
in the successful implementation of Physics components in their game or
application as well as help them identify the best practices they need to adopt
to improve their game or application performance.
Preface
[ 2 ]
A structured approach: I have tried to explain Physics and Unity3D in a
reader-friendly way. Most books claim to do this, but my experience with a
variety of books has proven otherwise. What students and developers will
nd in my book are short, precise explanations of terms and concepts that
are written in an understandable language. For example, I have used more
images rather than text to explain steps of implementations, which gives a
better understanding for readers.
What this book covers
Chapter 1, Introduction to Physics in Unity3D, serves as a quick introduction to Physics,
and specically Physics in Unity3D. We will also learn about in-built Physics, as well
as Unity3D and the uses of Physics in an interactive development.
Chapter 2, Using Different Colliders for Interaction, focuses on colliders, their types in
Unity3D, and how we can dene the collision shape of objects in a scene.
Chapter 3, Overview of Collision Matrix, explains matrices, their types, and how we can
dene a collision shape of objects in a scene explaining a matrix.
Chapter 4, Rigidbody Types and Their Properties, focuses on Rigidbodies and their types
in Unity3D.
Chapter 5, Joint Types and Their Properties, describes joints and their types in Unity 3D.
Chapter 6, Animation and Unity3D Physics, gives in-depth knowledge on how to use
Physics in animation in Unity3D. We will be developing complex animations and
also see some examples of animation using Physics.
Chapter 7, Optimizing Application's Performance Using Physics in Unity3D, teaches you
how you can optimize applications and games if you use Physics in Unity3D.
What you need for this book
The code examples in this book should work on most modern operating systems.
To install Unity3D, go to https://unity3d.com/unity/download. For the system
requirements, check out https://unity3d.com/unity/system-requirements.
Preface
[ 3 ]
The following is a list of software used for the examples and versions used
for testing:
Unity3D 4.1 and higher
MonoDevelop (this normally comes with Unity3D software)
Who this book is for
If you are familiar with the fundamentals of Physics and have some basic experience
of Unity game development, but have no knowledge of using these two together,
this book is for you. Educators and trainers who want to use Unity in an e-learning
setting will also benet from the book. For further reading, the following books
are recommended:
Unity 4.x Game Development by Example: Beginner's Guide, Ryan Henson
Creighton, Packt Publishing
Unity 4 Fundamentals: Get Started at Making Games with Unity, Alan Thorn,
Focal Press
Unity 4.x Game AI Programming, Aung Sithu Kyaw, Clifford Peters, and Thet
Naing Swe, Packt Publishing
Conventions
In this book, you will nd a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text, database table names, folder names, lenames, le extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"When a collision occurs, a trigger will call the
OnTriggerEnter function on the
trigger object's scripts."
A block of code is set as follows:
function OnTriggerStay(col:Collider)
{
isInRang = true;
}
function OnTriggerExit(col:Collider)
{
isInRang = false;
}
Preface
[ 4 ]
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "Select the
Cube option by navigating to GameObject | Create Other."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for us
to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to
feedback@packtpub.com,
and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on
www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you nd a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you would report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you nd any errata, please report them by visiting http://www.packtpub.
com/submit-errata
, selecting your book, clicking on the errata submission form link,
and entering the details of your errata. Once your errata are veried, your submission
will be accepted and the errata will be uploaded on our website, or added to any list of
existing errata, under the Errata section of that title. Any existing errata can be viewed
by selecting your title from http://www.packtpub.com/support.
Preface
[ 5 ]
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we
can pursue a remedy.
Please contact us at
copyright@packtpub.com with a link to the suspected
pirated material.
We appreciate your help in protecting our authors, and our ability to bring you
valuable content.
Questions
You can contact us at questions@packtpub.com if you are having a problem
with any aspect of the book, and we will do our best to address it.
Introduction to Physics
in Unity3D
Physics has been used for a long time in different sectors such as scientic, study,
and software. The use of Physics in interactive development and software is not new,
but its use has been the focus of special attention in recent years.
At rst glance, Physics gives the impression that it's all about long, webbed
equations and calculations. However, the contributions of Physics are tremendous
and have made developer's life easy. The idea of gaming was possible only because
of Physics. All of us remember our childhood games, which were facilitated by
the use of Physics; for example, the Ping Pong game. Isn't it amazing how much
Physics has touched our lives and how we cannot escape its inuence? There are
many games that possess primitive Physics, used to calculate the movement and
trajectory of a bouncing ball. If you look into the structure of Physics used for one of
the earliest games, Pong, you get a brief insight into how Physics was used in these
games. Game behavior, motion trajectory, and paddle movement were all handled
by primitive Physics.
In this chapter, we will learn about the following topics:
How Physics is used in interactive development
The basic components of Physics for interactive development
Physical simulation in Unity
In today's interactive world, the use of Physics is changing day by day. In recent
years, the use of Physics in games, software, and interactive development has
increased drastically. Now, we are able to make games and other applications using
Physics in different ways. In the modern era, the importance of in-game Physics and
interactive development has increased.
Introduction to Physics in Unity3D
[ 8 ]
If you look at the way Physics was used in older interactive applications or games,
you will nd that they were all based on some specic scenarios. The Physics code
was written according to the scenario of interactive development. For example, if
the Physics code is written for a ball to handle its trajectory motion, it only handles
the trajectory motion and nothing else; this means that every time a developer has
to write a new code for a new effect. Also, with the passage of time, if an update is
required, the developer has to modify or even rewrite the code. Based on such cases,
development became very complicated and time-consuming. Conditions became
worse when the number of scenarios increased. As mentioned earlier, the way
Physics is used is changing day by day, and it is required in various sectors. Let's
take a look at the areas where Physics is widely used these days:
Real Time
Development
3D Progress
Development
Physics based
Simulations
Physics Engine
Simulations
Use of Physics
Physics is useful in the following areas of interactive development:
Real-time programming where we need knowledge of electronics,
which is much related to Physics
A Physics engine for graphics software or games, where Physics is
heavily used
Creating 3D programs for various software and game engines
Physics-based simulations
Chapter 1
[ 9 ]
The most common component of Physics
used in interactive development
Rigidbody dynamics is the most common component used in interactive
development. For Physics-based simulation development, we use algorithms of
Rigidbody dynamics. Rigidbody dynamics is based on the Newtonian principle of
movement and mass.
Now, the question that arises here is what is a Rigidbody? An idealized solid whose
size and shape is xed and remains unaltered when some external forces are applied
and is used in Newtonian mechanics to model real objects is known as a Rigidbody.
For example, a box, wall, and so on.
The use of accurate Physics in interactive development is not feasible as it has its
own natural constraints. In interactive development, we cannot use accurate Physics
due to the standard frame rate restrictions, but the physical accuracy of a simulation
only needs to be believable.
Use of Physics in simulation and frame rate
In order to use Physics for interactive development, there are many things that need to
be taken care of. Physics simulations are related to the frame rate. The frame rate can
be described as the number of frames that are displayed per second. This is relevant
to animation, in which many images are displayed quickly to give the impression of
movement. The standard frame rate for most PCs and console games is 60 fps.
The interval of moving objects with their trajectories is called Physics simulation.
Almost every Physics simulation equation involves time, and the time required for
solving this is determined by interactive development.
Introduction to Physics in Unity3D
[ 10 ]
Basic components of Physics for
interactive development
There are a few basic components that can be used for interactive development.
Let's take a look at them one by one:
Integration
Collision
Resolution
Collision
Detection
Physics
Components
for Interactive
Development
Integration
There are multiple factors that have to be considered when we are talking about
the integration of Physics. How we track objects that participate in simulation is
of paramount importance in this regard.
To implement Physics in interactive development, we normally track all the objects
that are simulating in a data structure.
To implement Physics for each object, we need to know some important information
such as the object's physical properties, that is, mass, current velocity, current
position, orientation, the external forces acting on the object, and the future time of
an object.
What is future time?
Future time = the current time + the time slice for the frame
Chapter 1
[ 11 ]
Collision detection
There is no collision detection if only one object is moving in a vacuum. However,
most interactive developments involve more than one object and these objects
move in an environment. Therefore, a situation arises where two objects are moving
towards each other.
What will happen if no action is taken? These objects will just pass through each
other. In most interactive developments, however, we don't want the objects to pass
through each other.
In order to handle those scenarios where collision occurs, the interactive
development needs to know that two objects are colliding. One of Physics' most
important tasks is to identify these scenarios.
The collision detection code has to determine all such pairs of overlapping objects,
collect some additional data such as how far they overlap and in which orientation,
and provide this data to the interactive development for further processing.
In the later chapters, we will see how we can handle collision detection in Unity3D.
Collision resolution
What will happen after the collision? Let's take a look at one such scenario where
two or more objects overlap and see what can we do in this case. In many cases,
some specic rules are added to the interactive development.
For example, in a shooting game, when a bullet hits the player's ship, the game might
decide to show an explosion animation. Following this, before removing the player's
ship, the game might start the level again and reduce the number of lives of the
player. These effects of the collision are driven by the game itself and not by Physics
because they are very specic to the game.
However, there are certain cases where the game doesn't have to be involved.
We've covered the basics of all Physics components. Every simulation suitable for
interactive development will have these components. Other than the covered topics,
there are many more features to be included, such as joints, cloth simulations,
Physics-based animations, and so on.
Introduction to Physics in Unity3D
[ 12 ]
Physical simulation in Unity
We will now look at the physical simulations already available in Physics and how
Unity uses them. This section will also give you an overview of the built-in Physics
components in Unity3D. Let's take a look at the Physics simulation in Unity:
Unity is a powerful tool. It is able to take care of many problems involved
with interactive physical simulations. It embeds a state-of-the-art Physics
engine called PhysX.
It's Rigidbody is mostly targeted at rigid objects.
Using Unity we can make Physics approximations based on an object's
parameter values.
Built-in Physics in Unity3D
As I mentioned earlier, Unity is a powerful engine that has a number of built-in
Physics components. It handles physical simulations. By adjusting a few parameter
settings, we can create an object that behaves in a realistic way.
By controlling Physics from scripts, we can give an object the dynamics of a
vehicle, machine, cloth, and so on. The built-in components are very useful in fast
development. In most interactive developments, these simulations are required. By
making Physics a built-in component, Unity3D has made developers' lives easier.
Unity has two separate Physics engines: one for 3D Physics and
one for 2D Physics.
As such, there is a separate Rigidbody component for 3D Physics and an analogous
Rigidbody2D component for 2D Physics.
Now, let's explore the built-in components in Unity3D.
Built-in Physics components in Unity3D
The following gure depicts the basic built-in Physics components in Unity3D,
which help us in interactive development:
Chapter 1
[ 13 ]
Rigidbodies
Built-in
Physics
Components
Character
Controllers
Colliders
Joints
Physic
Materials
Rigidbodies
We have already discussed that in simulation or interactive development, the most
important component is a Rigidbody. It enables the physical behavior of an object.
The object to which a Rigidbody is attached can be made to respond to gravity. If we
want to create a ball and want it to respond to gravity, we need to add a Rigidbody
component to the object and gravity will be enabled by default.
A Rigidbody component takes the movement of the object to which it is attached;
therefore, we shouldn't try to move it using a script by changing the position and
rotation. Instead, we can apply forces to push the object and let the Physics engine
calculate the results.
Kinematic motion and Rigidbodies
Sometimes, it is desirable for a Rigidbody object's motion to not be controlled by the
Physics engine but by the script code instead. This type of motion produced from a
script is known as kinematic motion.
Introduction to Physics in Unity3D
[ 14 ]
Is Kinematic is one of the properties of a Rigidbody that will remove it from the
control of the Physics engine and allow it to be moved using a script. We can change
the value of Is Kinematic from a script to switch this property on and off for an object
by using both the script and the inspector.
Is Kinematic is useful, but we should keep in mind that enabling it
will affect performance. If enabled, the object will not be driven by the
Physics engine and can only be manipulated by its transform, which is
more performance consuming.
Colliders
It's one of the most important built-in components of Unity3D. A collider component
is used to dene the shape for the physical collision. We use different colliders
according to the shape of the objects. A collider, which is invisible, need not be
matched exactly to the shape of the object's mesh.
In the later chapters, we will see how to use different colliders.
In 3D, the following are the basic colliders:
Box Collider
Sphere Collider
Capsule Collider
Mesh Collider
Take a look at the following gure:
Box
Colliders
Mesh
Colliders
3D Colliders
Sphere
Colliders
Capsule
Colliders
3D Colliders
Chapter 1
[ 15 ]
There are differences between 3D colliders and 2D colliders. In 2D, the following are
the basic colliders:
Box Collider 2D
Circle Collider 2D
Polygon Collider 2D
Take a look at the following gure:
Box Collider
2D
Polygon
Collider 2D
Circle
Collider 2D
2D Colliders
Apart from the aforementioned core colliders, there are a few important terms about
the colliders that you need to know.
Static colliders
Colliders can be added to an object without a Rigidbody component in order to
create oors, walls, and so on. These are referred to as static colliders. Repositioning
static colliders by changing the transform position will impact the performance of
the Physics engine heavily.
To improve the performance, we should not reposition static
colliders by changing the transformation position.
Dynamic colliders
Colliders attached to a Rigidbody object are known as dynamic colliders. Static
colliders do not respond to collisions with dynamic colliders with any movement.
In the later chapters, we will learn about the aforementioned colliders and how to
implement these colliders in detail.
Introduction to Physics in Unity3D
[ 16 ]
Physic Materials
Different materials are used for different objects. As the colliders interact, their
surfaces need to simulate the properties of the material that they are supposed to
represent. We can congure the friction and bounce using Physic Materials.
Again, Physic Materials for 2D and 3D are different; they are called Physic Materials
3D and Physic Materials 2D.
Triggers
In scripting, we can detect when the collisions are going to occur and then we can
initiate taking actions using the
OnCollisionEnter function. We can congure a
collider, which does not behave as a solid object, as a trigger using the Is Trigger
property of Unity3D, and we will simply allow other colliders to pass through. When
a collision occurs, a trigger will call the OnTriggerEnter function on the trigger
object's scripts. Using these functions, we can handle a number of scenarios where an
action after the collision is required.
The following points will give you sources where you can nd more
details on this particular topic:
Collider.OnCollisionEnter(Collision) at http://
docs.unity3d.com/ScriptReference/Collider.
OnCollisionEnter.html
Collider.OnCollisionStay(Collision) at http://
docs.unity3d.com/ScriptReference/Collider.
OnCollisionStay.html
Collider.OnCollisionExit(Collision) at http://
docs.unity3d.com/ScriptReference/Collider.
OnCollisionExit.html
Collider.OnTriggerEnter(Collider) at http://
docs.unity3d.com/ScriptReference/Collider.
OnTriggerEnter.html
Collider.OnTriggerStay(Collider) at http://
docs.unity3d.com/ScriptReference/Collider.
OnTriggerStay.html
Collider.OnTriggerExit(Collider) at http://
docs.unity3d.com/ScriptReference/Collider.
OnTriggerExit.html
Chapter 1
[ 17 ]
Joints
Often, one Rigidbody object is attached to another using joints. Unity provides
different joints to help us in different scenarios. We can attach one Rigidbody object
to another or to a xed point in space using a joint component. If we want a joint to
allow at least some freedom of motion and so on, then Unity provides different joint
components that enforce different restrictions.
The following gure depicts the types of joints:
Hinge Joints
Spring Joints
Joints
Joints also have other options that enable specic effects; for example, we can set a
joint to break when the force applied to it exceeds a decided limit.
We will learn more about joints in the later chapters.
Character controllers
In game development, often a character is required, and for this, a controller
is always required. A character in a rst- or third-person game will often need
some collision-based Physics so that character doesn't fall on the oor or walk
over the walls.
Unity3D provides a component to create this behavior, which is called
CharacterController. This component uses a Capsule Collider. The controller
has functions to set the object's speed and direction.
收藏
分享
暂无回复
Author