开发者

XNA - controlling an object with keyboard input

开发者 https://www.devze.com 2023-01-22 14:38 出处:网络
Ok so I have a ship which moves up and down based on the axis regardless of where 开发者_运维技巧the ship is facing.

Ok so I have a ship which moves up and down based on the axis regardless of where 开发者_运维技巧the ship is facing.

How do I make the ship move in the direction it's facing? i.e. if my ship is facing east, key up makes it go north rather than east.


Your question isn't very clear - I will assume you're using models and matrices (as opposed to SpriteBatch or something else). So, making a guess - I'd say that the order of your matrix operations is incorrect.

This answer to a similar question may help.

Each matrix operation happens around the origin. So if you're doing your rotation after you move your ship into position, your rotation will also effectively "rotate" the direction of movement.


The easiest way is to make an angle and velocity variable so when you click left and right you change the angle and when you click up and down you changle the speed of your ship.

    KeyboardState ks;
    float speed = 0;
    float angle = 0;
    protected override void Update(GameTime gameTime)
    {
        ks = Keyboard.GetState();
        if(ks.IsKeyDown(Keys.Up)) speed += 10;
        if (ks.IsKeyDown(Keys.Down)) speed -= 10;
        if (ks.IsKeyDown(Keys.Right)) angle += 10;
        if (ks.IsKeyDown(Keys.Left)) angle -= 10;
    }


You need to have direction vector like this

Vector3 direction = Vector3.Transform(Vector3.Forward, Matrix.CreateFromYawPitchRoll(yaw, pitch, roll));

Next, get your velocity vector

Vector3 velocity = direction * speed;

And move your ship

float time (float) = gameTime.ElapsedTime.TotalSeconds;
position += velocity * time;

In this example yaw is angle, pitch and roll keep 0.

0

精彩评论

暂无评论...
验证码 换一张
取 消