Rigid Body Unity



  1. On the object I added a Rigidbody and it already has a box collider. And the floor: I want to make a bouncing ball effect. I'm using the official unity tutorial: Tutorial. However, my object falls through the floor.
  2. Use Rigidbody.MovePosition to move a Rigidbody, complying with the Rigidbody's interpolation setting. If Rigidbody interpolation is enabled on the Rigidbody, calling Rigidbody.MovePosition results in a smooth transition between the two positions in any intermediate frames rendered.

Using RigidBody AddForce method to move Game Object in Unity. While normal movement of gameobject is possible by changing its position coordinates, for rigid bodies we can also use some built-in methods to enhnance movement effects of game objects.

These are tips for using Rigid Bodies and Physics in Unity. I was maintaining these in a document on my PC and decided I may as well store them publicly so other people can benefit from what I have learned: The battle of ides.

Rigidbodies and the Hierarchy

Non-kinematic rigid bodies will ignore the hierarchy. If you make one rigid body a child of another and translate the parent. Then the child will NOT move with the the parent. The child’s transform will update so that it remains in place in world space. If you want to couple rigid bodies you need to use joints.

Avoid scaling and especially non-uniform scaling of colliders. There is a big performance hit for non-uniform scaling. Negative scale makes no sense with physics so don’t. Set the scale of the GameObject to 1,1,1 and use the properties of the collider to set its size and position. Another option is to attach the collider to a child game object.

Try to separate physics geometry and render geometry in prefabs. This makes it easy to do things like LOD.

OnCollision Events

OnCollisionEnter, OnCollisionStay, OnCollisionExit events only fire on the transform with the rigidbody component on it. All colliders beneath a rigid body in the hierarchy are grouped into one big collider. If you try to capture these events with a script placed on a child collider the events will NOT fire for that script.

OnCollisionEnter, OnCollisionStay, OnCollisionExit are called in the physics loop (once per FixedUpdate call).

OnCollisionStay is NOT called if the rigidbody it is attached to is sleeping.

OnCollisionEnter, OnCollisionStay, OnCollisionExit events are called once per rigid body, per physics frame. So if a plane implements OnCollisionStay and has a cube, ball and cylinder sitting on it (each of which has a rigidbody) then OnCollisionStay will be called three times per FixedUpdate call. If the cube, ball and cylinder were all grouped in the hierarchy under a single rigid body then there would be one OnCollisionStay call.

Manual

Collisions

The Collision object contains the “collider” field which is the collider on the other object that was hit. If you want the collider on this object then look in the contacts array. There may be more than one collider in that array.

OnCollisionEnter, OnCollisionStay, OnCollisionExit calls generally occur in pairs each participant rigidbody receives a call. Most of the time the collision information is identical but WheelColliders can produce different Contacts arrays for each participant in a collision.

Collision.contacts can sometimes have zero length. Unity claims that the collision.contacts array will always have at least one value. THIS IS NOT THE CASE FOR OBJECTS WITH A COMBINATION OF REGULAR COLLIDERS AND WHEEL COLLIDERS. The following scenario can generate a frame with OnCollision calls that have zero length contact arrays. If the wheel collider suspension is being compressed over a number of frames and a regular collider grounds. Then the first frame of the regular collider hitting the ground will have collision.contacts.Length = 0.

Colliders

Contacts for mesh colliders and boxcolliders are calculated on vertices of a mesh that penetrate another collider.

  • A SphereCollider will usually generate one contact point.
  • A BoxCollider collider contact will usually have one,two or four contact points.
  • Mesh colliders can produce hundreds of contact points. Keep them simple.

Avoid mesh colliders if possible. They are expensive. Mesh colliders must be convex to collide with other mesh colliders.

Moving And Rotating Rigid Bodies

Avoid regularly setting transform.postion and transform.rotation on rigidbodies. PhysX must do a big solve when this happens. This reduces the stability of the physics simulation and has a heavy performance cost.

The correct way to move and rotate rigidbodies is by setting the velocity and angularVelocity values.


rigidbody.transform.Translate(1,0,0); //WRONG

is equivalent to:

rigidbody.velocity = new Vector3(1f/Time.fixedDeltaTime,0,0);

Note that you need to zero the velocity on the next FixedUpdate frame to stop the rigid body.

FixedUpdate Update and Coroutines

FixedUpdate is for physics and Update is for rendering.

Fixed Update will normally be called at 60 fps.

Update will typically be called at 30 – 60 fps or more.

When using coroutines for physics calculations be sure to use WaitForFixedUpdate NOT WaitForUpdate. Update is for rendering, Fixed update is for physics.

Floating Point Precision Errors

Keep your game within 6000 units of the origin. Floating point precision drops the further from the origin you get. You will start to notice glitches if you get too far from the origin. This limit seems to be around 6000 units.

