Unity physics system introduction doc finishing

When I was working this week, I saw the use of physical materials in the project, and I realized that I had never used it, and I didn’t know the relationship between him and other physical components such as rigid body, so I read the official doc again., for some practice and summary.

Unity supports multiple physics engines. I usually use the Object Oriented 3D physics engine, so I mainly study the content here.

This article describes the main components available through Unity’s built-in 3D physics engine that you can use in Object Oriented projects. This section includes the following topics:

  • Overview of the main concepts related to physical systems: rigid bodies, colliders, joints, physical joins, and character controllers.
    Some notes on specific physical environments: continuous collision detection and multi-scene physics.
  • Description of physical debugging visualization.

Rigid body

Rigid body (Rigidbody) is the main component that implements the physical behavior of the game object. After connecting the rigid body, the object will immediately respond to gravity. If one or more components __ collider __ are also added, the game object will move due to the collision.

Since the rigid body component takes over the motion of the attached game object, you should not try to move the game object by changing transformation properties such as position and rotation with the help of scripts. Instead, apply __ force __ to push the game object and let the physics engine calculate the result.

That is to say, the role of the rigid body is to allow the object to respond to force, but it will not produce force, we need to generate force through scripts or collisions.

In some cases, it may be desirable for the game object to have a rigid body and let the motion of the rigid body out of the control of the physics engine. For example, you may want to control the character directly from the script code, but still allow triggers to detect the character. This non-physical motion generated by the script is called _ kinematic _ motion. The rigid body component has a property called Is Kinematic that lets the rigid body out of the control of the physics engine and allows the rigid body to be moved kinematically through the script. It is possible to script to change the value of Is Kinematic to turn the physics engine on and off for an object, but this incurs performance overhead and should be used with caution.

The question arises here, if you want the game object to be free from the control of the physics engine, why not just remove the rigid body? Also through settings

Sleep

When the rigid body moves below the specified minimum linear speed or RPM, the physics engine considers the rigid body to have stopped. When this happens, the game object will not move again until it is hit or forced, so it is set to “sleep” mode. This optimization means that it will not take processor time to update the rigid body before it is “woken up” the next time (i.e. into motion again).

In most cases, sleep and wake-up of rigid body components occur transparently. However, if a static collider (i.e., a collider without a rigid body) is moved into or away from a game object by modifying __ transforming __ position, the game object may not be awakened. This can cause problems, such as a rigid body game object hanging in the air when the floor has been removed from under it. In this case, you can use the WakeUp function to explicitly wake up the game object.

That is to say, if a rigid body has entered a sleep state, using a static collider to try to change the force state of the rigid body may not be effective, and we need to explicitly wake up.

Collider

The collider component defines the shape of the game object to be used for physical collisions. Colliders are invisible and their shape does not need to be exactly the same as the mesh of the game object. A rough approximation of the mesh is usually more efficient and difficult to detect during game play.

Primitive collider

The simplest (and least processor overhead) colliders are the __ primitive __ collider types. In 3D, these colliders are box colliders, sphere colliders, and capsule colliders. In 2D, you can use 2D box colliders, and 2D round colliders. Any number of these colliders can be added to a single game object to create __ composite collider __.

Compound collider

Composite colliders simulate the shape of Game objects while keeping processor overhead low. For more flexibility, additional colliders can be added to child game objects. For example, the box can be rotated relative to the local axis of the parent game object. When creating a composite collider like this, only one rigid body component should be used on the root game object in the hierarchy view.

The original collider does not properly handle clipping transforms. If a combination of rotation and non-uniform proportions is used in the transform hierarchy view so that the resulting shape is no longer the original shape, the original collider cannot correctly represent this shape.

Grid collider

However, in some cases, even composite colliders are not accurate enough. In 3D, mesh colliders can be used to precisely match the shape of the game object mesh. In 2D, 2D polygon colliders don’t perfectly match the shape of sprite graphics, but you can refine the shape to any level of detail you need.

