Skip to content

格式

typescript
Physics.CapsuleCast(p0, p1, radius, direction, maxDistance, mask, cast_trigger)

所属类: Physics

描述

进行胶囊体射线检测。

该方法会在场景中发射一个胶囊体形状的射线,检测胶囊体与物体是否相交,并存储与第一个物体的相交信息。

参数

参数名类型描述
p0Vector3胶囊体的一个端点
p1Vector3胶囊体的另一个端点
radiusnumber胶囊体的半径
directionVector3胶囊体投射的方向
maxDistancenumber胶囊体投射的最大距离
masknumber进行碰撞检测的层级(位运算)
cast_triggerQueryTriggerInteraction?射线是否与触发器进行碰撞检测

返回值

类型描述
RaycastHit|undefined射线是否与物体相交

代码示例

typeScript
class New_TypeScript
    extends Component {

        private hit:RaycastHit;

    OnStart(): void {
        
        //在场景中创建一个立方体
        let cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        //为该立方体添加一个BoxCollider组件
        cube.AddComponent<BoxCollider>(BoxCollider);
        //将该立方体的位置设置为(0,2,0)
        cube.transform.position = new Vector3(0,2,0); 

    }

    OnUpdate(): void {

        let p0 = new Vector3(0,1,0);
        let p1 = new Vector3(0,-1,0);
        let dire = new Vector3(0,1,0);
        //进行胶囊体体射线检测
        this.hit = Physics.CapsuleCast(p0,p1,0.5,dire,10000,1);
        if (this.hit) {
            Debug.Log(this.hit.point);
        } else {
            Debug.Log("未击中物体");
        }
    }

}