Examples

08 - Collision

Starting from example 4, this example adds some collision detection functions which allows us to know when the two bodies are touching. The box changes color depending on its collision state.

Collision check is made with isTouchingBody() function.

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 ArrayList 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, 100);
  
  //Add a box to the world
  myBox = new PPBox(50, 90);
  myBox.setPosition(250, 100);
  myBox.setStrokeWidth(1);
  myBox.setFillColor(new Color(40,40,100));
  myBox.setStrokeColor(new Color(40,40,40));
  world.add(myBox);
  
  //Add a static circle to the world
  myCircle = new PPCircle(50);
  myCircle.setPosition(220, 250);
  myCircle.setStrokeWidth(1);
  myCircle.setStaticBody(true);
  myCircle.setFillColor(new Color(100,20,20));
  myCircle.setStrokeColor(new Color(40,40,40));
  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();  
  
  //Check collision
  if(myBox.isTouchingBody(myCircle)) myBox.setFillColor( new Color(0,255,0) );
  else myBox.setFillColor ( new Color(40,40,100) );
}


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

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


void checkKey() {  
  if(keyIsPressed[38])myBox.addForce(0, -90000); //UP
  if(keyIsPressed[40])myBox.addForce(0, 90000); //DOWN
  if(keyIsPressed[37])myBox.addForce(-90000, 0); //LEFT
  if(keyIsPressed[39])myBox.addForce(90000, 0); //RIGHT
}