xxxxxxxxxx
139
let ball = {
pos: {x: 0, y:0},
vel: {x:0, y:0},
radius: 10,
mass: 11
}
let prev_ball;
const G = {x:0, y:9.8};
let dt = 0.01;
let currentTime;
let accumulator = 0.0;
function setup() {
createCanvas(400, 400);
ball.pos = {x: width/2, y:20};
currentTime = millis() /1000;
prev_ball = ball;
mainLoop();
}
const verlet_integration = (obj, acc, dt) => {
obj.pos.y += dt * (obj.vel.y * acc.y /2);
obj.vel.y += dt * (acc.y + acc.y) /2;
obj.pos.x += dt * (obj.vel.x * acc.x /2);
obj.vel.x += dt * (acc.x + acc.x) /2;
}
const getAcceleration = (force, mass) => {
return {x:force.x/mass , y: force.y/mass};
}
function render(obj) {
background(12);
ellipseMode(CENTER);
fill(255);
ellipse(obj.pos.x, obj.pos.y, obj.radius, obj.radius)
}
const lerpp = (a, b, mu) => {
return a * mu + b * (1-mu)
}
function simulate(dt) {
let force = {x:0, y: 0};
let acc = getAcceleration(force, ball.mass);
acc.x += G.x;
acc.y += G.y;
verlet_integration(ball, acc, dt);
if(ball.pos.y > height) {
ball.pos.y = 0;
ball.pos.x = random(0, width);
ball.vel.x = 0;
ball.vel.y = 0;
}
}
let tickCount = 0;
function mainLoop() {
simulate(dt);
tickCount++;
setInterval(mainLoop, 100);
}
function mousePressed() {
dt = 1/61;
}
function mouseReleased() {
dt = 0.01;
}
function draw() {
let newTime = millis() /1000;
let frameTime = newTime - currentTime;
if ( frameTime > 0.25 )
frameTime = 0.25;
currentTime = newTime;
accumulator += (frameTime);
while (accumulator >= dt ) {
prev_ball = ball;
prev_ball.pos.x = ball.pos.x;
prev_ball.pos.y = ball.pos.y;
prev_ball.vel.x = ball.vel.x;
prev_ball.vel.y = ball.vel.y;
//simulate(dt);
accumulator -= dt;
}
const mu = accumulator /dt;
let newBall_x = lerpp(ball.pos.x, prev_ball.pos.x, mu);
let newBall_y = lerpp(ball.pos.y, prev_ball.pos.y, mu);
let newBall = ball;
newBall.pos = {x: newBall_x, y:newBall_y};
render(newBall);
}