I'm making a game in XNA. I need a player to move from block to block (40x40pixels) and I need to be able to set the speed that the player is able to move at. Right now, I have this code:

Update Method - updates 60 frames per second or whatnot

protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            ProcessKeyboard();

            base.Update(gameTime);
        }

Process's keyboard button's and movement by 40 pixels

private void ProcessKeyboard(){
            KeyboardState keyState = Keyboard.GetState();
            if (keyState.IsKeyDown(Keys.Left)){
                player.Position.X -= 40;  //move player 40 pixels
            }
        }

Since the Update method works at 60 frames per second or something, the player moves too quickly. I don't want to limit the update method, but I can't think of a logical way to implement a wait/timer method into the keyboard processing either. Can anyone help me?


I've tried this, but it doesn't work right:

private void Wait(int waittime){
            System.Threading.Thread.Sleep(waittime);
        }
private void ProcessKeyboard(){
            KeyboardState keyState = Keyboard.GetState();
            if (keyState.IsKeyDown(Keys.Left)){
                Wait(100);
                player.Position.X -= 40;  //move player 40 pixels
            }
        }

How fast do you want the player to move? Current rate (if the 60 frames a second is accurate) is 2400 pixels/second. Once you know that, it's simple math and a counter to keep the player at your set speed.

How fast do you want the player to move? Current rate (if the 60 frames a second is accurate) is 2400 pixels/second. Once you know that, it's simple math and a counter to keep the player at your set speed.

But I don't know how to do any of that in C# and not entirely sure how I'd set it up. Also the 60 fps wouldn't be constant, would it? So I don't see how that helps

Edited 5 Years Ago by Slyvr: n/a

This article has been dead for over six months. Start a new discussion instead.