Vector3.Distance Need Help

Hi.

I want when distance between player and enemy is equal or less than 0.3f, then print(“OK”). but when distance is <= 0.3f, don’t print anything.
anyone know why do this happen?

this my code:

void Update ()
{
    //Get Player and Enemies Position
    Vector3 PlayerDistance = transform.position;
    Vector3 EnemyDistance = GameObject.FindWithTag("Enemy").transform.position;

    //Get Distance Between Player and Enemies
    float distance = Vector3.Distance(PlayerDistance, EnemyDistance);
    if (distance <= 0.3)
    {
        print("OK");
    }
}

i suggest you to declare the enemy in the start, because the Find method is very slow

Try this:

    Vector3 distance = PlayerDistance.transform.position - EnemyDistance.transform.position;

        if (distance.magnitude <= 0.3)

        {

            print("OK");

        }
1 Like

OK,Thanks Mino92.

magnitude is equal with:

distance = Mathf.Sqrt(Mathf.Pow((EnemyPos.x - PlayerPos.x),2) + Mathf.Pow((EnemyPos.y - PlayerPos.y),2));

Right?

Dunno… i have a dubt, have you try to invert the enemy with the player?

float distance = Vector3.Distance(EnemyDistance, PlayerDistance);

Not exactly.
The math is Squareroot of (X^2 + Y^2 + Z^2)

What you have are only x and y, so you will have the magnitude of a Vector2.
Your math will only be correct if the Z value of the enemy and the player are equal (E.G. 0).

To speed up the calculation I suggest using sqrmagnitude. Should look sth like this:

Transform enemy;
public float distance = 0.3f;
void Awake()
{
  // distances ^ 2 to counter the squared distance by sqrMagnitude
  distance = Math.Pow(distance, 2);
  enemy = GameObject.Find("enemy").transform;
}

void Update() {
  float diff = (enemy.position - transform.position).sqrMagnitude;
if(diff <= this.distance){
  // distance is less than 0.3f.
}
}

This will execute much faster, because it does not have to calulate the square root of the Vector3.

Edit: Magnitude will calculate the same result for enemy - player and player - enemy. It’s value is absolute because the values are multiplied by themselves.

I think doing it from Csharp code manually is slower because the magnitude (and sqrMagnitude) methods are native and should (in theory) be faster. I didn’t test that though.

1 Like

You guys are performance-optimizing his code before his code even works.

@behdadsoft , Try outputting the distance with Debug.Log("Distance is "+distance); to see what actual value of the distance is. If that number is not what you expect, then try outputting the objects’ positions the same way and see which one is coming back wrong.

You can also use Debug.DrawLine(PlayerDistance, EnemyDistance); to visualize the two points in the Scene View, which may also help debugging.

3 Likes

Thanks TheFudge, it’s work correctly when I use sqrMagnitude.

but really I confused. why (a - b).magnitude won’t work?