I have been having great trouble getting my sprite to jump. So far I have a section of code which with a single tap of "W" will send the sprite in a constant velocity upwards. I need to be able to make my sprite come back down to the ground a certain time or height after begining the jump. There is also a constant pull of velocity 2 on the sprite to simulate some kind of gravity.
// Walking = true when there is collision detected between the sprite and ground
if (Walking == true)
if (keystate.IsKeyDown(Keys.W))
{
Jumping = true;
}
if (Jumping == true)
{
spritePosition.Y -= 10;
}
Any ideas and help would be appreciated but I'd prefer a modified version of my code posted if at all possible.
public class Player
{
private Vector2 Velocity, Position;
private bool is_jumping;
private const float LandPosition = 500f;
public Player(Vector2 Position)
{
this.Position = new Vector2(Position.X, LandPosition);
Velocity = Vector2.Zero;
is_jumping = false;
}
public void UpdatePlayer(Gametime gametime, KeyboardState keystate, KeyboardState previousKeyBoardState)
{
if (!is_jumping)
if (keystate.isKeyDown(Keys.Space) && previousKeyBoardState.isKeyUp(Keys.Space))
do_jump(10f);
else
{
Velocity.Y++;
if (Position.Y >= LandPosition)
is_jumping = false;
}
Position += Velocity;
}
private void do_jump(float speed)
{
is_jumping = true;
Velocity = new Vector2(Velocity.X, -speed);
}
}
fun little mix of psuedocode and some real code, just add the variables that I didn't include at the top.
Also check out Stack Overflow Physics ;) Good luck with your game.
edit: that should be complete, let me know how things go.