# Is it possible to project a vector on another vector to calculate the distance without raycasting

I have the following game scenario:

Player is P and there are 2 enemies E1 and E2

I want to calculate the distance between the ennemies and the player base which is anywhere in that green line, and not the actual player character.

Currently if if I try to calculate the distance between enemies and players I get something like this:

But what i really want is this:

Now i could've just raycast from the enemies forward to hit the "base collider" but this is what am trying to avoid.

My question is:

If the green line is always going to be a "longer version" of the player Transform.Right vector, is there a way to project the Enemies Transform.forward vector, and now where it intersects with the player vector like this:

If you're curious about the reason behind this, then this image should clarify it:

Basically I need to create a "high threat zone" in front of the player, and based on the enemy distance to the "player base", i will give different feedback.

Thank you!

• You need to define which line your base is on, not at a certain point. But if this line is sure to be on the x-axis, you can simply use the difference of Y. Apr 16, 2022 at 15:49
• that's the problem, the player is not always facing the same direction, sometimes the Y difference works perfectly fine, sometimes not. Apr 16, 2022 at 17:07

Solved it with Vector3.Project()

So basically what i needed to do is to project the enemies normal (in this case the forward) on the distance vector.

And then use the projection result's magnitude to determine the distance.

1. Defines the face direction(vfront) of the base.
2. v1 = e1 - p; v2= e2 - p
3. Obtain the dot product of v1 and v2 to vfront. If the result < 0, the point is behind the "line".

Dot Product

• thanks, but the goal is not to JUST know if the point has crossed the line or not, but to also know how far is it from the the line (perpendicularly), I already solved the problem though, check out my answer in this thread if you're curious. Apr 16, 2022 at 20:55