Examples

05B - Adjust velocity

Starting from the example 05A, we create a smooth effect of propulsion for the spaceship by setting the angular velocity of the spaceship. The only modified part of the 05B example is the checkKey() function.

Since there is no gravity, you need to USE ARROWS in order to apply a force to the ship and move it forward.

Applet

This browser does not have a Java Plug-in.
Get the latest Java Plug-in here.

Code

//Import all Phys2D libraries
import pphys2d.bodies.*;
import pphys2d.joints.*;
import pphys2d.shapes.*;
import pphys2d.phys2d.raw.collide.*;
import pphys2d.phys2d.raw.strategies.*;
import pphys2d.phys2d.raw.forcesource.*;
import pphys2d.phys2d.util.*;
import pphys2d.phys2d.raw.shapes.*;
import pphys2d.*;

//Create a PPhys2D world
PPWorld world = new PPWorld();

//Create a PPhys2D Box
PPBox myBox;

//Create a PPhys2D Circle
PPCircle myCircle;

//Create an Array to hold keys
boolean[] keyIsPressed = new boolean[512];

void setup () {
  
  //Set size and framerate
  frameRate(30);
  size(500,500);

  //Set a standard world gravity
  world.setGravity(0, 0);
  
  //Add a box to the world
  myBox = new PPBox(65, 108);
  myBox.setPosition(250, 100);
  myBox.setStrokeWidth(1);
  myBox.setRotation(2*PI);
  //Attach "/data/spaceship.png" to the body
  myBox.attachImage(loadImage("spaceship.png"));
  world.add(myBox);
  
  //Add a static circle to the world
  myCircle = new PPCircle(75);
  myCircle.setPosition(220, 250);
  myCircle.setStaticBody(true);
  //Attach "/data/panet.png" to the body
  myCircle.attachImage(loadImage("planet.png"));
  world.add(myCircle);
  
  //Set world edges in dark gray
  world.setEdges(this, new Color (40, 40, 40));

}

void draw () {
  //Clear screen
  background(255); 
  //Draw world
  world.draw(this);  
  //Check if a key has been pressed add add force
  checkKey();
  
  
}

void keyPressed() {
  //Set presed key code
  keyIsPressed[keyCode] = true;
}

void keyReleased() {
  //Set presed key code
  keyIsPressed[keyCode] = false;
}

void checkKey() {    

  if( keyIsPressed[38]) {
    //UP
    float rotation = myBox.getRotation()-PI/2.0;
    float force = 40000.0f;
    myBox.addForce(cos(rotation)*force, sin(rotation)*force);    
  }
  
  if(keyIsPressed[40]) {
    //DOWN
    float rotation = myBox.getRotation()-PI/2.0;
    float force = -40000.0f;
    myBox.addForce(cos(rotation)*force, sin(rotation)*force);
  }
  
  if(keyIsPressed[37]) {
    //LEFT
    myBox.adjustAngularVelocity(-0.1);
  }
  
  if(keyIsPressed[39]) { 
    //RIGHT
    myBox.adjustAngularVelocity(0.1);
  }
}