简体   繁体   中英

How to rotate 2D object?

I tried to search this but all of the results have been really close to what I needed but not quite the same. So I have to ask, how do I rotate a 2D object with using our keyboard as inputs? More specifically, if I pressed & held the left arrow key, the 2D object will rotate left (counter clockwise) and vice versa. I should also mention the 2D object is stationary.

position = new Vector2(box.X, 475);// 475 is the gameWindow height
//box.X is for when I have to move the object along the X-axis.

This is the position of my current 2D object, which is sitting along the bottom. I guess it's almost exactly like one of those marble shooter type of things (Marble buster, Sparkle unleashed, etc...).

You will need some variable where you will store current roatation, and one function where you will determinate what key is pressed. Inside your object class put Rotation = 0.0f; what will be used for that.

Then inside your update method you need this:

KeyboardState keyBoardState = Keyboard.GetState();
if (keyBoardState.IsKeyDown(Keys.Left)){Rotation -= 0.1f;}
if (keyBoardState.IsKeyDown(Keys.Right)){Rotation += 0.1f;}

And then in draw method:

spriteBatch.Begin();
spriteBatch.Draw(Texture, Position, null, Color.White, Rotation, ObjectCenter, 1.0f, SpriteEffects.None, 0);
spriteBatch.End();

You will also need ObjectCenter variable, it's vector2 object and over that point object will rotate. for that check this answer: Rotating a sprite around its center

EDIT: GameTime XNA have two update functions. Draw and Update. Do not mix those two functions. Use draw only for drawing to screen and update for collision, moving object, update object. System try to execute this 60 times per second, and if due too much calculations or slower computer it can go below that value. (btw: XNA have IsRunningSlowly flag that is set to true in this case)

So if you wish to be sure that object will move 5 pixels every millisecond you have to multiply your value like that:

time = gameTime.ElapsedGameTime.TotalMilliseconds;
player.position.x += 5 * time;

So, if you wish to rotate object for 0.1 radian per second:

time = gameTime.ElapsedGameTime.TotalSeconds;
player.rotate += 0.1 * time;

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