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_name | type | description |
|---|---|---|
| ray | Ray | The ray to be cast. |
| radius | number | The radius of the sphere. |
| maxDistance | number | The maximum distance the sphere can be cast. |
| mask | number | The layers to perform collision detection on (bitwise operation). |
| cast_trigger | QueryTriggerInteraction? | Determines whether the ray should collide with triggers. |
return
| type | description |
|---|---|
RaycastHit|undefined | True 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");
}
}
}