Examples

06 - Array of bodies

This example starts from scratch and shows how to creates an array of bodies. This is the simplest way to create a lot of objects without having to code each of them.

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 an Array to hold the balls
PPCircle[] balls = new PPCircle[8];

void setup () {

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

  //Set a standard world gravity
  world.setGravity(0, 200);

  //Create 10 balls and add them to the world
  for(int i=0; i <balls.length; i++) {    
    balls[i] = new PPCircle(random(20,50));
    balls[i].setFillColor(new Color((int)random(100,140), (int)random(100,140), (int)random(100,140)));
    balls[i].setStrokeColor(new Color(190,190,190));
    balls[i].setStrokeWidth(2);   
    balls[i].setPosition(random(50,450), random(50,150));
    world.add(balls[i]);
  }

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