C#Vector2如何将对象移向一个角度

时间:2012-04-13 20:35:57

标签: c# xna-4.0

我想将一个物体移动到给定的角度,但它只向上和向下移动,只有Y轴 Vector2 unitV = new Vector2((float)Math.Sin(player.angle), (float)Math.Cos(player.angle));
unitV.Normalize();
player.model.Position += Vector2.Multiply(unitV,player.model.Speed) * (float)gameTime.ElapsedGameTime.TotalSeconds;

1 个答案:

答案 0 :(得分:1)

我刚练习时遇到了这个问题,但这是我找到的解决方案。我希望这对你有用。使用XNA 4 C sharp。

声明:

Texture2D sprite;
Vector2 spritePosition = Vector2.Zero;
Vector2 spriteOriginalPos;
float spriterotation = 0;
float anglecorrection = (Math.PI * 90 / 180.0);
float speed = 1;

请注意,需要进行角度校正才能将物体移向“向上”角度。

负载:

//Load basic texture to make it recognizable :)
sprite= Content.Load<Texture2D>("spritetexture");
//Default position in middle
spritePosition = new Vector2(
                    (graphics.GraphicsDevice.Viewport.Width / 2) - (sprite.Width / 2),
                    (graphics.GraphicsDevice.Viewport.Height / 2) - (sprite.Height / 2));
//Sprite centering
spriteOriginalPos.X = sprite.Width / 2;
spriteOriginalPos.Y = sprite.Height / 2;

更新

if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Up))
{
    spritePosition.X += speed * (float)Math.Cos(spriterotation - anglecorrection);
    spritePosition.Y += speed * (float)Math.Sin(spriterotation - anglecorrection);
}

绘制:

spriteBatch.Draw(sprite, spritePosition, null, Color.Black, spriterotation, spriteOriginalPos, 1.0f, SpriteEffects.None, 0f);