Spaceship with drag

back

Notes

Use the left and right arrow keys to rotate the ship. Press the up arrow key to turn on the engine.

This ship now has a DRAG component. This causes the ship to slow down gradually when the engine is off.

Source

/* @pjs preload="ship.png"; */

Spritesheet ship;

float ROTATION_SPEED = 2.8;
float ACCELERATION = 2.0;
float MAX_SPEED = 2.5;
float DRAG = 0.98;

boolean leftKeyDown, rightKeyDown, upKeyDown;

float angle = -90;
PVector shipPosition;
PVector shipVelocity;
PVector shipAcceleration;
float angularVelocity;

int ship_frame;

void setup(){
  size(640, 480);
  
  imageMode(CENTER);
  
  // Load images
  ship = new Spritesheet(loadImage("ship.png"), 2);
  shipPosition = new PVector(width/2, height/2, 0);
  shipVelocity = new PVector(0,0,0);
  shipAcceleration = new PVector(0,0,0);
}

void draw(){
  background(#333333);
  
  if(leftKeyDown){
    angularVelocity = -ROTATION_SPEED; 
  }else if(rightKeyDown){
    angularVelocity = ROTATION_SPEED;
  }else{
    angularVelocity = 0; 
  }
  
  if(upKeyDown){
    shipAcceleration.set(cos(radians(angle)) * ACCELERATION, sin(radians(angle)) * ACCELERATION, 0);
    ship_frame = 1; 
  }else{
    shipAcceleration.set(0, 0, 0);
    ship_frame = 0; 
  }
  
  shipVelocity.add(shipAcceleration);
  shipVelocity.limit(MAX_SPEED);
  if(shipAcceleration.mag() == 0){
    shipVelocity.mult(DRAG);
  }
  shipPosition.add(shipVelocity);
  
  angle += angularVelocity;
  
  // Keep the ship on the screen
  if(shipPosition.x > width) shipPosition.x = 0;
  if(shipPosition.x < 0) shipPosition.x = width;
  if(shipPosition.y > height) shipPosition.y = 0;
  if(shipPosition.y < 0) shipPosition.y = height;
  
  pushMatrix();
  translate(shipPosition.x, shipPosition.y);
  rotate(radians(angle));
  image(ship.getFrame(ship_frame), 0, 0);
  popMatrix();
}

void keyPressed(){
  if(key == CODED){
     if(keyCode == LEFT){
       leftKeyDown = true;
     }
     if(keyCode == RIGHT){
       rightKeyDown = true;
     }
     if(keyCode == UP){
       upKeyDown = true;
     }
  }
}

void keyReleased(){
  if(key == CODED){
     if(keyCode == LEFT || keyCode == RIGHT){
        leftKeyDown = rightKeyDown = false;
     }
     if(keyCode == UP){
       upKeyDown = false;
     }
  }
}

class Spritesheet{
 PImage[] frames;
 
 Spritesheet(PImage img, int noFrames){
  int frameHeight = img.height / noFrames;
  frames = new PImage[noFrames];
  for(int i = 0; i < frames.length; i++){
    frames[i] = img.get(0, frameHeight * i, img.width, frameHeight);
  }
 }
 
 PImage getFrame(int frame){
   if(frame < frames.length)
     return frames[frame];
   return null;
 }
}

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