使用 Raycast 检测障碍物

Detect obstacle using Raycast

逻辑是,如果汽车使用 Raycast 发现任何障碍物,一个函数将旋转车轮的角度,以便汽车向左或向右行驶。但似乎汽车卡在了 Raycast 发现障碍物的某个地方,函数 WillColllide() returns true,false,true,false sequentially

var willColliedVar:boolean;

function WillColllide():boolean{
    var hit:RaycastHit;
    if(Physics.Raycast(distenceDitactorFl.transform.position,distenceDitactorFl.transform.forward,hit) && hit.collider.tag =="wall") {
        var hitDistence = Mathf.RoundToInt(hit.distance);
        if(hitDistence >=4 && hitDistence<=5){      
            return true;    
        }
    }
    if (Physics.Raycast(distenceDitactorFr.transform.position,distenceDitactorFr.transform.forward,hit, 5) && hit.collider.tag =="wall") {
        var hitDistence2 = Mathf.RoundToInt(hit.distance);
        if(hitDistence2 >=4 && hitDistence2<=5){
            return true;    
        }
    }
    return false;
}
function MoveForward():void{
    wheelRr.motorTorque = maxTorque * 0.25;
    wheelRl.motorTorque = maxTorque *0.25;
}
function TurnStraight():void{
    wheelFl.steerAngle = 0;
    wheelFr.steerAngle = 0;
}

function TurnLeft(steerAngle:int):void{
    wheelFl.steerAngle = -steerAngle;
    wheelFr.steerAngle = -steerAngle;
}
function Update () {
    MoveForward();
    if(willColliedVar){
        TurnRight(steerRotationLow);
    }else{
        TurnStraight();
    }
}
function LateUpdate () {

}
function FixedUpdate(){
    willColliedVar = WillColllide();
}

尝试传递对“5”层的引用时不要使用“5”,您实际上是在传递对多个层(3 和 1)的引用,而必须先输入 int layerMask = 1<<5; 然后传入 layerMask 而不是 5。使用 int layerMask = 1<<5; 然后 layerMask = ~layerMask; 用于所有 除了 层 5.