Unity how to check collision
Unity how to check collision
Introduction to collision
Compound colliders
Compound colliders approximate the shape of a GameObject while keeping a low processor overhead. To get further flexibility, you can add additional colliders on child GameObjects. For instance, you can rotate boxes relative to the local axes of the parent GameObject. When you create a compound collider like this, you should only use one Rigidbody A component that allows a GameObject to be affected by simulated gravity and other forces. More info
See in Glossary component, placed on the root GameObject in the hierarchy.
Primitive colliders do not work correctly with shear transforms. If you use a combination of rotations and non-uniform scales in the Transform hierarchy so that the resulting shape is no longer a primitive shape, the primitive collider cannot represent it correctly.
Mesh colliders
There are some cases, however, where even compound colliders are not accurate enough. In 3D, you can use Mesh Colliders A free-form collider component which accepts a mesh reference to define its collision surface shape. More info
See in Glossary to match the shape of the GameObject’s mesh exactly. In 2D, the Polygon Collider 2D does not match the shape of the sprite A 2D graphic objects. If you are used to working in 3D, Sprites are essentially just standard textures but there are special techniques for combining and managing sprite textures for efficiency and convenience during development. More info
See in Glossary graphic perfectly but you can refine the shape to any level of detail The Level Of Detail (LOD) technique is an optimization that reduces the number of triangles that Unity has to render for a GameObject when its distance from the Camera increases. More info
See in Glossary you like.
The benefit of this is that a convex mesh collider can collide with other mesh colliders so you can use this feature when you have a moving character with a suitable shape. However, a good rule is to use mesh colliders for scene A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary geometry and approximate the shape of moving GameObjects using compound primitive colliders.
Static colliders
You can add colliders to a GameObject without a Rigidbody component to create floors, walls and other motionless elements of a Scene. These are referred to as static colliders. At the opposite, colliders on a GameObject that has a Rigidbody are known as dynamic colliders. Static colliders can interact with dynamic colliders but since they don’t have a Rigidbody, they don’t move in response to collisions.
Physics materials
When colliders interact, their surfaces need to simulate the properties of the material they are supposed to represent. For example, a sheet of ice will be slippery while a rubber ball will offer a lot of friction and be very bouncy. Although the shape of colliders is not deformed during collisions, their friction and bounce can be configured using Physics Materials. Getting the parameters just right can involve a bit of trial and error. A slippery material like ice, for example, has zero (or very low) friction. A grippy material like rubber has high friction and near-perfect bounciness. See the reference pages for Physic Material and Physics Material 2D for further details on the available parameters. Note that for historical reasons, the 3D asset is actually called Physic Material A physics asset for adjusting the friction and bouncing effects of colliding objects. More info
See in Glossary (without the S) but the 2D equivalent is called Physics Material 2D Use to adjust the friction and bounce that occurs between 2D physics objects when they collide More info
See in Glossary (with the S).
Triggers
Collision callbacks for scripts
When collisions occur, the physics engine calls functions with specific names on any scripts attached to the objects involved. You can place any code you like in these functions to respond to the collision event. For example, you might play a crash sound effect when a car bumps into an obstacle.
Collider interactions
Colliders interact with each other differently depending on how their Rigidbody components are configured. The three important configurations are the Static Collider (ie, no Rigidbody is attached at all), the Rigidbody Collider and the Kinematic Rigidbody Collider.
Static Collider
A static collider is a GameObject that has a Collider but no Rigidbody. Static colliders are mostly used for level geometry which always stays at the same place and never moves around. Incoming Rigidbody objects collide with static colliders but don’t move them.
In particular cases, the physics engine optimizes for static colliders that never move. For instance, a vehicle resting on top of a static collider remains asleep even if you move this static collider. You can enable, disable, or move static colliders in runtime without specially affecting the physics engine computation speed. Also, you can safely scale a static Mesh Collider as long as the scale is uniform (not skewed).
Rigidbody Collider
This is a GameObject with a Collider and a normal, non-kinematic Rigidbody attached. Rigidbody colliders are fully simulated by the physics engine and can react to collisions and forces applied from a script. They can collide with other objects (including static colliders) and are the most commonly used Collider configuration in games that use physics.
Kinematic Rigidbody Collider
This is a GameObject with a Collider and a kinematic Rigidbody attached (ie, the IsKinematic property of the Rigidbody is enabled). You can move a kinematic rigidbody object from a script by modifying its Transform Component A Transform component determines the Position, Rotation, and Scale of each object in the scene. Every GameObject has a Transform. More info
See in Glossary but it will not respond to collisions and forces like a non-kinematic rigidbody. Kinematic rigidbodies should be used for colliders that can be moved or disabled/enabled occasionally but that should otherwise behave like static colliders. An example of this is a sliding door that should normally act as an immovable physical obstacle but can be opened when necessary. Unlike a static collider, a moving kinematic rigidbody will apply friction to other objects and will “wake up” other rigidbodies when they make contact.
Even when immobile, kinematic rigidbody colliders have different behavior to static colliders. For example, if the collider is set to as a trigger then you also need to add a rigidbody to it in order to receive trigger events in your script. If you don’t want the trigger to fall under gravity or otherwise be affected by physics then you can set the IsKinematic property on its rigidbody.
A Rigidbody component can be switched between normal and kinematic behavior at any time using the IsKinematic property.
A common example of this is the “ragdoll” effect where a character normally moves under animation but is thrown physically by an explosion or a heavy collision. The character’s limbs can each be given their own Rigidbody component with IsKinematic enabled by default. The limbs move normally by animation until IsKinematic is switched off for all of them and they immediately behave as physics objects. At this point, a collision or explosion force will send the character flying with its limbs thrown in a convincing way.
Collision action matrix
When two objects collide, a number of different script events can occur depending on the configurations of the colliding objects’ rigidbodies. The charts below give details of which event functions are called based on the components that are attached to the objects. Some of the combinations only cause one of the two objects to be affected by the collision, but the general rule is that physics will not be applied to an object that doesn’t have a Rigidbody component attached.
Unity Collision 2D and 3D: Super Simple Guide
Collision detection is required for all types of games. Detecting and utilizing the collision is implemented in a different manner in different game engines. Unity Collision works based on the collider component that can be added to any Gameobject. Also, you need to understand how colliders and Rigidbody work together to efficiently use them. Without a basic understanding of how Unity Colliders work, it will be very difficult to code the game mechanics. In this post, we will see how to use colliders in Unity and where to use OnCollisionEnter and OnTriggerEnter functions.
Introduction to Unity Colliders
Unity colliders are very simple to use. Unity has divided the colliders into 2D and 3D. So, you have to be very careful which collider you are using. All your codes and collision detection will change to 2D and 3D. Further, there are types of colliders, static collider, Rigidbody collider, kinematic Rigidbody collider, etc. The collider used in all these are the same, the type is for how the object to which the collider is added behaves when collided with.
Unity Collider Types
Static collider
Static colliders are considered to be non-moving objects by Unity. Do not confuse static Gameobject with the static collider. If a Rigidbody is not attached to a collider then it’s a static collider. They do not move when an object Collides to with them. Though, they can be moved using transform, moving a static collider leads to performance loss during runtime.
Rigidbody collider or Dynamic Collider
A Rigidbody collider works like a real-world object. It is governed by the forces of physics. If you apply force on it, it will move. In Unity, Rigidbody is used on an object which will move a lot during gameplay. Check the screenshot for how a Rigidbody is attached to a game object.
Kinematic Rigidbody collider
A kinematic Rigidbody is a Rigidbody that behaves like a static object. So, the next question is then why use a kinematic Rigidbody. The main reason to use a kinematic Rigidbody is to tell Unity that the object does not respond to forces but will be movable by script during runtime. The performance loss is very less in moving a kinematic Rigidbody compared to a Static object.
Unity Collision Detection 3D
Adding a 3D collider in Unity
To add a collider to your Gameobject, select the object in Hierarchy view and click on Add Component in the Inspector window. Then select the type of Collider based on your requirement.
You can adjust the size of the collider using the Edit Collider button.
Non-trigger and Trigger collider
In Unity you can mark a collider as trigger using the check box in the inspector window. The behavior of the object changes if it is marked as a trigger.
Unity Colliders not marked as trigger
Unity will detect a collision only if one of the objects is a Rigidbody. That is, if you have two Gameobject marked as static colliders then collision between them will not be detected. It’s the same case with two kinematic Rigidbody. If you use the OnCollisionEnter function in any of the above cases, the function will not be called during a Collision. Find the collision matrix for unity colliders in the image below.
Unity collider marked as Trigger
When you mark a collider as a trigger, it no longer behaves like a solid object. It allows the other object to pass through it. But the time of one object entering another object’s space can trigger a function. With that, you can know if a collision has happened without actually creating a collision. You have to use the OnTriggerEnter function if the collider is Marked as a trigger. The collision matrix is a little different in the case of triggers.
Trigger collision doesn’t work in Unity if both the colliders are static colliders. In all the other cases the OnTriggerEnter is called. Knowing these basic things about colliders will help you set them up easily in your game.
If you did not understand the matrix completely then here is a simple comparison to help you. Consider static colliders as objects that don’t move like walls. Rigidbody collider denotes a moving object like a ball. Kinematic Rigidbody denotes that the object is not moved by physics but can be moved by script or animation.
Unity does not want to detect collision between two static objects so normal collision is detected only if one of the Gameobject is movable by physics. Whereas trigger function works a little differently. It works only if one of the colliders is marked as trigger and can be moved either by physics or script.
Setting Collision Layers in Unity
One you have added your colliders and Rigidbody now it’s time to set the layers. Unity gives you control to decide which layers collide with each other.
This setting is available in Edit>Project settings> Physics
You can just uncheck the layers that you don’t want to collide. For example, if you don’t want the friend layer to collide with the water layer. Then just uncheck the box in water row of the Friend colomn.
Remember to create all your layers first before editing this setting.
3D collider shapes in Unity
Collider shape | Where to use | Effect on Performance |
---|---|---|
Box Collider | Object shaped like cube | Less Performance intensive |
Sphere Collider | 3D round shaped objects | Less Performance intensive |
Capsule Colliders | For Characters | Less Performance intensive |
Mesh Colliders | Objects with Uneven shapes | Performance intensive |
Terrain Colliders | For Unity terrains | Very Performance intensive |
Detect Collision in Unity 3D
Unity OnCollisionEnter
OnCollisionEnter function is called if the colliders are non-trigger and one of them has a non-kinematic Rigidbody.
In this script we are using a normal collision. “col” returns the collider of the game object. We further check if the game object is an enemy. If yes, we destroy it. Remember either the parent Gameobject or the enemy game object needs to have a Rigidbody for this script to work.
Unity OnTriggerEnter
OnTriggerEnter function is called if the colliders are set as trigger and one of them has a non-kinematic Rigidbody.
Pro tip: If the object is marked as trigger, it will pass through the obstacles.
Other features in Unity OnCollisionEnter and OnTriggerEnter
Both the examples of Unity OnCollisionEnter and OnTriggerEnter above show that you can get the Gameobject of the colliding object. Apart from that you can get a lot of data from the collision class object. Here is the list of things that you can get from the collision class
Other Unity Collider functions
That summarizes the collider function in Unity. If you have any questions, you can post it in the comment box below.
There are few more functions to detect whether the Gameobject has exited the collision phase or its still colliding with another object.
Non-Trigger Collision
Trigger Collision
Unity Collision Detection 2D
Collision in 2D is very similar to 3D, but there is a change in terminology when it comes to 2D. Unity has put in a lot of effort to distinguish 2D colliders from 3D.
2D Collision in Unity uses Physics2D. Everything in Physics2D has a suffix 2D added to it. It’s a physics engine on its own but for the 2D world.
Rigidbody2D
Rigidbody2D works very similar to Rigidbody but it reacts only to the components which are part of Physics2D. You can set a Rigidbody2D as Kinematic and also decide whether it reacts to physics forces or not.
To add a Rigidbody2D, select your 2D Gameobject and go to the inspector window. Click on Add component and select Rigidbody2D.
As you can see the parameters of Rigidbody2D are slightly different compared to a regular 3D Rigidbody. You can set the Rigidbody type as Static, Dynamic or Kinematic based on how your Gameobject will behave in your game.
Also, in 3D Rigidbody the physics material needs to be set from the collider but in case of Rigidbody2D, you can set the material from Rigidbopdy2D.
Adding a 2D collider
Select your Gameobject and click on Add Component in the inspector window. Add a 2D collider from the component list.
Use this comparison table and add the required collider.
3D collider | 2D Collider |
---|---|
OnCollisionEnter | OnCollisionEnter2D |
OnTriggerEnter | OnTriggerEnter2D |
OnCollisionExit | OnCollisionExit2D |
OnTriggerExit | OnTriggerExit2D |
OnCollisionStay | OnCollisionStay2D |
OnTriggerStay | OnTriggerStay2D |
Collider | Collider2D |
Collision | Collision2D |
Rigidbody | Rigidbody2D |
BoxCollider | BoxCollider2D |
MeshCollider | PolygonCollider2D |
SphereCollider | CircleCollider |
CapsuleCollider | CapsuleCollider2D |
TerrainCollider | EdgeCollider2D or TilemapCollider2D |
WheelCollider | CircleCollider2D |
2D Collision layer setting in Unity
Similar to 3D you can decide which layers will collide with each other in physics 2D.
To set this you have to go to Edit>Project settings>Physics2D
Functions in Unity Collision 2D
OnCollisionEnter2D
This can be used to detect collision between two colliders that are not set as Trigger and at least one of them has a Rigidbody attached to it.
OnTriggerEnter2D
OnTiggerEnter2D is used to detect collision between 2D collides that are set as a trigger. You need to use this even if one of the Collider is set as Trigger.
Other Unity 2D collider functions
Non-Trigger 2D Collision
Trigger 2D Collision
Sample script for 2D collision detection functions
If you have any other questions regarding Unity collider then leave them in the comment box below.
Detect collision in Unity 3D
In this tutorial, we will see how to detect collision in unity 3D between different game objects. We will use Collision class to detect the collisions between game objects.
We will use below scene for demo.
Demo Scene
We will move player object with keyboard input and check it’s collision with other objects.
Steps to detect collision in Unity 3D
Step 1:
The game object on which collision detection will be triggered should be having Rigid Body and Collider components. For this demo, we will attach Rigid body component to the player game object. Box collider is already available to primitive Cube objects.
Player Object
Make sure Is Kinematic check box is unchecked.
Step 2:
Attach Collider components to the other game objects. Here we have added Box Collider to Ground and Enemy Game Objects. Rigid Body component is optional. Make sure that “Is Trigger” checkbox is unchecked.
Enemy Object
Step 3: Attach below script to Player game object.
Our setup is complete. Run the application to see the results.
Result
Collide with specific objects – layers
We can also detect collision for specific set of objects. We can use layers for the same. For this example, we will do the following changes:
With above settings Player Layer Objects with not collide with Enemy layered objects.
Hope you get an idea about to detect collision in unity 3D. Post your comments for queries and feedback. Thanks for reading.
Unity collision detection 2D everything you need to know + examples
Here we are, I can feel another mystery, Unity collision detection 2D.
What? It’s too difficult this time!?
I don’t think so.
It’s a big case, I know, but if we want to create video games we need to face the truth:
Manage collisions.
Don’t worry we will find all the necessary information and this time we will have another partner to help for our investigation: Unity.
Yes, Unity will help us, then we just need to start analyzing the clues.
Step by step we will understand how to manage the collisions in our game and this monstrous case will become a lovely little kitten.
Unity Collisions Vocabulary
Hey partner, here is what I already discovered, there are some important notionsВ to know before proceeding and understanding В Unity collision detection 2D:
Physics Engine 2D
To detect collisions and simulate the real world physics system Unity provides a built-in physics engine, so all the maths behind acceleration, forces, gravity, collision detection etc… it’s already there.
Fewww! It seems other brave detectives already solved the case of physics! Thank you whoever you are!
Collision Detection
It’s the detection of an intersection between two or multiple objects. Often it’s related to simulate the physical world in our game.
Let me list for you some detections we would like to handle:
The detection means that in some way we need to be warned when a collision happens!
Please have a look at wikipedia for a large definition about collision detections in video games.
Collider 2D
It’s a component to define the shape of a Gameobject for physical purposes.
If the Gameobject sprite is a complex drawing, just an approximation of its shape will be necessary to work, because the Collider 2D is invisible and not distinguishable during the gameplay!
So the sprite is the drawing, the collider is the shape, what does it mean?
The sprite is what the user sees, the collider is whatВ the engine considers for collisions.
Trigger 2D
It’s a particular behavior of a Collider 2D, when we simply want to detect when one collider overlaps another one without creating a collision.
So the object with this behavior stops being a solid object and allows other colliders to pass through.
RigidBody 2D
It’s a component that allows the physics engine to control the object, it means it will be affected by gravity, forces and collisions too!
Are you ready to play with Vectors?
Right, to move our objects in different directions we need to manage vectors too! Why don’t you have a look at this article for a good refresh: Vector In Game Development: Understand The Basics Of Vector Math
While the physics engine 2D moves colliders and makes them interact with each other, the Rigidbody 2D component is in charge of the communication of these movements with the Transform components.
In this way the Gameobject will change according to the collider!
How to…
How can we add a Collider 2D or Rigidbody 2D to a Gameobject?
1- Select a Gameobject in the scene and click on add component.
2- Type “collider 2D” or “rigidbody 2D” in the search box and select the component (for Collider 2D we will see different types, we’re just going to talk about it).
How can we set a collider as a trigger?
Just enabling the right checkbox property in the Collider 2D component.
Which Collider 2D should we use?
Have you noticed there is more than one Collider 2D to choose from?В
Yes, Unity provides us a list of different already pre-set Collider 2Ds.
Unity has an explanation for each one, we just need to enrich it with some helpful examples.
Let’s line up all the suspects then and have a look at each one of them (On the left is the sprite, on the right its collider)
Box Collider 2D
Box collider 2D is for square and rectangle collision areas.
Circle Collider 2D
Circle collider 2D is for circular collision areas.
Capsule Collider 2D
Capsule collider 2D is for circular or lozenge-shaped collision areas.
Polygon Collider 2DВ
Polygon collider 2D is for freeform collision areas.
Edge Collider 2D
Edge collider 2D is for freeform collision areas and areas which aren’t completely enclosed (such as rounded convex corners).
Composite Collider 2D
Composite collider 2D is for merging Box Collider 2Ds and Polygon Collider 2Ds.
Tilemap Collider 2D
Tilemap Collider 2D is for each Tile set in the corresponding Tilemap component of a Tilemap Gameobject. We’ll talk about it in the Tilemap investigation!
Rigidbody 2D Types
More than one Rigidbody 2D type? Are you sure? I knew it! Some witnesses saw something!
Let’s try to find out the version of the story of each Rigidbody 2D.
Dynamic Rigidbody 2D
It’s the most common and most performance-expensive type, because it interacts with everything and it’s designed to move under simulation. It interacts with all the body types.
В If we want a normal object affected by physics, this is our body!
The ball in this example has a dynamic Rigidbody 2D and it can be moved by applying forces and it’s affected by gravity!
Static Rigidbody 2D
Opposite to dynamic, it’s designed to not move under simulation, Indeed it has infinite mass, heavy right? It only collides with dynamic Rigidbody 2D.
It is also the least resource-intensive body type to use.
You don’t really need to set the Rigidbody 2D for static objects,В just the collider 2D is necessary to detect collisions, but if a static object needs to be moved or reconfigured at run time, it is faster to do so when it has its own Rigidbody 2D and В this will be our body!
Let’s add a box with static Rigidbody2D, it will be an obstacle to overcome!
Kinematic Rigidbody 2D
Like the dynamic is designed to move under simulation, but only controlling it, it’s not affected by gravity and forces. It’s faster in terms of performance-expensive. It interacts only with dynamic body types.
If we want to move something not influenced by forces and gravity, remember it’s nature of interaction only with dynamic body types, this is our body!
What ifВ we add a kinematic Rigidbody 2D instead of the static one to the box? In this way we can control its movement without the influence of gravity. It will become a perfect movement trap for a platform video game!
Collision Detection 2D in scripts
Well! Now we know many things about Unity collision detection 2D, we are ready В to understand what we can do when a collision happens.
Unity, our partner provides us two different ways to handle the collisions depending if a collider is a trigger or not.
We just need to add the snippets below to the script of our Gameobject with a collider to handle the collisions and do what we want after the detection.
Collision 2D
Trigger 2D
Keep in mind… Mind the gap!
Hey partner! Unity collision detection 2D is not a secret anymore for us, but we can’t solve this case without considering these clues:
Colliders 2D Properties
Each collider type has propertiesВ over the trigger one, please check the documentation for each type to understand what these properties do (in the section “Which Collider 2D should we use” you can find a link for each collider type to its documentation).В
Rigidbody 2D properties
There are some properties like mass and gravity we will need to know, I suggest having a look at the official documentation for an explanation of all of them.
Static collider 2D
It was “static Rigidbody 2D” wasn’t it? You’re right, but if we need just the collision detection without any reconfiguration or movement to place the object somewhere else, we can avoid adding the Rigidbody 2D component.
Put something below or set the gravity value to 0 to avoid falling objects.
It’s a common mistake, when we add a dynamic or static Rigidbody 2D to an object, if we start the game the object will fall out of the screen. To avoid this we can either place a floor underneath with a collider, or set the gravity value attribute in the rigidbody component to 0.
2D is NOT 3D
As you already noticed Unity provides many of these components in 2 versions, for instance Box Collider 2D and Box Collider, well the difference is the second one is for 3D. So keep in mind to use only 2D components in 2D games, first for performances and second to avoid mixing things that won’t work like 3D components and 2D methods in scripts (OnCollisionEnter2D is NOT OnCollisionEnter).
OnCollisionEnter2D won’t work if the trigger is enabled and vice versa.
Remember my friend, for collisions “OnCollisionEnter2D, OnCollisionStay2D, OnCollisionExit2D”, but if we enable the trigger behaviour in a collider they will stop working and we should use “OnTriggerEnter2D, OnTriggerStay2D, OnTriggerExit2D”.
Simple collisions 2D game
Hey! Look what I found in the secret files of the blog, An old record! Someone already tried to solve this case.
Here is my reconstruction of the record:
W hoever will be able to reproduce it will help to solve the lost case of collision 2D game.
Besides this they will win the best detective of the month prize!
Do you think you will be able to figure it out?
If not, don’t worry, you can find the complete project on GitHub, but promise me to look at it only as the last resort! рџ‰
Conclusion
It was a hard job, we needed a lot of research, so let’s do a final recap:
No collision fear anymore, we solved the case and acquired the knowledge required to create a wonderful video game with collision detection.
We are ready to solve the next case.
Goodbye partner, see you soon for the next job!
Colliders
Collider components define the shape of an object for the purposes of physical collisions. A collider, which is invisible, need not be the exact same shape as the object’s mesh and in fact, a rough approximation is often more efficient and indistinguishable in gameplay.
The simplest (and least processor-intensive) colliders are the so-called primitive collider types. In 3D, these are the Box Collider, Sphere Collider and Capsule Collider. In 2D, you can use the Box Collider 2D and Circle Collider 2D. Any number of these can be added to a single object to create compound colliders.
With careful positioning and sizing, compound colliders can often approximate the shape of an object quite well while keeping a low processor overhead. Further flexibility can be gained by having additional colliders on child objects (eg, boxes can be rotated relative to the local axes of the parent object). When creating a compound collider like this, there should only be one Rigidbody component, placed on the root object in the hierarchy.
There are some cases, however, where even compound colliders are not accurate enough. In 3D, you can use Mesh Colliders to match the shape of the object’s mesh exactly. In 2D, the Polygon Collider 2D will generally not match the shape of the sprite graphic perfectly but you can refine the shape to any level of detail you like. These colliders are much more processor-intensive than primitive types, however, so use them sparingly to maintain good performance. Also, a mesh collider will normally be unable to collide with another mesh collider (ie, nothing will happen when they make contact). You can get around this in some cases by marking the mesh collider as Convex in the inspector. This will generate the collider shape as a “convex hull” which is like the original mesh but with any undercuts filled in. The benefit of this is that a convex mesh collider can collide with other mesh colliders so you may be able to use this feature when you have a moving character with a suitable shape. However, a good general rule is to use mesh colliders for scene geometry and approximate the shape of moving objects using compound primitive colliders.
Colliders can be added to an object without a Rigidbody component to create floors, walls and other motionless elements of a scene. These are referred to as static colliders. In general, you should not reposition static colliders by changing the Transform position since this will impact heavily on the performance of the physics engine. Colliders on an object that does have a Rigidbody are known as dynamic colliders. Static colliders can interact with dynamic colliders but since they don’t have a Rigidbody, they will not move in response to collisions.
The reference pages for the various collider types linked above have further information about their properties and uses.
Physics materials
When colliders interact, their surfaces need to simulate the properties of the material they are supposed to represent. For example, a sheet of ice will be slippery while a rubber ball will offer a lot of friction and be very bouncy. Although the shape of colliders is not deformed during collisions, their friction and bounce can be configured using Physics Materials. Getting the parameters just right can involve a bit of trial and error but an ice material, for example will have zero (or very low) friction and a rubber material with have high friction and near-perfect bounciness. See the reference pages for Physic Material and Physics Material 2D for further details on the available parameters. Note that for historical reasons, the 3D asset is actually called Physic Material (without the S) but the 2D equivalent is called Physics Material 2D (with the S).
Triggers
The scripting system can detect when collisions occur and initiate actions using the OnCollisionEnter function. However, you can also use the physics engine simply to detect when one collider enters the space of another without creating a collision. A collider configured as a Trigger (using the Is Trigger property) does not behave as a solid object and will simply allow other colliders to pass through. When a collider enters its space, a trigger will call the OnTriggerEnter function on the trigger object’s scripts.
Script actions taken on collision
When collisions occur, the physics engine calls functions with specific names on any scripts attached to the objects involved. You can place any code you like in these functions to respond to the collision event. For example, you might play a crash sound effect when a car bumps into an obstacle.
Collider interactions
Colliders interact with each other differently depending on how their Rigidbody components are configured. The three important configurations are the Static Collider (ie, no Rigidbody is attached at all), the Rigidbody Collider and the Kinematic Rigidbody Collider.
Static Collider
This is a GameObject that has a Collider but no Rigidbody. Static colliders are used for level geometry which always stays at the same place and never moves around. Incoming rigidbody objects will collide with the static collider but will not move it.
The physics engine assumes that static colliders never move or change and can make useful optimizations based on this assumption. Consequently, static colliders should not be disabled/enabled, moved or scaled during gameplay. If you do change a static collider then this will result in extra internal recomputation by the physics engine which causes a major drop in performance. Worse still, the changes can sometimes leave the collider in an undefined state that produces erroneous physics calculations. For example a raycast against an altered Static Collider could fail to detect it, or detect it at a random position in space. Furthermore, Rigidbodies that are hit by a moving static collider will not necessarily be “awoken” and the static collider will not apply any friction. For these reasons, only colliders that are Rigidbodies should be altered. If you want a collider object that is not affected by incoming rigidbodies but can still be moved from a script then you should attach a Kinematic Rigidbody component to it rather than no Rigidbody at all.
Rigidbody Collider
This is a GameObject with a Collider and a normal, non-kinematic Rigidbody attached. Rigidbody colliders are fully simulated by the physics engine and can react to collisions and forces applied from a script. They can collide with other objects (including static colliders) and are the most commonly used Collider configuration in games that use physics.
Kinematic Rigidbody Collider
This is a GameObject with a Collider and a kinematic Rigidbody attached (ie, the IsKinematic property of the Rigidbody is enabled). You can move a kinematic rigidbody object from a script by modifying its Transform Component but it will not respond to collisions and forces like a non-kinematic rigidbody. Kinematic rigidbodies should be used for colliders that can be moved or disabled/enabled occasionally but that should otherwise behave like static colliders. An example of this is a sliding door that should normally act as an immovable physical obstacle but can be opened when necessary. Unlike a static collider, a moving kinematic rigidbody will apply friction to other objects and will “wake up” other rigidbodies when they make contact.
Even when immobile, kinematic rigidbody colliders have different behavior to static colliders. For example, if the collider is set to as a trigger then you also need to add a rigidbody to it in order to receive trigger events in your script. If you don’t want the trigger to fall under gravity or otherwise be affected by physics then you can set the IsKinematic property on its rigidbody.
A Rigidbody component can be switched between normal and kinematic behavior at any time using the IsKinematic property.
A common example of this is the “ragdoll” effect where a character normally moves under animation but is thrown physically by an explosion or a heavy collision. The character’s limbs can each be given their own Rigidbody component with IsKinematic enabled by default. The limbs will move normallly by animation until IsKinematic is switched off for all of them and they immediately behave as physics objects. At this point, a collision or explosion force will send the character flying with its limbs thrown in a convincing way.
Collision action matrix
When two objects collide, a number of different script events can occur depending on the configurations of the colliding objects’ rigidbodies. The charts below give details of which event functions are called based on the components that are attached to the objects. Some of the combinations only cause one of the two objects to be affected by the collision, but the general rule is that physics will not be applied to an object that doesn’t have a Rigidbody component attached.
Collision detection occurs and messages are sent upon collision | ||||||
---|---|---|---|---|---|---|
Static Collider | Rigidbody Collider | Kinematic Rigidbody Collider | Static Trigger Collider | Rigidbody Trigger Collider | Kinematic Rigidbody Trigger Collider | |
Static Collider | Y | |||||
Rigidbody Collider | Y | Y | Y | |||
Kinematic Rigidbody Collider | Y | |||||
Static Trigger Collider | ||||||
Rigidbody Trigger Collider | ||||||
Kinematic Rigidbody Trigger Collider |
Trigger messages are sent upon collision | ||||||
---|---|---|---|---|---|---|
Static Collider | Rigidbody Collider | Kinematic Rigidbody Collider | Static Trigger Collider | Rigidbody Trigger Collider | Kinematic Rigidbody Trigger Collider | |
Static Collider | Y | Y | ||||
Rigidbody Collider | Y | Y | Y | |||
Kinematic Rigidbody Collider | Y | Y | Y | |||
Static Trigger Collider | Y | Y | Y | Y | ||
Rigidbody Trigger Collider | Y | Y | Y | Y | Y | Y |
Kinematic Rigidbody Trigger Collider | Y | Y | Y | Y | Y | Y |
Did you find this page useful? Please give it a rating: