Use Vector3s to get to a coordinate a specific angle and distance away (c#)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By wooshuwu

This probably has a simple math solution I’m just not thinking of, but I would like to be able to calculate a 3D coordinate/Vector3 value that is x units away from object y’s origin, at an angle of alpha. The method should be generalized enough to where it can be applied if y’s origin/position changes, i.e. the calculation method ideally should be using variable values.

:bust_in_silhouette: Reply From: Ninfur

If I understand the question correctly you want to calculate a polar coordinate. This is achieved by using cos(a) to calculate the x value of a direction vector, and sin(a) for the y (or in this case, z) value of the direction vector. Finally the direction vector is multiplied by the distance you want to move.

I don’t have code for this in C#, but this is what it could look like in GDScript

func polar_offset(pos: Vector3, angle: float, distance: float) -> Vector3:
    return pos + Vector3(cos(angle), 0, sin(angle)) * distance

Example:

var pos = Vector3(10, 10, 10)
pos = polar_offset(pos, deg2rad(90), 5)
print(pos) # Results in (10, 10, 15)
pos= Noise.polar_offset2(v, deg2rad(45), 10)
print(pos) # Results in (17.071068, 10, 22.071068)

Thank you so much! I successfully implemented this c# equivalent:

public Vector3 PolarOffsets(Vector3 Pos, float Angle, float Dist){
        // Vector3 temp = Pos + new Vector3(Mathf.Cos(Angle), 0f, Mathf.Sin(Angle));
        Vector3 temp = new Vector3(Mathf.Cos(Angle), Mathf.Sin(Angle), 0f)*Dist;

        return(temp + Pos);
    }

Due to the angle of the camera, I had to make the Sin the y coordinate rather than the z coordinate value. Mathf is included either in the Godot or System library and should be readily available for usage.

And this is the method call:

PolarOffsets(RefPose.origin, Mathf.Deg2Rad(40), (float)DistH.Value);

where RefPose was a Transform variable and the origin property is a Vector3. Any Vector3 can be used instead.

wooshuwu | 2022-04-06 23:27