Hello,
I would like to have an object orbit another one in a circular path. I’ve previously implemented a solution that has the object follow a list of waypoints, but am not sure how to handle this problem. With the waypoints, each path between points was left to PathAI, but if I try to control an object so finely that it goes in a circle, will there be any point to using PathAI to benefit from its features, such as avoidance?
Hi
I would recommend updating the target of the AI every frame to be just a small distance further along the circle.
Something like
var center = enemy.position;
// Get the direction from the center to our position
var dir = transform.position - center;
// Figure out the angle of that vector
var angle = Mathf.Atan2(dir.z, dir.x);
// Desired distance to the center of the orbit
var radius = 4;
// Pick a point slightly further along the circle so that the agent knows where to move
angle += 20 * Mathf.deg2rad;
// Calculate the position on the circle
target.position = new Vector3(Mathf.Cos(angle) * radius, dir.y, Mathf.Sin(angle) * radius) + center;
I haven’t tested the above code, but I think it should work.
See also https://en.wikipedia.org/wiki/Sine
2 Likes
Thank you for the code snippet! Worked great, and the only suggestion I would make to anyone else trying this, is to make sure the radius is longer than the object it is orbiting around. The next movement target/position, should end up outside the target being orbited.
1 Like