Balls

by soulwire

HTML

<script src="https://rawgithub.com/soulwire/sketch.js/master/js/sketch.js"></script>

JavaScript

function Vector( x, y ) {
    this.set( x, y );
}

Vector.prototype = {
    set: function( x, y ) {
        this.x = x || 0;
        this.y = y || 0;
    },
    add: function( v ) {
        this.x += v.x;
        this.y += v.y;
        return this;
    },
    sub: function( v ) {
        this.x -= v.x;
        this.y -= v.y;
        return this;
    },
    mult: function( f ) {
        this.x *= f;
        this.y *= f;
        return this;
    },
    perp: function( neg ) {
        var tmp = this.x;
        if ( neg ) {
            this.x = -this.y;
            this.y = tmp;
        } else {
            this.x = this.y;
            this.y = -tmp;
        }
        return this;
    },
    proj: function( v ) {
        return this.dot( v ) / v.norm();
    },
    dot: function( v ) {
        return this.x * v.x + this.y * v.y;
    },
    norm: function() { // length
        return Math.sqrt( this.x * this.x + this.y * this.y );
    },
    normalize: function() {

        var m = this.norm();

        if ( m === 0 ) return this;

        this.x /= m;
        this.y /= m;

        return this;
    },
    clone: function() {
        return new Vector( this.x, this.y );
    }
};

function Circle( x, y, mass ) {
    this.radius = ( mass * 10 ) || 10;
    this.fixed = false;
    this.mass = mass || 1.0;
    this.cof = 0.8; // coefficient of friction with another body
    this.moi = this.mass * this.radius * this.radius / 2;
    this.restitution = 1.0; // bounciness
    this.pos = new Vector( x, y );
    this.vel = new Vector();
    this.acc = new Vector();
    this.angular = {
        pos: 0, // angle
        vel: 0,
        acc: 0
    };
}

Circle.prototype = {
    update: function() {

    },
    draw: function( ctx ) {
        ctx.save();
        ctx.translate( this.pos.x, this.pos.y );
        ctx.rotate( this.angular.pos );
        ctx.beginPath();
        ctx.arc( 0, 0, this.radius, 0, Math.PI * 2 );
        ctx.moveTo( 0, 0 );
        ctx.lineTo( this.radius, 0 );
...