📜  unity spherecast - C# (1)

📅  最后修改于: 2023-12-03 15:05:44.932000             🧑  作者: Mango

Unity Spherecast - C#

Unity Spherecast is a physics function in Unity that casts a sphere in a specific direction and returns information about any collision that occurs. It can be used to detect objects with colliders in a certain direction and distance, and can also be used to determine the normal of the surface that the sphere hits.

Syntax
public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
Parameters
  • origin: the center of the spherecast in world coordinates.
  • radius: the radius of the sphere.
  • direction: the direction in which to cast the sphere.
  • hitInfo: the struct to store information about the collision.
  • maxDistance: the maximum distance to check for collisions.
  • layerMask: a layer mask that is used to selectively ignore colliders.
  • queryTriggerInteraction: specifies whether to detect triggers and/or colliders.
Return Value
  • If the sphere intersects with any colliders, the function returns true.
  • If the sphere does not intersect with any colliders, the function returns false.
Example
using UnityEngine;

public class SphereCastExample : MonoBehaviour
{
    public float radius = 0.5f;
    public float distance = 10f;
    public LayerMask mask;
    private RaycastHit hit;

    void Update()
    {
        if (Physics.SphereCast(transform.position, radius, transform.forward, out hit, distance, mask))
        {
            Debug.Log("Object hit: " + hit.transform.name);
        }
    }
}

In this example, a sphere is cast from the current position in the forward direction for a maximum distance of 10 units. If the sphere intersects with any colliders in the specified layer mask, the name of the object is logged to the console.

Notes
  • Spherecast is more expensive than a standard raycast because it checks all colliders in the sphere's path.
  • Spherecast can be used to check for collisions with both static and dynamic objects.
  • The radius of the sphere must be greater than zero.