PhysicsJS Boilerplate

PhysicsJS by Jasper Palfree <wellcaffeinated.net> http://wellcaffeinated.net/PhysicsJS

by Abhishek Nandy

HTML

<script src="http://wellcaffeinated.net/PhysicsJS/examples/physicsjs-full.js"></script>
<canvas id="viewport" width="500" height="500"></canvas>

JavaScript

/**
 * PhysicsJS by Jasper Palfree <wellcaffeinated.net>
 * http://wellcaffeinated.net/PhysicsJS
 *
 * Boilerplate
 */
Physics(function (world) {
    var renderer = Physics.renderer('canvas', {
    el: 'viewport', // id of the canvas element
    width: 500,
    height: 500
});
world.add( renderer );

var square = Physics.body('convex-polygon', {
    x: 250,
    y: 250,
    vx: 0.01,
    vertices: [
        {x: 0, y: 50},
        {x: 50, y: 50},
        {x: 50, y: 0},
        {x: 0, y: 0}
    ]
});

    
world.add( square );
world.render();
    
// subscribe to ticker to advance the simulation
Physics.util.ticker.subscribe(function( time, dt ){
    world.step( time );
});

// start the ticker
Physics.util.ticker.start();
world.subscribe('step', function(){
    world.render();
});
    
world.add( Physics.behavior('constant-acceleration') );

var bounds = Physics.aabb(0, 0, 500, 500);

world.add( Physics.behavior('edge-collision-detection', {
    aabb: bounds
}) );
// ensure objects bounce when edge collision is detected
world.add( Physics.behavior('body-impulse-response') );
    //adding Newtonion motion
    world.add( Physics.behavior('newtonian', { strength: .5 }) );

world.add( Physics.behavior('edge-collision-detection', {
    aabb: bounds,
    restitution: 0.3
}) );

world.add( Physics.body('convex-polygon', {
    x: 50,
    y: 50,
    vx: 0.05,
    vertices: [
        {x: 0, y: 40},
        {x: 30, y: 20},
        {x: 30, y: -20},
        {x: 0, y: -40}
    ]
}) );
    
world.add( Physics.body('circle', {x: 400,
                y: 100,
                vx: 0,
                radius: 30
}) );
    
    
world.add( Physics.body('circle', {x: 160,
                y: 300,
                radius: 45,
                mass: 2,
                vx: 0.05,
                vy: -0.15,
                angularVelocity: 0.01
}) );

world.add( Physics.body('circle', {x: 400,
               x: Physics.util.random(60, 400),
                y: Physics.util.random(500),
           ...