NModds Posted April 1, 2018 Share Posted April 1, 2018 (edited) Hi all, I just wanted to share a general equation for implementing relative distance or offset from entity given world coords (hash: 0x2274BC1C4885E333). I thought it was as straight forward as the difference of two vectors but it's not. I put in a bunch of numbers on my screen and realized it was using a dot product of directions. Here is my implementation: public Vector3 RelativeDistance(Vector3 Origin, Vector3 Rotation, Vector3 Position){ Vector3 RightVector = RelativeRightVector(Rotation); Vector3 ForwardVector = RotationToDirection(Rotation); return new Vector3(-1 * Vector3.Dot(RightVector, (Origin - Position)), -1 * Vector3.Dot(ForwardVector, (Origin - Position)), Position.Z - Origin.Z);}public Vector3 RelativeRightVector(Vector3 Rotation)//source is from scripthookdotnet{ double num = Math.Cos(Rotation.Y * (Math.PI / 180.0)); return new Vector3((float)(Math.Cos(-Rotation.Z * (Math.PI / 180.0)) * num), (float)(Math.Sin(Rotation.Z * (Math.PI / 180.0)) * num), (float)Math.Sin(-Rotation.Y * (Math.PI / 180.0)));}public Vector3 RotationToDirection(Vector3 Rotation)//I forgot where I got this from, I had it for a long time{ float z = Rotation.Z; float num = z * 0.0174532924f; float x = Rotation.X; float num2 = x * 0.0174532924f; float num3 = Math.Abs((float)Math.Cos((double)num2)); return new Vector3 { X = (-(float)Math.Sin(num)) * num3, Y = (float)Math.Cos(num) * num3, Z = (float)Math.Sin(num2) };} Edited April 2, 2018 by nm710 ikt 1 Link to comment Share on other sites More sharing options...
ikt Posted June 19, 2021 Share Posted June 19, 2021 (edited) Since GTAForums mangled the code, here it is again, but less mangled (and in C++, and assuming all rotations are in radians). template <typename Vector3T> Vector3T RotationToDirection(Vector3T rot) { auto rotZ = (rot.z); auto rotX = (rot.x); auto multXY = abs(cos(rotX)); Vector3T v{}; v.x = -sin(rotZ) * multXY; v.y = cos(rotZ) * multXY; v.z = sin(rotX); return v; } template <typename Vector3T> Vector3T RelativeRightVector(Vector3T rot) { auto num = cos(rot.y); Vector3T v{}; v.x = cos(-rot.z) * num; v.y = sin(rot.z) * num; v.z = sin(-rot.y); return v; } template <typename Vector3T> Vector3T GetRelativeOffsetGivenWorldCoords(Vector3T position1, Vector3T position2, Vector3T rot) { Vector3T right = RelativeRightVector(rot); Vector3T forward = RotationToDirection(rot); Vector3T v{}; v.x = -1 * Dot(right, (position1 - position2)); v.y = -1 * Dot(forward, (position1 - position2)); v.z = position2.z - position1.z; return v; } Honestly, why'd they go and delete all newlines from code blocks? Edited June 19, 2021 by ikt OnlyRealNubs 1 Link to comment Share on other sites More sharing options...