In-depth understanding of Unity's Physics class: a detailed technical guide (7) (Part 1)

Preface

Unity's Physics class is the core of Unity's physics system and provides a set of APIs for processing and controlling physical simulations. This class provides global properties and methods for controlling the physics system, as well as detecting and applying forces to game objects, handling collision and trigger events, etc. In order to allow developers to better understand this Physics class, its properties are explained in detail , which makes the article too long, so it is divided into parts to explain.


In order to make the properties and methods of Unity's Physics class clearer, we can divide them according toPurpose and functionsort:

1.Basic physical properties:

①Global physics properties: (These properties set the general behavior of the physics simulation)
Physics.gravity: Define the gravity value in the game world.
Physics.defaultContactOffset: The offset of the contact point between two colliding objects.
Physics.defaultSolverIterations: Number of iterations used by the physics solver to solve for contacts and joints.
Physics.defaultSolverVelocityIterations: The default number of solver speed iterations used by the physics solver to improve joint and tie point accuracy.
Physics.defaultMaxAngularSpeed:The maximum angular velocity of the object.
Physics.defaultMaxDepenetrationVelocity: The maximum speed of an object when penetration occurs.
Physics.autoSimulation:Whether to automatically simulate physics.
Physics.autoSyncTransforms:Whether to automatically synchronize the object's transformations (Transforms) after each simulation.
Physics.defaultPhysicsScene:Default physics scene in Unity.

② Collision detection settings: (These properties are mainly responsible for the parameter settings of collision detection)
Physics.bounceThreshold: The minimum speed (speed threshold) when two objects collide with each other. Collisions below this threshold will be regarded as inelastic collisions.
Physics.sleepThreshold: The minimum threshold before the object enters the sleep state. Objects with a speed lower than this value will enter the sleep state.
Physics.queriesHitBackfaces: Whether to detect the back side. This Boolean property defines whether the ray cast will hit the back side.
Physics.queriesHitTriggers: Whether to detect triggers. This Boolean property defines whether physics queries (ray casting, sphere casting, etc.) will detect triggers.
Physics.reuseCollisionCallbacks:Whether the collision callback of the same pair of colliding objects should be triggered multiple times in the same frame (whether to reuse the collision callback).

③ Cloth and mutual collision: (These properties are related to the physical behavior of the cloth and the mutual collision between objects)
Physics.clothGravity: The gravity of the cloth.
Physics.interCollisionDistance: Set the minimum separation distance for collision between cloths.
Physics.interCollisionStiffness:Set the stiffness of collision between cloths.
Physics.interCollisionSettingsToggle:Whether to enable cloth mutual collision setting.


Physics.gravity

Physics.gravity is a Vector3 type, which is used to represent the direction and magnitude of global gravity. This value takes effect for all Rigidbody objects in Unity, unless the useGravity attribute of the Rigidbody object is set to false.

The default value is (0, -9.81, 0), which simulates real-world gravity (downward acceleration of 9.81 m/s²).
You can modify this value to change the gravity of the game world.

For example, you can increase gravity with the following code:

Physics.gravity = new Vector3(0, -20.0f, 0);

Or you can create a gravity to the right:

Physics.gravity = new Vector3(9.81f, 0, 0);

