if Statement Help Increment Value

I have this code below that basically what I want to do is when my players y distance from the floor increases I want my camera to zoom out. The camera script works as well as the code below. The only problem is when i have more than one distance value like below it will skip the first distance value and wait until i reach the second one. Are my if statements incorrect?

 function Update() 
    { //Camera Zoom out when player reaches certain height
        var distance = Vector3.Distance(floor.position, Target.position);
        if (distance > 19.3f)
        {
        	cameraDistance = 22
        }
        if (distance > 22)
        {
        	cameraDistance = 24;
        }
        else 
        {
        	cameraDistance = 20;
        }
    }

2 Answers

2

Once the distance is greater than 19.3 the if statements will stop because it has reached a true statement. Your if statements should look something like this:

if (distance > 19.3 && distance <= 22)
{
   cameraDistance = 22;
}
else if (distance > 22)
{
   cameraDistance = 24;
}
else
{
   cameraDistance = 20;
}

You should convert the second “if” to an “else if” because in your script if you are between 19.3 and 22 it also executes the “else” sothat cameraDistance will never be 22.

function Update() 
{ //Camera Zoom out when player reaches certain height
    var distance = Vector3.Distance(floor.position, Target.position);
    if (distance > 19.3f)
    {
        cameraDistance = 22
    }
    else if (distance > 22)
    {
        cameraDistance = 24;
    }
    else 
    {
        cameraDistance = 20;
    }
}