XNA - Hold longer to jump higher

后端 未结 2 1079
野趣味
野趣味 2021-01-27 07:35

I\'m looking for a simple method for my game, so that when you hold down the space bar, you jump higher. When you \'tap\' you don\'t jump to maximum height. There would need to

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-27 08:14

    In your update function that handles jumping, you could have it keep track of how long the character has been off the ground and have it's upward velocity stop increasing after an amount of time.

    For instance, something like the following should work

    class Player
    {
        private const int gravity = 2; //force of gravity on the object
        private const int maxHeight = 5; //change as needed
        private const int msecsToMax = 1500; //change as needed
    
        private int yPos = 0;
        private int timeOffGround = 0;
        private yVel = 0;
    
        //other functions and stuff
    
        void update(GameTime gt)
        {
            //check if the player is on the ground and update as necessary
            if(isOnGround())
                timeOffGround = 0;
            else
                timeOffGround += gt.ElapsedGameTime.TotalMilliseconds;
    
            //update the player's velocity
            yVel -= isOnGround() ? 0 : gravity; //no velocity when on the ground
            if(Keyboard.GetState().IsKeyDown(Keys.SPACE) && timeOffGround < msecsToMax))
                yVel += (maxHeight / msecToMax);
    
            yPos += yVel;
        }
    }
    

提交回复
热议问题