EduCSE Blog

Share

Position Verlet Algorithm

Author: Win Aung Cho
Position Verlet Algorithm

Acceleration can be calculated from acting force on to the particle divided by mass of particle.

x(t+Δt)=2x(t)-x(t-Δt)+Δt²•F(x(t))/m + O[Δt⁴]
v(t)=1/(2Δt)•[x(t+Δt) - x(t-Δt)] + O[Δt²]
Following class defined for the particle model as a point object without mass, damping and friction.
Gravitational acceleration is included in motion.
class Point {
		constructor(x, y, vx, vy) {
			this.pos = new Vector(x, y);
			this.oldpos = new Vector(x + (vx || 0), y + (vy || 0)); // velocity x, y
			this.radius = 15;
			this.color = "e62a4f";
			this.fixed = false;
		}
		update() {
		    if (this.fixed) return;
			let vel = SUB(this.pos, this.oldpos);
			this.oldpos.set(this.pos.x, this.pos.y);
			this.pos.add(vel);
			this.pos.add(MUL(Gravity, stepTime*stepTime));
		}
		checkborder() {
		    if (this.fixed) return;
			let vel = SUB(this.pos, this.oldpos);
			
			if(this.pos.x > CANVAS_WIDTH - this.radius) {
				this.pos.x = CANVAS_WIDTH - this.radius;
				this.oldpos.x = this.pos.x + vel.x;
			}
			if(this.pos.x < this.radius) {
				this.pos.x = this.radius;
				this.oldpos.x = this.pos.x + vel.x;
			}
			if(this.pos.y > CANVAS_HEIGHT - this.radius) {
				this.pos.y = CANVAS_HEIGHT - this.radius;
				this.oldpos.y = this.pos.y + vel.y;
			}
			if(this.pos.y < this.radius) {
				this.pos.y = this.radius;
				this.oldpos.y = this.pos.y + vel.y;
			}
		};
		render(ctx) {
			ctx.beginPath();
			ctx.fillStyle = this.color;
			ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2);
			ctx.fill();
			ctx.closePath();
		}
	}
Process loop is defined by following function.

function animate() {
		ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
		for(let d of dots) {
			d.update();
			d.checkborder();
			d.render(ctx);
		}
		requestAnimationFrame(animate);
	}



Demo


Author: Win Aung Cho
12-Jun-2022 08:21:56 PM*