[SOLVED] Distance and direction between two entities

Hi,

I have a game where policemen need to find the player.

I have successfully calculated the distance between the two instances :

const policeManPosition = this.policeEntity.getPosition();
const playerPosition = this.playerEntity.getPosition();

const distance = Math.hypot(
    playerPosition.x - policeManPosition.x,
    playerPosition.z - policeManPosition.z
);

but i need to be sure, the player is in the front of the policeman, and not behind it ?

Any coding idea ?

Thanks

Hi @vogloblinsky!

Why you don’t use the method below to determine the distance?

var distance = this.policeEntity.getPosition().distance(this.playerEntity.getPosition());

To see if the player is in front of the police I would check my topic below.

https://forum.playcanvas.com/t/solved-get-angle-between-two-entities/

I hope this helps you on your way.

Are you familiar with the dot product?

If you take the vector from the policeman to the player positions, and dot it with the forward vector of the policeman.

If the result is more than 0, it is in front of the policeman. If less than 0, it is behind.

Thanks @Albertos, your link and this post ([SOLVED] Get angle between two entities) helps a lot.

1 Like

Also, don’t forget to take advantage of the built-in APIs PlayCanvas has to help you with these kinds of computations. They make your life so much easier, unless you’re trying to learn the math for yourself. For example: Math, Quat, BoundingBox, Ray, Vec3 (as @Albertos referenced with .distance())