Quick question about method

   private bool InAttackRangeOfPlayer()
        {
            float DistanceToPlayer = Vector3.Distance(player.transform.position, transform.position);
            return DistanceToPlayer < chaseDistance;
        }

How come it’s DistanceToPlayer < chaseDistance? Can’t we just return DistanceToPlayer? It doesn’t calculate value for if it’s lower?

What do you mean by this?

The function Vector3.Distance returns a float value. The value is always positive and it never will be less than 0 regardless of where the vectors are, so there’s no such thing as a “lower” value in this particular case unless you are thinking of lower than the chaseDistance, but that’s impossible for the Distance function to know, you have to make the comparison manually.

Read the documentation for further information.

If your math is a little rusty, I highly suggest taking the Math course.

Maybe I didn’t phrase it properly, it just returns a value?

Don’t get me started on math, I firmly believe math and coding are not deeply related, and the more I learn to code, the more I am convinced that I am right and school is wrong. School has been wrong about a lot of things.

I can explain with more detail but I need you to explain to me where the confusion is coming from.

The function Vector3.Distance has a return type of float, that alone cannot determine if the player is close enough to be attacked.

Here’s the function declaration, you can see it returns a float.

public static float Distance(Vector3 a, Vector3 b);

return DistanceToPlayer < chaseDistance;

What exactly does this line return?

It returns a bool.

If the DistanceToPlayer is less than chaseDistance it will return true, if it is bigger, it will return false.

So since it’s declared as a bool, it returns a bool true or false value?

float DistanceToPlayer = Vector3.Distance(player.transform.position, transform.position);

Then what is this line?

Remember that the function that this return line is in is a bool function. That means that the function must return either true or false. Because of this, we can return any type of expression that we could also use in an if statement.

Since DistanceToPlayer < chaseDistance is something that is either true or false, this can be returned by the method.

This could also have been written like this:

if(DistanceToPlayer < chaseDistance)
{
    return true;
} else
{
    return false;
}
2 Likes

Quote of the day. lol

2 Likes

Continuing from another thread. This is an example of why I don’t think you’re understanding all this Unity jazz.

Asking questions like this.

It’s not exactly complicated. It’s a basic expression. The variable name even describes to you what’s happening.

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms