简体   繁体   中英

Calculating the position of an orbiting object with a pivot point based on angle or vector

I'm trying to get an object to orbit around a point at a fixed distance. I've tried some methods such as setting the position of the object to the normalized vector multiplied by how far away I want the object to be from the pivot, but the input vector is sometimes (0, 0), which when multiplied results in 0 causing the orbiting object to snap to the position of the pivot.

In object based scene hierarchies such as the Unity Game Engine, you are able to parent an object to another, and use that parent as a pivot point, causing the child to behave in exactly the way I want my orbiting object to behave.

Example of this behavior in Unity:

此行为的示例

I don't need the rotation of the child to change as I already have that handled, I just need the position of the object to move based on the angle so it always maintains the same distance from the pivot.Is there a formula to calculate this position based on either an angle or a vector or any resources that I could use to learn more about how to achieve something like this?

All I need is to take input of an angle or vector and receive a position relative to the pivot location as output.

If anything needs clarification let me know. Thanks!

If your pivot point has coordinates (x, y) , then you only need to set the position of your object (ideally its center of mass) to
(x + r*cos(t), y + r*sin(t))
where r is the distance from the pivot and t is an angle, presumably a function of time (or something you periodically increase).

In C++, you have std::sin and std::cos . They take radians as argument, so if you want for example t=0 and t=1 to produce the same result, you can use 2*pi*t instead of just t .

I don't know how the parenting thing is implemented in game engines like Unity, but you could use some sort of observer pattern (or just straight callbacks), where the orbiting object has the position of its center of orbit, and whenever the pivot object position changes, it calls the orbiting object to update its center of orbit. Or the orbiting object could keep a reference to the pivot point, but then you need to explicitly take care of lifetime considerations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM