Simple Physics Engine :: Motion

A demo in several parts.

by klenwell

HTML

<canvas id="the_canvas" width="250" height="250"></canvas>

JavaScript

var fps = 30;
var mspf = 1000 / fps;

window.animate = (function () {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback, element) {
        window.setTimeout(callback, mspf);
    };
})();

var GraphicsApi = {

    init: function (canvas) {
        this.ctx = canvas.getContext('2d');
        this.center_x = canvas.width / 2;
        this.center_y = canvas.height / 2;
    },

    draw_circle: function (x, y, r, color, line_width, stroke_color) {
        var screen_x = this.world_to_screen_x(x);
        var screen_y = this.world_to_screen_y(y);

        this.ctx.beginPath();
        this.ctx.arc(screen_x, screen_y, r, 0, Math.PI * 2, false);
        this.ctx.fillStyle = color;
        this.ctx.fill();

        if (line_width) {
            this.ctx.lineWidth = line_width;
            this.ctx.strokeStyle = stroke_color;
            this.ctx.stroke();
        }

        this.ctx.closePath();
    },

    world_to_screen_x: function (x) {
        return this.center_x + x;
    },

    world_to_screen_y: function (y) {
        return this.center_y - y;
    },
};

function World() {
    this.balls = [];
    this.x = 0;
    this.y = 0;
    this.r = 100;
    this.color = 'white';
    this.line = 2;
    this.stroke = 'lightgray';

    this.init = function () {};

    this.add_ball = function (ball) {
        this.balls.push(ball);
    }

    this.update = function () {
        this.balls.map(function (ball) {
            ball.move();
        });
    };

    this.draw = function () {
        GraphicsApi.draw_circle(this.x, this.y, this.r, this.color, this.line,
        this.stroke);
        this.balls.map(function (ball) {
            ball.draw();
        });
    };
}

function Ball(x, y, radius, color) {
    this.x = x;
    this.y = y;
    this.r = radius;
    this.color = color;

    this.m = 10;
    this.vx = 0;
    this.vy...