Get coordinate with angle and distance

Hello,

Basically I have a base in the center of the screen, and I want enemies to spawn at random angle from player, offscreen then fly towards the base.

The trouble I have is whats the best way to get coordinate that is X distance away, at Z angle? Something like draw a stick of 5 meters at 37 degrees and get the coordinate of the end point.

I sort of know you can do this with casting ray at angle and getting end point, but I was wondering if there is less costly way to do this?

thanks

If you had a decent math teacher, they’ll have shown you that what we call “trigonometry” is also useful for studying circles. In particular, the famous sine and cosine functions actually give you points on a circle.

Unity’s Mathf class has both sin and cos functions, but they use radians instead of degrees. What are radians? Well, they’re a lot like degrees.

//convert from degrees to radians
var radians = degrees * Mathf.Deg2Rad;

So, let’s say you want a point that’s 36 degrees around a circle.

var degrees = 36;
var radians = degrees * Mathf.Deg2Rad;
var x = Mathf.Cos(radians);
var y = Mathf.Sin(radians);
var pos = Vector3(x, y, 0); //Vector2 is fine, if you're in 2D

Now, that gives us a point around a “unit circle”, which has a radius equal to exactly one. You want a radius of five? Just multiply!

var radius = 5;
pos = pos * radius;

Presuming you’re working on a 2D plane (and in C#).

Vector3 pos = new Vector3();
float dist = 5f;
float a = Random.Range(0, 2f) * Mathf.PI;
pos.x = Mathf.Sin(a) * dist;
pos.z = Mathf.Cos(a) * dist;

If you wanted to set specific angles (in degrees) you’ll need to add a little more maths.

Vector3 pos = new Vector3();
float dist = 5f;
float angle = 37; //degrees
float a = angle* Mathf.PI / 180f;
pos.x = Mathf.Sin(a) * dist;
pos.z = Mathf.Cos(a) * dist;

Then probably create a quick function for return the position from degrees and distance.

void Start(){
    GetPosition(37f, 5f);
}

Vector3 GetPosition(float degrees, float dist){
    float a = degrees * Mathf.PI / 180f;
    return new Vector3(Mathf.Sin(a) * dist, 0, Mathf.Cos(a) * dist);
}

@rutter, but if i work in 3d space what i need to modify?