- Home /
Getting the distance in a known direction
Hi, I would like to calculate the distance between my Player and a Wall using a known direction (-Transform.left in my example).
Using Vector2.Distance doesn't work, as it only gives the absolute distance. I could use a line of raycasts to try to hit the Player and get the distance that way but that wouldn't be really accurate enough.
I hope someone can help me thx.
Answer by JonPQ · Aug 10, 2019 at 12:01 AM
Distance from point to a line... Define your wall, by any point on the wall, and a vector along its edge. 'ray'
float distance = Vector3.Cross(ray.direction, myPoint - ray.originPoint).magnitude;
Doesn't the ray.direction has to be normalized? otherwise this might not work.
This worked after some time of trying it out. But I have another question. Is it possible to get information about if the myPoint is behind the wall, so the Distance should be negative.
So that this points in the right direction:
Oh ok I used the z of the resulting vector ins$$anonymous$$d of the magnitude.
red up on dot product and vector product (cross product). With these two things you can do many powerful vector and point checks. for example.. take 3 points... 2 are for your wall, the 3rd is for another point on left or right of the wall. if you zero out the Y height. and turn your 3 points into 2 vectors... one for wall, one for wall point to your other point. Dot product will give you angle delta, you can use it fro ai$$anonymous$$g, or field of view checks. and cross product sign of result's Y will give you info about whether your point is on left or right of the wall. (as you discovered)
Answer by sacredgeometry · Aug 09, 2019 at 10:21 PM
Trigonometry
sin(theta) = opposite / hypotenuse
or
hypotenuse * sin(theta) = opposite
Solve for the opposite. (If thats wrong ... its been a long time since I did trig in school but its on the internet so you can double check)
I knew it would be something with trigonometry.
So you mean i could calculate the distance i need like this?:
![Showing the trigonometry in the example]from the question][1]
I really should know this kind of stuff but thx a lot!
[1]: /storage/temp/144366-screenshot-20190810-012555-photos.jpg
I was thinking like this:
That is supposed to be a right angle but the spline tool doesnt like straight corners.
But either way works. You just have to work with either the surface normal or tangent.