These colliders have a higher processor overhead than the original type, so use caution to maintain good performance. ** Also, mesh colliders cannot collide with another mesh collider ** (i.e., nothing happens when they make contact). In some cases, this can be resolved by marking the mesh collider as Convex in Inspector. This setting produces a collider shape in the form of a “convex shell”, similar to the original mesh, but filled with undercuts.

The benefit of this is that convex mesh colliders can collide with other mesh colliders, so this feature can be used when there is a moving character with a suitable shape. However, one applicable rule is to use mesh colliders for scene geometry and approximate the shape of the moving game object using composite primitive colliders.

Static collider (no rigid body)

Colliders can be added to game objects without rigid body components, creating floors, walls, and other stationary elements of the scene. These are called _ static _ colliders. Conversely, colliders on game objects with rigid bodies are called _ dynamic _ colliders. Static colliders can interact with dynamic colliders, but because there is no rigid body, they do not respond to collisions by moving.

Physical material

When colliders interact, their surfaces need to simulate the properties of the material they should represent. For example, a piece of ice will be smooth, while a rubber ball will provide a lot of friction and have good elasticity. Although the shape of the collider will not deform upon collision, the friction and elasticity of the collider can be configured using Physics Materials __. It may take multiple trials and error corrections to get the correct parameters, such as ice will have zero (or very low) friction, while rubber will have high friction and near perfect elasticity. For more details on available parameters, please refer to the reference pages for Physical Materials and 2D Physical Materials. Note that for historical reasons, 3D resources are actually called Physics Materials.

Trigger

Scripting systems can use the OnCollisionEnter function to detect when a collision occurs and initiate an action. However, you can also use the physics engine directly to detect when a collider enters the space of another object without causing a collision. Colliders configured to __ trigger __ (using the Is Trigger property) do not behave as physical objects, only allowing other colliders to pass through. When a collider enters its space, the trigger will call the OnTriggerEnter function in the trigger object’s script

Collider callback

When a collision occurs, the physics engine calls a function with a specific name on all scripts attached to the relevant object. Any code needed can be placed in these functions to respond to the collision event. For example, when a car hits an obstacle, a collision sound can be played.

In the first physical update that detects a collision, the OnCollisionEnter function will be called. During the update that maintains contact, OnCollisionStay will be called, and finally OnCollisionExit will indicate that contact has been interrupted. Triggering a collision invokes the simulated OnTriggerEnter, OnTriggerStay, and OnTriggerExit functions. Note that for 2D physics, an equivalent function with the word 2D appended to the name, such as OnCollisionEnter2D, can be used. See the script reference page for the MonoBehaviour class for complete details on these functions and code examples.

For normal non-triggered collisions, there is an additional detail that at least one of the objects involved must have a non-moving rigid body (i.e., the Is Kinematic must be closed). If both objects are moving rigid bodies, functions such as OnCollisionEnter will not be called. For triggered collisions, this restriction does not apply, so both the moving and non-moving rigid bodies prompt for OnTriggerEnter when entering the triggered collider.

This is also better understood, if two rigid bodies touch together, it will not coincide, and naturally there will be no OnCollisionEnter event

That is to say, according to the Is Trigger property of the collision body of the collision object, the collision is divided into trigger collision and non-trigger collision, which will trigger different functions respectively, instead of triggering collision, at least one object needs to have a non-moving rigid body

Collider interaction

The interaction of colliders with each other varies depending on the configuration of the rigid body components. Three important configurations are _ Static Collider (i.e. no rigid body attached at all), Rigidbody Collider _ and _ Kinematic Rigidbody Collider _.

Static collider

Static colliders are game objects that have colliders but no rigid bodies. Static colliders are used in most cases to represent level geometry that always stays in the same place and never moves around. Close rigid body objects will collide with static colliders, but will not move static colliders.

In special cases, the physics engine is optimized for static colliders that never move. For example, even if you move a static collider, a vehicle parked on a static collider will remain asleep. You can enable, disable, or move static colliders at runtime without particularly affecting the computing speed of the physics engine. In addition, static mesh colliders can be safely scaled as long as the scaling ratio is uniform (no bias).

Rigid body collider

