Use the arrow keys to move the player left and right.
The player now gradually accelerates from zero to top speed while a key is pressed.
/* @pjs preload="ground.png, player.png"; */ PImage player; PImage ground; int x_velocity = 0; int x_acceleration; int x = 0; // Define movement constants int MAX_SPEED = 10; // pixels/frame int ACCELERATION = 1; // pixels/frame/frame // Setup the example void setup(){ size(640, 480); // Load images ground = loadImage("ground.png"); player = loadImage("player.png"); } // 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){ // Add the ground blocks image(ground, i, height - ground.height); } if(abs(x_velocity) < MAX_SPEED){ x_velocity += x_acceleration; } x += x_velocity; image(player, x, height - player.height - ground.height); } void keyPressed(){ if( key == CODED){ if(keyCode == LEFT){ // If the LEFT key is down, set the player velocity to move left x_acceleration = -ACCELERATION; }else if(keyCode == RIGHT){ // If the RIGHT key is down, set the player velocity to move right x_acceleration = ACCELERATION; } } } void keyReleased(){ // Stop the player from moving horizontally x_velocity = 0; x_acceleration = 0; }