Use the arrow keys to move the player left and right. Press the up arrow to jump.
While in the air, press the up arrow to jump again.
/* @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; boolean canDoubleJump = true; int GROUND_LEVEL; int MAX_SPEED = 10; int ACCELERATION = 1; float DRAG = 0.9; int GRAVITY = 2; int JUMP_SPEED = -25; // 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(){ 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; } if(abs(x_acceleration) == 0){ x_velocity *= DRAG; } x += x_velocity; // Since we're jumping we need gravity y_velocity += GRAVITY; y += y_velocity; 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); } // This function draws horizontal lines across the stage void drawHeightMarkers(){ stroke(255, 50); for(int y = height-32; y >= 64; y-=32){ line(0, y, width, y); } } boolean isOnGround(){ return y == GROUND_LEVEL; } 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(isOnGround() || canDoubleJump){ y_velocity = JUMP_SPEED; canDoubleJump = isOnGround(); } } } } void keyReleased(){ x_acceleration = 0; }