Spaceship

back

Notes

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

This is an example of Asteroids-style motion. The ship moves in straight lines until the engine is turned on and accelerates. When the ship reaches any of the stage boundaries it is repositioned to the opposite side. The ship rotates at ROTATION_SPEED degrees/second.

Source

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

Spritesheet ship;

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

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);
  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