In this set of examples, we'll look at the components of platformer-style movement. Here, the movement is very simple: the player is either stopped or moving at full speed. It works but it doesn't feel very good.
Use the arrow keys to move the player left and right.
/* @pjs preload="ground.png, player.png"; */ PImage player; PImage ground; int x_velocity = 0; int x = 0; // Define movement constants int MAX_SPEED = 10; // pixels/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); } 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_velocity = -MAX_SPEED; }else if(keyCode == RIGHT){ // If the RIGHT key is down, set the player velocity to move right x_velocity = MAX_SPEED; } } } void keyReleased(){ // Stop the player from moving horizontally x_velocity = 0; }