Examples

Pong game

Create a Pong game in 75 lines of code. Player's pong is controlled by mouse while the other Pong is controlled by computer.

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.*;
import pphys2d.phys2d.raw.*;
import pphys2d.phys2d.math.*;

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

//Create a PPhys2D Box
PPBox block1;

//Create a PPhys2D Box
PPBox block2;

//Create a PPhys2D Ciircle
PPCircle ball;

void setup () {
  
  //Set size and framerate
  frameRate(30);
  size(500,500);
  
  //Set World
  world.setGravity(0, 0);
  world.setEdges(this, new Color (200, 200, 200));
  world.setEdgesRestitution(1f);
  world.setDamping(1f);

  //Add user pong
  block1 = new PPBox(50, 10);
  block1.setPosition(250.0f, 50);
  block1.setRestitution(0.99f);
  block1.setStaticBody(true);
  block1.setFillColor(new Color(0,0,0));  
  block1.setStrokeColor(new Color(0,0,0));
  block1.setFriction(0); 
  world.add(block1);
  
  //Add computer pong
  block2 = new PPBox(50, 10);
  block2.setPosition(250.0f, 450);
  block2.setRestitution(0.99f);
  block2.setStaticBody(true);
  block2.setFillColor(new Color(0,0,0));  
  block2.setStrokeColor(new Color(0,0,0)); 
  block2.setFriction(0); 
  world.add(block2);
  
  //Add ball
  ball = new PPCircle(10);
  ball.setRestitution(0.99f);
  ball.setDamping(0f);
  ball.setForce(random(1200000, 2000000), random(1200000, 2000000));  
  ball.setPosition(250, 250);
  ball.setFillColor(new Color(0,0,0));  
  ball.setStrokeColor(new Color(0,0,0)); 
  ball.setFriction(0); 
  world.add(ball); 

}

void draw () {
  
  //Clear screen
  background(255); 
  
  //Set pongs position
  block1.setPosition( mouseX, block1.getY()) ;  
  block2.setPosition( ball.getX(), block2.getY());
  
  //Check collision and add random forces
  if(ball.isTouchingBody(block2)) ball.addForce(random(-500000,  500000), random(-200000, -30000));
  if(ball.isTouchingBody(block1)) ball.addForce(random(-500000, 500000), random( 200000,  30000));

  //Draw world
  world.draw(this);   
}