简体   繁体   English

如何旋转2D对象?

[英]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? 因此,我不得不问,如何使用键盘作为输入来旋转2D对象? More specifically, if I pressed & held the left arrow key, the 2D object will rotate left (counter clockwise) and vice versa. 更具体地说,如果我按住左箭头键,则2D对象将向左旋转(逆时针),反之亦然。 I should also mention the 2D object is stationary. 我还应该提到2D对象是固定的。

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. 这是我当前的2D对象的位置,它位于底部。 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; 在您的对象类中放入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: 然后在draw方法中:

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. 您还需要ObjectCenter变量,它是vector2对象,并且在该点上对象将旋转。 for that check this answer: Rotating a sprite around its center 为此检查此答案: 围绕其中心旋转精灵

EDIT: GameTime XNA have two update functions. 编辑:GameTime XNA具有两个更新功能。 Draw and Update. 绘制和更新。 Do not mix those two functions. 请勿混用这两个功能。 Use draw only for drawing to screen and update for collision, moving object, update object. 仅将draw用于屏幕绘制,并更新碰撞,移动对象,更新对象。 System try to execute this 60 times per second, and if due too much calculations or slower computer it can go below that value. 系统尝试每秒执行此操作60次,如果由于计算量过多或计算机速度较慢而导致速度低于该值。 (btw: XNA have IsRunningSlowly flag that is set to true in this case) (顺便说一句:XNA具有IsRunningSlowly标志,在这种情况下将其设置为true)

So if you wish to be sure that object will move 5 pixels every millisecond you have to multiply your value like that: 因此,如果您希望确保对象每毫秒移动5个像素,则必须像这样乘以值:

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

So, if you wish to rotate object for 0.1 radian per second: 因此,如果您希望以每秒0.1弧度的速度旋转对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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