This code can be called anywhere, but a common practice is to set it when the game starts (such as within the MonoBehaviour's Start method).
注意:Modifying Physics.gravity will affect all Rigidbody objects, which may have a big impact on the physical behavior of the game, so you should fully consider it before modifying it.


Physics.defaultContactOffset

Physics.defaultContactOffset is a floating point number representing the default contact offset. Contact offset is the gap between colliders that make contact around the contact point and is used to ensure stable physics simulation. This gap allows Unity to predict collisions between two objects.

 
Unity starts calculating collisions between objects when they approach a distance that is a fraction of their radius or size. defaultContactOffset defines the size of this "small portion". For example, a sphere with a radius of 1 and a sphere with a radius of 2, if defaultContactOffset is set to 0.1, then when the distance between the two spheres is less than or equal to 0.3, Unity will start to calculate the collision between them.

By default, this value is 0.01, which is suitable for most games. You can modify this value as needed, but be aware that if this value is set too large, it may cause objects to collide in places that do not appear to be in contact; if this value is set too small, it may cause physical The simulation is unstable, especially when objects are moving or rotating at high speeds.

Here's an example of how to set this value:

// 设置默认接触偏移为0.02
Physics.defaultContactOffset = 0.02f;

Physics.defaultSolverIterations

Physics.defaultSolverIterations controls how many iterations the physics engine performs when solving constraints such as joints or collisions.

 
When objects interact with each other in Unity's physics environment, in order to correctly simulate these interactions, the physics engine must "solve" a series of mathematical constraints. This includes how things collide, how they bounce back, how they interact with each other in collisions, and more. Because these constraints can affect each other, the physics engine must solve them multiple iterations to ensure accurate results.

Setting the number of iterations is a trade-off:

Higher number of iterations: Can provide more accurate and stable physics simulation, but may increase computational complexity and CPU load.

Lower number of iterations: Might be faster, but can lead to inaccurate or unstable simulations, especially in complex physics interactions.

By default, the value of defaultSolverIterations is 6. This is a compromise value that the Unity team has found to provide reasonable accuracy and performance for most games.

If you encounter instability in the physics simulation in your game (for example, joints separating when under stress, or objects moving through other objects at high speeds), you may consider increasing this value. But keep in mind that increasing the number of iterations will increase the load on the CPU, so performance testing should be done when making such changes.

// 设置默认求解器迭代次数为8
Physics.defaultSolverIterations = 8;

Physics.defaultSolverVelocityIterations

Physics.defaultSolverVelocityIterations is a property that controls the number of iterations when the Unity physics engine solves velocity constraints. This value indicates the default number of iterations the solver should perform when solving velocity constraints such as how collisions between bodies affect their velocity.

 
Velocity constraints in physics simulations are mathematical equations that describe how objects change their velocity due to collisions. The solver's job is to find velocity values ​​that satisfy these constraints, which usually requires multiple iterations, as each iteration finds a slightly better solution to the constraints.

Likewise, setting the number of iterations is also a trade-off:

Higher number of iterations: will provide more accurate speed simulation results, but will increase computational complexity and CPU load.

Lower number of iterations: May be faster, but may result in less accurate speed simulation.

By default, defaultSolverVelocityIterations has a value of 1, which is the setting that provides reasonable velocity simulation accuracy and performance for most application scenarios.

If you find that the speed of objects in your game behaves erratically or inaccurately after a collision, consider increasing this value. But similar to what was stated earlier, increasing the number of iterations increases the computational burden, so performance testing should be done when making changes.

Physics.defaultSolverVelocityIterations = 3;

注意: When changing this value it is best to test in an actual game environment to confirm whether the change improves the accuracy of the speed simulation and ensure that it does not cause performance issues.


Physics.defaultMaxAngularSpeed

Physics.defaultMaxAngularSpeed ​​defines the maximum angular speed (in radians/second) an object can achieve in a physics simulation. When you change this value, it will affect all newly created rigidbodies (Rigidbodies), but will not affect existing rigidbodies.

 
Angular speed describes how fast an object rotates about its axis of rotation. If the angular velocity of an object is too high, it may lead to unrealistic or unstable results in the physics simulation. By setting a global upper limit on the maximum angular velocity, you can ensure the stability of the physics simulation to a certain extent.

Application scenario :
Improve the stability of physics simulation:
If you have objects in your game that rotate very quickly after a collision, this may cause problems in the simulation, such as objects passing through other objects instead of colliding with them correctly. By limiting the angular velocity, you can avoid this type of problem.

Specific game logic:
In some games, you may want to limit the rotation speed of objects. For example, in a flight sim, you probably don't want the plane to spin too fast through the air.

Example:
Suppose you create a ball that can be hit, and when it is hit, its angular velocity increases. But you don't want it to spin so fast that it doesn't look realistic.

void Start()
{
    
    
    Physics.defaultMaxAngularSpeed = 10.0f;
    Rigidbody rb = gameObject.AddComponent<Rigidbody>();
}
void OnCollisionEnter(Collision collision)
{
    
    
    // 当球被击打时增加角速度
    if (collision.gameObject.CompareTag("Bat"))
    {
    
    
        Rigidbody rb = GetComponent<Rigidbody>();
        rb.angularVelocity = new Vector3(0, 15, 0); // 试图设置一个很大的角速度
    }
}

In the above code, even if we try to set a very high angular velocity for the ball, due to the limitation of Physics.defaultMaxAngularSpeed, its angular velocitywill not exceed 10.0 rad/second


Physics.defaultMaxDepenetrationVelocity

Physics.defaultMaxDepenetrationVelocity controls the maximum velocity at which the physics engine attempts to separate two objects when they overlap. In a physical simulation, ideally, two objects should not penetrate or overlap each other, but in actual situations, objects may overlap due to the discrete nature of calculations or other reasons. When this happens, the physics engine attempts to correct the overlap by applying a "de-penetration" velocity, causing the two objects to move apart again.

 
This property defines the upper speed limit for solving this object overlapping problem. Higher values ​​will cause objects to separate faster, but may also cause the simulation to be unstable. Lower values ​​may cause objects to separate more slowly, but may appear more natural.

Application scenario:
Enhance physical stability: If there are a large number of objects in your game that often overlap, or there are large objects that often overlap, you can increase this value appropriately so that these objects can be separated faster.

Specific game logic: In some cases, you may want to make objects move apart more slowly after overlapping to achieve a specific effect or game logic.

Example:
Suppose you are developing a tower defense game. Enemies in the game may overlap in some situations. You want enemies to separate relatively quickly when they overlap to avoid situations that look unrealistic.

void Start()
{
    
    
    Physics.defaultMaxDepenetrationVelocity = 5.0f;
}

With the above code, we increase the upper limit on penetration speed, which will allow overlapping enemies to separate faster.


Physics.autoSimulation

Physics.autoSimulation controls whether Unity automatically performs physics simulation every frame. When this property is set to true (the default), physics simulation occurs automatically every frame, which means that all rigidbodies, colliders, and other physics-related components are simulated according to the physics rules.

 
If this property is set to false, physics simulation will not be performed automatically. This means that developers need to explicitlyCall the Physics.Simulate methodto perform physical simulation manually.

Application scenario:
Controlling the time of physical simulation: Sometimes, you may need to perform physical simulation at a specific moment or under specific conditions, rather than every frame. At this point, you can turn off automatic simulation and call Physics.Simulate manually.

Pause and Resume: For example, if you want to stop all physics activity in the game pause menu, you can set autoSimulation to false. When the player returns to the game from the pause menu, set it to true again.

Advanced Physics: In some cases, you may want to perform multiple physics simulations within a frame to achieve a specific effect or accuracy. This can be achieved by turning off automatic simulation and calling the simulation manually.

Example:
Suppose in the game, when the player presses the "P" key, the game will pause, and all physical activities should also be paused at this time.

void Update()
{
    
    
    if (Input.GetKeyDown(KeyCode.P))
    {
    
    
        if (Physics.autoSimulation)
            Physics.autoSimulation = false;
        else
            Physics.autoSimulation = true;
    }
}

The above code will toggle the state of Physics.autoSimulation based on player input, pausing or continuing the physics simulation.


Physics.autoSyncTransforms

Physics.autoSyncTransforms controls whether the physics system automatically synchronizes the rigid body's Transforms at the end of each frame.

When this property is set to true (default value), after each frame, the Transforms results of the physical simulation for the rigid body will automatically be applied to its corresponding Transforms component (Transform component). This means that if you look at the position or rotation of a rigidbody in Unity, it will reflect the latest results of the physics simulation.

In contrast, when Physics.autoSyncTransforms is set to false, the results of the physics simulation are not automatically updated to the Transform component. In order to apply the results of a physics simulation, you need to explicitly call Physics.SyncTransforms.

Application scenario:
Manual control of update time : In some cases, developers may want more fine-grained control over when to synchronize the results of a physics simulation. For example, when the results need to be synchronized after some specific operations or calculations.

Optimize performance : In some specific scenarios, you may not need to synchronize physics results every frame. For example, when simulating a large number of objects but only need to update their visible state occasionally.

Example:
Suppose you have a scene that contains a large number of rigid bodies, but you only want to synchronize their transformation results every 0.5 seconds, not every frame.

private float syncInterval = 0.5f;
private float timeSinceLastSync = 0f;

void Start()
{
    
    
    Physics.autoSyncTransforms = false;
}

void Update()
{
    
    
    timeSinceLastSync += Time.deltaTime;
    if (timeSinceLastSync >= syncInterval)
    {
    
    
        Physics.SyncTransforms();
        timeSinceLastSync = 0f;
    }
}

The above code first disables automatic synchronization. It then accumulates time in the Update method and calls Physics.SyncTransforms when the specified interval is reached to manually synchronize the results of the physics simulation.


Physics.defaultPhysicsScene

In Unity, a Physics Scene is a container for physical simulations. Each physics scene manages its own set of objects, colliders, and other physics properties, allowing developers to simulate physics effects independently without conflicting with other physics scenes.

 
Physics.defaultPhysicsScene returns the default physics scene in the currently loaded main scene. In most common application scenarios, this is the only physical scenario that exists. But when using the multiphysics feature, this property provides a way to reference the main physics scene without having to get it through other methods.

Many interesting effects can be achieved using the multi-physics scene function, such as:

  • Simulate two or more completely independent physical environments in parallel.
  • Creates an "off-screen" physics scene that is used only for calculations, the results of which do not directly reflect the visible state of the game.

Application scenario:
Query the status of the default physics scene: For example, you may want to know if there are any active rigid bodies in the default physics scene.

if (Physics.defaultPhysicsScene.IsActive())
{
    
    
    // //如果默认物理场景处于活动状态,执行操作
}

Perform a specific physics simulation in the default physics scene: For example, you want to perform a specific ray detection in the default physics scene.

RaycastHit hit;
if (Physics.defaultPhysicsScene.Raycast(origin, direction, out hit, maxDistance))
{
    
    
    // 处理光线投射结果
}

Summary: Physics.defaultPhysicsScene provides a reference to the default physics scene in the current main scene. This is useful in most cases, but especially when using the multiphysics feature, it becomes the key method of getting the master physics scene.


Physics.bounceThreshold

Physics.bounceThreshold is a velocity threshold used to determine when two colliding objects should bounce. This is a floating point value in meters per second.

In the Unity physics engine, when two objects collide, if their relative velocity exceeds this threshold, the objects will bounce. Relative velocity refers to the difference in velocity between two objects along the collision normal at the moment of collision.

By default, this threshold is 2 meters/second. This means that if the relative speed of two objects when they collide is greater than 2 meters/second, the objects will bounce back. If the relative speed of the two objects is less than this threshold, the objects will not bounce back, but the collision will be handled according to the physical material friction.

You can modify this threshold based on your game needs. For example, if you want objects in your game to bounce around more easily, you can set this threshold lower. On the other hand, if you want objects in your game to bounce harder, you can set this threshold higher.

Here's an example of how to set this value:

// 设置反弹阈值为1米/秒
Physics.bounceThreshold = 1.0f;

Physics.sleepThreshold

Physics.sleepThreshold defines the minimum energy required for an object to enter sleep, which is a floating point value.

 
In Unity's physics engine, objects may enter a so-called "sleep" state. An object "sleeps" when its energy (or its momentum) drops to a very low level and there is no other interaction for a period of time. This means that the physics engine will no longer calculate physics interactions for it until some external force or collision acts on it again, causing it to "wake up". This is an optimization that significantly reduces unnecessary physics calculations on inactive objects, thereby improving game performance.

By default, the sleepThreshold value is 0.005. This means that if an object's energy falls below this value, it will be marked as sleeping until it is subjected to enough external force to make it active again.

You can adjust this threshold based on your game's needs. For example, if you want the object to go to sleep more easily, you can increase the threshold; conversely, if you want the object to stay active for longer, you can lower the threshold.

Here's an example of how to set this value:

// 设置睡眠阈值为0.01
Physics.sleepThreshold = 0.01f;

注意: Adjusting this value may affect the physical behavior of the game, especially when objects start and stop interacting. Therefore, sufficient testing is required when changing this value to ensure that it will not have a negative impact on the gameplay of the game.


Physics.queriesHitBackfaces

Physics.queriesHitBackfaces This property determines whether physical raycasts, sphere casts, capsule casts, and box casts are allowed to detect the backface of a 3D model. The "back" of a 3D model refers to those parts that cannot be seen outside the model, that is, those faces whose normals face the inside of the model.

When queriesHitBackfaces is true: Physics queries are able to detect the back faces of the model.
When queriesHitBackfaces is false: Physics queries ignore the back faces of the model.

Application scenario:
Collision detection: Backface detection is often disabled when you want the physics query to interact only with the outside of the model. This is the default setting because in most cases you don't want, for example, a ray coming from inside the model to collide with the interior of the model.

Specific game logic: Allowing backside detection can be useful if your game has a scene or mechanic that requires inspection of the inside of a model (e.g., displaying an effect inside a transparent model).

Example:
Suppose you have a translucent sphere and want the player to fire a ray from the inside of the sphere and detect the internal collision point of the sphere. In this case, you need to set Physics.queriesHitBackfaces to true so that the ray can detect the inside of the sphere.

void Start() 
{
    
    
    Physics.queriesHitBackfaces = true;

    Ray ray = new Ray(sphereCenter, Vector3.forward);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit)) 
    {
    
    
        Debug.Log("击中球体内部点: " + hit.point);
    }
}

