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
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;
}
}
During the accent of a jump, the Y velocity is completely
overridden by a power curve. During the decent, gravity takes
over. The jump velocity is controlled by the jumpTime
field
which measures time into the accent of the current jump.
First off you will need some simple global variables,
public bool isJumping; //Is the player in a jump?
private bool wasJumping; //Did the player just exit a jump?
private float jumpTime; //Time the player has been in a jump (Useful for adding a power curve or to max out on jump height)
MaxJumpTime = .8f; //If you want to max out a jump, otherwise remove the relevant parts of the code
JumpLaunchVelocity = -3000.0f; //How much velocity to "jump" with, this may depend on your speed of your player, so it will need some ajustment
Here is the function that does most of the work:
private float DoJump(float velocityY, GameTime gameTime)
{
// If the player wants to jump
if (isJumping)
{
// Begin or continue a jump
if ((!wasJumping && IsOnGround) || jumpTime > 0.0f)
{
//Do things like animate, or play a sound here
jumpTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
}
// If we are in the ascent of the jump
if (0.0f < jumpTime && jumpTime <= MaxJumpTime)
{
// Fully override the vertical velocity with a power curve that gives players more control over the top of the jump (If you dont want this you can remove the Math.Pow)
velocityY = JumpLaunchVelocity * (1.0f - (float)Math.Pow(jumpTime / MaxJumpTime, JumpControlPower));
}
else
jumpTime = 0.0f; // Reached the apex of the jump
}
else
{
// Continues not jumping or cancels a jump in progress
jumpTime = 0.0f;
}
wasJumping = isJumping;
return velocityY;
}
In your update when you calculate position and stuff:
velocity.Y = DoJump(velocity.Y, gameTime);
Take a look at the Platformer Starter Kit if you run into any problems!