PhysicsJS Boilerplate

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

by AntonLapshin

HTML

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

JavaScript

Physics(function( world ){
    var renderer = Physics.renderer('canvas', {
        el: 'viewport',
        width: 500,
        height: 500,
        meta: true
    });
    world.add( renderer );
    
    var square = Physics.body('convex-polygon', {
        x: 250,
        y: 250,
        //vx: 0.05,
        mass: 1,
        vertices: [
            {x: 0, y: 50},
            {x: 50, y: 50},
            {x: 50, y: 0},
            {x: 0, y: 0}
        ]
    });
    world.add( square );
    square.name = 'square';
    
    world.subscribe('step', function(){
        world.render();
    });    

    Physics.util.ticker.subscribe(function( time, dt ){
        world.step( time );
    });
    
    Physics.util.ticker.start();
   
    //world.add( Physics.behavior('constant-acceleration') );
    var bounds = Physics.aabb(0, 0, 500, 500);
    world.add( Physics.behavior('edge-collision-detection', {
        aabb: bounds,
            restitution: 0
        }) );
    world.add( Physics.behavior('body-impulse-response') );
    
    var speed = 0.05;
    var vx, vy;
    var snake = [];
    var index = 0;
    
    var rcm = Physics.behavior('rigid-constraint-manager');
    world.add( rcm );  
    var targetLength = 11;
    
    var head = Physics.body('convex-polygon', { x: 10, y: 10, mass: 1, vertices: [
        { x: 0, y: 10 },
        { x: 10, y: 10 },
        { x: 10, y: 0 },
        { x: 0, y: 0 }
    ]});
    head.name = 'head';
    snake.push(head);
    world.add(head);
    
    var createItem = function(){
        var item = Physics.body('convex-polygon', { x: 10, y: 10, mass: 0.0001, vertices: [
            { x: 0, y: 10 },
            { x: 10, y: 10 },
            { x: 10, y: 0 },
            { x: 0, y: 0 }
        ]});
        item.name = 'item';
        snake.push(item);
        world.add(item);
        rcm.constrain( snake[index], item, targetLength ); 
        index++;
    }
    
    //var c3 = Physics.body('circle', { x: 10, y: 10, radius: 10, mass: 0.00001 });
 ...