Use the arrow keys to move the player left and right. Press the up arrow to jump.
Jumping is a combination of two things: an upward velocity and gravity. When the up arrow is pressed and the player is touching the ground, an upward velocity is added to the player. Gravity then accelerates the character back towards the ground. The parabolic path of the player while jumping is simply a result of the player being affected by gravity.
/* @pjs preload="ground.png, player.png"; */ PImage player; PImage ground; float x_velocity = 0; float y_velocity = 0; float x_acceleration; float x = 0; float y = 0; // Define movement constants int MAX_SPEED = 10; int ACCELERATION = 1; float DRAG = 0.9; int GRAVITY = 2; // pixels/frame/frame int JUMP_SPEED = -25; // pixels/frame(negative y is up) // Define collision constants int GROUND_LEVEL; // Setup the example void setup(){ size(640, 480); // Load images ground = loadImage("ground.png"); player = loadImage("player.png"); GROUND_LEVEL = 480-64;//height - player.height - ground.height; y = GROUND_LEVEL; } // The draw() method is called every frame void draw(){ // Set stage background to something sky colored background(#4488cc); // Create some ground for the player to walk on for(int i = 0; i < width; i += ground.width){ image(ground, i, height - ground.height); } // Set player maximum movement speed if(abs(x_velocity) < MAX_SPEED){ x_velocity += x_acceleration; } // Add drag to the player that slows them down when they are not accelerating if(abs(x_acceleration) == 0){ x_velocity *= DRAG; } x += x_velocity; // Since we're jumping we need gravity y_velocity += GRAVITY; y += y_velocity; // Collide the player with the ground if(y > GROUND_LEVEL){ y = GROUND_LEVEL; } // Just for fun, draw some height markers so we can see how high we're jumping drawHeightMarkers(); image(player, x, y); } void drawHeightMarkers(){ stroke(255, 50); for(int y = height-32; y >= 64; y-=32){ line(0, y, width, y); } } void keyPressed(){ if( key == CODED){ if(keyCode == LEFT){ x_acceleration = -ACCELERATION; }else if(keyCode == RIGHT){ x_acceleration = ACCELERATION; }else if(keyCode == UP){ // Jump when the player is touching the ground and the up arrow is pressed if(y == GROUND_LEVEL){ y_velocity = JUMP_SPEED; } } } } void keyReleased(){ x_acceleration = 0; }