Drag

back

Notes

Use the arrow keys to move the player left and right.

Source

/* @pjs preload="ground.png, player.png"; */

PImage player;
PImage ground;

float x_velocity = 0;
float x_acceleration;
float x = 0;

int MAX_SPEED = 10; // pixels/frame
int ACCELERATION = 1; // pixels/frame/frame
float DRAG = 0.9; // percentage

// 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){
     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){
    // Add drag to the player that slows them down when they are not accelerating
    x_velocity *= DRAG;
  }
  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(){
  x_acceleration = 0;
}

Warning: Cannot load module "http" because required module "raphf" is not loaded in Unknown on line 0