The above code snippet will output the collision point inside the sphere, but only if you have set queriesHitBackfaces to true.


Physics.queriesHitTriggers

Physics.queriesHitTriggers determines whether physics queries (such as ray casting or sphere overlap checks) should consider interacting with trigger colliders.

 
Trigger colliders (objects with a Collider set as a trigger) are different in Unity from regular colliders. They do not cause a physical response, that is, they do not push away or physically interact with the trigger object when the object enters the trigger. Instead, when an object enters a trigger, it sends a series of events, such as OnTriggerEnter, OnTriggerStay, and OnTriggerExit.

Physics.queriesHitTriggers is used to determine whether these trigger colliders should also be included when making physics queries. When its value is true, queries (such as Raycast or OverlapSphere) also detect trigger colliders. When its value is false, the query ignores trigger colliders. I won’t give an example here.


Physics.reuseCollisionCallbacks

Physics.reuseCollisionCallbacks determines whether previous collision callbacks are reused in consecutive physics simulation frames. This property can be useful in specific performance optimization scenarios.

 
When objects remain in collision in consecutive physics simulation frames (for example, one object is on top of another), Unity needs to decide whether to trigger a collision callback (such as OnCollisionStay) every frame.

If Physics.reuseCollisionCallbacks is set to true, Unity will not generate new callbacks for the same collision pair in successive collision states. This can reduce unnecessary callbacks and potentially improve performance, especially when there are a lot of ongoing collisions happening in the scene.

