Velocity Verlet Physics Object
A simple physics object that is updated by Velocity Verlet Integration.
by Carl Baumann
HTML
<canvas id="myCanvas" width="640" height="640"></canvas>
CSS
canvas { background: #eee; }
JavaScript
/* near constant acceleration velocity verlet integration, error of dAcc*dt*dt
pos += vel*dt + 0.5*acc*dt*dt;
vel += acc*dt
*/
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
let t0 = performance.now();
let config={
gravity : new Vector2(0,98),
wallDrag : 0.9
};
function Vector2(x=0,y=0) {
this.x = x;
this.y = y;
this.str = function() {
return "x: " + this.x + " y:" + this.y;
}
this.magnitude = function() {
return Math.sqrt(this.x*this.x + this.y*this.y);
}
this.sqrdMagnitude = function() {
return (this.x*this.x + this.y*this.y);
}
this.normalized = function() {
let temp = new Vector2();
temp.x = this.x / this.magnitude();
temp.y = this.y / this.magnitude();
return temp;
}
this.add = function(v2) {
let temp = new Vector2();
temp.x = this.x + v2.x;
temp.y = this.y + v2.y;
return temp;
}
this.subtract = function(v2) {
let temp = new Vector2();
temp.x = this.x - v2.x;
temp.y = this.y - v2.y;
return temp;
}
this.scale = function(scl) {
let temp = new Vector2();
temp.x = this.x * scl;
temp.y = this.y * scl;
return temp;
}
this.dot = function(v2) {
return this.x*v2.x + this.y*v2.y;
}
}
function PhysicsObject(pos, mass, vel = new Vector2(),acc = new Vector2()) {
this.pos = pos;
this.mass = mass;
this.vel = vel;
this.acc = acc;
this.forces = [];
this.netForce = new Vector2(0,0);
this.gravForce = config.gravity.scale(this.mass);
this.addForce = function(f) {
this.netForce = this.netForce.add(f);
}
this.clearForces = function() {
this.forces = [];
this.netForce.x = 0;
this.netForce.y = 0;
}
this.step = function(dt) {
this.pos = this.pos.add(this.vel.scale(dt));//.add(this.acc.scale(0.5*dt*dt)));
/* console.log("POS: "+this.pos.str()); */
this.vel = this.vel.add(this.acc.scale(dt));
/* console.log("VEL: "+this.vel.str()); */
...