This is a game object with colliders and normal non-moving rigid bodies attached. Rigid body colliders are completely simulated by the physics engine and respond to collisions and forces applied via scripts. Rigid body colliders can collide with other objects, including static colliders, and are the most commonly used collider configuration in games that use physics components.

Moving rigid body collider

This is a game object with a collider and _ motion _ rigid body attached (i.e. the IsKinematic property of the rigid body is enabled). Moving rigid body objects can be moved (by modifying the object’s transform components) using scripts, but the object does not respond to collisions and forces like a non-moving rigid body. Moving rigid bodies should be used for colliders that meet the following characteristics: Occasionally may be moved or disabled/enabled, otherwise behavior should be like static colliders. An example of this is a sliding door, which is often used as an immovable physical barrier but can be opened if necessary. Unlike a static collider, a moving rigid body exerts friction on other objects and “wakes up” the other rigid body when the two parties come into contact.

A moving rigid body collider behaves differently to a static collider even when it is immobile. For example, if you set a collider as a trigger, you also need to add a rigid body to it to receive trigger events in your script. If you don’t want the trigger to fall under gravity or be physically affected in other ways, you can set the IsKinematic property on its rigid body.

The IsKinematic property allows rigid body components to switch between normal and athletic behavior at any time.

Collider operation matrix

For details, please take a look at doc: https://docs.unity3d.com/cn/2021.2/Manual/CollidersOverview.html

Intersection between rigid body and collider

Here is a summary of rigid bodies and colliders.

From the perspective of the physics engine, only the rigid body can respond to the force, and the role of the collider is to generate force, and the collider can be associated with a physical material, which is used to set parameters such as friction coefficient and rebound coefficient to correspond to the control. Generate different forces during collisions.

At the same time, the rigid body has a switch called IsKinematic, which can control whether the rigid body participates in the calculation of the physics engine, thereby controlling whether the rigid body responds to the force

The collider has a switch called Is Trigger, which is used to control whether the collider is a trigger. Once it is a trigger, the collider will not generate force when colliding with another collider, but let other colliders pass through and trigger OnTriggerEnter, OnTriggerStay and other functions at the same time

Another thing to note is that the collider has a specific shape, the rigid body does not, and it can be understood that the shape of the rigid body is the collection of all colliders that generate force

Joint

A joint assembly connects a rigid body to another rigid body or a fixed point in space. A joint exerts a force that makes the rigid body move, and a joint restriction function can limit that movement. A joint gives the rigid body the following degrees of freedom:

Unity offers the following joints that can apply different forces and constraints to rigid body components, giving these rigid bodies different motions:

Properties:Functions:
Character JointsSimulate ball and socket joints, such as hips or shoulders. Constraint rigid body movement along all linear degrees of freedom and achieve all angular degrees of freedom. The rigid body attached to the Character Joint is oriented around each axis and rotates from a shared origin.
Configurable JointsSimulate any skeletal joint, such as those in ragdoll. You can configure this joint to drive and restrict the movement of a rigid body with any degree of freedom.
Fixed JointLimits the movement of a rigid body to follow the movement of the rigid body it is attached to. This joint is useful when you need some rigid body that can be easily separated from each other, or when you want to connect the movement of two rigid bodies without having to parent in the Transform hierarchy view.
Hinge JointConnects a rigid body to another rigid body or a point in space at a shared origin and allows the rigid body to rotate about a specific axis from that origin. Used to simulate door and finger joints.
Spring JointsSeparate the rigid bodies from each other, but stretch the distance between the rigid bodies slightly. The spring acts like a piece of elasticity, trying to pull the two anchor points together into the exact same position.

Joints have other options that can be used to achieve specific effects. For example, a joint can be set to ensure that the joint is destroyed when the force exerted by the rigid body on the joint exceeds a certain threshold. Some joints allow __ driving force to be generated between the connected rigid bodies __ to make them move automatically.

Note: If kinematic chains are to be constructed in the context of industrial applications, such as simulating robotic arms with realistic physical behavior, physical joins should be used instead of the conventional joints described here.

Physical bonding