If set to false (the default), a new callback will be generated every frame for ongoing collisions.

Example:
Imagine a scene with many objects moving on the ground. Collisions will continue to occur between the ground and objects. In this case, triggering the OnCollisionStay callback every frame may not be necessary and may waste performance.

// 禁用重复使用碰撞回调
Physics.reuseCollisionCallbacks = false;

By setting Physics.reuseCollisionCallbacks to true, you tell Unity that in successive simulation frames, as long as the collision pair remains the same, reuse the callback from the previous frame instead of generating a new callback for each frame.

注意事项:
Using this property may affect game logic as some callbacks may not fire on consecutive collisions. Make sure your game logic doesn't rely on receiving these callbacks every frame.


Physics.clothGravity

Physics.clothGravity represents the global gravity vector applied during cloth simulation. Cloth simulation is used in Unity to create soft objects such as flags, clothing or curtains that can interact with the environment or other objects.

 
Normally, cloth objects are affected by Physics.gravity. But in some cases, you may want the cloth object to be affected by gravity differently than other physics objects in the scene. Physics.clothGravity allows you to define a specific gravity vector for cloth, which may be useful when creating specific effects or optimizations.

Example:
Suppose you are making a game in which the player enters a space station, and inside the space station, due to some technology, gravity is partially offset. But you still want the cloth on the player's spacesuit to be affected by normal gravity like it is on Earth.

