简体   繁体   中英

Rotating a 2D Image Towards a Point in C#

I have been working with rotating Texture2D sprites. I have been using:

float circle = MathHelper.Pi * 2;
RotationAngle = RotationAngle % circle;

and

ScreenManager.SpriteBatch.Draw(car, screenpos, null, Color.White, RotationAngle, car_origin, 1.0f, SpriteEffects.None, 0f);

for the most part to handle the rotation of my test texture "car". It seems like the rotation angle of Pi*2 is a value between 0 and -6.283185 or 0 and 6.283185 depending on the direction. Now what I would like to do is rotate a texture in a certain direction (say the texture is an arrow) towards a location (a vector2 such as the current mouse position). I am not quite sure how to go about how I'd need to modify this rotation angle based on a vector2 position.

You don't need to wrap an angle when passing it to SpriteBatch.Draw . But if you do want to wrap an angle for some reason, it's best to use MathHelper.WrapAngle ( MSDN ).

Now say you have a Vector2 that represents a direction and a distance (as you might have, for example, if you did mousePos - carPos , for the direction and distance from the car to the cursor). And you want to take that direction and convert it to an angle. Use an extension method like this one:

public static float Angle(this Vector2 v)
{
    return (float)Math.Atan2(v.Y, v.X);
}

So, to get your angle you'd do something like: (mousePos - carPos).Angle() .

See the documentation for Atan2 for more details.

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