A physical junction is a set of junctions organized in the form of a logical tree, where each parent-child relationship reflects the relative motion of mutual constraints.

The main purpose of physical bonding is to provide realistic physical behavior for non-gaming industrial applications involving joints. Compared to conventional joints, physical bonding is much more convenient for simulating robotic arms and kinematic chains.

Physical Joints and Joints

Joining SettingsUse Regular Joint Settings
Hierarchical viewGame object + joint; Game object + jointGame object + rigid body; Game object + rigid body + joint
RelationshipsGame objects have hierarchical relationships (parent-child) Note: The physics engine uses Unity to transform hierarchical views to express parent-child relationships.Game objects do not necessarily have hierarchical relationships. Note: In more advanced scenarios, you are free to simulate loops of motion.
Physical bodyBoth game objects have an join body component that defines physical body properties (etc.).Both game objects have a rigid body component that defines physical body properties (etc.).
JointThe joins of the child game objects contain joint properties where you can select the joint type.One of the game objects also has a joint component. The joint properties depend on the type of joint component you add.

However, the overall resulting behavior is not the same in both cases, especially if you extend this principle to multiple physical bodies and joints.

If you try to model a kinematic chain with regular joints, such as in a rag doll, robotic arm, or a mechanism with multiple parallel hinges, the physics engine may encounter situations that cannot be solved and leave some constraints that cannot be met. This can lead to Stuttering and unrealistic movements. Not only do these joints look weird, but it is also impossible to use them to simulate real devices, hindering modeling or Prototyping of industrial designs.

Building Physical Joints in Unity

To build a physical join in Unity, you must add an join component to each GameObject that makes up the join. The configuration of each join component can be centralized in one location:

The physical properties of the corresponding game object. Basically, its quality and how it responds to the physical environment.

The type and properties of the joints that link the GameObject to its parent GameObject (outside of the joined root).

The following example shows a simple physical joint involving 3 physical bodies and 2 joints:

To build such an interface in Unity:

Create a linear hierarchy of 3 game objects.

  1. Add a Junction component for each of the three GameObjects.

  2. Configure each joint assembly (according to the above figure):

GameObjectJunction Component Configuration
A (root)You can only define physical properties for game object A.
BYou can define: the physical properties of the game object B. The type and properties of the joints that are connected to the game object A.
CYou can define: the physical properties of the game object C. The type and properties of the joints connected to the game object B.

Note: By definition, a joint can only have one root and loops of motion are not allowed. If you need loops of motion, use regular joints.

Limitations: If you want to build very long splice chains, still note that Unity supports a maximum level depth of 64 game objects.

Joint type and degrees of freedom

With the joint, you can select and configure four types of joint:

  • Fixed joints: Set rigid, unbreakable and unstretchable links between physical bodies.

Prismatic joints: block all movement except sliding along a specific axis.

  • Rotating joints: allow rotation around a specific axis (such as a hinge).

  • Spherical Joints: Anatomical joints that allow two swings and one twist.

** All locked degrees of freedom in engagement are by design unbreakable and unstretchable. To achieve this, the physics engine uses reduced-dimensional coordinate space, where the physics body only has coordinates on the unlocked axis of motion **.

In contrast, for regular iterative joints, the physics engine uses the largest coordinate space, and only if the solver can converge after a set of iterations can the constraint be guaranteed to be satisfied.

Character controller

Characters in first- or third-person games often require some collision-based physics so that the character doesn’t fall through the floor or through walls. However, often times, the acceleration and movement of the character are not physically realistic, so the character can accelerate, brake, and change direction almost instantaneously regardless of momentum.

In 3D physics, such behaviors can be created using __ character controller __. This component provides the character with a simple capsule collider that is always upright. The controller has its own special function to set the speed and direction of the object, but unlike real colliders, the controller does not require a rigid body and the momentum effect is not realistic.

Character controllers cannot pass through static colliders in the scene, so will stick to the floor and be blocked by walls. Controllers can push rigid body objects aside while moving, but will not be accelerated by approaching collisions. This means that standard 3D colliders can be used to create scenes for controllers to walk, but you are not limited by the real physical behavior of the character itself.

