The Idea
I came across this idea of multiplication circles from a YouTube video that I stumbled upon and I thought that would be a fun thing to try and recreate using JavasSript and the canvas element.
The Original Video
The Problem
I smoothed out the animation the best I could but it still doesn't look as proper as I'd like. I suspect coming up with a solution would require a decent amount of math. To grasp the problem in detail I think it's easier to look at the code
window.onload = () => {
const app = document.querySelector('#app')
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const { cos, sin, PI } = Math
const Tao = PI * 2
const width = window.innerWidth
const height = window.innerHeight
const cx = width / 2
const cy = height / 2
const baseNumberingSystem = 200
const stop = 34
let color = 'teal'
let multiplier = 0
let drawQue = []
// setup canvas
canvas.width = width
canvas.height = height
class Circle {
constructor(x, y, r, strokeColor, fillColor) {
this.x = x
this.y = y
this.r = r
this.strokeColor = strokeColor || '#fff'
this.fillColor = fillColor || '#fff'
}
draw(stroke, fill) {
ctx.moveTo(this.x, this.y)
ctx.beginPath()
ctx.arc(this.x, this.y, this.r, 0, Tao)
ctx.closePath()
if (fill) {
ctx.fillStyle = this.fillColor
ctx.fill()
}
if (stroke) {
ctx.strokeStyle = this.strokeColor
ctx.stroke()
}
}
createChildCircleAt(degree, radius, strokeColor, fillColor) {
const radian = degreeToRadian(degree)
const x = this.x + (this.r * cos(radian))
const y = this.y + (this.r * sin(radian))
return new Circle(x, y, radius, strokeColor, fillColor)
}
divideCircle(nTimes, radius) {
const degree = 360 / nTimes
let division = 1;
while (division <= nTimes) {
drawQue.push(this.createChildCircleAt(division * degree, radius))
division++
}
}
}
function degreeToRadian(degree) {
return degree * (PI / 180)
}
function draw() {
const mainCircle = new Circle(cx, cy, cy * 0.9)
// empty the que
drawQue = []
// clear canvas
ctx.clearRect(0, 0, width, height)
ctx.fillStyle = "black"
ctx.fillRect(0, 0, width, height)
// redraw everything
mainCircle.draw()
mainCircle.divideCircle(baseNumberingSystem, 4)
drawQue.forEach(item => item.draw())
// draw modular times table
for (let i = 1; i <= drawQue.length; i++) {
const product = i * multiplier;
const firstPoint = drawQue[i]
const secondPoint = drawQue[product % drawQue.length]
if (firstPoint && secondPoint) {
ctx.beginPath()
ctx.moveTo(firstPoint.x, firstPoint.y)
ctx.strokeStyle = color
ctx.lineTo(secondPoint.x, secondPoint.y)
ctx.closePath()
ctx.stroke()
}
}
}
function animate() {
multiplier+= 0.1
multiplier = parseFloat(multiplier.toFixed(2))
draw()
console.log(multiplier, stop)
if (multiplier === stop) {
clearInterval(animation)
}
}
app.appendChild(canvas)
let animation = setInterval(animate, 120)
}
So the main issue comes from when we increment the multiplier by values less than 1 in an attempt to make the animation more fluid feeling. Example: multiplier+= 0.1. When we do this it increase the amount of times our if block in our draw function will fail because the secondPoint will return null.
const product = i * multiplier; // this is sometimes a decimal
const firstPoint = drawQue[i]
const secondPoint = drawQue[product % drawQue.length] // therefore this will often not be found
// Then this if block wont execute. Which is good because if it did we the code would crash
// But I think what we need is an if clause to still draw a line to a value in between the two
// closest indices of our drawQue
if (firstPoint && secondPoint) {
//...
}
Possible Solution
I think what I'd need to do is when we fail to find the secondPoint get the remainder of product % drawQue.length and use that to create a new circle in between the two closest circles in the drawQue array and use that new circle as the second point of our line.
If you use requestAnimationFrame it looks smooth
function animate() {
if (multiplier != stop) {
multiplier+= 0.1
multiplier = parseFloat(multiplier.toFixed(2))
draw()
requestAnimationFrame(animate);
}
}
app.appendChild(canvas)
animate()
My possible solution ended up working. I'll leave the added else if block here for anyone whos interested. I also had to store the degree value in my circle objects when they were made as well as calculate the distance between each subdivision of the circle.
Added If Else Statement
for (let i = 1; i <= drawQue.length; i++) {
const product = i * multiplier;
const newIndex = product % drawQue.length
const firstPoint = drawQue[i]
const secondPoint = drawQue[newIndex]
if (firstPoint && secondPoint) {
ctx.beginPath()
ctx.moveTo(firstPoint.x, firstPoint.y)
ctx.strokeStyle = color
ctx.lineTo(secondPoint.x, secondPoint.y)
ctx.closePath()
ctx.stroke()
} else if (!secondPoint) {
const percent = newIndex % 1
const closest = drawQue[Math.floor(newIndex)]
const newDegree = closest.degree + (degreeIncriments * percent)
const target = mainCircle.createChildCircleAt(newDegree, 4)
if (firstPoint && target) {
ctx.beginPath()
ctx.moveTo(firstPoint.x, firstPoint.y)
ctx.strokeStyle = color
ctx.lineTo(target.x, target.y)
ctx.closePath()
ctx.stroke()
}
}
Other changes
// ...
const degreeIncriments = 360 / baseNumberingSystem
// ...
class Circle {
constructor(/* ... */, degree )
// ...
this.degree = degree || 0
}
Hope someone finds this useful...
I'm working on an HTML Canvas demo to learn more about circle to circle collision detection and response. I believe that the detection code is correct but the response math is not quite there.
The demo has been implemented using TypeScript, which is a typed superset of JavaScript that is transpiled to plain JavaScript.
I believe that the problem exists within the checkCollision method of the Circle class, specifically the math for calculating the new velocity.
The blue circle position is controlled by the mouse (using an event listener). If the red circle collides from the right side of the blue circle, the collision response seems to work correctly, but if it approaches from the left it does not respond correctly.
I am looking for some guidance on how I can revise the checkCollision math to correctly handle the collision from any angle.
Here is a CodePen for a live demo and dev environment:
CodePen
class DemoCanvas {
canvasWidth: number = 500;
canvasHeight: number = 500;
canvas: HTMLCanvasElement = document.createElement('canvas');
constructor() {
this.canvas.width = this.canvasWidth;
this.canvas.height = this.canvasHeight;
this.canvas.style.border = '1px solid black';
this.canvas.style.position = 'absolute';
this.canvas.style.left = '50%';
this.canvas.style.top = '50%';
this.canvas.style.transform = 'translate(-50%, -50%)';
document.body.appendChild(this.canvas);
}
clear() {
this.canvas.getContext('2d').clearRect(0, 0, this.canvas.width, this.canvas.height);
}
getContext(): CanvasRenderingContext2D {
return this.canvas.getContext('2d');
}
getWidth(): number {
return this.canvasWidth;
}
getHeight(): number {
return this.canvasHeight;
}
getTop(): number {
return this.canvas.getBoundingClientRect().top;
}
getRight(): number {
return this.canvas.getBoundingClientRect().right;
}
getBottom(): number {
return this.canvas.getBoundingClientRect().bottom;
}
getLeft(): number {
return this.canvas.getBoundingClientRect().left;
}
}
class Circle {
x: number;
y: number;
xVelocity: number;
yVelocity: number;
radius: number;
color: string;
canvas: DemoCanvas;
context: CanvasRenderingContext2D;
constructor(x: number, y: number, xVelocity: number, yVelocity: number, color: string, gameCanvas: DemoCanvas) {
this.radius = 20;
this.x = x;
this.y = y;
this.xVelocity = xVelocity;
this.yVelocity = yVelocity;
this.color = color;
this.canvas = gameCanvas;
this.context = this.canvas.getContext();
}
public draw(): void {
this.context.fillStyle = this.color;
this.context.beginPath();
this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
this.context.fill();
}
public move(): void {
this.x += this.xVelocity;
this.y += this.yVelocity;
}
checkWallCollision(gameCanvas: DemoCanvas): void {
let top = 0;
let right = 500;
let bottom = 500;
let left = 0;
if(this.y < top + this.radius) {
this.y = top + this.radius;
this.yVelocity *= -1;
}
if(this.x > right - this.radius) {
this.x = right - this.radius;
this.xVelocity *= -1;
}
if(this.y > bottom - this.radius) {
this.y = bottom - this.radius;
this.yVelocity *= -1;
}
if(this.x < left + this.radius) {
this.x = left + this.radius;
this.xVelocity *= -1;
}
}
checkCollision(x1: number, y1: number, r1: number, x2: number, y2: number, r2: number) {
let distance: number = Math.abs((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
// Detect collision
if(distance < (r1 + r2) * (r1 + r2)) {
// Respond to collision
let newVelocityX1 = (circle1.xVelocity + circle2.xVelocity) / 2;
let newVelocityY1 = (circle1.yVelocity + circle1.yVelocity) / 2;
circle1.x = circle1.x + newVelocityX1;
circle1.y = circle1.y + newVelocityY1;
circle1.xVelocity = newVelocityX1;
circle1.yVelocity = newVelocityY1;
}
}
}
let demoCanvas = new DemoCanvas();
let circle1: Circle = new Circle(250, 250, 5, 5, "#F77", demoCanvas);
let circle2: Circle = new Circle(250, 540, 5, 5, "#7FF", demoCanvas);
addEventListener('mousemove', function(e) {
let mouseX = e.clientX - demoCanvas.getLeft();
let mouseY = e.clientY - demoCanvas.getTop();
circle2.x = mouseX;
circle2.y = mouseY;
});
function loop() {
demoCanvas.clear();
circle1.draw();
circle2.draw();
circle1.move();
circle1.checkWallCollision(demoCanvas);
circle2.checkWallCollision(demoCanvas);
circle1.checkCollision(circle1.x, circle1.y, circle1.radius, circle2.x, circle2.y, circle2.radius);
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
Elasic 2D collision
The problem is likely because the balls do not move away from each other and then in the next frame they are still overlapping and it gets worse. My guess from just looking at the code.
A simple solution.
Before you can have the two balls change direction you must ensure that they are positioned correctly. They must be just touching, (no overlay) or they can get caught up in each other.
Detect collision, and fix position.
// note I am using javascript.
// b1,b2 are the two balls or circles
// b1.dx,b1.dy are velocity (deltas) to save space same for b2
// get dist between them
// first vect from one to the next
const dx = b2.x - b1.x;
const dy = b2.y - b1.y;
// then distance
const dist = Math.sqrt(dx*dx + dy*dy);
// then check overlap
if(b1.radius + b2.radius >= dist){ // the balls overlap
// normalise the vector between them
const nx = dx / dist;
const ny = dy / dist;
// now move each ball away from each other
// along the same line as the line between them
// Use the ratio of the radius to work out where they touch
const touchDistFromB1 = (dist * (b1.radius / (b1.radius + b2.radius)))
const contactX = b1.x + nx * touchDistFromB1;
const contactY = b1.y + ny * touchDistFromB1;
// now move each ball so that they just touch
// move b1 back
b1.x = contactX - nx * b1.radius;
b1.y = contactY - ny * b1.radius;
// and b2 in the other direction
b2.x = contactX + nx * b2.radius;
b2.y = contactY + ny * b2.radius;
If one is static
If one of the balls is static then you can keep its position and move the other ball.
// from contact test for b1 is immovable
if(b1.radius + b2.radius >= dist){ // the balls overlap
// normalise the vector between them
const nx = dx / dist;
const ny = dy / dist;
// move b2 away from b1 along the contact line the distance of the radius summed
b2.x = b1.x + nx * (b1.radius + b2.radius);
b2.y = b1.y + ny * (b1.radius + b2.radius);
Now you have the balls correctly separated a you can calculate the new trajectories
Changing the trajectories.
There are a wide variety of ways to do this, but the one I like best is the elastic collision. I created a function from the Elastic collision in Two dimensional space wiki source and have been using it in games for some time.
The function and information is in the snippet at the bottom.
Next I will show how to call the function continuing on from the code above
// get the direction and velocity of each ball
const v1 = Math.sqrt(b1.dx * b1.dx + b1.dy * b1.dy);
const v2 = Math.sqrt(b2.dx * b2.dx + b2.dy * b2.dy);
// get the direction of travel of each ball
const dir1 = Math.atan2(b1.dy, b1.dx);
const dir2 = Math.atan2(b2.dy, b2.dx);
// get the direction from ball1 center to ball2 cenet
const directOfContact = Math.atan2(ny, nx);
// You will also need a mass. You could use the area of a circle, or the
// volume of a sphere to get the mass of each ball with its radius
// this will make them react more realistically
// An approximation is good as it is the ratio not the mass that is important
// Thus ball are spheres. Volume is the cubed radius
const mass1 = Math.pow(b1.radius,3);
const mass1 = Math.pow(b2.radius,3);
And finally you can call the function
ellastic2DCollistionD(b1, b2, v1, v2, d1, d2, directOfContact, mass1, mass2);
And it will correctly set the deltas of both balls.
Moving the ball position along their deltas is done after the collision function
b1.x += b1.dx;
b1.y += b1.dy;
b2.x += b1.dx;
b2.y += b1.dy;
If one of the balls is static you just ignore the deltas.
Elasic 2D collision function
Derived from information at Elastic collision in Two dimensional space wiki
// obj1, obj2 are the object that will have their deltas change
// velocity1, velocity2 is the velocity of each
// dir1, dir2 is the direction of travel
// contactDir is the direction from the center of the first object to the center of the second.
// mass1, mass2 is the mass of the first and second objects.
//
// function ellastic2DCollistionD(obj1, obj2, velocity1, velocity2, dir1, dir2, contactDir, mass1, mass2){
// The function applies the formula below twice, once fro each object, allowing for a little optimisation.
// The formula of each object's new velocity is
//
// For 2D moving objects
// v1,v2 is velocity
// m1, m2 is the mass
// d1 , d2 us the direction of moment
// p is the angle of contact;
//
// v1* cos(d1-p) * (m1 - m2) + 2 * m2 * v2 * cos(d2- p)
// vx = ----------------------------------------------------- * cos(p) + v1 * sin(d1-p) * cos(p + PI/2)
// m1 + m2
// v1* cos(d1-p) * (m1 - m2) + 2 * m2 * v2 * cos(d2- p)
// vy = ----------------------------------------------------- * sin(p) + v1 * sin(d1-p) * sin(p + PI/2)
// m1 + m2
// More info can be found at https://en.wikipedia.org/wiki/Elastic_collision#Two-dimensional
// to keep the code readable I use abbreviated names
function ellastic2DCollistionD(obj1, obj2, v1, v2, d1, d2, cDir, m1, m2){
const mm = m1 - m2;
const mmt = m1 + m2;
const v1s = v1 * Math.sin(d1 - cDir);
const cp = Math.cos(cDir);
const sp = Math.sin(cDir);
var cdp1 = v1 * Math.cos(d1 - cDir);
var cdp2 = v2 * Math.cos(d2 - cDir);
const cpp = Math.cos(cDir + Math.PI / 2)
const spp = Math.sin(cDir + Math.PI / 2)
var t = (cdp1 * mm + 2 * m2 * cdp2) / mmt;
obj1.dx = t * cp + v1s * cpp;
obj1.dy = t * sp + v1s * spp;
cDir += Math.PI;
const v2s = v2 * Math.sin(d2 - cDir);
cdp1 = v1 * Math.cos(d1 - cDir);
cdp2 = v2 * Math.cos(d2 - cDir);
t = (cdp2 * -mm + 2 * m1 * cdp1) / mmt;
obj2.dx = t * -cp + v2s * -cpp;
obj2.dy = t * -sp + v2s * -spp;
}
Note just realized that you are using a typeScript and the function above is specifically type agnostic. Does not care about obj1, obj2 type, and will add the deltas to any object that you pass.
You will have to change the function for typeScript.
The velocity vector should change by a multiple of the normal vector at the collision point, which is also the normalized vector between the circle mid points.
There are several posts here and elsewhere on elastic circle collisions and the computation of the impulse exchange (for instance Collision of circular objects, with jsfiddle for planet billiard https://stackoverflow.com/a/23671054/3088138).
If circle2 is bound to the mouse, then the event listener should also update the velocity using the difference to the previous point and the difference of time stamps, or better some kind of moving average thereof. The mass of this circle in the collision formulas is to be considered infinite.
As you are using requestAnimationFrame, the spacing of the times it is called is to be considered random. It would be better to use actual time stamps and some effort at implementing the Euler method (or whatever the resulting order 1 integration method amounts to) using the actual time increments. The collision procedure should not contain a position update, as that is the domain of the integration step, which in turn makes it necessary to add a test that the disks are actually moving together.
I'm making a game in javascript using EaselJS. I've run into problems with collision detection.
I'm using this for hit detection (as I'm checking if shapes hit, not just points) https://github.com/olsn/Collision-Detection-for-EaselJS
Which seems to work great, but for some reason the coordinates of different shapes always seem 'off'. I had the exact same problem without olsns collision detection. I think this is because they are in different coordinate spaces but I've no idea how to get uniform coordinates. Ideally I want everything using the same coordinate system, there is only keyboard interaction so mouse coordinates do not really matter.
I've messed around with localtoglobal, globaltolocal and localtolocal but nothing seems to work as needed.
I feel like I'm missing something important in how easelJS handles coordinates.
Here's some (relevant) code:
window.stage = new createjs.Stage("CanvasGeo");
function drawShip() {
// Initializes ship graphics
shipG = new createjs.Shape();
shipG.graphics.beginFill("DeepSkyBlue").drawCircle(x, y, circlesize);
stage.addChild(shipG);
}
function drawShape() {
shapeG = new createjs.Shape();
if (type == "Rect") {
shapeG.graphics.beginFill(colour).drawRect(x, y, shapesize, shapesize);
} else if (type == "Triangle") {
shapeG.graphics.beginFill(colour).drawPolyStar(x, y, shapesize, 3, 0.5, getRandomInt(1, 359));
} else if (type == "Star") {
shapeG.graphics.beginFill(colour).drawPolyStar(x, y, shapesize, 5, 0.7, getRandomInt(1, 359));
}
stage.addChild(shapeG);
}
function findSpawnPoint() {
var direction = getRandomInt(1, 5);
switch (direction) {
// TOP
case 1:
console.log("Spawn shape on top");
x = getRandomInt((shapesize * 2), canvasWidth - (shapesize * 2));
y = -1 * shapesize;
xVel = getRandomSpeed();
yVel = Math.abs(getRandomSpeed());
break;
// LEFT
case 2:
console.log("Spawn shape on left");
x = -1 * shapesize;
y = getRandomInt((shapesize * 2), canvasHeight - (shapesize * 2));
xVel = Math.abs(getRandomSpeed());
yVel = getRandomSpeed();
break;
// RIGHT
case 3:
console.log("Spawn shape on right");
x = shapesize + canvasWidth;
y = getRandomInt((shapesize * 2), canvasHeight - (shapesize * 2));
xVel = -1 * Math.abs(getRandomSpeed());
yVel = getRandomSpeed();
break;
// BOTTOM
case 4:
console.log("Spawn shape on bottom");
x = getRandomInt((shapesize * 2), canvasWidth - (shapesize * 2));
y = shapesize + canvasHeight;
xVel = getRandomSpeed();
yVel = -1 * Math.abs(getRandomSpeed());
break;
}
}
this.hitCheck = function(ship) {
if (!null == ndgmr.checkRectCollision(shapeG, ship)) {
this.hitAction();
}
}
Thanks for any help :)
I've got the linear component of collision resolution down relatively well, but I can't quite figure out how to do the same for the angular one. From what I've read, it's something like... torque = point of collision x linear velocity. (cross product) I tried to incorporate an example I found into my code but I actually don't see any rotation at all when objects collide. The other fiddle works perfectly with a rudimentary implementation of the seperating axis theorem and the angular velocity calculations. Here's what I've come up with...
Property definitions (orientation, angular velocity, and angular acceleration):
rotation: 0,
angularVelocity: 0,
angularAcceleration: 0
Calculating the angular velocity in the collision response:
var pivotA = this.vector(bodyA.x, bodyA.y);
bodyA.angularVelocity = 1 * 0.2 * (bodyA.angularVelocity / Math.abs(bodyA.angularVelocity)) * pivotA.subtract(isCircle ? pivotA.add(bodyA.radius) : {
x: pivotA.x + boundsA.width,
y: pivotA.y + boundsA.height
}).vCross(bodyA.velocity);
var pivotB = this.vector(bodyB.x, bodyB.y);
bodyB.angularVelocity = 1 * 0.2 * (bodyB.angularVelocity / Math.abs(bodyB.angularVelocity)) * pivotB.subtract(isCircle ? pivotB.add(bodyB.radius) : {
x: pivotB.x + boundsB.width,
y: pivotB.y + boundsB.height
}).vCross(bodyB.velocity);
Updating the orientation in the update loop:
var torque = 0;
torque += core.objects[o].angularVelocity * -1;
core.objects[o].angularAcceleration = torque / core.objects[o].momentOfInertia();
core.objects[o].angularVelocity += core.objects[o].angularAcceleration;
core.objects[o].rotation += core.objects[o].angularVelocity;
I would post the code that I have for calculating the moments of inertia but there's a seperate one for every object so that would be a bit... lengthy. Nonetheless, here's the one for a circle as an example:
return this.mass * this.radius * this.radius / 2;
Just to show the result, here's my fiddle. As shown, objects do not rotate on collision. (not exactly visible with the circles, but it should work for the zero and seven)
What am I doing wrong?
EDIT: Reason they weren't rotating at all was because of an error with groups in the response function -- it rotates now, just not correctly. However, I've commented that out for now as it messes things up.
Also, I've tried another method for rotation. Here's the code in the response:
_bodyA.angularVelocity = direction.vCross(_bodyA.velocity) / (isCircle ? _bodyA.radius : boundsA.width);
_bodyB.angularVelocity = direction.vCross(_bodyB.velocity) / (isCircle ? _bodyB.radius : boundsB.width);
Note that direction refers to the "collision normal".
Angular and linear acceleration due to force vector
Angular and directional accelerations due to an applied force are two components of the same thing and can not be separated. To get one you need to solve for both.
Define the calculations
From simple physics and standing on shoulders we know the following.
F is force (equivalent to inertia)
Fv is linear force
Fa is angular force
a is acceleration could be linear or rotational depending on where it is used
v is velocity. For angular situations it is the tangential component only
m is mass
r is radius
For linear forces
F = m * v
From which we derive
m = F / v
v = F / m
For rotational force (v is tangential velocity)
F = r * r * m * (v / r) and simplify F = r * m * v
From which we derive
m = F / ( r * v )
v = F / ( r * m )
r = F / ( v * m )
Because the forces we apply are instantaneous we can interchange a acceleration and v velocity to give all the following formulas
Linear
F = m * a
m = F / a
a = F / m
Rotational
F = r * m * a
m = F / ( r * a )
a = F / ( r * m )
r = F / ( a * m )
As we are only interested in the change in velocity for both linear and rotation solutions
a1 = F / m
a2 = F / ( r * m )
Where a1 is acceleration in pixels per frame2 and a2 is acceleration in radians per frame2 ( the frame squared just denotes it is acceleration)
From 1D to 2D
Because this is a 2D solution and all above are 1D we need to use vectors. I for this problem use two forms of the 2D vector. Polar that has a magnitude (length, distance, the like...) and direction. Cartesian which has x and y. What a vector represents depends on how it is used.
The following functions are used as helpers in the solution. They are written in ES6 so for non compliant browsers you will have to adapt them, though I would not ever suggest you use these as they are written for convenience, they are very inefficient and do a lot of redundant calculations.
Converts a vector from polar to cartesian returning a new one
function polarToCart(pVec, retV = {x : 0, y : 0}) {
retV.x = Math.cos(pVec.dir) * pVec.mag;
retV.y = Math.sin(pVec.dir) * pVec.mag;
return retV;
}
Converts a vector from cartesian to polar returning a new one
function cartToPolar(vec, retV = {dir : 0, mag : 0}) {
retV.dir = Math.atan2(vec.y, vec.x);
retV.mag = Math.hypot(vec.x, vec.y);
return retV;
}
Creates a polar vector
function polar(mag = 1, dir = 0) {
return validatePolar({dir : dir,mag : mag});
}
Create a vector as a cartesian
function vector(x = 1, y = 0) {
return {x : x, y : y};
}
True is the arg vec is a vector in polar form
function isPolar(vec) {
if (vec.mag !== undefined && vec.dir !== undefined) {return true;}
return false;
}
Returns true if arg vec is a vector in cartesian form
function isCart(vec) {
if (vec.x !== undefined && vec.y !== undefined) {return true;}
return false;
}
Returns a new vector in polar form also ensures that vec.mag is positive
function asPolar(vec){
if(isCart(vec)){ return cartToPolar(vec); }
if(vec.mag < 0){
vec.mag = - vec.mag;
vec.dir += PI;
}
return { dir : vec.dir, mag : vec.mag };
}
Copy and converts an unknown vec to cart if not already
function asCart(vec){
if(isPolar(vec)){ return polarToCart(vec); }
return { x : vec.x, y : vec.y};
}
Calculations can result in a negative magnitude though this is valid for some calculations this results in the incorrect vector (reversed) this simply validates that the polar vector has a positive magnitude it does not change the vector just the sign and direction
function validatePolar(vec) {
if (isPolar(vec)) {
if (vec.mag < 0) {
vec.mag = - vec.mag;
vec.dir += PI;
}
}
return vec;
}
The Box
Now we can define an object that we can use to play with. A simple box that has position, size, mass, orientation, velocity and rotation
function createBox(x,y,w,h){
var box = {
x : x, // pos
y : y,
r : 0.1, // its rotation AKA orientation or direction in radians
h : h, // its height
w : w, // its width
dx : 0, // delta x in pixels per frame 1/60th second
dy : 0, // delta y
dr : 0.0, // deltat rotation in radians per frame 1/60th second
mass : w * h, // mass in things
update :function(){
this.x += this.dx;
this.y += this.dy;
this.r += this.dr;
},
}
return box;
}
Applying a force to an object
So now we can redefine some terms
F (force) is a vector force the magnitude is the force and it has a direction
var force = polar(100,0); // create a force 100 units to the right (0 radians)
The force is meaningless without a position where it is applied.
Position is a vector that just holds and x and y location
var location = vector(canvas.width/2, canvas.height/2); // defines a point in the middle of the canvas
Directional vector holds the direction and distance between to positional vectors
var l1 = vector(canvas.width/2, canvas.height/2); // defines a point in the middle of the canvas
var l2 = vector(100,100);
var direction = asPolar(vector(l2.x - l1.x, l2.y - l1.y)); // get the direction as polar vector
direction now has the direction from canvas center to point (100,100) and the distance.
The last thing we need to do is extract the components from a force vector along a directional vector. When you apply a force to an object the force is split into two, one is the force along the line to the object center and adds to the object acceleration, the other force is at 90deg to the line to the object center (the tangent) and that is the force that changes rotation.
To get the two components you get the difference in direction between the force vector and the directional vector from where the force is applied to the object center.
var force = polar(100,0); // the force
var forceLoc = vector(50,50); // the location the force is applied
var direction2Center = asPolar(vector(box.x - forceLoc.x, box.y - forceLoc.y)); // get the direction as polar vector
var pheta = direction2Center - force.dir; // get the angle between the force and object center
Now that you have that angle pheta the force can be split into its rotational and linear components with trig.
var F = force.mag; // get the force magnitude
var Fv = Math.cos(pheta) * F; // get the linear force
var Fa = Math.sin(pheta) * F; // get the angular force
Now the forces can be converted back to accelerations for linear a = F/m and angular a = F/(m*r)
accelV = Fv / box.mass; // linear acceleration in pixels
accelA = Fa / (box.mass * direction2Center.mag); // angular acceleration in radians
You then convert the linear force back to a vector that has a direction to the center of the object
var forceV = polar(Fv, direction2Center);
Convert is back to the cartesian so we can add it to the object deltaX and deltaY
forceV = asCart(forceV);
And add the acceleration to the box
box.dx += forceV.x;
box.dy += forceV.y;
Rotational acceleration is just one dimensional so just add it to the delta rotation of the box
box.dr += accelA;
And that is it.
Function to apply force to Box
The function if attached to the box will apply a force vector at a location to the box.
Attach to the box like so
box.applyForce = applyForce; // bind function to the box;
You can then call the function via the box
box.applyForce(force, locationOfForce);
function applyForce(force, loc){ // force is a vector, loc is a coordinate
var toCenter = asPolar(vector(this.x - loc.x, this.y - loc.y)); // get the vector to the center
var pheta = toCenter.dir - force.dir; // get the angle between the force and the line to center
var Fv = Math.cos(pheta) * force.mag; // Split the force into the velocity force along the line to the center
var Fa = Math.sin(pheta) * force.mag; // and the angular force at the tangent to the line to the center
var accel = asPolar(toCenter); // copy the direction to center
accel.mag = Fv / this.mass; // now use F = m * a in the form a = F/m to get acceleration
var deltaV = asCart(accel); // convert acceleration to cartesian
this.dx += deltaV.x // update the box delta V
this.dy += deltaV.y //
var accelA = Fa / (toCenter.mag * this.mass); // for the angular component get the rotation
// acceleration from F=m*a*r in the
// form a = F/(m*r)
this.dr += accelA;// now add that to the box delta r
}
The Demo
The demo is only about the function applyForce the stuff to do with gravity and bouncing are only very bad approximations and should not be used for any physic type of stuff as they do not conserve energy.
Click and drag to apply a force to the object in the direction that the mouse is moved.
const PI90 = Math.PI / 2;
const PI = Math.PI;
const PI2 = Math.PI * 2;
const INSET = 10; // playfeild inset
const ARROW_SIZE = 6
const SCALE_VEC = 10;
const SCALE_FORCE = 0.15;
const LINE_W = 2;
const LIFE = 12;
const FONT_SIZE = 20;
const FONT = "Arial Black";
const WALL_NORMS = [PI90,PI,-PI90,0]; // dirction of the wall normals
var box = createBox(200, 200, 50, 100);
box.applyForce = applyForce; // Add this function to the box
// render / update function
var mouse = (function(){
function preventDefault(e) { e.preventDefault(); }
var i;
var mouse = {
x : 0, y : 0,buttonRaw : 0,
bm : [1, 2, 4, 6, 5, 3], // masks for setting and clearing button raw bits;
mouseEvents : "mousemove,mousedown,mouseup".split(",")
};
function mouseMove(e) {
var t = e.type, m = mouse;
m.x = e.offsetX; m.y = e.offsetY;
if (m.x === undefined) { m.x = e.clientX; m.y = e.clientY; }
if (t === "mousedown") { m.buttonRaw |= m.bm[e.which-1];
} else if (t === "mouseup") { m.buttonRaw &= m.bm[e.which + 2];}
e.preventDefault();
}
mouse.start = function(element = document){
if(mouse.element !== undefined){ mouse.removeMouse();}
mouse.element = element;
mouse.mouseEvents.forEach(n => { element.addEventListener(n, mouseMove); } );
}
mouse.remove = function(){
if(mouse.element !== undefined){
mouse.mouseEvents.forEach(n => { mouse.element.removeEventListener(n, mouseMove); } );
mouse.element = undefined;
}
}
return mouse;
})();
var canvas,ctx;
function createCanvas(){
canvas = document.createElement("canvas");
canvas.style.position = "absolute";
canvas.style.left = "0px";
canvas.style.top = "0px";
canvas.style.zIndex = 1000;
document.body.appendChild(canvas);
}
function resizeCanvas(){
if(canvas === undefined){
createCanvas();
}
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx = canvas.getContext("2d");
if(box){
box.w = canvas.width * 0.10;
box.h = box.w * 2;
box.mass = box.w * box.h;
}
}
window.addEventListener("resize",resizeCanvas);
resizeCanvas();
mouse.start(canvas)
var tempVecs = [];
function addTempVec(v,vec,col,life = LIFE,scale = SCALE_VEC){tempVecs.push({v:v,vec:vec,col:col,scale:scale,life:life,sLife:life});}
function drawTempVecs(){
for(var i = 0; i < tempVecs.length; i ++ ){
var t = tempVecs[i]; t.life -= 1;
if(t.life <= 0){tempVecs.splice(i, 1); i--; continue}
ctx.globalAlpha = (t.life / t.sLife)*0.25;
drawVec(t.v, t.vec ,t.col, t.scale)
}
}
function drawVec(v,vec,col,scale = SCALE_VEC){
vec = asPolar(vec)
ctx.setTransform(1,0,0,1,v.x,v.y);
var d = vec.dir;
var m = vec.mag;
ctx.rotate(d);
ctx.beginPath();
ctx.lineWidth = LINE_W;
ctx.strokeStyle = col;
ctx.moveTo(0,0);
ctx.lineTo(m * scale,0);
ctx.moveTo(m * scale-ARROW_SIZE,-ARROW_SIZE);
ctx.lineTo(m * scale,0);
ctx.lineTo(m * scale-ARROW_SIZE,ARROW_SIZE);
ctx.stroke();
}
function drawText(text,x,y,font,size,col){
ctx.font = size + "px "+font;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.setTransform(1,0,0,1,x,y);
ctx.globalAlpha = 1;
ctx.fillStyle = col;
ctx.fillText(text,0,0);
}
function createBox(x,y,w,h){
var box = {
x : x, // pos
y : y,
r : 0.1, // its rotation AKA orientation or direction in radians
h : h, // its height, and I will assume that its depth is always equal to its height
w : w, // its width
dx : 0, // delta x in pixels per frame 1/60th second
dy : 0, // delta y
dr : 0.0, // deltat rotation in radians per frame 1/60th second
getDesc : function(){
var vel = Math.hypot(this.dx ,this.dy);
var radius = Math.hypot(this.w,this.h)/2
var rVel = Math.abs(this.dr * radius);
var str = "V " + (vel*60).toFixed(0) + "pps ";
str += Math.abs(this.dr * 60 * 60).toFixed(0) + "rpm ";
str += "Va " + (rVel*60).toFixed(0) + "pps ";
return str;
},
mass : function(){ return (this.w * this.h * this.h)/1000; }, // mass in K things
draw : function(){
ctx.globalAlpha = 1;
ctx.setTransform(1,0,0,1,this.x,this.y);
ctx.rotate(this.r);
ctx.fillStyle = "#444";
ctx.fillRect(-this.w/2, -this.h/2, this.w, this.h)
ctx.strokeRect(-this.w/2, -this.h/2, this.w, this.h)
},
update :function(){
this.x += this.dx;
this.y += this.dy;
this.dy += 0.061; // alittle gravity
this.r += this.dr;
},
getPoint : function(which){
var dx,dy,x,y,xx,yy,velocityA,velocityT,velocity;
dx = Math.cos(this.r);
dy = Math.sin(this.r);
switch(which){
case 0:
x = -this.w /2;
y = -this.h /2;
break;
case 1:
x = this.w /2;
y = -this.h /2;
break;
case 2:
x = this.w /2;
y = this.h /2;
break;
case 3:
x = -this.w /2;
y = this.h /2;
break;
case 4:
x = this.x;
y = this.y;
}
var xx,yy;
xx = x * dx + y * -dy;
yy = x * dy + y * dx;
var details = asPolar(vector(xx, yy))
xx += this.x;
yy += this.y;
velocityA = polar(details.mag * this.dr, details.dir + PI90);
velocityT = vectorAdd(velocity = vector(this.dx, this.dy), velocityA);
return {
velocity : velocity, // only directional
velocityT : velocityT, // total
velocityA : velocityA, // angular only
pos : vector(xx, yy),
radius : details.mag,
}
},
}
box.mass = box.mass(); // Mass remains the same so just set it with its function
return box;
}
// calculations can result in a negative magnitude though this is valide for some
// calculations this results in the incorrect vector (reversed)
// this simply validates that the polat vector has a positive magnitude
// it does not change the vector just the sign and direction
function validatePolar(vec){
if(isPolar(vec)){
if(vec.mag < 0){
vec.mag = - vec.mag;
vec.dir += PI;
}
}
return vec;
}
// converts a vector from polar to cartesian returning a new one
function polarToCart(pVec, retV = {x : 0, y : 0}){
retV.x = Math.cos(pVec.dir) * pVec.mag;
retV.y = Math.sin(pVec.dir) * pVec.mag;
return retV;
}
// converts a vector from cartesian to polar returning a new one
function cartToPolar(vec, retV = {dir : 0, mag : 0}){
retV.dir = Math.atan2(vec.y,vec.x);
retV.mag = Math.hypot(vec.x,vec.y);
return retV;
}
function polar (mag = 1, dir = 0) { return validatePolar({dir : dir, mag : mag}); } // create a polar vector
function vector (x= 1, y= 0) { return {x: x, y: y}; } // create a cartesian vector
function isPolar (vec) { if(vec.mag !== undefined && vec.dir !== undefined) { return true; } return false; }// returns true if polar
function isCart (vec) { if(vec.x !== undefined && vec.y !== undefined) { return true; } return false; }// returns true if cartesian
// copy and converts an unknown vec to polar if not already
function asPolar(vec){
if(isCart(vec)){ return cartToPolar(vec); }
if(vec.mag < 0){
vec.mag = - vec.mag;
vec.dir += PI;
}
return { dir : vec.dir, mag : vec.mag };
}
// copy and converts an unknown vec to cart if not already
function asCart(vec){
if(isPolar(vec)){ return polarToCart(vec); }
return { x : vec.x, y : vec.y};
}
// normalise makes a vector a unit length and returns it as a cartesian
function normalise(vec){
var vp = asPolar(vec);
vap.mag = 1;
return asCart(vp);
}
function vectorAdd(vec1, vec2){
var v1 = asCart(vec1);
var v2 = asCart(vec2);
return vector(v1.x + v2.x, v1.y + v2.y);
}
// This splits the vector (polar or cartesian) into the components along dir and the tangent to that dir
function vectorComponentsForDir(vec,dir){
var v = asPolar(vec); // as polar
var pheta = v.dir - dir;
var Fv = Math.cos(pheta) * v.mag;
var Fa = Math.sin(pheta) * v.mag;
var d1 = dir;
var d2 = dir + PI90;
if(Fv < 0){
d1 += PI;
Fv = -Fv;
}
if(Fa < 0){
d2 += PI;
Fa = -Fa;
}
return {
along : polar(Fv,d1),
tangent : polar(Fa,d2)
};
}
function doCollision(pointDetails, wallIndex){
var vv = asPolar(pointDetails.velocity); // Cartesian V make sure the velocity is in cartesian form
var va = asPolar(pointDetails.velocityA); // Angular V make sure the velocity is in cartesian form
var vvc = vectorComponentsForDir(vv, WALL_NORMS[wallIndex])
var vac = vectorComponentsForDir(va, WALL_NORMS[wallIndex])
vvc.along.mag *= 1.18; // Elastic collision requiers that the two equal forces from the wall
vac.along.mag *= 1.18; // against the box and the box against the wall be summed.
// As the wall can not move the result is that the force is twice
// the force the box applies to the wall (Yes and currently force is in
// velocity form untill the next line)
vvc.along.mag *= box.mass; // convert to force
//vac.along.mag/= pointDetails.radius
vac.along.mag *= box.mass
vvc.along.dir += PI; // force is in the oppisite direction so turn it 180
vac.along.dir += PI; // force is in the oppisite direction so turn it 180
// split the force into components based on the wall normal. One along the norm the
// other along the wall
vvc.tangent.mag *= 0.18; // add friction along the wall
vac.tangent.mag *= 0.18;
vvc.tangent.mag *= box.mass //
vac.tangent.mag *= box.mass
vvc.tangent.dir += PI; // force is in the oppisite direction so turn it 180
vac.tangent.dir += PI; // force is in the oppisite direction so turn it 180
// apply the force out from the wall
box.applyForce(vvc.along, pointDetails.pos)
// apply the force along the wall
box.applyForce(vvc.tangent, pointDetails.pos)
// apply the force out from the wall
box.applyForce(vac.along, pointDetails.pos)
// apply the force along the wall
box.applyForce(vac.tangent, pointDetails.pos)
//addTempVec(pointDetails.pos, vvc.tangent, "red", LIFE, 10)
//addTempVec(pointDetails.pos, vac.tangent, "red", LIFE, 10)
}
function applyForce(force, loc){ // force is a vector, loc is a coordinate
validatePolar(force); // make sure the force is a valid polar
// addTempVec(loc, force,"White", LIFE, SCALE_FORCE) // show the force
var l = asCart(loc); // make sure the location is in cartesian form
var toCenter = asPolar(vector(this.x - l.x, this.y - l.y));
var pheta = toCenter.dir - force.dir;
var Fv = Math.cos(pheta) * force.mag;
var Fa = Math.sin(pheta) * force.mag;
var accel = asPolar(toCenter); // copy the direction to center
accel.mag = Fv / this.mass; // now use F = m * a in the form a = F/m
var deltaV = asCart(accel); // convert it to cartesian
this.dx += deltaV.x // update the box delta V
this.dy += deltaV.y
var accelA = Fa / (toCenter.mag * this.mass); // for the angular component get the rotation
// acceleration
this.dr += accelA;// now add that to the box delta r
}
// make a box
ctx.globalAlpha = 1;
var lx,ly;
function update(){
// clearLog();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.lineWidth = 1;
ctx.strokeStyle = "black";
ctx.fillStyle = "#888";
ctx.fillRect(INSET, INSET, canvas.width - INSET * 2, canvas.height - INSET * 2);
ctx.strokeRect(INSET, INSET, canvas.width - INSET * 2, canvas.height - INSET * 2);
ctx.lineWidth = 2;
ctx.strokeStyle = "black";
box.update();
box.draw();
if(mouse.buttonRaw & 1){
var force = asPolar(vector(mouse.x - lx, mouse.y - ly));
force.mag *= box.mass * 0.1;
box.applyForce(force,vector(mouse.x, mouse.y))
addTempVec(vector(mouse.x, mouse.y), asPolar(vector(mouse.x - lx, mouse.y - ly)), "Cyan", LIFE, 5);
}
lx = mouse.x;
ly = mouse.y;
for(i = 0; i < 4; i++){
var p = box.getPoint(i);
// only do one collision per frame or we will end up adding energy
if(p.pos.x < INSET){
box.x += (INSET) - p.pos.x;
doCollision(p,3)
}else
if( p.pos.x > canvas.width-INSET){
box.x += (canvas.width - INSET) - p.pos.x;
doCollision(p,1)
}else
if(p.pos.y < INSET){
box.y += (INSET) -p.pos.y;
doCollision(p,0)
}else
if( p.pos.y > canvas.height-INSET){
box.y += (canvas.height - INSET) -p.pos.y;
doCollision(p,2)
}
drawVec(p.pos,p.velocity,"blue")
}
drawTempVecs();
ctx.globalAlpha = 1;
drawText(box.getDesc(),canvas.width/2,FONT_SIZE,FONT,FONT_SIZE,"black");
drawText("Click drag to apply force to box",canvas.width/2,FONT_SIZE +17,FONT,14,"black");
requestAnimationFrame(update)
}
update();