# Distance to object using trigonometry/vectors (help needed)

Hello everyone,

I’m currently trying to create a kind of camera/texture projection system. It’ll require to find/calculate the distance from a camera to an object/actor - in a specific way - and this is where my trigonometry and vector math can’t keep up.

I’d like to get the distance value of either A or B in the following image. Anyone got an idea of how to do this in BP or maybe even show a set up?

FYI image just shows how I think it should be done via either the camera’s forward or side vector. Maybe there is a better method.

You did not name all sides of triangle. So B is b from picture, C will be side from camera to actor. and D from actor to point on camera forward vector.
You can calculate C vector as actor location - camera location. Now DOT product of 2 vectors is equal to cosine between them. Also B/C = cosine of that angle. B= cos(alpha)*C

All that in blueprint friendly way:

• Vector_C = world_location (actor) - world_location (camera)
• Angle_Cos = DotProduct of: normalize ( vector_C ) and forward_Vector ( Camera )
• Distance_B = length ( Vector_C ) * Angle_Cos

hope it halp,

Thank you Nawrot - it works! I should probably have mentioned that it needs to work in 3D space. Now the issue is that is only works in 2D space - in other words; when the object is moved in Z or Y the distance doesn’t increase or decrease. How would I implement all axis?

It should work in 3d space. To see what is going on you need to make some line traces. For eg i am not sure if camera forward vector is actually same as screen orientation (i think it is but i am not sure).

Get line trace node, set it to draw for duration. And do line trace from camera to object, from camera location to for eg 5000*forward camera vector + cam location. This should draw your triangle in 3d. See if there everything is like it should be. You also can turn on 3d widgets for vectors, then you will have small yellow box in 3d space that represents vector.

See if you have errors, reference to object (or camera) may be null.

Also you want B distance and ofc if you move point in perpendicular plane to camera forward vector, (and all you want is distance from camera to that plane), it will not change. Try rotating camera (this will change plane orientation and also distance).

PS.
I am not sure how that camera texture projection should work. If you want to make shader you need to do all above in material shader editor.