我希望你能帮助我。
当用户单击右键时,我正在根据鼠标位置移动我的精灵,如下所示:
protected override void Update(GameTime gameTime)
{
int nextX = SpritePosition.X;
int nextY = SpritePosition.Y;
int SpriteWidth = 135;
int SpriteHeight = 135;
int Speed = 3;
MouseState ms = Mouse.GetState();
if (ms.RightButton == ButtonState.Pressed)
{
if (ms.X > SpritePosition.X + SpriteWidth) //check to move right
{
nextX = SpritePosition.X + Speed;
}
else if (ms.X < SpritePosition.X) //check to move left
{
nextX = SpritePosition.X - Speed;
}
if (ms.Y > SpritePosition.Y + SpriteHeight) //Check to move bottom
{
nextY = SpritePosition.Y + Speed;
}
else if (ms.Y < SpritePosition.Y) //Check to move top
{
nextY = SpritePosition.Y - Speed;
}
//Change the Sprite position to be updated in the DRAW.
SpritePosition = new Rectangle(nextX, nextY, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
}
base.Update(gameTime);
}
它现在正在工作,但它的移动方式是这样的:
错误移动http://i.imgur.com/xGsFy38.png
我希望它移动的方式如下:向右移动http://i.imgur.com/kkEnoYD.png
伙计们,现在我从以下答案中尝试了以下方法:
Vector2 From = new Vector2(SpritePosition.X, SpritePosition.Y);
Vector2 To = new Vector2(ms.X, ms.Y);
From = Vector2.Subtract(From,To );
Vector2 Direction = Vector2.Normalize(From);
Direction = Direction * Speed;
SpritePosition = new Vector2(Direction.X, Direction.Y);
我的精灵不动,我做错了什么?