0 votes

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.

Godot version v3.3.4
in Engine by (52 points)

1 Answer

+1 vote
Best answer

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)
by (640 points)
selected by

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.