// 设置全局重力为宇宙空间站的重力
Physics.gravity = new Vector3(0, -4.9f, 0); // 假设宇宙空间站内部的重力是地球的一半

// 设置布料的重力为正常的地球重力
Physics.clothGravity = new Vector3(0, -9.8f, 0);

注意事项:
Setting Physics.clothGravity does not affect non-cloth objects. It only works for cloth simulation.
If you want the cloth to be affected by the same gravity as other objects, make sure Physics.clothGravity and Physics.gravity have the same value.


Physics.interCollisionDistance

Physics.interCollisionDistance is used to define the intercollision distance between cloth particles in Unity's cloth simulation. Cloth simulation in Unity is particle-based, where each particle represents a part of the cloth, and the interactions and connections between particles determine the behavior and shape of the cloth.

 
The collision distance defines the minimum distance between two cloth particles. When two particles are close enough that the distance between them is less than this set collision distance, they will be pushed away to ensure that they remain This is the minimum distance.

This setting is useful for avoiding banding and collision anomalies in cloth. For example, consider a fluttering curtain or flag, you don't want it to fold onto its own back or pass through itself. Adjusting this value can help ensure that the cloth remains physically correct during simulation.

Example:
Let's say you have a cloth-simulated flag where when the wind is too strong, some parts of the flag will pierce through other parts. To avoid this, you can increase the collision distance:

// 增加布料的互碰距离
Physics.interCollisionDistance = 0.05f;

This will ensure that cloth particles are at least 0.05 units apart from each other.

注意事项:
Adjusting this value may have an impact on the performance of the cloth. Values ​​that are too high may result in unrealistic simulations or unnecessary calculations.
This setting is best fine-tuned after observing the cloth's behavior at runtime to ensure ideal results.


Physics.interCollisionStiffness

The Physics.interCollisionStiffness property is used to define the collision stiffness between cloth particles. The stiffness of a cloth can be thought of as the strength that prevents overlap or penetration between particles.

 
The recommended value range for this attribute is 0 to 1, where 0 represents no stiffness and 1 represents greater stiffness. Higher values ​​will cause cloth to collide more strongly between particles, while lower values ​​may result in more overlap between cloth particles.