Detailed settings: https://docs.unity3d.com/cn/2021.2/Manual/class-CharacterController.html

Continuous collision detection

CCD ensures that fast-moving objects collide with objects without passing through them. Unity provides the following CCD methods:

  • Sweep-based CCD
  • Inferential CCD

To use a sweep-based CCD, select a rigid body (RigidBody) in the Inspector window and set Collision Detection to Continuous or Continuous Dynamic. To use an inferential CCD, set Collision Detection to Continuous Speculative.

Sweep-based CCD

Sweep-based CCDs use the Time of Impact (TOI) algorithm to calculate the potential collision of an object (using the object’s current speed) by sweeping the object’s forward trajectory. If there is contact along the direction of the object’s movement, the algorithm calculates the impact time and moves the object until that time is reached. The algorithm can perform sub-steps from this time, that is, calculate the speed after TOI, and then re-sweep, at the cost of more CPU cycles.

However, ** because this method relies on linear sweeping, the angular motion of the object is ignored, which can cause tunneling effects when the object rotates rapidly **. For example, a pachinko club on a pinball machine is fixed at one end and rotates around a fixed point. The pachinko club only does angular motion, not linear motion. Therefore, it is easy to miss the pachinko:

Another problem with this approach is performance. If there are a large number of CCD-enabled high-speed objects nearby, the CCD overhead will quickly increase due to additional sweeping, so the physics engine has to perform more CCD sub-steps

Inferential CCD

Inferential CCD works by increasing the coarse sieve phase axis alignment minimum bounding box (AABB) of an object based on the linear and angular motion of the object. The algorithm is a speculative algorithm because all potential touchpoints in the next physics step are picked. All touchpoints are then fed to the solver, thus ensuring that all touchpoint constraints are met so that the object does not pass through any collisions.

The following figure shows how a sphere moving from t0 obtains the expected t1 position (if there is no wall in its path). By expanding the AABB using the target pose, the speculative algorithm picks two touchpoints between the normals to n1 and n2. The algorithm then tells the solver to follow these touchpoints so that the sphere does not pass through the wall.

AABB, which is based on the current speed and expands, helps detect all potential touchpoints along the motion trajectory, enabling the solver to prevent objects from passing through.

Speculative CCDs are generally less expensive than sweep-based methods because touchpoints are calculated only in the collision detection phase (not in the solution and integration phases). In addition, since speculative CCDs extend the coarse screen phase AABB based on the linear and angular motion of the object, touchpoints that may be missed by sweep-based CCDs can be found.

Phantom collision

However, speculative CCDs can cause ghost collisions; in such collisions, the motion of the object is affected by speculative touchpoints, which should not happen. This is because speculative CCDs collect all potential touchpoints based on the closest point algorithm, so touchpoint normals are less accurate. This usually causes high-speed objects to slide and jump up along the subdivided collision features, but it shouldn’t. For example, in the figure below, the sphere moves horizontally to the right starting at t0, and the predicted position after integration is t1. The enlarged AABB overlaps the boxes b0 and b1, while the CCD produces two speculative touchpoints at c0 and c1. Since the speculative CCD uses the closest point algorithm to generate the touchpoint, c0 has a very skewed normal, so the solver treats it as a ramp.

The solver considers the touchpoint at c0 to be a ramp because the nearest point algorithm generates an inaccurate touchpoint normal

Tunneling

A speculative CCD may also cause tunneling to occur, as speculative touchpoints are only calculated during the collision detection phase. During touchpoint solving, if an object gains too much energy from the solver, after integration, its final position may be outside the initially expanded AABB. If a collision occurs immediately outside the AABB, the object will pierce out to the right.

For example, the image below shows the sphere moving to the left from t0 while the club rotates clockwise. If the sphere gains too much energy from the impact, it may end up leaving the enlarged AABB (red dot rectangle) and falling at t1. If a collision occurs immediately outside the AABB (as shown in the blue box below), the sphere may end up piercing through the right. This is because the solver only calculates the internal touchpoint of the enlarged AABB and does not perform collision detection during the solution and integration phases