Search code examples
c#sleepmonogame

How to slow down MonoGame


I'm making a tile-based graphical roguelike game with MonoGame, and when handling input the player moves too fast. Moving the player with separate individual key presses does not make the application terribly fun to play.

How could I add some time between the game loops? When using Thread.Sleep the whole program gets stuck and doesn't handle any input.


Solution

  • Here's what I decided to do in the end.

    I'm separating my game objects into components, and one is called Movement. Since the movement is tile-based, I couldn't use speeds or vectors or anything like that.

    The code is simplified, I did not include everything here.

    public class Movement 
    {
        // define a movement interval and store the elapsed time between moves
        private double interval, elapsedTime;
    
        public Movement(double interval) 
        {
            this.interval = interval;
        }
    
        // called when arrow keys are pressed (player)
        public void Move(Direction dir) 
        {
            if(elapsedTime > interval)
            {
                // move
            }
        }
    
        // called once per frame from the main class Update method
        public void Update(GameTime gameTime)
        {
            if(elapsedTime > interval)
                elapsedTime -= interval;
    
            // add milliseconds elapsed during the frame to elapsedTime
            elapsedTime += gameTime.ElapsedGameTime.TotalMilliseconds; 
        }
    }
    
    public enum Direction 
    {
        LEFT,
        RIGHT,
        UP,
        DOWN
    }