简体   繁体   中英

C# Vector2 How to move an object toward an angle

我想将对象移动到给定的角度,但是它只能在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;

I just met this problem while practicing, but here is the solution i found. I hope this will work for you. Used XNA 4 C sharp.

Declaration:

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

Note that the anglecorrection is needed to move the object toward its "up" angle.

Load:

//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;

Update:

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

Draw:

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

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