Apply gravity between two or more objects in HTML5 Canvas

JavascriptWeb DevelopmentFront End Scripts

To apply gravity between two or more object in Canvas:

var distX = ob1.x - ob2.x,
distY = ob1.y - ob2.y;

var val = distX *distX + distY * distY;
var r = Math.sqrt(val);
var F = 50 / val;

var rhat_x = distX / r;
var rhat_y = distY / r;

var Fx = F * rhat_x;
var Fy = F * rhat_y;

ob1.vx += -Fx;
ob1.vy += -Fy;

ob2.vx += Fx;
ob2.vy += Fy;
raja
Published on 10-Apr-2018 16:13:25
Advertisements