Particles - Polygon Moment of Inertia
Now angular momentum seems to work. Changing mass makes moment of inertia change accordingly; higher masses mean rotation is harder. Can apply torque given an arbitrary value, but cannot apply torque based on a force vector.
by djwelsh
HTML
<canvas id="c" width="400" height="400"></canvas>
<label>Mass: <input id="" type="text" value="" /> kg</label>
<label>Mass: <input id="" type="text" value="" /> kg</label>
CSS
canvas {
width: 400px;
height: 400px;
outline: 1px solid #ccc;
}
label {
display: block;
}
JavaScript
Polygon.getMomentOfInertia = function (points, density) {
var numPoints = (points.length - 1);
var Ix = 0;
var Iy = 0;
var Ixy = 0;
var a = 0;
var j = numPoints - 1; // The last vertex is the 'previous' one to the first
//Loop through all vertices and overlap the last.
for (i = 0; i < numPoints; i++) {
a = points[j].x * points[i].y - points[i].x * points[j].y;
Ixy += ((points[j].x * points[i].y + 2 * points[j].x * points[j].y + 2 * points[i].x * points[i].y + points[i].x * points[j].y) * a);
j = i; //j is previous vertex to i
}
Ixy /= 24;
return Ixy * density;
};
var polygon = new Polygon({
cx : 200,
cy : 200,
points : [
{ x : -10, y : 70 },
{ x : 50, y : 50 },
{ x : 100, y : 0 },
{ x : 80, y : -20 },
{ x : -30, y : -50 },
{ x : -80, y : 10 }
],
mass : 10000,
rotation : 0,
rotationalVelocity : Math.PI / 50
});
var ctx = (document.getElementById('c')).getContext('2d')
//Math timing
var lastTime = (new Date()).getTime();
var thisTime = 0;
var timeElapsed = 0;
var timeInterval = 1000; //1 second
function update () {
thisTime = (new Date()).getTime();
timeElapsed = thisTime - lastTime;
//Hand the change in time since the last update; this is
// used to calculate incrementally for smooth animation.
polygon.update(timeElapsed / 1000);
lastTime = thisTime;
//Make sure updates happen at least as often as the max
// potential likely framerate (60fps here).
setTimeout(update, 1000 / 60);
}
//We draw as often as the API lets us; thanks to the update
// function, we always have a value to draw that makes sense.
function draw () {
ctx.clearRect(0, 0, 400, 400);
polygon.draw(ctx);
requestAnimationFrame(draw);
}
/*
* Creates a polygon with notional center of mass at cx,cy.
* Points determine vertices as vectors from the center.
*...