MonoGame - Have an object circle around a point

末鹿安然 提交于 2019-12-11 18:49:55

问题


I have an object with a Vector2 Position, and a cursor with Vector2 Position.

When I hold a certain key, I want the object to circle around the object, but I'm having trouble calculating the correct coordinates.

I've managed to make the object circle around the cursor (but it's not going in a perfect circle, but more of a spiral) with this code:

Vector2 diff= Vector2.Normalize(cursor.Location - this.Location);

float angle = (float)Math.Atan2(diff.Y, diff.X) + (float)(90 * (Math.PI / 180));
this.Position += new Vector2((float)(speed * Math.Cos(angle)), (float)(speed* Math.Sin(angle)));

I calculate the angle between cursor's and object's locations, and add 90° (in radians) to that value, which, by my logic, should make the object travel in a perfect circle. However, the distance between the cursor and the object quickly spreads.

What am I calculating wrong here?


回答1:


Usually when you want something to circle around a point, you define the distance to an amount and you incrementally change the angle in your Update method. THEN in your draw method you can draw it where you should by calculating the position from the cursor.Location, the distance from the cursor and the desired distance.

In most situations like these you want your orbiter to have the same loation like your cursor, so calculating the new position in the Draw method works best, given that these calculations are cheap and super fast (you generally do not want to hog down your Draw method).

I am not able to check it right now, but what you should be doing is something in these lines:

Given that your object should rotate D distance away from your cursor with an angular velocity of AngularVelocity (per second), then when this initially happens, set a variable angle to zero. Then in your update do:

angle += (gameTime.ElapsedGameTime.TotalSeconds * AngularVelocity)

and in your Draw method do:

var displacedPosition = new Vector2(D * Math.Sin(angle), D * Math.Cos(angle));

and render your orbiter using the displacedPosition instead of the normal position if it is currently orbiting.



来源:https://stackoverflow.com/questions/24935239/monogame-have-an-object-circle-around-a-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!