Example:
Suppose you are simulating a stiffer cloth, such as canvas, and you may want the particles to have a high collision stiffness with each other so that the cloth behaves more stably and with less overlap.

// 设置布料的互碰刚度为较大值
Physics.interCollisionStiffness = 1.0f;

But if you are simulating a soft, easily compressible cloth, such as cotton or silk, you may want the particles to collide with each other with a lower stiffness:

// 设置布料的互碰刚度为较低值
Physics.interCollisionStiffness = 0.3f;

注意事项:
Setting interCollisionStiffness too high may cause unrealistic effects or instability of the simulation, especially around edges or tight parts of the cloth.
If you encounter any problems when using interCollisionStiffness, such as unstable simulation or unsatisfactory results, try adjusting this value in conjunction with the Physics.interCollisionDistance property for best results.


Physics.interCollisionSettingsToggle

Physics.interCollisionSettingsToggle is a Boolean property used to enable or disable the collision settings between cloth particles. When you use Unity's cloth simulation, this property determines whether the settings for Physics.interCollisionDistance and Physics.interCollisionStiffness are applied.

 
When interCollisionSettingsToggle is set to true, collision between cloth particles will be enabled, and the values ​​of interCollisionDistance and interCollisionStiffness will affect the behavior of the cloth.

In contrast, if interCollisionSettingsToggle is set to false, collisions between particles of the cloth will not be considered, regardless of the values ​​of interCollisionDistance and interCollisionStiffness.

// 启用布料的互碰设置
Physics.interCollisionSettingsToggle = true;

注意事项:
Enabling collisions between cloth particles can increase the realism of the simulation, but may reduce performance. Consider the complexity of your simulation and required performance before enabling this setting.


2. Ray casting and shape detection:

Physics.Linecast: Casts a line between two points, returning True if the line collides with the collider.
Physics.Raycast: Emits a ray from the origin of the ray in the direction of the ray.
Physics.RaycastAll:will return a RaycastHit array consisting of all colliders in the scene that interact with the ray.
Physics.RaycastNonAlloc:Similar to RaycastAll, but does not allocate a new array for the result. You need to provide a RaycastHit array, and the method will fill the results into this array.
Physics.CapsuleCast: Casts a capsule and returns a boolean value indicating whether the capsule intersects any collider.
Physics.CapsuleCastAll :Returns a RaycastHit array consisting of all colliders in the scene that interact with the capsule.
Physics.CapsuleCastNonAlloc: Similar to the CapsuleCastAll method, but requires you to provide a RaycastHit array to populate with the results.
Physics.BoxCast: Casts a box and returns a boolean indicating whether the box intersects any collider.
Physics.BoxCastAll :Returns a RaycastHit array of all colliders interacting with this box.
Physics.BoxCastNonAlloc: Similar to the BoxCastAll method, but needs to provide a RaycastHit array to populate the results.
Physics.SphereCast: Projects a sphere and returns a boolean indicating whether the sphere intersects any collider.
Physics.SphereCastAll: Returns a RaycastHit array consisting of all colliders that intersect this ball.
Physics.SphereCastNonAlloc: Similar to the SphereCastAll method, but needs to provide a RaycastHit array to populate the results.

NonAllocversion methods are particularly useful in performance-sensitive scenarios because theyAvoid unnecessary memory allocation


Physics.Linecast

Physics.Linecast is an important method of Unity's physics system, used to detect whether there are any colliders on the straight path between two points. This detection is useful in many situations, such as determining whether a character is in the player's line of sight, the activity of a trigger, and other situations where straight path collision detection is required.

(All definitions below are explained using the overload that passes the most parameters)

definition

 public static bool Linecast(Vector3 start, Vector3 end, out RaycastHit hitInfo, [UnityEngine.Internal.DefaultValue("DefaultRaycastLayers")] int layerMask, [UnityEngine.Internal.DefaultValue("QueryTriggerInteraction.UseGlobal")] QueryTriggerInteraction queryTriggerInteraction);