Keep your forces below 10,000 Newtons. Forces above this can cause instability.

Keep your torques even smaller. PhysX clamps angularVelocity (The setting is in the Physics settings). There is no point applying a torque that will accelerate more that this limit in a single frame.

Keep your velocities within 1000 units of zero. If you need to go faster than this then use a moving reference frame.

Keep your masses bellow 10000 kg and above .01 kg. Jittering and instability may result if you push this too far.

Rigid Body Unity

PD Controllers

This is a large topic I will write a separate page on it.

Update (14 August 2020): Looking for an article on the Interpolate property on Unity Rigidbodies? We’ve put one together recently, so have a look here.

It isn’t particularly difficult to set up physics-based movement for objects in Unity — simply add a Rigidbody component onto an object that has a Collider component, and you’ll have yourself an object that moves and collides realistically with other objects.

If you start having fast-moving objects however, you might start to see these objects tunnel through obstacles.

The illusion of motion and tunnelling

Before we delve into why tunnelling occurs, it is important to understand this: the motion that we see in animated media is an illusion. Anything that appears to move on a screen does so because the screen is showing us a rapid sequence of images. This tricks our minds into thinking that there is motion, even though what we saw was a series of static images.

Similarly, the motion of the ball that we saw above was made of many individual images, each one showing the ball at different positions. How much a ball moves from one image to the next depends on how fast it is moving. Hence, a slower-moving ball moves very little from image to image, while a fast-moving ball can move a distance equal to several times its diameter from one image to another.

Because fast-moving objects cover so much distance from one frame to the next, it may skip over thinner objects (as pictured in the image above right) without registering a collision, since there is such a large gap between its positions in any two frames. This is what causes the tunnelling phenomenon you see.

The solution: Continuous collision

To address this problem, physics engines utilise a collision algorithm that projects a shape across an object’s path of travel. This shape is then used to check for any collisions from the object’s displacement between frames.

This method of detecting collisions is called continuous collision detection, whereas the one that doesn’t prevent tunnelling is called discrete collision detection.

Discrete vs. Continuous collision

Although continuous collision detection is clearly the better choice, game engines generally do not enable continuous collision detection for all objects in their physics engines. This is for a simple reason: continuous collision detection is significantly more expensive, so having too many objects using it can unnecessarily use up computing power! Since only fast-moving objects suffer from the tunnelling problem, developers often enable continuous collision detection only for these objects.

In Unity, the option to turn on continuous collision detection can be found on the Rigidbody2D and Rigidbody components, which are used in 2D and 3D games respectively to give objects physics-based movement. Again, the idea here is to set the collision detection mode to Continuous for fast-moving objects, and leave the rest of the objects at the default value of Discrete.

Article continues after the advertisement:

Continuous Dynamic vs. Speculative

If you look at the Rigidbody component, you will find that it has 2 additional values in Collision Detection compared to its Rigidbody2D counterpart: Continuous Dynamic and Continuous Speculative. These additional collision detection modes are further optimisations, unique to Unity’s 3D physics system, and in place because 3D collision detection can be potentially much more expensive than its 2D counterpart.

Rigidbody components that use the Continuous mode only use continuous collision detection on static objects (i.e. Collider components without a Rigidbody, which means the object does not move using Physics). Ms excel in computer. This means that, in theory, tunnelling can still occur when you are colliding with any object using a Rigidbody component.

Objects using the Continuous Dynamic mode will not have these issues, as they will use continuous collision against all objects, except against Rigidbody objects using Discrete collision detection.

Continuous Speculative is even better. It collides against everything — static and dynamic objects in all modes of collision; is computationally faster than the other 2 modes of continuous collision; and detects certain kinds of collisions caused by spinning objects that are missed by other modes of continuous collision.

However, because it speculates (i.e. predicts) collisions based on objects’ current motions, collisions that are detected can sometimes be inaccurate.

Making sense of everything

Rigidbody Unity

All of this can be pretty confusing, isn’t it? Here are some good rule of thumbs to help you decide which modes to use:

  1. If there are no fast-moving objects in your game, you can safely use Discrete collision detection for all your objects. An object can be considered to be fast-moving if it can travels a distance larger than its width or height within a frame.
  2. If you don’t care about collision accuracy in your game,Continuous Speculative will be the way to go with your fast-moving objects. The rest of the objects in the game can use Discrete.
  3. For dynamic objects (i.e. objects with Rigidbody) that don’t touch fast-moving objects at all, you can safely use Discrete collision.
  4. For dynamic objects that are not fast-moving, use Continuous collision on them if you need them to always collide with fast-moving objects.
  5. For dynamic objects that are fast-moving, always use Continuous Dynamic collision.

Rigid Body Physics Unity

As a summary to help make sense of all the information above, here is a table that outlines how each of the collision modes interact with one another:

How To Reference A Rigidbody In Unity

Article continues after the advertisement: