A moving object to go around another target moving object - javascript

I have the first moving object that moves down the screen by y axis, I have another object that is positioned 400 pixels below the first moving object, but I want the first moving object to go around the object that is stationary which is 400 pixels down.
How can I achieve this? I tried this:
var tX = target.x;
var tY = target.y;
var magnitude = 0.2;
dx = tX + player.x;
dy = tY + player.y;
angle = Math.atan(dy, dx);
player.x = player.x - magnitude * Math.cos(angle);
player.y = player.y - magnitude * Math.sin(angle);
What's happening is the first moving object is just bouncing off the object that's 400 pixels below but I need the first moving object to go around this below 400 pixels object. how can this be achieved?
More code:
var resArrayPlayerHome;
function nearestToPlayer(player) {
resArrayPlayerHome = arrayPlayerHome.filter(player2 => player2.shirtNumber != player.shirtNumber);
var numObj = findClosest2({ x: player.x, y: player.y });
const result = resArrayPlayerHome.filter(player => player.shirtNumber == numObj.shirtNumber);
return result;
}
const findClosest2 = (target) => resArrayPlayerHome
.reduce((a, item) => getDist(item, target) < getDist(a, target) ? item : a);
var nearPlayer = nearestToPlayer(player);
for (var j = 0; j < arrayPlayerHome.length; j++) {
topY = arrayPlayerHome[j].y - 15;
bottomY = arrayPlayerHome[j].y + 15;
var lengthTop = topY + bottomY;
leftX = arrayPlayerHome[j].x - 15;
rightX = arrayPlayerHome[j].x + 15;
var lengthLeft = leftX + rightX;
if (arrayPlayerHome[j].shirtNumber == nearPlayer[0].shirtNumber && (((player.y - 30) <= arrayPlayerHome[j].y && (player.y + 30) >= arrayPlayerHome[j].y) && ((player.x - 30) <= arrayPlayerHome[j].x && (player.x + 30) >= arrayPlayerHome[j].x))) {
//this.angle1 = Math.atan2(target.y - player.y, target.x - player.x);
//var tX = arrayPlayerHome[j].x - player.x;
//var tY = arrayPlayerHome[j].y - player.y;
var magnitude = 0.2;
dx = arrayPlayerHome[j].x - player.x;
dy = arrayPlayerHome[j].y - player.y;
let dist = Math.hypot(dx, dy);
dx /= dist;
dy /= dist;
if (dx != 0 || dy != 0) {
if (
player.x >= arrayPlayerHome[j].x + 30 ||
player.x <= arrayPlayerHome[j].x - 30 ||
player.y >= arrayPlayerHome[j].y + 30 ||
player.y <= arrayPlayerHome[j].y - 30
) {for (var x = 0; x < 4; x++) {
for (var y = 0; y < 4; y++) {
var tX = target.x;
var tY = target.y;
var magnitude = 0.2;
dx = tX + player.x;
dy = tY + player.y;
angle = Math.atan(dy, dx);
player.x = player.x - magnitude * Math.cos(angle);
player.y = player.y - magnitude * Math.sin(angle);
}
}
}else{
console.log("ssssss");
for (var x = 0; x < 4; x++) {
for (var y = 0; y < 4; y++) {
var tX = target.x;
var tY = target.y;
var magnitude = 0.2;
dx = tX + player.x;
dy = tY + player.y;
angle = Math.atan(dy, dx);
player.x = player.x - magnitude * Math.cos(angle);
player.y = player.y - magnitude * Math.sin(angle);
}
}
}
}
}
}

Related

MouseDown Event is not working on other computers

I have a problem with a mousedown event that is so weird for me. I'm at intermediate level but I have a beginner problem.
I'm making a game in which a player can control a ball and there are some bricks with texts on them. The player must first shoot a word e.g (Ethiopia) and there is another brick with the same word. Then after shooting Ethiopia the player must shoot the other Ethiopia.
Code :
function dummyHttpRequest() {
return `Iran
Denmark
Sweden
Iraq
Brazil
Ethiopia
England
Finland
Canada`;
}
var isindrag = false;
const canvas = document.getElementById("mycanvas");
const ctx = canvas.getContext("2d");
ctx.font = "12pt Arial";
ctx.fillStyle = "blue";
ctx.fillText("Mouse Speed : ", 0, 20);
var x = canvas.width / 2;
var y = canvas.height / 2;
var posbricks = [];
var times = 0;
var dx = 0;
var dy = 0;
var radius = 15;
var oldx = 0;
var oldy = 0;
var speed = 0;
var friction = 0.005;
//const XHRnames = new XMLHttpRequest();
//XHRnames.open("GET", "data.txt", false);
//XHRnames.send();
//var names = XHRnames.responseText.split("\n");
var names = dummyHttpRequest().split("\n");
var namesResults = [];
var numberOfSelected = [];
for (i in names) {
numberOfSelected[i] = 0;
}
for (var i = 0; i < names.length * 2; i++) {
randnumf();
}
function randnumf() {
var randnum = Math.round(Math.random() * (names.length - 1));
if (numberOfSelected[randnum] < 2) {
namesResults[i + 3] = names[randnum];
numberOfSelected[randnum]++;
}
else {
randnumf();
}
}
var whatitemshooted;
var isshooted = false;
var interval = setInterval(function () {
times++;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.closePath();
if (dx > 0) {
dx -= friction;
}
else if (dx < 0) {
dx += friction;
}
if (dy > 0) {
dy -= friction;
}
else if (dy < 0) {
dy += friction;
}
x += dx;
y += dy;
if (isindrag) {
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(oldx, oldy);
ctx.stroke();
ctx.closePath();
}
for (var i = 1; i <= 6; i++) {
if (times == 1) {
posbricks[i - 1] = [];
}
for (var j = 1; j <= 3; j++) {
if (times == 1) {
posbricks[i - 1][j - 1] = { x: (i - 1) * 100, y: (j - 1) * 70, text: namesResults[(i * 3) + j - 1] };
//console.log(posbricks[i - 1][j - 1].text);
}
var fontsize = 20 - posbricks[i - 1][j - 1].text.length;
ctx.font = fontsize + "pt Arial";
ctx.fillStyle = "blue";
ctx.fillRect(posbricks[i - 1][j - 1].x, posbricks[i - 1][j - 1].y, 70, 30);
ctx.fillStyle = "yellow";
ctx.fillText(posbricks[i - 1][j - 1].text, posbricks[i - 1][j - 1].x + 5, posbricks[i - 1][j - 1].y + 20);
if (y - radius <= posbricks[i - 1][j - 1].y + 20 && y + radius >= posbricks[i - 1][j - 1].y && x + radius >= posbricks[i - 1][j - 1].x && x - radius <= posbricks[i - 1][j - 1].x + 40) {
dx = -dx;
dy = -dy;
if (isshooted) {
var condition = whatitemshooted.x != posbricks[i - 1][j - 1].x || whatitemshooted.y != posbricks[i - 1][j - 1].y;
}
if (!isshooted) {
isshooted = true;
whatitemshooted = posbricks[i - 1][j - 1];
}
else {
if (posbricks[i - 1][j - 1].text == whatitemshooted.text && condition) {
ctx.clearRect(posbricks[i - 1][j - 1].x, posbricks[i - 1][j - 1].y, 110, 20);
posbricks[i - 1][j - 1].x = NaN;
posbricks[i - 1][j - 1].y = NaN;
ctx.clearRect(whatitemshooted.x, whatitemshooted.y, 110, 20);
whatitemshooted.x = NaN;
whatitemshooted.y = NaN;
isshooted = false;
}
whatitemshooted = null;
}
}
}
}
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fill();
checkCollision();
}, 10);
/*
oldx = x;
x = event.clientX;
y = event.clientY;
speed = Math.abs(x - oldx);
*/
function checkCollision() {
if (x >= canvas.width - radius || x <= radius) {
dx = -dx;
}
if (y >= canvas.height - radius || y <= radius) {
dy = -dy;
}
}
canvas.addEventListener("mousedown", function (event) {
if (event.clientX >= x && event.clientX <= x + (radius * 2) && event.clientY >= y && event.clientY <= y + (radius * 2)) {
dx = 0;
dy = 0;
isindrag = true;
oldx = x;
oldy = y;
}
});
canvas.addEventListener("mousemove", function (event) {
if (isindrag) {
x = event.clientX;
y = event.clientY;
}
});
canvas.addEventListener("mouseup", function (event) {
if (isindrag && event.clientX < canvas.width && event.clientY < canvas.height && event.clientX > 0 && event.clientY > 0) {
isindrag = false;
dx = -(x - oldx) / 30;
dy = -(y - oldy) / 30;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<canvas id="mycanvas" width="600" height="600"></canvas>
<script src="index.js"></script>
</body>
</html>
In Data.txt :
Iran
Denmark
Sweden
Iraq
Brazil
Ethiopia
England
Finland
Canada
On my computer (with web server for chrome) it runs completely fine but on my other computer (in a website) the ball doesn't move when I drag it.
What should I do?

Collision detection, control by mouse

i have a simple physics engine to detect collisions between circles and paddles, right now i can set the paddle to be controlled by the mouse or not. but i want to be able to control one of the circles by mouse instead. at the bottom where bat[i].update() will control the specified paddle by that index. but i want to be able to control the circle by the mouse instead to further expand this engine. is there any way i can do this?
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext("2d");
const mouse = { x: 0, y: 0, button: false }
function mouseEvents(e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
["down", "up", "move"].forEach(name => document.addEventListener("mouse" + name, mouseEvents));
// short cut vars
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
const gravity = 0;
var balls = []
var bats = []
// constants and helpers
const PI2 = Math.PI * 2;
const setStyle = (ctx, style) => { Object.keys(style).forEach(key => ctx[key] = style[key]) };
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function distance(x1, y1, x2, y2) {
const xDist = x2 - x1;
const yDist = y2 - y1;
return Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2));
}
// the ball
class ball {
constructor() {
this.r = 25
this.x = random(50, 1500)
this.y = random(50, 1500)
this.dx = 15
this.dy = 15
this.mass = 1
this.maxSpeed = 15
this.style = {
lineWidth: 12,
strokeStyle: "green"
}
}
draw(ctx) {
setStyle(ctx, this.style);
ctx.beginPath();
ctx.arc(this.x, this.y, this.r - this.style.lineWidth * 0.45, 0, PI2);
ctx.stroke();
}
update() {
this.dy += gravity;
var speed = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
var x = this.x + this.dx;
var y = this.y + this.dy;
if (y > canvas.height - this.r) {
y = (canvas.height - this.r) - (y - (canvas.height - this.r));
this.dy = -this.dy;
}
if (y < this.r) {
y = this.r - (y - this.r);
this.dy = -this.dy;
}
if (x > canvas.width - this.r) {
x = (canvas.width - this.r) - (x - (canvas.width - this.r));
this.dx = -this.dx;
}
if (x < this.r) {
x = this.r - (x - this.r);
this.dx = -this.dx;
}
this.x = x;
this.y = y;
if (speed > this.maxSpeed) { // if over speed then slow the ball down gradualy
var reduceSpeed = this.maxSpeed + (speed - this.maxSpeed) * 0.9; // reduce speed if over max speed
this.dx = (this.dx / speed) * reduceSpeed;
this.dy = (this.dy / speed) * reduceSpeed;
}
for (var i = 0; i < balls.length; i++) {
if (this === balls[i]) continue
if (distance(this.x, this.y, balls[i].x, balls[i].y) < this.r * 2) {
resolveCollision(this, balls[i])
}
}
}
}
class player {
constructor() {
this.r = 50
this.x = random(50, 1500)
this.y = random(50, 1500)
this.dx = 0.2
this.dy = 0.2
this.mass = 1
this.maxSpeed = 1000
this.style = {
lineWidth: 12,
strokeStyle: "blue"
}
}
draw(ctx) {
setStyle(ctx, this.style);
ctx.beginPath();
ctx.arc(this.x, this.y, this.r - this.style.lineWidth * 0.45, 0, PI2);
ctx.stroke();
}
update() {
this.dx = mouse.x - this.x;
this.dy = mouse.y - this.y;
var x = this.x + this.dx;
var y = this.y + this.dy;
x < this.width / 2 && (x / 2);
y < this.height / 2 && (y / 2);
x > canvas.width / 2 && (x = canvas.width / 2);
y > canvas.height / 2 && (y = canvas.height / 2);
this.dx = x - this.x;
this.dy = y - this.y;
this.x = x;
this.y = y;
for (var i = 0; i < balls.length; i++) {
if (this === balls[i]) continue
if (distance(this.x, this.y, balls[i].x, balls[i].y) < this.r * 2) {
resolveCollision(this, balls[i])
}
}
}
}
const ballShadow = {
r: 50,
x: 50,
y: 50,
dx: 0.2,
dy: 0.2,
}
//bat
class bat {
constructor(x, y, w, h) {
this.x = x
this.y = y
this.dx = 0
this.dy = 0
this.width = w
this.height = h
this.style = {
lineWidth: 2,
strokeStyle: "black",
}
}
draw(ctx) {
setStyle(ctx, this.style);
ctx.strokeRect(this.x - this.width / 2, this.y - this.height / 2, this.width, this.height);
}
update() {
this.dx = mouse.x - this.x;
this.dy = mouse.y - this.y;
var x = this.x + this.dx;
var y = this.y + this.dy;
x < this.width / 2 && (x = this.width / 2);
y < this.height / 2 && (y = this.height / 2);
x > canvas.width - this.width / 2 && (x = canvas.width - this.width / 2);
y > canvas.height - this.height / 2 && (y = canvas.height - this.height / 2);
this.dx = x - this.x;
this.dy = y - this.y;
this.x = x;
this.y = y;
}
}
function doBatBall(bat, ball) {
var mirrorX = 1;
var mirrorY = 1;
const s = ballShadow; // alias
s.x = ball.x;
s.y = ball.y;
s.dx = ball.dx;
s.dy = ball.dy;
s.x -= s.dx;
s.y -= s.dy;
// get the bat half width height
const batW2 = bat.width / 2;
const batH2 = bat.height / 2;
// and bat size plus radius of ball
var batH = batH2 + ball.r;
var batW = batW2 + ball.r;
// set ball position relative to bats last pos
s.x -= bat.x;
s.y -= bat.y;
// set ball delta relative to bat
s.dx -= bat.dx;
s.dy -= bat.dy;
// mirror x and or y if needed
if (s.x < 0) {
mirrorX = -1;
s.x = -s.x;
s.dx = -s.dx;
}
if (s.y < 0) {
mirrorY = -1;
s.y = -s.y;
s.dy = -s.dy;
}
// bat now only has a bottom, right sides and bottom right corner
var distY = (batH - s.y); // distance from bottom
var distX = (batW - s.x); // distance from right
if (s.dx > 0 && s.dy > 0) { return } // ball moving away so no hit
var ballSpeed = Math.sqrt(s.dx * s.dx + s.dy * s.dy) // get ball speed relative to bat
// get x location of intercept for bottom of bat
var bottomX = s.x + (s.dx / s.dy) * distY;
// get y location of intercept for right of bat
var rightY = s.y + (s.dy / s.dx) * distX;
// get distance to bottom and right intercepts
var distB = Math.hypot(bottomX - s.x, batH - s.y);
var distR = Math.hypot(batW - s.x, rightY - s.y);
var hit = false;
if (s.dy < 0 && bottomX <= batW2 && distB <= ballSpeed && distB < distR) { // if hit is on bottom and bottom hit is closest
hit = true;
s.y = batH - s.dy * ((ballSpeed - distB) / ballSpeed);
s.dy = -s.dy;
}
if (!hit && s.dx < 0 && rightY <= batH2 && distR <= ballSpeed && distR <= distB) { // if hit is on right and right hit is closest
hit = true;
s.x = batW - s.dx * ((ballSpeed - distR) / ballSpeed);;
s.dx = -s.dx;
}
if (!hit) { // if no hit may have intercepted the corner.
// find the distance that the corner is from the line segment from the balls pos to the next pos
const u = ((batW2 - s.x) * s.dx + (batH2 - s.y) * s.dy) / (ballSpeed * ballSpeed);
// get the closest point on the line to the corner
var cpx = s.x + s.dx * u;
var cpy = s.y + s.dy * u;
// get ball radius squared
const radSqr = ball.r * ball.r;
// get the distance of that point from the corner squared
const dist = (cpx - batW2) * (cpx - batW2) + (cpy - batH2) * (cpy - batH2);
// is that distance greater than ball radius
if (dist > radSqr) { return } // no hit
// solves the triangle from center to closest point on balls trajectory
var d = Math.sqrt(radSqr - dist) / ballSpeed;
// intercept point is closest to line start
cpx -= s.dx * d;
cpy -= s.dy * d;
// get the distance from the ball current pos to the intercept point
d = Math.hypot(cpx - s.x, cpy - s.y);
// is the distance greater than the ball speed then its a miss
if (d > ballSpeed) { return } // no hit return
s.x = cpx; // position of contact
s.y = cpy;
// find the normalised tangent at intercept point
const ty = (cpx - batW2) / ball.r;
const tx = -(cpy - batH2) / ball.r;
// calculate the reflection vector
const bsx = s.dx / ballSpeed; // normalise ball speed
const bsy = s.dy / ballSpeed;
const dot = (bsx * tx + bsy * ty) * 2;
// get the distance the ball travels past the intercept
d = ballSpeed - d;
// the reflected vector is the balls new delta (this delta is normalised)
s.dx = (tx * dot - bsx);
s.dy = (ty * dot - bsy);
// move the ball the remaining distance away from corner
s.x += s.dx * d;
s.y += s.dy * d;
// set the ball delta to the balls speed
s.dx *= ballSpeed
s.dy *= ballSpeed
hit = true;
}
// if the ball hit the bat restore absolute position
if (hit) {
// reverse mirror
s.x *= mirrorX;
s.dx *= mirrorX;
s.y *= mirrorY;
s.dy *= mirrorY;
// remove bat relative position
s.x += bat.x;
s.y += bat.y;
// remove bat relative delta
s.dx += bat.dx;
s.dy += bat.dy;
// set the balls new position and delta
ball.x = s.x;
ball.y = s.y;
ball.dx = s.dx;
ball.dy = s.dy;
}
}
function rotate(velocity, angle) {
const rotatedVelocities = {
x: velocity.x * Math.cos(angle) + velocity.y * Math.sin(angle),
y: -velocity.x * Math.sin(angle) + velocity.y * Math.cos(angle)
};
return rotatedVelocities;
}
function resolveCollision(particle, otherParticle) {
const xVelocityDiff = particle.dx - otherParticle.dx;
const yVelocityDiff = particle.dy - otherParticle.dy;
const xDist = otherParticle.x - particle.x;
const yDist = otherParticle.y - particle.y;
if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {
const angle = Math.atan2(otherParticle.y - particle.y, otherParticle.x - particle.x);
const m1 = particle.mass;
const m2 = otherParticle.mass;
const u1 = rotate({ x: particle.dx, y: particle.dy }, angle);
const u2 = rotate({ x: otherParticle.dx, y: otherParticle.dy }, angle);
const v1 = {
x: u1.x * (m1 - m2) / (m1 + m2) + u2.x * 2 * m2 / (m1 + m2),
y: u1.y
};
const v2 = {
x: u2.x * (m1 - m2) / (m1 + m2) + u1.x * 2 * m2 / (m1 + m2),
y: u2.y
};
const vFinal1 = rotate(v1, -angle);
const vFinal2 = rotate(v2, -angle);
particle.dx = vFinal1.x;
particle.dy = vFinal1.y;
otherParticle.dx = vFinal2.x;
otherParticle.dy = vFinal2.y;
}
}
for (let i = 0; i < 10; i++) {
balls.push(new ball())
}
balls.push(new player())
//x,y,w,h
bats.push(new bat((window.innerWidth / 2) - 150, window.innerHeight / 2, 10, 100))
bats.push(new bat((window.innerWidth / 2) + 150, window.innerHeight / 2, 10, 100))
// main update function
function update(timer) {
if (w !== innerWidth || h !== innerHeight) {
cw = (w = canvas.width = innerWidth) / 2;
ch = (h = canvas.height = innerHeight) / 2;
}
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.globalAlpha = 1; // reset alpha
ctx.clearRect(0, 0, w, h);
// move bat and ball
for (var i = 0; i < balls.length; i++) {
for (var j = 0; j < bats.length; j++) {
doBatBall(bats[j], balls[i])
}
balls[i].update()
balls[i].draw(ctx)
}
bats.forEach(bat => {
//bat.update();
bat.draw(ctx);
})
// check for bal bat contact and change ball position and trajectory if needed
// draw ball and bat
requestAnimationFrame(update);
}
requestAnimationFrame(update);
<body>
<canvas></canvas>
</body>
The balls cannot have 0 speed, but player can. Because of that, it fails at dividing by zero:
const u = ((batW2 - s.x) * s.dx + (batH2 - s.y) * s.dy) / (ballSpeed * ballSpeed);
Simply add || 1 to the end of the line should fix it.
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext("2d");
const mouse = { x: 0, y: 0, button: false }
function mouseEvents(e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
["down", "up", "move"].forEach(name => document.addEventListener("mouse" + name, mouseEvents));
// short cut vars
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
const gravity = 0;
var balls = []
var bats = []
// constants and helpers
const PI2 = Math.PI * 2;
const setStyle = (ctx, style) => { Object.keys(style).forEach(key => ctx[key] = style[key]) };
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function distance(x1, y1, x2, y2) {
const xDist = x2 - x1;
const yDist = y2 - y1;
return Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2));
}
// the ball
class ball {
constructor() {
this.r = 25
this.x = random(50, 1500)
this.y = random(50, 1500)
this.dx = 15
this.dy = 15
this.mass = 1
this.maxSpeed = 15
this.style = {
lineWidth: 12,
strokeStyle: "green"
}
}
draw(ctx) {
setStyle(ctx, this.style);
ctx.beginPath();
ctx.arc(this.x, this.y, this.r - this.style.lineWidth * 0.45, 0, PI2);
ctx.stroke();
}
update() {
this.dy += gravity;
var speed = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
var x = this.x + this.dx;
var y = this.y + this.dy;
if (y > canvas.height - this.r) {
y = (canvas.height - this.r) - (y - (canvas.height - this.r));
this.dy = -this.dy;
}
if (y < this.r) {
y = this.r - (y - this.r);
this.dy = -this.dy;
}
if (x > canvas.width - this.r) {
x = (canvas.width - this.r) - (x - (canvas.width - this.r));
this.dx = -this.dx;
}
if (x < this.r) {
x = this.r - (x - this.r);
this.dx = -this.dx;
}
this.x = x;
this.y = y;
if (speed > this.maxSpeed) { // if over speed then slow the ball down gradualy
var reduceSpeed = this.maxSpeed + (speed - this.maxSpeed) * 0.9; // reduce speed if over max speed
this.dx = (this.dx / speed) * reduceSpeed;
this.dy = (this.dy / speed) * reduceSpeed;
}
for (var i = 0; i < balls.length; i++) {
if (this === balls[i]) continue
if (distance(this.x, this.y, balls[i].x, balls[i].y) < this.r * 2) {
resolveCollision(this, balls[i])
}
}
}
}
class player {
constructor() {
this.r = 50
this.x = random(50, 1500)
this.y = random(50, 1500)
this.dx = 0.2
this.dy = 0.2
this.mass = 1
this.maxSpeed = 1000
this.width = this.r
this.height = this.r
this.style = {
lineWidth: 12,
strokeStyle: "blue"
}
}
draw(ctx) {
setStyle(ctx, this.style);
ctx.beginPath();
ctx.arc(this.x, this.y, this.r - this.style.lineWidth * 0.45, 0, PI2);
ctx.stroke();
}
update() {
this.dx = mouse.x - this.x;
this.dy = mouse.y - this.y;
var x = this.x + this.dx;
var y = this.y + this.dy;
/* change */
/*
x < this.width / 2 && (x / 2);
y < this.height / 2 && (y / 2);
x > canvas.width / 2 && (x = canvas.width / 2);
y > canvas.height / 2 && (y = canvas.height / 2);
*/
x < this.width && (x = this.width);
y < this.height && (y = this.height);
x > canvas.width - this.width && (x = canvas.width - this.width);
y > canvas.height - this.height && (y = canvas.height - this.height);
/* end change */
this.dx = x - this.x;
this.dy = y - this.y;
this.x = x;
this.y = y;
for (var i = 0; i < balls.length; i++) {
if (this === balls[i]) continue
if (distance(this.x, this.y, balls[i].x, balls[i].y) < this.r * 2) {
resolveCollision(this, balls[i])
}
}
}
}
const ballShadow = {
r: 50,
x: 50,
y: 50,
dx: 0.2,
dy: 0.2,
}
//bat
class bat {
constructor(x, y, w, h) {
this.x = x
this.y = y
this.dx = 0
this.dy = 0
this.width = w
this.height = h
this.style = {
lineWidth: 2,
strokeStyle: "black",
}
}
draw(ctx) {
setStyle(ctx, this.style);
ctx.strokeRect(this.x - this.width / 2, this.y - this.height / 2, this.width, this.height);
}
update() {
this.dx = mouse.x - this.x;
this.dy = mouse.y - this.y;
var x = this.x + this.dx;
var y = this.y + this.dy;
x < this.width / 2 && (x = this.width / 2);
y < this.height / 2 && (y = this.height / 2);
x > canvas.width - this.width / 2 && (x = canvas.width - this.width / 2);
y > canvas.height - this.height / 2 && (y = canvas.height - this.height / 2);
this.dx = x - this.x;
this.dy = y - this.y;
this.x = x;
this.y = y;
}
}
function doBatBall(bat, ball) {
var mirrorX = 1;
var mirrorY = 1;
const s = ballShadow; // alias
s.x = ball.x;
s.y = ball.y;
s.dx = ball.dx;
s.dy = ball.dy;
s.x -= s.dx;
s.y -= s.dy;
// get the bat half width height
const batW2 = bat.width / 2;
const batH2 = bat.height / 2;
// and bat size plus radius of ball
var batH = batH2 + ball.r;
var batW = batW2 + ball.r;
// set ball position relative to bats last pos
s.x -= bat.x;
s.y -= bat.y;
// set ball delta relative to bat
s.dx -= bat.dx;
s.dy -= bat.dy;
// mirror x and or y if needed
if (s.x < 0) {
mirrorX = -1;
s.x = -s.x;
s.dx = -s.dx;
}
if (s.y < 0) {
mirrorY = -1;
s.y = -s.y;
s.dy = -s.dy;
}
// bat now only has a bottom, right sides and bottom right corner
var distY = (batH - s.y); // distance from bottom
var distX = (batW - s.x); // distance from right
if (s.dx > 0 && s.dy > 0) { return } // ball moving away so no hit
var ballSpeed = Math.sqrt(s.dx * s.dx + s.dy * s.dy) // get ball speed relative to bat
// get x location of intercept for bottom of bat
var bottomX = s.x + (s.dx / s.dy) * distY;
// get y location of intercept for right of bat
var rightY = s.y + (s.dy / s.dx) * distX;
// get distance to bottom and right intercepts
var distB = Math.hypot(bottomX - s.x, batH - s.y);
var distR = Math.hypot(batW - s.x, rightY - s.y);
var hit = false;
if (s.dy < 0 && bottomX <= batW2 && distB <= ballSpeed && distB < distR) { // if hit is on bottom and bottom hit is closest
hit = true;
s.y = batH - s.dy * ((ballSpeed - distB) / ballSpeed);
s.dy = -s.dy;
}
if (!hit && s.dx < 0 && rightY <= batH2 && distR <= ballSpeed && distR <= distB) { // if hit is on right and right hit is closest
hit = true;
s.x = batW - s.dx * ((ballSpeed - distR) / ballSpeed);;
s.dx = -s.dx;
}
if (!hit) { // if no hit may have intercepted the corner.
// find the distance that the corner is from the line segment from the balls pos to the next pos
/* change */
// const u = ((batW2 - s.x) * s.dx + (batH2 - s.y) * s.dy) / (ballSpeed * ballSpeed);
const u = ((batW2 - s.x) * s.dx + (batH2 - s.y) * s.dy) / (ballSpeed * ballSpeed) || 1;
/* end change */
// get the closest point on the line to the corner
var cpx = s.x + s.dx * u;
var cpy = s.y + s.dy * u;
// get ball radius squared
const radSqr = ball.r * ball.r;
// get the distance of that point from the corner squared
const dist = (cpx - batW2) * (cpx - batW2) + (cpy - batH2) * (cpy - batH2);
// is that distance greater than ball radius
if (dist > radSqr) { return } // no hit
// solves the triangle from center to closest point on balls trajectory
var d = Math.sqrt(radSqr - dist) / ballSpeed;
// intercept point is closest to line start
cpx -= s.dx * d;
cpy -= s.dy * d;
// get the distance from the ball current pos to the intercept point
d = Math.hypot(cpx - s.x, cpy - s.y);
// is the distance greater than the ball speed then its a miss
if (d > ballSpeed) { return } // no hit return
s.x = cpx; // position of contact
s.y = cpy;
// find the normalised tangent at intercept point
const ty = (cpx - batW2) / ball.r;
const tx = -(cpy - batH2) / ball.r;
// calculate the reflection vector
const bsx = s.dx / ballSpeed; // normalise ball speed
const bsy = s.dy / ballSpeed;
const dot = (bsx * tx + bsy * ty) * 2;
// get the distance the ball travels past the intercept
d = ballSpeed - d;
// the reflected vector is the balls new delta (this delta is normalised)
s.dx = (tx * dot - bsx);
s.dy = (ty * dot - bsy);
// move the ball the remaining distance away from corner
s.x += s.dx * d;
s.y += s.dy * d;
// set the ball delta to the balls speed
s.dx *= ballSpeed
s.dy *= ballSpeed
hit = true;
}
// if the ball hit the bat restore absolute position
if (hit) {
// reverse mirror
s.x *= mirrorX;
s.dx *= mirrorX;
s.y *= mirrorY;
s.dy *= mirrorY;
// remove bat relative position
s.x += bat.x;
s.y += bat.y;
// remove bat relative delta
s.dx += bat.dx;
s.dy += bat.dy;
// set the balls new position and delta
ball.x = s.x;
ball.y = s.y;
ball.dx = s.dx;
ball.dy = s.dy;
}
}
function rotate(velocity, angle) {
const rotatedVelocities = {
x: velocity.x * Math.cos(angle) + velocity.y * Math.sin(angle),
y: -velocity.x * Math.sin(angle) + velocity.y * Math.cos(angle)
};
return rotatedVelocities;
}
function resolveCollision(particle, otherParticle) {
const xVelocityDiff = particle.dx - otherParticle.dx;
const yVelocityDiff = particle.dy - otherParticle.dy;
const xDist = otherParticle.x - particle.x;
const yDist = otherParticle.y - particle.y;
if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {
const angle = Math.atan2(otherParticle.y - particle.y, otherParticle.x - particle.x);
const m1 = particle.mass;
const m2 = otherParticle.mass;
const u1 = rotate({ x: particle.dx, y: particle.dy }, angle);
const u2 = rotate({ x: otherParticle.dx, y: otherParticle.dy }, angle);
const v1 = {
x: u1.x * (m1 - m2) / (m1 + m2) + u2.x * 2 * m2 / (m1 + m2),
y: u1.y
};
const v2 = {
x: u2.x * (m1 - m2) / (m1 + m2) + u1.x * 2 * m2 / (m1 + m2),
y: u2.y
};
const vFinal1 = rotate(v1, -angle);
const vFinal2 = rotate(v2, -angle);
particle.dx = vFinal1.x;
particle.dy = vFinal1.y;
otherParticle.dx = vFinal2.x;
otherParticle.dy = vFinal2.y;
}
}
for (let i = 0; i < 10; i++) {
balls.push(new ball())
}
balls.push(new player())
//x,y,w,h
bats.push(new bat((window.innerWidth / 2) - 150, window.innerHeight / 2, 10, 100))
bats.push(new bat((window.innerWidth / 2) + 150, window.innerHeight / 2, 10, 100))
// main update function
function update(timer) {
if (w !== innerWidth || h !== innerHeight) {
cw = (w = canvas.width = innerWidth) / 2;
ch = (h = canvas.height = innerHeight) / 2;
}
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.globalAlpha = 1; // reset alpha
ctx.clearRect(0, 0, w, h);
// move bat and ball
for (var i = 0; i < balls.length; i++) {
for (var j = 0; j < bats.length; j++) {
doBatBall(bats[j], balls[i])
}
balls[i].update()
balls[i].draw(ctx)
}
bats.forEach(bat => {
//bat.update();
bat.draw(ctx);
})
// check for bal bat contact and change ball position and trajectory if needed
// draw ball and bat
requestAnimationFrame(update);
}
requestAnimationFrame(update);
<body>
<canvas></canvas>
</body>
Adding your player to the array of balls is not what you want to do. Keep that object separate. Create your player as a variable and in your loop just draw and update the player
let player = new Player();
function update(timer) {
...
player.update();
player.draw(ctx);
...
}
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext("2d");
const mouse = { x: 0, y: 0, button: false }
function mouseEvents(e) {
mouse.x = e.x;
mouse.y = e.y;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
["down", "up", "move"].forEach(name => document.addEventListener("mouse" + name, mouseEvents));
// short cut vars
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
const gravity = 0;
var balls = []
var bats = []
// constants and helpers
const PI2 = Math.PI * 2;
const setStyle = (ctx, style) => { Object.keys(style).forEach(key => ctx[key] = style[key]) };
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function distance(x1, y1, x2, y2) {
const xDist = x2 - x1;
const yDist = y2 - y1;
return Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2));
}
// the ball
class ball {
constructor() {
this.r = 25
this.x = random(50, 1500)
this.y = random(50, 1500)
this.dx = 15
this.dy = 15
this.mass = 1
this.maxSpeed = 15
this.style = {
lineWidth: 12,
strokeStyle: "green"
}
}
draw(ctx) {
setStyle(ctx, this.style);
ctx.beginPath();
ctx.arc(this.x, this.y, this.r - this.style.lineWidth * 0.45, 0, PI2);
ctx.stroke();
}
update() {
this.dy += gravity;
var speed = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
var x = this.x + this.dx;
var y = this.y + this.dy;
if (y > canvas.height - this.r) {
y = (canvas.height - this.r) - (y - (canvas.height - this.r));
this.dy = -this.dy;
}
if (y < this.r) {
y = this.r - (y - this.r);
this.dy = -this.dy;
}
if (x > canvas.width - this.r) {
x = (canvas.width - this.r) - (x - (canvas.width - this.r));
this.dx = -this.dx;
}
if (x < this.r) {
x = this.r - (x - this.r);
this.dx = -this.dx;
}
this.x = x;
this.y = y;
if (speed > this.maxSpeed) { // if over speed then slow the ball down gradualy
var reduceSpeed = this.maxSpeed + (speed - this.maxSpeed) * 0.9; // reduce speed if over max speed
this.dx = (this.dx / speed) * reduceSpeed;
this.dy = (this.dy / speed) * reduceSpeed;
}
for (var i = 0; i < balls.length; i++) {
if (this === balls[i]) continue
if (distance(this.x, this.y, balls[i].x, balls[i].y) < this.r * 2) {
resolveCollision(this, balls[i])
}
}
}
}
class Player {
constructor() {
this.r = 50
this.x = random(50, 1500)
this.y = random(50, 1500)
this.dx = 0.2
this.dy = 0.2
this.mass = 1
this.maxSpeed = 1000
this.style = {
lineWidth: 12,
strokeStyle: "blue"
}
}
draw(ctx) {
setStyle(ctx, this.style);
ctx.beginPath();
ctx.arc(this.x, this.y, this.r - this.style.lineWidth * 0.45, 0, PI2);
ctx.stroke();
}
update() {
this.dx = mouse.x - this.x;
this.dy = mouse.y - this.y;
var x = this.x + this.dx;
var y = this.y + this.dy;
/*x < this.width / 2 && (x / 2);
y < this.height / 2 && (y / 2);
x > canvas.width / 2 && (x = canvas.width / 2);
y > canvas.height / 2 && (y = canvas.height / 2);*/
this.dx = x - this.x;
this.dy = y - this.y;
this.x = x;
this.y = y;
for (var i = 0; i < balls.length; i++) {
//if (this === balls[i]) continue
if (distance(this.x, this.y, balls[i].x, balls[i].y) < this.r * 2) {
resolveCollision(this, balls[i])
}
}
}
}
const ballShadow = {
r: 50,
x: 50,
y: 50,
dx: 0.2,
dy: 0.2,
}
//bat
class bat {
constructor(x, y, w, h) {
this.x = x
this.y = y
this.dx = 0
this.dy = 0
this.width = w
this.height = h
this.style = {
lineWidth: 2,
strokeStyle: "black",
}
}
draw(ctx) {
setStyle(ctx, this.style);
ctx.strokeRect(this.x - this.width / 2, this.y - this.height / 2, this.width, this.height);
}
update() {
this.dx = mouse.x - this.x;
this.dy = mouse.y - this.y;
var x = this.x + this.dx;
var y = this.y + this.dy;
x < this.width / 2 && (x = this.width / 2);
y < this.height / 2 && (y = this.height / 2);
x > canvas.width - this.width / 2 && (x = canvas.width - this.width / 2);
y > canvas.height - this.height / 2 && (y = canvas.height - this.height / 2);
this.dx = x - this.x;
this.dy = y - this.y;
this.x = x;
this.y = y;
}
}
function doBatBall(bat, ball) {
var mirrorX = 1;
var mirrorY = 1;
const s = ballShadow; // alias
s.x = ball.x;
s.y = ball.y;
s.dx = ball.dx;
s.dy = ball.dy;
s.x -= s.dx;
s.y -= s.dy;
// get the bat half width height
const batW2 = bat.width / 2;
const batH2 = bat.height / 2;
// and bat size plus radius of ball
var batH = batH2 + ball.r;
var batW = batW2 + ball.r;
// set ball position relative to bats last pos
s.x -= bat.x;
s.y -= bat.y;
// set ball delta relative to bat
s.dx -= bat.dx;
s.dy -= bat.dy;
// mirror x and or y if needed
if (s.x < 0) {
mirrorX = -1;
s.x = -s.x;
s.dx = -s.dx;
}
if (s.y < 0) {
mirrorY = -1;
s.y = -s.y;
s.dy = -s.dy;
}
// bat now only has a bottom, right sides and bottom right corner
var distY = (batH - s.y); // distance from bottom
var distX = (batW - s.x); // distance from right
if (s.dx > 0 && s.dy > 0) { return } // ball moving away so no hit
var ballSpeed = Math.sqrt(s.dx * s.dx + s.dy * s.dy) // get ball speed relative to bat
// get x location of intercept for bottom of bat
var bottomX = s.x + (s.dx / s.dy) * distY;
// get y location of intercept for right of bat
var rightY = s.y + (s.dy / s.dx) * distX;
// get distance to bottom and right intercepts
var distB = Math.hypot(bottomX - s.x, batH - s.y);
var distR = Math.hypot(batW - s.x, rightY - s.y);
var hit = false;
if (s.dy < 0 && bottomX <= batW2 && distB <= ballSpeed && distB < distR) { // if hit is on bottom and bottom hit is closest
hit = true;
s.y = batH - s.dy * ((ballSpeed - distB) / ballSpeed);
s.dy = -s.dy;
}
if (!hit && s.dx < 0 && rightY <= batH2 && distR <= ballSpeed && distR <= distB) { // if hit is on right and right hit is closest
hit = true;
s.x = batW - s.dx * ((ballSpeed - distR) / ballSpeed);;
s.dx = -s.dx;
}
if (!hit) { // if no hit may have intercepted the corner.
// find the distance that the corner is from the line segment from the balls pos to the next pos
const u = ((batW2 - s.x) * s.dx + (batH2 - s.y) * s.dy) / (ballSpeed * ballSpeed);
// get the closest point on the line to the corner
var cpx = s.x + s.dx * u;
var cpy = s.y + s.dy * u;
// get ball radius squared
const radSqr = ball.r * ball.r;
// get the distance of that point from the corner squared
const dist = (cpx - batW2) * (cpx - batW2) + (cpy - batH2) * (cpy - batH2);
// is that distance greater than ball radius
if (dist > radSqr) { return } // no hit
// solves the triangle from center to closest point on balls trajectory
var d = Math.sqrt(radSqr - dist) / ballSpeed;
// intercept point is closest to line start
cpx -= s.dx * d;
cpy -= s.dy * d;
// get the distance from the ball current pos to the intercept point
d = Math.hypot(cpx - s.x, cpy - s.y);
// is the distance greater than the ball speed then its a miss
if (d > ballSpeed) { return } // no hit return
s.x = cpx; // position of contact
s.y = cpy;
// find the normalised tangent at intercept point
const ty = (cpx - batW2) / ball.r;
const tx = -(cpy - batH2) / ball.r;
// calculate the reflection vector
const bsx = s.dx / ballSpeed; // normalise ball speed
const bsy = s.dy / ballSpeed;
const dot = (bsx * tx + bsy * ty) * 2;
// get the distance the ball travels past the intercept
d = ballSpeed - d;
// the reflected vector is the balls new delta (this delta is normalised)
s.dx = (tx * dot - bsx);
s.dy = (ty * dot - bsy);
// move the ball the remaining distance away from corner
s.x += s.dx * d;
s.y += s.dy * d;
// set the ball delta to the balls speed
s.dx *= ballSpeed
s.dy *= ballSpeed
hit = true;
}
// if the ball hit the bat restore absolute position
if (hit) {
// reverse mirror
s.x *= mirrorX;
s.dx *= mirrorX;
s.y *= mirrorY;
s.dy *= mirrorY;
// remove bat relative position
s.x += bat.x;
s.y += bat.y;
// remove bat relative delta
s.dx += bat.dx;
s.dy += bat.dy;
// set the balls new position and delta
ball.x = s.x;
ball.y = s.y;
ball.dx = s.dx;
ball.dy = s.dy;
}
}
function rotate(velocity, angle) {
const rotatedVelocities = {
x: velocity.x * Math.cos(angle) + velocity.y * Math.sin(angle),
y: -velocity.x * Math.sin(angle) + velocity.y * Math.cos(angle)
};
return rotatedVelocities;
}
function resolveCollision(particle, otherParticle) {
const xVelocityDiff = particle.dx - otherParticle.dx;
const yVelocityDiff = particle.dy - otherParticle.dy;
const xDist = otherParticle.x - particle.x;
const yDist = otherParticle.y - particle.y;
if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {
const angle = Math.atan2(otherParticle.y - particle.y, otherParticle.x - particle.x);
const m1 = particle.mass;
const m2 = otherParticle.mass;
const u1 = rotate({ x: particle.dx, y: particle.dy }, angle);
const u2 = rotate({ x: otherParticle.dx, y: otherParticle.dy }, angle);
const v1 = {
x: u1.x * (m1 - m2) / (m1 + m2) + u2.x * 2 * m2 / (m1 + m2),
y: u1.y
};
const v2 = {
x: u2.x * (m1 - m2) / (m1 + m2) + u1.x * 2 * m2 / (m1 + m2),
y: u2.y
};
const vFinal1 = rotate(v1, -angle);
const vFinal2 = rotate(v2, -angle);
particle.dx = vFinal1.x;
particle.dy = vFinal1.y;
otherParticle.dx = vFinal2.x;
otherParticle.dy = vFinal2.y;
}
}
for (let i = 0; i < 10; i++) {
balls.push(new ball())
}
let player = new Player();
//x,y,w,h
bats.push(new bat((window.innerWidth / 2) - 150, window.innerHeight / 2, 10, 100))
bats.push(new bat((window.innerWidth / 2) + 150, window.innerHeight / 2, 10, 100))
// main update function
function update(timer) {
if (w !== innerWidth || h !== innerHeight) {
cw = (w = canvas.width = innerWidth) / 2;
ch = (h = canvas.height = innerHeight) / 2;
}
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.globalAlpha = 1; // reset alpha
ctx.clearRect(0, 0, w, h);
// move bat and ball
for (var i = 1; i < balls.length; i++) {
for (var j = 0; j < bats.length; j++) {
doBatBall(bats[j], balls[i])
}
balls[i].update()
balls[i].draw(ctx)
}
player.update();
player.draw(ctx);
bats.forEach(bat => {
//bat.update();
bat.draw(ctx);
})
// check for bal bat contact and change ball position and trajectory if needed
// draw ball and bat
requestAnimationFrame(update);
}
update();
<canvas></canvas>
Keep in mind the mouse is not exactly in the center of the circle because you are not accounting for the canvas position in the mousemove function. Also you have something limiting your player objects ability to move over the whole canvas.
EDIT:
This is what was causing your player to not be able to move over the whole canvas so comment it out.
/* x < this.width / 2 && (x / 2);
y < this.height / 2 && (y / 2);
x > canvas.width / 2 && (x = canvas.width / 2);
y > canvas.height / 2 && (y = canvas.height / 2);*/
And your collision is slightly off because in you player class you are checking distance against this.r * 2. I would change it to
for (var i = 0; i < balls.length; i++) {
//if (this === balls[i]) continue //not really needed
if (distance(this.x, this.y, balls[i].x, balls[i].y) < this.r + balls[i].r) {
resolveCollision(this, balls[i])
}

Adding gravity to billiard physics in JS canvas animation

I am trying to write aa small physics demo using Javascript. I have multiple balls that bounce off each other just fine, but things go wrong when I try to add gravity.
I am trying to conserve the momentum once they hit, but when I add constant gravity to each one, the physics start to break down.
Here is what I have in terms of code:
class Ball {
constructor ({
x,
y,
vx,
vy,
radius,
color = 'red',
}) {
this.x = x
this.y = y
this.vx = vx
this.vy = vy
this.radius = radius
this.color = color
this.mass = 1
}
render (ctx) {
ctx.save()
ctx.fillStyle = this.color
ctx.strokeStyle = this.color
ctx.translate(this.x, this.y)
ctx.strokeRect(-this.radius, -this.radius, this.radius * 2, this.radius * 2)
ctx.beginPath()
ctx.arc(0, 0, this.radius, Math.PI * 2, false)
ctx.closePath()
ctx.fill()
ctx.restore()
return this
}
getBounds () {
return {
x: this.x - this.radius,
y: this.y - this.radius,
width: this.radius * 2,
height: this.radius * 2
}
}
}
const intersects = (rectA, rectB) => {
return !(rectA.x + rectA.width < rectB.x ||
rectB.x + rectB.width < rectA.x ||
rectA.y + rectA.height < rectB.y ||
rectB.y + rectB.height < rectA.y)
}
const checkWall = (ball) => {
const bounceFactor = 0.5
if (ball.x + ball.radius > canvas.width) {
ball.x = canvas.width - ball.radius
ball.vx *= -bounceFactor
}
if (ball.x - ball.radius < 0) {
ball.x = ball.radius
ball.vx *= -bounceFactor
}
if (ball.y + ball.radius > canvas.height) {
ball.y = canvas.height - ball.radius
ball.vy *= -1
}
if (ball.y - ball.radius < 0) {
ball.y = ball.radius
ball.vy *= -bounceFactor
}
}
const rotate = (x, y, sin, cos, reverse) => {
return {
x: reverse ? x * cos + y * sin : x * cos - y * sin,
y: reverse ? y * cos - x * sin : y * cos + x * sin
}
}
const checkCollision = (ball0, ball1, dt) => {
const dx = ball1.x - ball0.x
const dy = ball1.y - ball0.y
const dist = Math.sqrt(dx * dx + dy * dy)
const minDist = ball0.radius + ball1.radius
if (dist < minDist) {
//calculate angle, sine, and cosine
const angle = Math.atan2(dy, dx)
const sin = Math.sin(angle)
const cos = Math.cos(angle)
//rotate ball0's position
const pos0 = {x: 0, y: 0}
//rotate ball1's position
const pos1 = rotate(dx, dy, sin, cos, true)
//rotate ball0's velocity
const vel0 = rotate(ball0.vx, ball0.vy, sin, cos, true)
//rotate ball1's velocity
const vel1 = rotate(ball1.vx, ball1.vy, sin, cos, true)
//collision reaction
const vxTotal = (vel0.x - vel1.x)
vel0.x = ((ball0.mass - ball1.mass) * vel0.x + 2 * ball1.mass * vel1.x) /
(ball0.mass + ball1.mass)
vel1.x = vxTotal + vel0.x
const absV = Math.abs(vel0.x) + Math.abs(vel1.x)
const overlap = (ball0.radius + ball1.radius) - Math.abs(pos0.x - pos1.x)
pos0.x += vel0.x / absV * overlap
pos1.x += vel1.x / absV * overlap
//rotate positions back
const pos0F = rotate(pos0.x, pos0.y, sin, cos, false)
const pos1F = rotate(pos1.x, pos1.y, sin, cos, false)
//adjust positions to actual screen positions
ball1.x = ball0.x + pos1F.x
ball1.y = ball0.y + pos1F.y
ball0.x = ball0.x + pos0F.x
ball0.y = ball0.y + pos0F.y
//rotate velocities back
const vel0F = rotate(vel0.x, vel0.y, sin, cos, false)
const vel1F = rotate(vel1.x, vel1.y, sin, cos, false)
ball0.vx = vel0F.x
ball0.vy = vel0F.y
ball1.vx = vel1F.x
ball1.vy = vel1F.y
}
}
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
let oldTime = 0
canvas.width = innerWidth
canvas.height = innerHeight
document.body.appendChild(canvas)
const log = document.getElementById('log')
const balls = new Array(36).fill(null).map(_ => new Ball({
x: Math.random() * innerWidth,
y: Math.random() * innerHeight,
vx: (Math.random() * 2 - 1) * 5,
vy: (Math.random() * 2 - 1) * 5,
radius: 20,
}))
requestAnimationFrame(updateFrame)
function updateFrame (ts) {
const dt = ts - oldTime
oldTime = ts
ctx.clearRect(0, 0, innerWidth, innerHeight)
for (let i = 0; i < balls.length; i++) {
const ball = balls[i]
// ADD GRAVITY HERE
ball.vy += 2
ball.x += ball.vx * (dt * 0.005)
ball.y += ball.vy * (dt * 0.005)
checkWall(ball)
}
for (let i = 0; i < balls.length; i++) {
const ball0 = balls[i]
for (let j = i + 1; j < balls.length; j++) {
const ball1 = balls[j]
// CHECK FOR COLLISIONS HERE
checkCollision(ball0, ball1, dt)
}
}
for (let i = 0; i < balls.length; i++) {
const ball = balls[i]
ball.render(ctx)
}
// const dist = ball2.x - ball1.x
// if (Math.abs(dist) < ball1.radius + ball2.radius) {
// const vxTotal = ball1.vx - ball2.vx
// ball1.vx = ((ball1.mass - ball2.mass) * ball1.vx + 2 * ball2.mass * ball2.vx) / (ball1.mass + ball2.mass)
// ball2.vx = vxTotal + ball1.vx
// ball1.x += ball1.vx
// ball2.x += ball2.vx
// }
// ball.vy += 0.5
// ball.x += ball.vx
// ball.y += ball.vy
//
// ball.render(ctx)
requestAnimationFrame(updateFrame)
}
* { margin: 0; padding: 0; }
As you can see, I have checkCollision helper method, which calculates the kinetic energy and new velocities of a ball once it has collided with another ball. My update loop looks like this:
// add velocities to balls position
// check if its hitting any wall and bounce it back
for (let i = 0; i < balls.length; i++) {
const ball = balls[i]
// Add constant gravity to the vertical velocity
// When balls stack up on each other at the bottom, the gravity is still applied and my
// "checkCollision" method freaks out and the physics start to explode
ball.vy += 0.8
ball.x += ball.vx * (dt * 0.005)
ball.y += ball.vy * (dt * 0.005)
checkWall(ball)
}
for (let i = 0; i < balls.length; i++) {
const ball0 = balls[i]
for (let j = i + 1; j < balls.length; j++) {
const ball1 = balls[j]
// Check collisions between two balls
checkCollision(ball0, ball1, dt)
}
}
// Finally render the ball on-screen
for (let i = 0; i < balls.length; i++) {
const ball = balls[i]
ball.render(ctx)
}
How do I calculate aa gravity, while preventing the physics from exploding when the balls start stacking on top of each other?
It seems that the gravity force is colliding with the "checkCollision" method. The checkCollision method tries to move them back in place, but the constant gravity overwrites it and continues pulling them down.
EDIT: After some reading I understand some Verlet integration is in order, but am having difficulties with wrapping my head around it.
for (let i = 0; i < balls.length; i++) {
const ball = balls[i]
// This line needs to be converted to verlet motion?
ball.vy += 2
ball.x += ball.vx * (dt * 0.005)
ball.y += ball.vy * (dt * 0.005)
checkWall(ball)
}
Balls do not overlap
There is a fundamental flaw in the collision testing due to the fact that the collisions are calculated only when 2 balls overlap. In the real world this never happens.
The result of "collide on overlap" when many balls are interacting, will result in behavior that does not conserve the total energy of the system.
Resolve by order of collision
You can resolve collisions such that balls never overlap however the amount of processing is indeterminate per frame, growing exponentially as the density of balls increases.
The approach is to locate the first collision between balls in the time between frames. Resolve that collision and then with the new position of that collision find the next collision closest in time forward from the last. Do that until there are no pending collisions for that frame. (There is more to it than that) The result is that the simulation will never be in the impossible state where balls overlap.
Check out my Pool simulator on CodePen that uses this method to simulate pool balls. The balls can have any speed and always resolve correctly.
Verlet integration.
However you can reduce the noise using the overlapping collisions by using verlet integration which will keep the total energy of the balls at a more stable level.
To do that we introduce 2 new properties of the ball, px, py that hold the previous position of the ball.
Each frame we calculate the balls velocity as the difference between the current position and the new position. That velocity is used to do the calculations for the frame.
When a ball changes direction (hits wall or another ball) we also need to change the balls previous position to match where it would have been on the new trajectory.
Use constant time steps.
Using time steps based on time since last frame will also introduce noise and should not be used in the overlap collision method.
Reduce time, increase iteration
To further combat the noise you need to slow the overall speed of the balls to reduce the amount they overlay and thus more closely behave as if they collided at the point ballA.radius + ballB.radius apart. Also you should test every ball against every other ball, not just ball against balls above it in the balls array.
To keep the animation speed up you solve the ball V ball V wall collisions a few times per frame. The example does 5. The best value depends on the total energy of the balls, the level of noise that is acceptable, and the CPU power of the device its running on.
Accuracy matters
Your collision function is also way out there. I had a quick look and it did not look right. I added an alternative in the example.
When a ball hits a wall it does so at some time between the frames. You must move the ball away from the wall by the correct distance. Not doing so is like simulating a ball that sticks to a wall a tiny bit each time it hits, further diverging from what really happens.
Example
This is a rewrite of your original code. Click canvas to add some energy.
const ctx = canvas.getContext("2d");
const BOUNCE = 0.75;
const resolveSteps = 5;
var oldTime = 0;
const $setOf = (count, fn = (i) => i) => {var a = [], i = 0; while (i < count) { a.push(fn(i++)) } return a };
const $rand = (min = 1, max = min + (min = 0)) => Math.random() * (max - min) + min;
const $randP = (min = 1, max = min + (min = 0), p = 2) => Math.random() ** p * (max - min) + min;
var W = canvas.width, H = canvas.height;
const BALL_COUNT = 80;
const BALL_RADIUS = 15, BALL_MIN_RADIUS = 6;
const GRAV = 0.5 / resolveSteps;
requestAnimationFrame(updateFrame);
canvas.addEventListener("click", () => {
balls.forEach(b => {
b.px = b.x + (Math.random() * 18 - 9);
b.py = b.y + (Math.random() * -18);
})
});
class Ball {
constructor({x, y, vx, vy, radius}) {
this.x = x;
this.y = y;
this.px = x - vx;
this.py = y - vy;
this.vx = vx;
this.vy = vy;
this.radius = radius;
this.mass = radius * radius * Math.PI * (4 / 3); // use sphere volume as mass
}
render(ctx) {
ctx.moveTo(this.x + this.radius, this.y);
ctx.arc(this.x, this.y, this.radius, Math.PI * 2, false);
}
move() {
this.vx = this.x - this.px;
this.vy = this.y - this.py;
this.vy += GRAV;
this.px = this.x;
this.py = this.y;
this.x += this.vx;
this.y += this.vy;
this.checkWall();
}
checkWall() {
const ball = this;
const top = ball.radius;
const left = ball.radius;
const bottom = H - ball.radius;
const right = W - ball.radius;
if (ball.x > right) {
const away = (ball.x - right) * BOUNCE;
ball.x = right - away;
ball.vx = -Math.abs(ball.vx) * BOUNCE;
ball.px = ball.x - ball.vx;
} else if (ball.x < left) {
const away = (ball.x - left) * BOUNCE;
ball.x = left + away;
ball.vx = Math.abs(ball.vx) * BOUNCE;
ball.px = ball.x - ball.vx;
}
if (ball.y > bottom) {
const away = (ball.y - bottom) * BOUNCE;
ball.y = bottom - away;
ball.vy = -Math.abs(ball.vy) * BOUNCE;
ball.py = ball.y - ball.vy;
} else if (ball.y < top) {
const away = (ball.y - top) * BOUNCE;
ball.y = top + away;
ball.vy = Math.abs(ball.vy) * BOUNCE;
ball.py = ball.y - ball.vy;
}
}
collisions() {
var b, dx, dy, nx, ny, cpx, cpy, p, d, i = 0;
var {x, y, vx, vy, px, py, radius: r, mass: m} = this;
while (i < balls.length) {
b = balls[i++];
if (this !== b) {
const rr = r + b.radius;
if (x + rr > b.x && x < b.x + rr && y + rr > b.y && y < b.y + rr) {
dx = x - b.x;
dy = y - b.y;
d = (dx * dx + dy * dy) ** 0.5;
if (d < rr) {
nx = (b.x - x) / d;
ny = (b.y - y) / d;
p = 2 * (vx * nx + vy * ny - b.vx * nx - b.vy * ny) / (m + b.mass);
cpx = (x * b.radius + b.x * r) / rr;
cpy = (y * b.radius + b.y * r) / rr;
x = cpx + r * (x - b.x) / d;
y = cpy + r * (y - b.y) / d;
b.x = cpx + b.radius * (b.x - x) / d;
b.y = cpy + b.radius * (b.y - y) / d;
px = x - (vx -= p * b.mass * nx);
py = y - (vy -= p * b.mass * ny);
b.px = b.x - (b.vx += p * m * nx);
b.py = b.y - (b.vy += p * m * ny);
}
}
}
}
this.x = x;
this.y = y;
this.px = px;
this.py = py;
this.vx = vx;
this.vy = vy;
this.checkWall();
}
}
const balls = (() => {
return $setOf(BALL_COUNT, () => new Ball({
x: $rand(BALL_RADIUS, W - BALL_RADIUS),
y: $rand(BALL_RADIUS, H - BALL_RADIUS),
vx: $rand(-2, 2),
vy: $rand(-2, 2),
radius: $randP(BALL_MIN_RADIUS, BALL_RADIUS, 4),
}));
})();
function updateFrame(ts) {
var i = 0, j = resolveSteps;
ctx.clearRect(0, 0, W, H);
while (i < balls.length) { balls[i++].move() }
while (j--) {
i = 0;
while (i < balls.length) { balls[i++].collisions(balls) }
}
ctx.fillStyle = "#0F0";
ctx.beginPath();
i = 0;
while (i < balls.length) { balls[i++].render(ctx) }
ctx.fill();
requestAnimationFrame(updateFrame)
}
<canvas id="canvas" width="400" height="180" style="border:1px solid black;"></canvas>
<div style="position: absolute; top: 10px; left: 10px;">Click to stir</div>

How to draw rectangle spiral?

I'm trying to draw a one pixel width line going form the canvas center and evolving with the canvas width/height ratio as it's drawn.
var x = 0;
var y = 0;
var dx = 0;
var dy = -1;
var width = 200;
var height = 40;
//var i = width * height;
var counter = 0;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
setInterval(function(){
//for (i = Math.pow(Math.max(width, height), 2); i>0; i--) {
if ((-width/2 < x <= width/2) && (-height/2 < y <= height/2)) {
console.log("[ " + x + " , " + y + " ]");
ctx.fillStyle = "#FF0000";
ctx.fillRect(width/2 + x, height/2 - y,1,1);
}
if (x === y || (x < 0 && x === -y) || (x > 0 && x === 1-y) || ( -width/2 > x > width/2 ) || ( -height/2 > y > height/2 ) ) {
// change direction
var tempdx = dx;
dx = -dy;
dy = tempdx;
}
counter += 1;
//alert (counter);
x += dx;
y += dy;
}, 1);
I want the spiral to evolve as such:
I'd like to be able to get the ratio between height and width on the equation, so I don't need to calculate the coordinates for points outside the canvas. Also, the purpose is for it to adjust the spiral drawing to the canvas proportions.
Any help would be appreciated.
A friend helped me handling a proper solution. I only have a 1 pixel offset to solve where I need to move all the drawing to the left by one pixel.
Here's the fiddle for the solution achieved: http://jsfiddle.net/hitbyatruck/c4Kd6/
And the Javascript code below:
var width = 150;
var height = 50;
var x = -(width - height)/2;
var y = 0;
var dx = 1;
var dy = 0;
var x_limit = (width - height)/2;
var y_limit = 0;
var counter = 0;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
setInterval(function(){
if ((-width/2 < x && x <= width/2) && (-height/2 < y && y <= height/2)) {
console.log("[ " + x + " , " + y + " ]");
ctx.fillStyle = "#FF0000";
ctx.fillRect(width/2 + x, height/2 - y,1,1);
}
if( dx > 0 ){//Dir right
if(x > x_limit){
dx = 0;
dy = 1;
}
}
else if( dy > 0 ){ //Dir up
if(y > y_limit){
dx = -1;
dy = 0;
}
}
else if(dx < 0){ //Dir left
if(x < (-1 * x_limit)){
dx = 0;
dy = -1;
}
}
else if(dy < 0) { //Dir down
if(y < (-1 * y_limit)){
dx = 1;
dy = 0;
x_limit += 1;
y_limit += 1;
}
}
counter += 1;
//alert (counter);
x += dx;
y += dy;
}, 1);
I nearly crashed my browser trying this. Here, have some code before I hurt myself!
It computes y=f(x) for the diagonal, and y2=f(x) for the antidiagonal, then checks if we're above or below the diagonals when needed.
var x = 0;
var y = 0;
var dx = 0;
var dy = -1;
var width = 200;
var height = 40;
//var i = width * height;
var counter = 0;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
function diag1(x) {
return x*height/width;
}
function diag2(x) {
return -1/diag(x);
}
setInterval(function(){
//for (i = Math.pow(Math.max(width, height), 2); i>0; i--) {
if ((-width/2 < x && x <= width/2) && (-height/2 < y && y <= height/2)) {
console.log("[ " + x + " , " + y + " ]");
ctx.fillStyle = "#FF0000";
ctx.fillRect(width/2 + x, height/2 - y,1,1);
}
if (dx == 0) {
if (dy == 1) {
// moving up
if (y >= diag1(x)) {
// then move left
dy = 0;
dx = -1;
}
}
else {
// moving down
if (y <= diag2(x)) {
// then move right
dy = 0;
dx = 1;
}
}
}
else {
if (dx == 1) {
// moving right
if (y <= diag1(x)) {
// then move up
dy = 1;
dx = 0;
}
}
else {
// moving left
if (y <= diag2(x)) {
// then move down
dy = -1;
dx = 0;
}
}
}
counter += 1;
//alert (counter);
x += dx;
y += dy;
}, 1);

Error reading 'Cannot read property 'x' of undefined' in HTML5 Canvas code

I am having a problem with my JavaScript code. Since I made it so that you could delete shapes from the canvas an error is appearing when I try adding additional shapes to the canvas. The error reads: 'Cannot read property 'x' of undefined'. When the error appears, it quotes line 116 of the code, which reads: 'var dx = tmpRingB.x - tmpRing.x;'. I need to make it so this error does not appear. The code is as below.
var shapeObj = function (counter, context, canvas, settingsBox) {
//Where sound info goes (freq, vol, amp, adsr etc)
this.id = "shape"+counter;
this.ctx = context;
this.canvas = canvas;
this.sBox = settingsBox;
this.audioProperties = {
duration: Math.random()*1-0.1,
frequency: Math.random()*44000-220
}
this.x = Math.random()*this.ctx.canvas.width;
this.y = Math.random()*this.ctx.canvas.height;
this.radius = 40;
this.vx = Math.random()*6-3;
this.vy = Math.random()*6-3;
this.draw = function () {
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
this.ctx.closePath();
this.ctx.stroke();
}
this.clickTest = function (e) {
var canvasOffset = this.canvas.offset();
var canvasX = Math.floor(e.pageX-canvasOffset.left);
var canvasY = Math.floor(e.pageY-canvasOffset.top);
var dX = this.x-canvasX;
var dY = this.y-canvasY;
var distance = Math.sqrt((dX*dX)+(dY*dY));
if (distance <= this.radius) {
this.manageClick();
}
};
this.manageClick = function(){
alert('this is ' + this.id);
this.sBox.populate(this.audioProperties, this);
this.radius -= 10;
}
this.update = function(newProps){
// repopulate the shapes with new settings
}
}
var settingsBox = function (){
this.populate = function(props, obj){
for (a in props){
alert(props[a]);
}
}
}
$(document).ready(function() {
var canvas = $('#myCanvas');
var ctx = canvas.get(0).getContext("2d");
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
$(window).resize(resizeCanvas);
function resizeCanvas() {
canvas.attr("width", $(window).get(0).innerWidth - 2);
canvas.attr("height", $(window).get(0).innerHeight - 124);
canvasWidth = canvas.width();
canvasHeight = canvas.height();
};
resizeCanvas();
canvas.onselectstart = function () { return false; }
ctx.strokeStyle = "rgb(255, 255, 255)";
ctx.lineWidth = 5;
var playAnimation = true;
$(canvas).click(function(e) {
for (i = 0; i < objects.length; i++) {
objects[i].clickTest(e);
}
});
objects = [];
sBox = new settingsBox();
for (var i = 0; i < 4; i++) {
var ring = new shapeObj(i, ctx, canvas, sBox);
objects[i] = ring;
objects[i].draw();
}
$("#button4").click(function() {
var ring = new shapeObj(i, ctx, canvas, sBox);
objects[i] = ring;
objects[i++].draw();
playSoundA();
});
function animate() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
deadObjects = [];
for (var i = 0; i < objects.length; i++) {
var tmpRing = objects[i];
for (var j = i+1; j < objects.length; j++) {
var tmpRingB = objects[j];
var dx = tmpRingB.x - tmpRing.x;
var dy = tmpRingB.y - tmpRing.y;
var dist = Math.sqrt((dx * dx) + (dy * dy));
if(dist < tmpRing.radius + tmpRingB.radius) {
playSound();
//Put collision animations here!!!
var angle = Math.atan2(dy, dx);
var sine = Math.sin(angle);
var cosine = Math.cos(angle);
var x = 0;
var y = 0;
var xb = dx * cosine + dy * sine;
var yb = dy * cosine - dx * sine;
var vx = tmpRing.vx * cosine + tmpRing.vy * sine;
var vy = tmpRing.vy * cosine - tmpRing.vx * sine;
var vxb = tmpRingB.vx * cosine + tmpRingB.vy * sine;
var vyb = tmpRingB.vy * cosine - tmpRingB.vx * sine;
vx *= -1;
vxb *= -1;
xb = x + (tmpRing.radius + tmpRingB.radius);
tmpRing.x = tmpRing.x + (x * cosine - y * sine);
tmpRing.y = tmpRing.y + (y * cosine + x * sine);
tmpRingB.x = tmpRing.x + (xb * cosine - yb * sine);
tmpRingB.y = tmpRing.y + (yb * cosine + xb * sine);
tmpRing.vx = vx * cosine - vy * sine;
tmpRing.vy = vy * cosine + vx * sine;
tmpRingB.vx = vxb * cosine - vyb * sine;
tmpRingB.vy = vyb * cosine + vxb * sine;
tmpRing.loop = true;
};
};
tmpRing.x += tmpRing.vx;
tmpRing.y += tmpRing.vy;
if (tmpRing.x - tmpRing.radius < 0) {
playSound();
tmpRing.x = tmpRing.radius;
tmpRing.vx *= -1;
} else if (tmpRing.x + tmpRing.radius > ctx.canvas.width) {
playSound();
tmpRing.x = ctx.canvas.width - tmpRing.radius;
tmpRing.vx *= -1;
};
if (tmpRing.y - tmpRing.radius < 0) {
playSound();
tmpRing.y = tmpRing.radius;
tmpRing.vy *= -1;
} else if (tmpRing.y + tmpRing.radius > ctx.canvas.height) {
playSound();
tmpRing.y = ctx.canvas.height - tmpRing.radius;
tmpRing.vy *= -1;
};
if(tmpRing.radius <= 0) {
deadObjects.push(tmpRing);
}
objects[i].draw();
};
if (deadObjects.length > 0) {
for (var d = 0; d < deadObjects.length; d++) {
var tmpDeadObject = deadObjects[d];
objects.splice(objects.indexOf(tmpDeadObject), 1);
}
}
if(playAnimation) {
setTimeout(animate, 33);
};
};
animate();
});
Any ideas?
Thanks for the help.
Your object is undefined because you've deleted it. A simple solution is to check to see if the object is still defined.
insert the following line just before the line with the error.
if(!(tmpRingB && tmpRing)) continue;
a better solution is to clean house on your array when you delete it.

Categories