parameter:

  • start: starting position of line projection
  • end: the end position of the line projection
  • hitInfo: If the line cast intersects any collider, this parameter will contain detailed information about the intersection (such as intersection location, intersection's collider, etc.)
  • layerMask: The layer used to filter objects that intersect the line cast. This makes it possible to specify which layers should be taken into account and which layers should be ignored
  • queryTriggerInteraction: Specifies how to handle trigger colliders. Can be UseGlobal, Ignore or Collide

Return value:
true if the line segment intersects the collider, false otherwise.

Example:

public class LinecastExample : MonoBehaviour
{
    
    
    public Transform pointA;  //A点
    public Transform pointB;  //B点

    void Update()
    {
    
    
        RaycastHit hit;
        if (Physics.Linecast(pointA.position, pointB.position, out hit))
        {
    
    
            Debug.Log("击中障碍物!");
            Debug.DrawLine(pointA.position, hit.point, Color.red); 
        }
        else
        {
    
       
            Debug.Log("没有击中障碍物!");
            Debug.DrawLine(pointA.position, pointB.position, Color.green);  
        }
    }
}

In this example, we perform Linecast detection between pointA and pointB every frame. If the line segment intersects any object, we draw a red line in the scene view to the intersection point; otherwise, we draw a green line.
A common use for this method is to detect if there are obstacles between units in a strategy game, or to detect if a target is visible to the player in a first-person shooter.


Physics.Raycast

Physics.Raycast emits a ray from a specified position and direction and returns whether the ray intersects any collider. This is widely used in many game scenarios, such as bullet trajectories in shooting games, character sight detection, etc.

definition:

public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layerMask, QueryTriggerInteraction queryTriggerInteraction);

parameter:

  • origin: The starting point of the ray.
  • direction: The direction of the ray.
  • hit: This parameter will receive information about the hit if the ray intersects any collider.
  • maxDistance: The maximum length of the ray. Defaults to infinity, meaning the ray will continue until it hits an object or goes to infinity.
  • layerMask: Can be used to filter which layers should be considered. For example, you might want to test only objects in certain layers.
  • queryTriggerInteraction: defines how to handle triggers. Possible values ​​are UseGlobal, Ignore, or Collide.

return value:

Returns true if the ray intersects the collider; false otherwise.

Example:

using UnityEngine;

public class RaycastExample : MonoBehaviour
{
    
    
    public float rayLength = 10f; //最大长度
    public LayerMask hitLayers;   //层级

    void Update()
    {
    
    
        RaycastHit hit;
        Vector3 rayDirection = transform.TransformDirection(Vector3.forward); //游戏对象的前进方向
        
        if (Physics.Raycast(transform.position, rayDirection, out hit, rayLength, hitLayers))
        {
    
    
            Debug.Log("击中障碍物: " + hit.collider.name);
            Debug.DrawRay(transform.position, rayDirection * hit.distance, Color.red); 
        }
        else
        {
    
    
            Debug.DrawRay(transform.position, rayDirection * rayLength, Color.green);
        }
    }
}

In this example, each frame emits a ray from the object's current position in the direction in front of it. If the ray hits any object in the specified layer, the name of the hit object is printed in the console and a red line is drawn in the scene view to the hit point; otherwise, a green line is drawn.

By properly using Physics.Raycast, developers can implement many complex interactions and game logic, such as detecting whether an object is occluded, calculating trajectory, triggering interactive events, etc.


Physics.CapsuleCast

Physics.CapsuleCast is used to simulate emitting a capsule shape from a specified position and detect whether it interacts with any collider in the scene. This kind of capsule projection is very useful in various game scenarios, especially when you need to detect whether a larger object will collide with other objects when it moves.

definition:

 public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, [UnityEngine.Internal.DefaultValue("Mathf.Infinity")] float maxDistance, [UnityEngine.Internal.DefaultValue("DefaultRaycastLayers")] int layerMask, [UnityEngine.Internal.DefaultValue("QueryTriggerInteraction.UseGlobal")] QueryTriggerInteraction queryTriggerInteraction);

parameter:

  • point1 and point2: define the two endpoints of the capsule. The line segment part of the capsule is obtained by connecting these two points.
  • radius: The radius of the capsule.
  • direction: The direction in which the capsule is projected.
  • hitInfo: If the capsule interacts with any collider, this parameter will receive detailed information about the interaction point.
  • maxDistance: The maximum distance projected by the capsule.
  • layerMask: used to filter the layers that should be considered.
  • queryTriggerInteraction: defines how to handle triggers. Possible values ​​are UseGlobal, Ignore, or Collide.

return value:

Returns true if the capsule interacts with any collider in the scene; false otherwise.

Example:

public class CapsuleCastExample : MonoBehaviour
{
    
    
    public float capsuleHeight = 2f;   //胶囊高度
    public float capsuleRadius = 0.5f; //胶囊半径
    public float castDistance = 10f;  //投射最大距离
    public LayerMask hitLayers;       //层级

