Skip to content

format

typescript
Physics.SphereCast(ray, radius, maxDistance, mask, cast_trigger)

class: Physics

description

Performs a spherecast in the scene to detect intersections between a sphere and objects. Stores information about the first object intersected.

parameter

param_nametypedescription
rayRayThe ray to be cast.
radiusnumberThe radius of the sphere.
maxDistancenumberThe maximum distance the sphere can be cast.
masknumberThe layers to perform collision detection on (bitwise operation).
cast_triggerQueryTriggerInteraction?Determines whether the ray should collide with triggers.

return

typedescription
RaycastHit|undefinedTrue if the ray intersects with an object.

code example

typeScript
class New_TypeScript
    extends Component {

        private hit:RaycastHit;
        private ray:Ray;

    OnStart(): void {
        
        // Create a cube in the scene
        let cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        // Add a BoxCollider component to the cube
        cube.AddComponent<BoxCollider>(BoxCollider);
        // Set the position of the cube to (0,2,0)
        cube.transform.position = new Vector3(0,2,0); 
        // Create a ray from (0,0,0) towards the positive Y axis
        this.ray = new Ray(new Vector3(0,0,0),new Vector3(0,1,0));       

    }

    OnUpdate(): void {

        // Perform a spherecast
        this.hit = Physics.SphereCast(this.ray,1,10000,1);
        if (this.hit) {
            Debug.Log(this.hit.point);
        } else {
            Debug.Log("No object hit");
        }
    }

}