Detect obstacle using Raycast

832 views Asked by At

The logic is , if the Car finds any obstacle using Raycast a function will rotate the angle of a wheel so that car goes left or right. But it seem the car stuck in a certain place where Raycast finds a obstacle , the function 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();
}
1

There are 1 answers

0
maraaaaaaaa On BEST ANSWER

Do not use '5' when trying to pass reference to layer '5', you are actually passing reference to multiple layers (3 and 1), instead you have to put int layerMask = 1<<5; then pass in layerMask instead of 5. Use int layerMask = 1<<5; then layerMask = ~layerMask; for everything except layer 5.