    void Update()
    {
    
    
        Vector3 top = transform.position + Vector3.up * (capsuleHeight / 2);
        Vector3 bottom = transform.position - Vector3.up * (capsuleHeight / 2);
        Vector3 direction = transform.TransformDirection(Vector3.forward);

        RaycastHit hit;
        if (Physics.CapsuleCast(top, bottom, capsuleRadius, direction, out hit, castDistance, hitLayers))
        {
    
    
            Debug.Log("Hit: " + hit.collider.name);
        }
    }
}

In this example, the capsule is projected from the game object's position, in the direction in front of it. If the capsule interacts with any object in the specified layer, the name of the interacting object will be printed in the console.


Physics.BoxCast

Physics.BoxCast is used to simulate emitting a box from a specified location and detect whether it interacts with any collider in the scene. This kind of box projection can be used in various game scenarios, such as detecting whether a rectangular object will collide with other objects when it moves.

definition:

public static bool BoxCast(Vector3 center, Vector3 halfExtents, Vector3 direction, out RaycastHit hitInfo, [UnityEngine.Internal.DefaultValue("Quaternion.identity")] Quaternion orientation, [UnityEngine.Internal.DefaultValue("Mathf.Infinity")] float maxDistance, [UnityEngine.Internal.DefaultValue("DefaultRaycastLayers")] int layerMask, [UnityEngine.Internal.DefaultValue("QueryTriggerInteraction.UseGlobal")] QueryTriggerInteraction queryTriggerInteraction);

parameter:

  • center: The center point of the projection box.
  • halfExtents: Vector3 representing half the size of the box. Includes length, width and height.
  • direction: The direction in which the box is projected.
  • hitInfo: If the box interacts with any collider, this parameter will receive detailed information about the interaction point.
  • orientation: The direction of the box. Use Quaternion to define.
  • maxDistance: The maximum distance of projection.
  • layerMask: used to filter which layers should be considered.
  • queryTriggerInteraction: defines how to handle triggers. Possible values ​​are UseGlobal, Ignore, or Collide.

return value:

Returns true if the box interacts with any collider in the scene; false otherwise.

Example:

public class BoxCastExample : MonoBehaviour
{
    
    
    public Vector3 boxSize = new Vector3(1f, 1f, 1f);
    public float castDistance = 5f;
    public LayerMask hitLayers;

    void Update()
    {
    
    
        Vector3 direction = transform.TransformDirection(Vector3.forward);
        RaycastHit hit;
        if (Physics.BoxCast(transform.position, boxSize / 2, direction, out hit, transform.rotation, castDistance, hitLayers))
        {
    
    
            Debug.Log("Hit: " + hit.collider.name);
        }
    }
}

In this example, the box projection starts at the game object's position and goes in the direction in front of it. If the box interacts with any object in the specified layer, the name of the interacting object will be printed to the console.


Physics.SphereCast

Physics.SphereCast is used to simulate a virtual sphere being projected in a specified direction and detect whether the sphere interacts with any collider in the scene. This kind of spherical projection is often used for various purposes in game development, such as detecting obstacles ahead, simulating sonar, etc.

definition:

public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

parameter:

  • origin: The starting point of the projected sphere.
  • radius: The radius of the sphere.
  • direction: The direction in which the sphere is projected.
  • hitInfo: If the sphere interacts with any collider, this parameter will receive detailed information about the interaction point.
  • maxDistance: The maximum distance of projection.
  • layerMask: used to filter which layers should be considered.
  • queryTriggerInteraction: defines how to handle triggers. Possible values ​​are UseGlobal, Ignore, or Collide.

Return value:
true if the sphere interacts with any collider in the scene; false otherwise.

Example:

public class SphereCastExample : MonoBehaviour
{
    
    
    public float sphereRadius = 0.5f;   // 半径
    public float castDistance = 5f;     //最大距离
    public LayerMask hitLayers;

    void Update()
    {
    
    
        Vector3 direction = transform.TransformDirection(Vector3.forward);
        RaycastHit hit;
        if (Physics.SphereCast(transform.position, sphereRadius, direction, out hit, castDistance, hitLayers))
        {
    
    
            Debug.Log("Hit: " + hit.collider.name);
        }
    }
}

In this example, the sphere projection starts from the game object's position and proceeds in the direction in front of it. If the sphere interacts with any object in the specified layer, the name of the interacting object will be printed in the console.


Kind tips: Using this Physics class, especially the part involving physical simulation, requires an understanding of the basic principles of physics. Without an adequate understanding of physics, you may encounter unexpected results. In general, try to avoid creating unrealistic physical conditions (like zero friction, infinite forces, etc.).

In order to make the article not too lengthy, in the next chapter, I will explain the remaining properties and methods of the Physics class.

Guess you like

Origin blog.csdn.net/qq_33795300/article/details/131940834