Canvas game shooting and selecting issue + viewport - javascript

I got a problem with shooting in my canvas game. When I shoot bullet to target(enemy) and there is no other enemies on front of, bullet goes right, but when enemies are in front of player and they're covering straight path to target, bullet dissapears when met first enemy. I want bullet to go over enemies straight to target, and I have no idea how to achieve that.
Other problem is with that crosshair which I made, It can select multiple enemies, but I want to be able to select only one enemy. Any ideas how to deal with that? I'm almost sure, this is a small problem.
I want to make viewport then, but when I implement something from internet, it just doesn't work, and, I'm not just asking, I really tried hard to make this viewport, also like resolving other problems I mentioned. I hope you can help me out with some of these problems, thanks.
var ctx = $("#canvas")[0].getContext('2d'),
cHeight = canvas.height = 800,
cWidth = canvas.width = 1300,
canvasOffset = $('#canvas').offset(),
offsetX = canvasOffset.left,
offsetY = canvasOffset.top,
frameCounter = 0,
enemyList = [],
bulletList = [],
spawningEnemies_FLAG = true,
isLeftMouseButtonHeld_FLAG = false,
isAnyEnemySelected_FLAG = false,
cursors = ['default', 'pointer'],
enemiesOnMap = 10;
ctx.font = '22px Arial';
var sharedBehaviour = {
x: (cWidth / 2) - (cWidth / 8) + randomNumberFromRange(1, (cWidth / 8)),
y: (cHeight / 2) - (cHeight / 8) + randomNumberFromRange(1, (cHeight / 8)),
id: undefined,
type: 'entity',
width: 15,
height: 15,
fillColor: '#E15258',
targetX: null,
targetY: null,
bulletSpeed: 1,
aimAngle: null,
circleRadius: null,
circleColor: 'black',
circleWidth: 1,
// Statistics
hp: 10,
shield: 0,
speed: 1,
update( type ) {
if( type === 'player' ) {
enemyList.forEach( enemy => {
if ( enemy.isMouseOver() ) {
if( isLeftMouseButtonHeld_FLAG ) {
player.targetX = player.targetY = null;
}
}
});
}
// if there is target
if( this.targetX !== null ) {
// Find out distance to target
var distanceX = this.targetX - this.x; // distance on X axis
var distanceY = this.targetY - this.y; // distance on Y axis
var distanceToTarget = Math.sqrt( distanceX*distanceX + distanceY*distanceY ); // distance
// If distance is smaller or equal speed, then just set position
if( distanceToTarget <= this.speed ) {
this.x = this.targetX;
this.y = this.targetY;
// Then reset
this.targetX = this.targetY = null;
} else { // If distance is bigger than speed, so we want to move with speed
distanceX = distanceX / distanceToTarget;
distanceY = distanceY / distanceToTarget;
distanceX = distanceX * this.speed;
distanceY = distanceY * this.speed;
this.x += distanceX;
this.y += distanceY;
}
}
},
draw( ) {
drawRect( this.x - this.width/2,
this.y - this.height/2,
this.width,
this.height,
this.fillColor );
},
highlight( ) {
crosshair( this.x - this.width/2, this.y - this.height/2, this.width, this.height,
20, 25, // radius1, radius2
6, // endLineWidth
1, 2, // circle1Width, circle2Width
2, 2, 2, 2, // topLineWidth, rightLineWidth, bottomLineWidth, leftLineWidth
'#E15258', '#E15258', // circle1Color, circle2Color
'#C25975' ); // linesColor
},
isColliding( entity ) {
// Collision: rect to rect
return testCollisionRectRect( this, entity );
},
drawCircle( ) {
drawCircle( this.x, this.y, this.circleRadius, this.circleWidth, this.circleColor );
}
};
var player = Object.assign({}, sharedBehaviour, {
x: cWidth/2 - 10,
y: cHeight/2 - 10,
id: 980722,
type: 'player',
width: 20,
height: 20,
fillColor: '#82d877',
bulletSpeed: 1,
circleRadius: 200,
circleColor: 'black',
circleWidth: 1,
pressingC: false,
// Player stats
name: 'player1',
pd: 0,
hp: 10,
speed: 2.5
});
function createEnemy( x, y, id, width, height, fillColor, speed, type ) {
var newEnemy = Object.assign({}, sharedBehaviour, {
x,
y,
id,
width,
height,
type,
fillColor,
mouseX: null,
mouseY: null,
isHighlighted: false,
isClicked: false,
circleRadius: 50,
circleColor: 'red',
circleWidth: 1,
// Statistics
hp: 100,
shield: 0,
speed,
setTarget( entity ) {
this.targetX = entity.x + randomNumberFromRange(-50, 50);
this.targetY = entity.y + randomNumberFromRange(-50, 50);
},
isOnPlayer( val ) {
// Check if enemy is on player
var distanceX = player.x - this.x;
var distanceY = player.y - this.y;
return Math.sqrt( distanceX*distanceX + distanceY*distanceY ) < val;
},
isMouseOver( ) {
return (this.mouseX + this.width/2 >= this.x && this.mouseX + this.width/2 <= this.x + this.width && this.mouseY + this.height/2 >= this.y && this.mouseY + this.height/2 <= this.y + this.height);
}
});
enemyList.push( newEnemy );
}
function createBullet( actor ) {
var newBullet = Object.assign({}, sharedBehaviour, {
x: actor.x,
y: actor.y,
height: 7,
width: 7,
aimAngle: actor.aimAngle,
fillColor: 'green',
spdX: Math.cos(actor.aimAngle/180*Math.PI)*8,
spdY: Math.sin(actor.aimAngle/180*Math.PI)*8,
update ( ) {
this.x += this.spdX;
this.y += this.spdY;
}
});
bulletList.push( newBullet );
}
function newGame( ) {
// Reset all to its defaults
player.hp = 10;
frameCounter = 0;
enemyList = [];
bulletList = [];
spawningEnemies_FLAG = true;
isLeftMouseButtonHeld_FLAG = false;
// Spawning enemies
for( i=0; i < randomNumberFromRange(15, 25); i++ ) {
createEnemy( randomNumberFromRange(0, cWidth), randomNumberFromRange(0, cHeight), 'str' + (i+1), randomNumberFromRange(12, 18), randomNumberFromRange(12, 18), 'red', 1, 's' );
createEnemy( randomNumberFromRange(0, cWidth), randomNumberFromRange(0, cHeight), 'lor' + (i+1), randomNumberFromRange(10, 16), randomNumberFromRange(10, 16), 'lightblue', 1.5, 'l' );
}
requestAnimationFrame(update);
}
function update( ) {
frameCounter++;
ctx.clearRect(0,0,cWidth,cHeight);
enemyList.forEach( enemy => {
enemy.update();
});
// Update bullet position and remove if goes out of canvas
bulletList.forEach( bullet => {
bullet.update();
if ( bullet.x < 0 || bullet.x > cWidth || bullet.y < 0 || bullet.y > cHeight) {
bulletList.remove(bullet);
}
});
player.update('player');
enemyList.forEach( enemy => {
if( enemy.isHighlighted ) {
if( enemy.isMouseOver() ) {
enemy.draw();
enemy.highlight();
} else {
enemy.draw()
}
} else {
enemy.draw();
}
if( enemy.isClicked ) {
enemy.draw();
enemy.highlight();
} else {
enemy.draw();
}
if ( Math.random() < ( 1 / 15 ) ) { // 1 in 25 chance to look for player about once every 0.25 sec
if ( enemy.isOnPlayer( player.circleRadius ) ) {
if ( ! (enemy.isOnPlayer( 50 )) ) {
enemy.setTarget( player );
}
}
}
if ( Math.random() < ( 1 / 800 )) { // 1 in 500 chance to look for player about once every 5 sec
if ( ! (enemy.isOnPlayer( player.circleRadius )) ) {
enemy.setTarget( enemy );
}
}
if ( enemy.isOnPlayer(player.circleRadius/4 ) ) {
enemy.targetX = enemy.targetY = null; // Reset enemy target
}
// If bullet has collision with enemy, rcemove both and add reward
bulletList.forEach( bullet => {
if ( testCollisionRectRect(enemy, bullet) ) {
if( enemy.isClicked ) {
enemy.hp -= 5;
bulletList.remove(bullet);
if ( enemy.hp <= 0 ) {
enemyList.remove(enemy);
}
}
}
});
});
bulletList.forEach( bullet => {
bullet.draw();
});
player.draw();
player.drawCircle();
if ( frameCounter % 500 === 0 && spawningEnemies_FLAG ) {
createEnemy( randomNumberFromRange(0, cWidth), randomNumberFromRange(0, cHeight), 'str' + (i+1), randomNumberFromRange(12, 18), randomNumberFromRange(12, 18), 'red', 1, 's' );
createEnemy( randomNumberFromRange(0, cWidth), randomNumberFromRange(0, cHeight), 'lor' + (i+1), randomNumberFromRange(10, 16), randomNumberFromRange(10, 16), 'lightblue', 1.5, 'l' );
}
if ( enemyList.length === enemiesOnMap ) {
spawningEnemies_FLAG = false;
} else {
spawningEnemies_FLAG = true;
}
ctx.fillText(player.hp + " hp", 10, 25);
ctx.fillText('Map 1', cWidth-70, 25);
requestAnimationFrame(update);
}
document.onmousedown = function( mouse ) {
isLeftMouseButtonHeld_FLAG = true;
setPlayerTargetAndCheckAvailableArea( mouse );
}
document.onmouseup = function( mouse ) {
isLeftMouseButtonHeld_FLAG = false;
}
document.onmousemove = function( mouse ) {
if ( isLeftMouseButtonHeld_FLAG ) {
setPlayerTargetAndCheckAvailableArea( mouse );
}
var mouseX = mouse.clientX - document.getElementById('canvas').getBoundingClientRect().left;
var mouseY = mouse.clientY - document.getElementById('canvas').getBoundingClientRect().top;
var newX, newY;
enemyList.forEach( enemy => {
if( enemy.isClicked ) {
isAnyEnemySelected_FLAG = true;
newX = enemy.x;
newY = enemy.y;
}
});
if( isAnyEnemySelected_FLAG ) {
newX -= player.x;
newY -= player.y;
player.aimAngle = Math.atan2(newY, newX) / Math.PI * 180;
} else {
isAnyEnemySelected_FLAG = false;
mouseX -= player.x;
mouseY -= player.y;
player.aimAngle = Math.atan2(mouseY, mouseX) / Math.PI * 180;
}
var mousexX = parseInt(mouse.clientX - offsetX);
var mouseyY = parseInt(mouse.clientY - offsetY);
var currentCursor = 0;
enemyList.forEach( enemy => {
enemy.mouseX = mousexX;
enemy.mouseY = mouseyY;
if(enemy.isMouseOver()) {
currentCursor = 1;
if(enemy.isClicked) {
enemy.isHighlighted = false;
} else {
enemy.isHighlighted = true;
}
} else {
enemy.isHighlighted = false;
}
});
canvas.style.cursor = cursors[currentCursor];
}
document.onclick = function( mouse ) {
var mousexX = parseInt(mouse.clientX - offsetX);
var mouseyY = parseInt(mouse.clientY - offsetY);
enemyList.forEach( enemy => {
enemy.mouseX = mousexX;
enemy.mouseY = mouseyY;
if(enemy.isMouseOver()) {
if(enemy.isHighlighted) {
enemy.isHighlighted = false;
enemy.isClicked = true;
} else {
enemy.isClicked = false;
}
} else {
enemy.isClicked = false;
}
});
}
document.onkeydown = function ( key ) {
switch(key.keyCode) {
case 67:
player.pressingC = true;
break;
}
}
document.onkeyup = function ( key ) {
switch(key.keyCode) {
case 67:
player.pressingC = false;
if( isAnyEnemySelected_FLAG ) {
createBullet( player );
}
break;
}
}
function setPlayerTargetAndCheckAvailableArea ( mouse ) {
player.targetX = mouse.clientX - document.getElementById('canvas').getBoundingClientRect().left;
player.targetY = mouse.clientY - document.getElementById('canvas').getBoundingClientRect().top;
if (player.targetX < player.width/2) {
player.targetX = player.width/2;
}
if (player.targetX > cWidth - player.width/2) {
player.targetX = cWidth - player.width/2
}
if (player.targetY < player.height/2) {
player.targetY = player.height/2;
}
if (player.targetY > cHeight - player.height/2) {
player.targetY = cHeight - player.height/2
}
}
function randomNumberFromRange( min, max ) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function testCollisionRectRect( rectangle1, rectangle2 ) {
return rectangle1.x - rectangle1.width/2 <= rectangle2.x - rectangle2.width/2 + rectangle2.width
&& rectangle2.x - rectangle2.width/2 <= rectangle1.x - rectangle1.width/2 + rectangle1.width
&& rectangle1.y - rectangle1.height/2 <= rectangle2.y - rectangle2.height/2 + rectangle2.height
&& rectangle2.y - rectangle2.height/2 <= rectangle1.y - rectangle1.height/2 + rectangle1.height;
}
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
}; // Function to pop specific element drom array by value
function crosshair( x, y, width, height, radius1, radius2, endLineWidth, circle1Width, circle2Width, topLineWidth, rightLineWidth, bottomLineWidth, leftLineWidth, circle1Color, circle2Color, linesColor) {
drawCircle(x + width/2, y + height/2, radius1, circle1Width, circle1Color);
drawCircle(x + width/2, y + height/2, radius2, circle2Width, circle2Color);
drawLine(x + radius1 + width/2, y + height/2, x + (radius2 + endLineWidth) + width/2, y + height/2, linesColor, leftLineWidth);
drawLine(x - radius1 + width/2, y + height/2, x - (radius2 + endLineWidth) + width/2, y + height/2, linesColor, rightLineWidth);
drawLine(x + width/2, y + radius1 + height/2, x + width/2, y + (radius2 + endLineWidth) + height/2, linesColor, bottomLineWidth);
drawLine(x + width/2, y - radius1 + height/2, x + width/2, y - (radius2 + endLineWidth) + height/2, linesColor, topLineWidth);
}
function drawLine( startX, startY, endX, endY, color, width ) {
ctx.save();
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(endX,endY);
ctx.stroke();
ctx.restore();
}
function drawCircle( x, y, radius, lineWidth, strokeColor ) {
ctx.save();
ctx.beginPath();
ctx.arc( x, y, radius, 0, 2 * Math.PI, false);
ctx.lineWidth = lineWidth;
ctx.strokeStyle = strokeColor;
ctx.stroke();
ctx.restore();
}
function drawBorder( x, y, width, height, lineWidth, strokeColor ) {
ctx.save();
ctx.lineWidth = lineWidth;
ctx.strokeStyle = strokeColor;
ctx.strokeRect( x, y, width, height);
ctx.restore();
}
function drawRect( x, y, width, height, fillColor ) {
ctx.save();
ctx.fillStyle = fillColor;
ctx.fillRect( x, y, width, height );
ctx.restore();
}
newGame();
canvas {
border: 1px solid black;
background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<canvas id="canvas" width="1300" height="800"></canvas>

Related

Canavs is not drawing all the dots. Only one is showing up

In this script I’m trying to make a coordinate plane with two dots/circles. When I add the second dot in the code, it only shows the second one.
The part with the dots is this piece of code:
point(AX, AY, false, 'red', 6)
point(BX, BY, false, 'red', 6)
Can someone please help me with this problem? Thanks a lot!
start();
function start() {
console.clear();
document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var AX = document.getElementById("AX").value;
var AY = document.getElementById("AY").value;
var BX = document.getElementById("BX").value;
var BY = document.getElementById("BY").value;
var SQUARE_SIZE = 30;
var XSCALE = 1;
var YSCALE = 1;
var centerX = 0;
var centerY = 0;
selected = [];
points = [];
lines = [];
segments = [];
history = [];
circles = [];
function point(x, y, isSelected, color, r) {
this.x = x;
this.y = y;
this.color = color;
this.r = r;
this.add = function () {
plotPoint(this.x, this.y, this.color, this.r);
};
points.push(this);
if (isSelected) {
selected.push(this);
}
this.distance = function (gx, gy) {
return Math.sqrt(Math.pow(this.x - gx, 2) + Math.pow(this.y - gy, 2));
};
}
function point1(x, y, isSelected, color, r) {
this.x = x;
this.y = y;
this.color = color;
this.r = r;
this.add = function () {
plotPoint(this.x, this.y, this.color, this.r);
};
points.push(this);
if (isSelected) {
selected.push(this);
}
this.distance = function (gx, gy) {
return Math.sqrt(Math.pow(this.x - gx, 2) + Math.pow(this.y - gy, 2));
};
}
function circle(x, y, color, r) {
this.x = x;
this.y = y;
this.color = color;
this.r = r;
this.add = function () {
ctx.beginPath();
ctx.arc(convertX(x), convertY(y), r, 0, 2 * Math.PI);
ctx.stroke();
};
}
function line(m, b, color, width) {
this.m = m;
this.b = b;
this.color = color;
this.width = width;
lines.push(this);
}
function segment(a, b, color, width) {
this.a = a;
this.b = b;
this.color = color;
this.width = width;
this.getSlope = function () {
return (b.y - a.y) / (b.x - a.x);
};
this.getIntercept = function () {
var m = this.getSlope();
return a.y - m * a.x;
};
this.getLength = function () {
return Math.sqrt(this.a.x - this.b.x + this.a.y - this.b.y);
};
this.distance = function (gx, gy) {
//var m = (b.y-a.y)/(b.x-a.x)
//var bb = a.y-m*a.x
var m = this.getSlope();
var bb = this.getIntercept();
var pim = 1 / -m;
var pib = gy - pim * gx;
if (m === 0) {
pix = gx;
piy = this.a.y;
} else if (Math.abs(m) === Infinity) {
var pix = this.a.x;
var piy = gy;
} else {
var pix = (pib - bb) / (m - pim); //((gy-(gx/m)-bb)*m)/(m*m-1)
var piy = pim * pix + pib;
}
//console.log("m:"+m+" pim:"+pim+" pib:"+pib+" pix"+pix+" piy:"+piy)
if (
((this.a.x <= pix && pix <= this.b.x) ||
(this.b.x <= pix && pix <= this.a.x)) &&
((this.a.y <= piy && piy <= this.b.y) ||
(this.b.y <= piy && piy <= this.a.y))
) {
var d = Math.sqrt(Math.pow(gx - pix, 2) + Math.pow(gy - piy, 2));
return d;
} else {
var d = Math.min(this.a.distance(gx, gy), this.b.distance(gx, gy));
return d;
}
};
this.add = function () {
if (selected.indexOf(this) > -1) {
plotLine(this.a.x, this.a.y, this.b.x, this.b.y, color, width, [5, 2]);
} else {
plotLine(this.a.x, this.a.y, this.b.x, this.b.y, color, width);
}
};
segments.push(this);
}
// var a = new point(1,1)
// var b = new point(3,4)
// new segment(a,b)
//var testline = new line(1, 2, 'red', 1)
function drawLine(x1, y1, x2, y2, color, width, dash) {
ctx.save();
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = color;
ctx.lineWidth = width;
if (dash !== undefined) {
ctx.setLineDash(dash);
}
ctx.stroke();
ctx.restore();
}
function convertX(x) {
return ((x - xmin - centerX) / (xmax - xmin)) * width;
}
function revertX(x) {
return (x * (xmax - xmin)) / width + centerX + xmin;
}
function convertY(y) {
return ((ymax - y - centerY) / (ymax - ymin)) * height;
}
function revertY(y) {
return (y * (ymin - ymax)) / height - centerY - ymin;
}
function addAxis() {
var TICK = 0;
for (
var i = Math.floor(xmin + centerX);
i <= Math.floor(xmax + centerX);
i += XSCALE
) {
drawLine(
convertX(i),
convertY(0) + TICK,
convertX(i),
convertY(0) - TICK
);
}
for (
var i = Math.floor(ymin - centerY);
i <= Math.floor(ymax - centerY);
i += YSCALE
) {
drawLine(
convertX(0) - TICK,
convertY(i),
convertX(0) + TICK,
convertY(i)
);
}
}
function addGrid() {
for (
var i = Math.floor(ymin - centerY);
i <= Math.floor(ymax - centerY);
i += YSCALE
) {
drawLine(0, convertY(i), width, convertY(i), "lightgrey", 1);
}
for (
var i = Math.floor(xmin + centerX);
i <= Math.floor(xmax + centerX);
i += XSCALE
) {
drawLine(convertX(i), height, convertX(i), 0, "lightgrey", 1);
}
}
function addPoints() {
for (const p of points) {
p.add();
}
}
function addCircles() {
for (const c of circles) {
c.add();
}
}
function addLines() {
for (const l of lines) {
plotLine(
xmin + centerX,
l.m * (xmin + centerX) + l.b,
xmax + centerX,
l.m * (xmax + centerX) + l.b,
l.color,
l.width
);
}
}
function addSegments() {
for (const s of segments) {
s.add();
}
}
function plotPoint(x, y, color, r) {
if (r === undefined) {
r = 2;
}
if (color === undefined) {
color = "black";
}
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(convertX(x), convertY(y), r, 0, 2 * Math.PI);
ctx.fill();
}
function plotCircle(x, y, color, r) {
if (r === undefined) {
r = 2;
}
if (color === undefined) {
color = "black";
}
ctx.beginPath();
ctx.arc(convertX(x), convertY(y), r, 0, 2 * Math.PI);
ctx.stroke();
}
function plotLine(x1, y1, x2, y2, color, width, dash) {
ctx.save();
ctx.beginPath();
ctx.moveTo(convertX(x1), convertY(y1));
ctx.lineTo(convertX(x2), convertY(y2));
ctx.strokeStyle = color;
ctx.lineWidth = width;
if (dash !== undefined) {
ctx.setLineDash(dash);
}
ctx.stroke();
ctx.restore();
}
function snap(x) {
if ((x - Math.round(x)) * (x - Math.round(x)) < 0.01) {
return Math.round(x);
} else {
return x;
}
}
function mouseDown(evt) {
x = evt.clientX;
y = evt.clientY;
ocx = centerX;
ocy = centerY;
if (evt.buttons === 2) {
for (const p of points) {
if (
nx * nx - 2 * convertX(p.x) * nx + convertX(p.x) * convertX(p.x) <
36 &&
ny * ny - 2 * convertY(p.y) * ny + convertY(p.y) * convertY(p.y) < 36
) {
s = new segment(p, new point(revertX(x), revertY(y), true));
selected.push(s);
return;
}
}
new point(snap(revertX(x)), snap(revertY(y)));
}
if (evt.buttons === 1) {
for (const p of points) {
if (p.distance(revertX(x), revertY(y)) < 0.2) {
selected.push(p);
}
console.log(p.distance(revertX(x), revertY(y)));
}
for (const s of segments) {
if (s.distance(revertX(x), revertY(y)) < 0.2) {
selected.push(s);
}
console.log(s.distance(revertX(x), revertY(y)));
}
}
onresize();
}
function mouseUp() {
selected = [];
}
function mouseMove(evt) {
console.clear();
nx = evt.clientX;
ny = evt.clientY;
gx = revertX(nx);
gy = revertY(ny);
if (evt.buttons === 1) {
if (selected.length > 0) {
for (const p of selected) {
p.x = snap(gx);
p.y = snap(gy);
}
} else {
centerX = (x - nx) / SQUARE_SIZE + ocx;
centerY = (y - ny) / SQUARE_SIZE + ocy;
}
}
if (evt.buttons === 2) {
for (const p of selected) {
p.x = snap(gx);
p.y = snap(gy);
}
}
console.log("coords: " + gx + ", " + gy);
console.log("points: " + points);
console.log("segments:" + segments);
console.log("selected: " + selected);
onresize();
}
function keyPress(evt) {
if ((evt.keyCode = 32)) {
//space
if (selected.length > 0) selected = [];
}
onresize();
}
point(AX, AY, false, "red", 6);
point(BX, BY, false, "red", 6);
window.onresize = function () {
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
xmin = -width / SQUARE_SIZE / 2;
xmax = width / SQUARE_SIZE / 2;
ymin = -height / SQUARE_SIZE / 2;
ymax = height / SQUARE_SIZE / 2;
addGrid();
addAxis();
addPoints();
addLines();
addSegments();
addCircles();
ctx.font = "12px Arial";
ctx.fillStyle = "black";
ctx.fillText("Number of Points: " + points.length, 20, 30);
ctx.fillText("Points Slected: " + selected.length, 20, 50);
};
onresize();
}
<h2>LocusCreator v1.0 - © Niels Langerak</h2>
<p>Use the inputboxes to fill in all the info to make the locus.</p>
<p>Circle A - X:</p>
<input type="number" id="AX" value="0">
<p>Circle A - Y:</p>
<input type="number" id="AY" value="0">
<p>Circle B - X:</p>
<input type="number" id="BX" value="1">
<p>Circle B - Y:</p>
<input type="number" id="BY" value="1">
<button onclick="start()">Reload</button>
<canvas width=600px height=600px id='canvas'>
You should use the new keyword when creating your point:
new point(AX, AY, false, 'red', 6)
new point(BX, BY, false, 'red', 6)
It creates a new instance of point, but not overwrite it, as it works in your code.

Is there an error in the way this simulation calculates gravitational attraction and body collision?

N-Body gravity simulation seems to be working fine at first glance, and the same is true for body collisions, but once gravitationally attracted objects start to collide, they start to spiral around each other frantically and the collection of them as a whole have very erratic motion... The code (html-javascript) will be included below, and to reproduce what I'm talking about, you can create a new body by clicking in a random location on the screen.
The math for gravitational attraction is done in the Body.prototype.gravityCalc() method of the Body object type (line 261). The math for the collision resolution is found in the dynamic collision section of the bodyHandle() function (line 337).
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// event handling
document.addEventListener('keydown', keyDown);
document.addEventListener('mousedown', mouseDown)
document.addEventListener('mouseup', mouseUp)
document.addEventListener('mousemove', mouseMove);
document.addEventListener('touchstart', touchStart);
document.addEventListener('touchmove', touchMove);
document.addEventListener('touchend', touchEnd);
window.addEventListener('resize', resize);
window.onload = function() {reset()}
mouseDown = false;
nothingGrabbed = true;
mouseX = 0;
mouseY = 0;
function keyDown(data) {
if(data.key == "r") {
clearInterval(loop);
reset();
}
else if(data.key == 'g') {
gravityOn = !gravityOn;
}
else if(data.key == 'Delete') {
for(i = 0; i < bodies.length ; i++) {
if(((mouseX - bodies[i].x)**2 + (mouseY - bodies[i].y)**2) <= bodies[i].radius**2) {
bodies.splice(i, 1);
}
}
}
else if(data.key == 'c') {
gravity_c *= -1;
}
else if(data.key == 'f') {
falling = !falling;
}
else if(data.key == 'a') {
acceleration *= -1;
}
}
function mouseDown(data) {
mouseDown = true;
nothingGrabbed = true;
mouseX = data.clientX;
mouseY = canvas.height - data.clientY;
}
function mouseUp(data) {
mouseDown = false;
nothingGrabbed = true;
for(i = 0; i < bodies.length; i++) {
bodies[i].grabbed = false
}
}
function mouseMove(data) {
mouseX = data.clientX;
mouseY = canvas.height - data.clientY;
}
function touchStart(data) {
mouseDown = true;
nothingGrabbed = true;
mouseX = data.touches[0].clientX;
mouseY = canvas.height - data.touches[0].clientY;
}
function touchMove(data) {
mouseX = data.touches[0].clientX;
mouseY = canvas.height - data.touches[0].clientY;
}
function touchEnd(data) {
mouseDown = false;
nothingGrabbed = true;
for(i=0;i<bodies.length;i++) {
bodies[i].grabbed = false;
}
}
function resize(data) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Initialize Variables
function reset() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.color = 'rgb(70, 70, 70)';
scale = Math.min(canvas.width, canvas.height);
fps = 120;
running = true;
loop = setInterval(main, 1000/fps);
gravityOn = true // if true, objects are gravitationally attracted to each other
gravity_c = 334000 // universe's gravitational constant
boundaryCollision = true // if true, objects collide with edges of canvas
wallDampen = 0.7 // number to multiply by when an objects hit a wall
bodyCollision = true // if true, bodies will collide with each other
bodyDampen = 0.4 // number to multiply when two objects collide
falling = false // if true, objects will fall to the bottom of the screen
acceleration = 400
bodies = [] // a list of each Body object
collidingPairs = [] // a list of pairs of colliding bodies
/*
var bounds = 200;
for(i = 0; i<70; i++) { // randomly place bodies
Body.create({
x: Math.floor(Math.random()*canvas.width),
y: Math.floor(Math.random()*canvas.height),
a: Math.random()*Math.PI*2,
xV: Math.floor(Math.random() * (bounds - -bounds)) + -bounds,
yV: Math.floor(Math.random() * (bounds - -bounds)) + -bounds,
mass: Math.ceil(Math.random()*23)
})
} */
/*
Body.create({
x: canvas.width/2 - 50,
xV: 10,
yV: 0,
aV: 3,
y: canvas.height/2 + 0,
mass: 10
});
Body.create({
x: canvas.width/2 + 50,
xV: 0,
aV: 0,
y: canvas.height/2,
mass: 10
});
*/
Body.create({
x: canvas.width/2,
y: canvas.height/2,
mass: 24,
xV: -10.83
});
Body.create({
x: canvas.width/2,
y: canvas.height/2 + 150,
mass: 1,
xV: 260,
color: 'teal'
});
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Body Type Object
function Body(params) {
this.x = params.x || canvas.width/2;
this.y = params.y || canvas.height/2;
this.a = params.a || 0;
this.xV = params.xV || 0;
this.yV = params.yV || 0;
this.aV = params.aV || 0;
this.xA = params.xA || 0;
this.yA = params.yA || 0;
this.aA = params.aA || 0;
this.grabbed = false;
this.edgeBlock = params.edgeBlock || boundaryCollision;
this.gravity = params.gravityOn || gravityOn;
this.mass = params.mass || 6;
this.density = params.density || 0.008;
this.radius = params.radius || (this.mass/(Math.PI*this.density))**0.5;
this.color = params.color || 'crimson';
this.lineWidth = params.lineWidth || 2;
}
Body.create = function(params) {
bodies.push(new Body(params));
}
Body.prototype.move = function() {
this.xV += this.xA/fps;
this.yV += this.yA/fps;
this.aV += this.aA/fps;
this.x += this.xV/fps;
this.y += this.yV/fps;
this.a += this.aV/fps;
if(this.edgeBlock) {
if(this.x + this.radius > canvas.width) {
this.x = canvas.width - this.radius;
this.xV *= -wallDampen
}
else if(this.x - this.radius < 0) {
this.x = this.radius;
this.xV *= -wallDampen;
}
if(this.y + this.radius > canvas.height) {
this.y = canvas.height - this.radius;
this.yV *= -wallDampen;
}
else if(this.y - this.radius < 0) {
this.y = this.radius;
this.yV *= -wallDampen;
}
}
if(this.grabbed) {
this.xA = 0;
this.yA = 0;
this.xV = 0;
this.yV = 0;
this.x = mouseX;
this.y = mouseY;
}
}
Body.prototype.draw = function() {
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.lineWidth = this.lineWidth;
ctx.fillStyle = this.color;
ctx.arc(this.x, canvas.height - this.y, this.radius, 0, Math.PI*2, true);
ctx.fill();
ctx.stroke();
ctx.closePath()
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.lineWidth = this.linewidth;
ctx.moveTo(this.x, canvas.height - this.y);
ctx.lineTo(this.x + this.radius*Math.cos(this.a), canvas.height - (this.y + this.radius*Math.sin(this.a)))
ctx.stroke();
ctx.closePath();
}
// calculates gravitational attraction to 'otherObject'
Body.prototype.gravityCalc = function(otherObject) {
var x1 = this.x;
var y1 = this.y;
var x2 = otherObject.x;
var y2 = otherObject.y;
var distSquare = ((x2-x1)**2 + (y2-y1)**2);
var val = (gravity_c*otherObject.mass)/((distSquare)**(3/2));
var xA = val * (x2 - x1);
var yA = val * (y2 - y1);
return [xA, yA]
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Physics Code
function bodyHandle() {
for(i = 0; i < bodies.length; i++) {
if(mouseDown && nothingGrabbed) {
if(Math.abs((mouseX - bodies[i].x)**2 + (mouseY - bodies[i].y)**2) <= bodies[i].radius**2) {
bodies[i].grabbed = true;
nothingGrabbed = false;
}
}
bodies[i].draw()
if(running) {
if(falling) {
bodies[i].yV -= acceleration/fps;
}
bodies[i].move();
}
bodies[i].xA = 0;
bodies[i].yA = 0;
collidingPairs = []
if(gravityOn || bodyCollision) {
for(b = 0; b < bodies.length; b++) {
if(i != b) {
if(bodyCollision) {
var x1 = bodies[i].x;
var y1 = bodies[i].y;
var x2 = bodies[b].x;
var y2 = bodies[b].y;
var rSum = bodies[i].radius + bodies[b].radius;
var dist = { // vector
i: x2 - x1,
j: y2 - y1,
mag: ((x2-x1)**2 + (y2-y1)**2)**0.5,
norm: {
i: (x2-x1)/(((x2-x1)**2 + (y2-y1)**2)**0.5),
j: (y2-y1)/(((x2-x1)**2 + (y2-y1)**2)**0.5)
}
}
if(dist.mag <= rSum) { // static collision
var overlap = rSum - dist.mag;
bodies[i].x -= overlap/2 * dist.norm.i;
bodies[i].y -= overlap/2 * dist.norm.j;
bodies[b].x += overlap/2 * dist.norm.i;
bodies[b].y += overlap/2 * dist.norm.j;
collidingPairs.push([bodies[i], bodies[b]]);
}
}
if(gravityOn) {
if(bodies[i].gravity) {
var accel = bodies[i].gravityCalc(bodies[b]);
bodies[i].xA += accel[0];
bodies[i].yA += accel[1];
}
}
}
}
}
for(c = 0; c < collidingPairs.length; c++) { // dynamic collision
var x1 = collidingPairs[c][0].x;
var y1 = collidingPairs[c][0].y;
var r1 = collidingPairs[c][0].radius;
var x2 = collidingPairs[c][1].x;
var y2 = collidingPairs[c][1].y;
var r2 = collidingPairs[c][1].radius;
var dist = { // vector from b1 to b2
i: x2 - x1,
j: y2 - y1,
mag: ((x2-x1)**2 + (y2-y1)**2)**0.5,
norm: {
i: (x2-x1)/(((x2-x1)**2 + (y2-y1)**2)**0.5),
j: (y2-y1)/(((x2-x1)**2 + (y2-y1)**2)**0.5)
}
}
var m1 = collidingPairs[c][0].mass;
var m2 = collidingPairs[c][1].mass;
var norm = { // vector normal along 'wall' of collision
i: -dist.j/(((dist.i)**2 + (-dist.j)**2)**0.5),
j: dist.i/(((dist.i)**2 + (-dist.j)**2)**0.5)
}
var perp = { // vector normal pointing from b1 to b2
i: dist.norm.i,
j: dist.norm.j
}
var vel1 = { // vector of b1 velocity
i: collidingPairs[c][0].xV,
j: collidingPairs[c][0].yV,
dot: function(vect) {
return collidingPairs[c][0].xV * vect.i + collidingPairs[c][0].yV * vect.j
}
}
var vel2 = { // vector of b2 velocity
i: collidingPairs[c][1].xV,
j: collidingPairs[c][1].yV,
dot: function(vect) {
return collidingPairs[c][1].xV * vect.i + collidingPairs[c][1].yV * vect.j
}
}
// new velocities along perp^ of b1 and b2
var nV1Perp = (vel1.dot(perp))*(m1-m2)/(m1+m2) + (vel2.dot(perp))*(2*m2)/(m1+m2);
var nV2Perp = (vel1.dot(perp))*(2*m1)/(m1+m2) + (vel2.dot(perp))*(m2-m1)/(m1+m2);
/* testing rotation after collision
// velocities of the points of collision on b1 and b2
var pVel1M = vel1.dot(norm) + collidingPairs[c][0].aV*r1;
var pVel2M = vel2.dot(norm) + collidingPairs[c][1].aV*r2;
// moment of inertia for b1 and b2
var I1 = 1/2 * m1 * r1**2;
var I2 = 1/2 * m2 * r2**2;
// new velocities of the points of collisions on b1 and b2
var newpVel1M = ((I1-I2)/(I1+I2))*pVel1M + ((2*I2)/(I1+I2))*pVel2M;
var newpVel2M = ((2*I1)/(I1+I2))*pVel1M + ((I2-I1)/(I1+I2))*pVel2M;
var vectToCol1 = { // vector from x1,y1 to point of collision on b1
i: r1*perp.i,
j: r1*perp.j
};
var vectToCol2 = { // vector from x2,y2 to point of collision on b2
i: r2*-perp.i,
j: r2*-perp.j
};
// sign of cross product of pVelM and vectToCol
var vCrossR1 = (pVel1M*norm.i)*(vectToCol1.j) - (pVel1M*norm.j)*(vectToCol1.i);
vCrossR1 = vCrossR1/Math.abs(vCrossR1);
var vCrossR2 = (pVel2M*norm.i)*(vectToCol2.j) - (pVel2M*norm.j)*(vectToCol2.i);
vCrossR2 = vCrossR2/Math.abs(vCrossR2);
collidingPairs[c][0].aV = vCrossR1 * (newpVel1M)/r1;
collidingPairs[c][1].aV = vCrossR2 * (newpVel2M)/r2;
/* draw collision point velocity vectors [debugging]
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.moveTo(x1 + vectToCol1.i, canvas.height - (y1 + vectToCol1.j));
ctx.lineTo((x1+vectToCol1.i) + pVel1M*norm.i, (canvas.height- (y1+vectToCol1.j + pVel1M*norm.j)));
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.strokeStyle = 'white';
ctx.moveTo(x2 + vectToCol2.i, canvas.height - (y2 + vectToCol2.j));
ctx.lineTo((x2+vectToCol2.i) + pVel2M*norm.i, (canvas.height- (y2+vectToCol2.j + pVel2M*norm.j)));
ctx.stroke();
ctx.closePath();
console.log(pVel1M, pVel2M);
clearInterval(loop);
*/
collidingPairs[c][0].xV = vel1.dot(norm)*norm.i + nV1Perp*perp.i * bodyDampen;
collidingPairs[c][0].yV = vel1.dot(norm)*norm.j + nV1Perp*perp.j * bodyDampen;
collidingPairs[c][1].xV = vel2.dot(norm)*norm.i + nV2Perp*perp.i * bodyDampen;
collidingPairs[c][1].yV = vel2.dot(norm)*norm.j + nV2Perp*perp.j * bodyDampen;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Main Loop
function main() {
// blank out canvas
ctx.fillStyle = canvas.color;
ctx.fillRect(0, 0, canvas.width, canvas.height);
bodyHandle();
if(nothingGrabbed && mouseDown) {
bodies.push(new Body({x: mouseX,
y: mouseY,
mass: 90}));
bodies[bodies.length-1].move();
bodies[bodies.length-1].draw();
}
}
<html>
<meta name='viewport' content='width=device-width,height=device-height'>
<body>
<canvas id="canvas" width='300px' height='300px'></canvas>
<style>
body {
padding: 0;
margin: 0;
}
canvas {
padding: 0;
margin: 0;
}
</style>
</html>
I cannot tell you much about the code. Personally it seems to me that the animations could be correct.
If you want to test your code you could try to test if laws of conservation of energy and momentum are respected. You could, for example, sum the momentum of every object (mass times velocity) and see if the number are maintained constant when there are no forces from the outside (collisions with the wall). To do this I would suggest to make the free space available larger. Another quantity is the total energy (kinetic plus potential) which is a bit harder, but still easy to compute (to compute tot. pot. energy you have to sum over all pairs).

Canvas Impulse Animation Effect

I'm studying the following canvas animation by Matei Copot.
Can someone explain how the "impulse"/shooting effect works, and how, say I can simplify the code to only have 3 stationary dots a, b, and c (while showing the impulse effect between a-> b and between b -> c)?
var w = c.width = window.innerWidth,
h = c.height = window.innerHeight,
ctx = c.getContext( '2d' ),
opts = {
range: 180,
baseConnections: 3,
addedConnections: 5,
baseSize: 5,
minSize: 1,
dataToConnectionSize: .4,
sizeMultiplier: .7,
allowedDist: 40,
baseDist: 40,
addedDist: 30,
connectionAttempts: 100,
dataToConnections: 1,
baseSpeed: .04,
addedSpeed: .05,
baseGlowSpeed: .4,
addedGlowSpeed: .4,
rotVelX: .003,
rotVelY: .002,
repaintColor: '#111',
connectionColor: 'hsla(200,60%,light%,alp)',
rootColor: 'hsla(0,60%,light%,alp)',
endColor: 'hsla(160,20%,light%,alp)',
dataColor: 'hsla(40,80%,light%,alp)',
wireframeWidth: .1,
wireframeColor: '#88f',
depth: 250,
focalLength: 250,
vanishPoint: {
x: w / 2,
y: h / 2
}
},
squareRange = opts.range * opts.range,
squareAllowed = opts.allowedDist * opts.allowedDist,
mostDistant = opts.depth + opts.range,
sinX = sinY = 0,
cosX = cosY = 0,
connections = [],
toDevelop = [],
data = [],
all = [],
tick = 0,
totalProb = 0,
animating = false,
Tau = Math.PI * 2;
ctx.fillStyle = '#222';
ctx.fillRect( 0, 0, w, h );
ctx.fillStyle = '#ccc';
ctx.font = '50px Verdana';
ctx.fillText( 'Calculating Nodes', w / 2 - ctx.measureText( 'Calculating Nodes' ).width / 2, h / 2 - 15 );
window.setTimeout( init, 4 ); // to render the loading screen
function init(){
connections.length = 0;
data.length = 0;
all.length = 0;
toDevelop.length = 0;
var connection = new Connection( 0, 0, 0, opts.baseSize );
connection.step = Connection.rootStep;
connections.push( connection );
all.push( connection );
connection.link();
while( toDevelop.length > 0 ){
toDevelop[ 0 ].link();
toDevelop.shift();
}
if( !animating ){
animating = true;
anim();
}
}
function Connection( x, y, z, size ){
this.x = x;
this.y = y;
this.z = z;
this.size = size;
this.screen = {};
this.links = [];
this.probabilities = [];
this.isEnd = false;
this.glowSpeed = opts.baseGlowSpeed + opts.addedGlowSpeed * Math.random();
}
Connection.prototype.link = function(){
if( this.size < opts.minSize )
return this.isEnd = true;
var links = [],
connectionsNum = opts.baseConnections + Math.random() * opts.addedConnections |0,
attempt = opts.connectionAttempts,
alpha, beta, len,
cosA, sinA, cosB, sinB,
pos = {},
passedExisting, passedBuffered;
while( links.length < connectionsNum && --attempt > 0 ){
alpha = Math.random() * Math.PI;
beta = Math.random() * Tau;
len = opts.baseDist + opts.addedDist * Math.random();
cosA = Math.cos( alpha );
sinA = Math.sin( alpha );
cosB = Math.cos( beta );
sinB = Math.sin( beta );
pos.x = this.x + len * cosA * sinB;
pos.y = this.y + len * sinA * sinB;
pos.z = this.z + len * cosB;
if( pos.x*pos.x + pos.y*pos.y + pos.z*pos.z < squareRange ){
passedExisting = true;
passedBuffered = true;
for( var i = 0; i < connections.length; ++i )
if( squareDist( pos, connections[ i ] ) < squareAllowed )
passedExisting = false;
if( passedExisting )
for( var i = 0; i < links.length; ++i )
if( squareDist( pos, links[ i ] ) < squareAllowed )
passedBuffered = false;
if( passedExisting && passedBuffered )
links.push( { x: pos.x, y: pos.y, z: pos.z } );
}
}
if( links.length === 0 )
this.isEnd = true;
else {
for( var i = 0; i < links.length; ++i ){
var pos = links[ i ],
connection = new Connection( pos.x, pos.y, pos.z, this.size * opts.sizeMultiplier );
this.links[ i ] = connection;
all.push( connection );
connections.push( connection );
}
for( var i = 0; i < this.links.length; ++i )
toDevelop.push( this.links[ i ] );
}
}
Connection.prototype.step = function(){
this.setScreen();
this.screen.color = ( this.isEnd ? opts.endColor : opts.connectionColor ).replace( 'light', 30 + ( ( tick * this.glowSpeed ) % 30 ) ).replace( 'alp', .2 + ( 1 - this.screen.z / mostDistant ) * .8 );
for( var i = 0; i < this.links.length; ++i ){
ctx.moveTo( this.screen.x, this.screen.y );
ctx.lineTo( this.links[ i ].screen.x, this.links[ i ].screen.y );
}
}
Connection.rootStep = function(){
this.setScreen();
this.screen.color = opts.rootColor.replace( 'light', 30 + ( ( tick * this.glowSpeed ) % 30 ) ).replace( 'alp', ( 1 - this.screen.z / mostDistant ) * .8 );
for( var i = 0; i < this.links.length; ++i ){
ctx.moveTo( this.screen.x, this.screen.y );
ctx.lineTo( this.links[ i ].screen.x, this.links[ i ].screen.y );
}
}
Connection.prototype.draw = function(){
ctx.fillStyle = this.screen.color;
ctx.beginPath();
ctx.arc( this.screen.x, this.screen.y, this.screen.scale * this.size, 0, Tau );
ctx.fill();
}
function Data( connection ){
this.glowSpeed = opts.baseGlowSpeed + opts.addedGlowSpeed * Math.random();
this.speed = opts.baseSpeed + opts.addedSpeed * Math.random();
this.screen = {};
this.setConnection( connection );
}
Data.prototype.reset = function(){
this.setConnection( connections[ 0 ] );
this.ended = 2;
}
Data.prototype.step = function(){
this.proportion += this.speed;
if( this.proportion < 1 ){
this.x = this.ox + this.dx * this.proportion;
this.y = this.oy + this.dy * this.proportion;
this.z = this.oz + this.dz * this.proportion;
this.size = ( this.os + this.ds * this.proportion ) * opts.dataToConnectionSize;
} else
this.setConnection( this.nextConnection );
this.screen.lastX = this.screen.x;
this.screen.lastY = this.screen.y;
this.setScreen();
this.screen.color = opts.dataColor.replace( 'light', 40 + ( ( tick * this.glowSpeed ) % 50 ) ).replace( 'alp', .2 + ( 1 - this.screen.z / mostDistant ) * .6 );
}
Data.prototype.draw = function(){
if( this.ended )
return --this.ended; // not sre why the thing lasts 2 frames, but it does
ctx.beginPath();
ctx.strokeStyle = this.screen.color;
ctx.lineWidth = this.size * this.screen.scale;
ctx.moveTo( this.screen.lastX, this.screen.lastY );
ctx.lineTo( this.screen.x, this.screen.y );
ctx.stroke();
}
Data.prototype.setConnection = function( connection ){
if( connection.isEnd )
this.reset();
else {
this.connection = connection;
this.nextConnection = connection.links[ connection.links.length * Math.random() |0 ];
this.ox = connection.x; // original coordinates
this.oy = connection.y;
this.oz = connection.z;
this.os = connection.size; // base size
this.nx = this.nextConnection.x; // new
this.ny = this.nextConnection.y;
this.nz = this.nextConnection.z;
this.ns = this.nextConnection.size;
this.dx = this.nx - this.ox; // delta
this.dy = this.ny - this.oy;
this.dz = this.nz - this.oz;
this.ds = this.ns - this.os;
this.proportion = 0;
}
}
Connection.prototype.setScreen = Data.prototype.setScreen = function(){
var x = this.x,
y = this.y,
z = this.z;
// apply rotation on X axis
var Y = y;
y = y * cosX - z * sinX;
z = z * cosX + Y * sinX;
// rot on Y
var Z = z;
z = z * cosY - x * sinY;
x = x * cosY + Z * sinY;
this.screen.z = z;
// translate on Z
z += opts.depth;
this.screen.scale = opts.focalLength / z;
this.screen.x = opts.vanishPoint.x + x * this.screen.scale;
this.screen.y = opts.vanishPoint.y + y * this.screen.scale;
}
function squareDist( a, b ){
var x = b.x - a.x,
y = b.y - a.y,
z = b.z - a.z;
return x*x + y*y + z*z;
}
function anim(){
window.requestAnimationFrame( anim );
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = opts.repaintColor;
ctx.fillRect( 0, 0, w, h );
++tick;
var rotX = tick * opts.rotVelX,
rotY = tick * opts.rotVelY;
cosX = Math.cos( rotX );
sinX = Math.sin( rotX );
cosY = Math.cos( rotY );
sinY = Math.sin( rotY );
if( data.length < connections.length * opts.dataToConnections ){
var datum = new Data( connections[ 0 ] );
data.push( datum );
all.push( datum );
}
ctx.globalCompositeOperation = 'lighter';
ctx.beginPath();
ctx.lineWidth = opts.wireframeWidth;
ctx.strokeStyle = opts.wireframeColor;
all.map( function( item ){ item.step(); } );
ctx.stroke();
ctx.globalCompositeOperation = 'source-over';
all.sort( function( a, b ){ return b.screen.z - a.screen.z } );
all.map( function( item ){ item.draw(); } );
/*ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.arc( opts.vanishPoint.x, opts.vanishPoint.y, opts.range * opts.focalLength / opts.depth, 0, Tau );
ctx.stroke();*/
}
window.addEventListener( 'resize', function(){
opts.vanishPoint.x = ( w = c.width = window.innerWidth ) / 2;
opts.vanishPoint.y = ( h = c.height = window.innerHeight ) / 2;
ctx.fillRect( 0, 0, w, h );
});
window.addEventListener( 'click', init );
canvas {
position: absolute;
top: 0;
left: 0;
}
<canvas id=c></canvas>
<!--
ALGORITHM:
structure:
- gen( x,y,z ):
- create node at x,y,z // blue
- append some children to list:
- within a certain distance to parent
- outside a certain distance from any node
- within a global distance
- if no children
- don't append any
- set as end node // green-ish
- gen( 0,0,0 ) // red
- while list has items
- gen( position of first item )
- remove first item
impulse behaviour:
- pick( node ):
- if node is end node
- pick( original node )
- else
- pick( random node from node children )
- pick( original node)
-->

Collisions in JavaScript

In my code I am detecting collisions between a box and the balls, but as soon as the first collision occurs the console shows the following error:
"message": "Uncaught TypeError: Cannot read property 'x' of undefined"
What is the error in my code? What is the meaning of the displayed error?
// Creating code for multiple balls as well as record the movement of the player
var canvas, cxt, h, w, n = 10,
i, mousePos;
var ball = []; // Empty array
var p = {
x: 0,
y: 0,
length: 30,
breath: 30,
color: 'black'
}
function init() {
canvas = document.querySelector('#style');
cxt = canvas.getContext('2d');
h = canvas.height;
w = canvas.width;
ballType(n);
// Add a mousemove event listener to the canvas
canvas.addEventListener('mousemove', mouseMoved);
main();
}
function mouseMoved(evt) {
mousePos = getMousePos(canvas, evt);
}
function getMousePos(canvas, evt) {
// Necessary work in the canvas coordinate system
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function movePlayerWithMouse() {
if (mousePos !== undefined) {
p.x = mousePos.x;
p.y = mousePos.y;
}
}
function ballType(n) {
var cl = ['red', 'green', 'blue', 'yellow', 'purple', 'orange', 'pink', 'cyan', 'grey', 'pink'];
for (i = 0; i < n; i++) {
var e = Math.floor(10 * Math.random());
f = {
x: 100,
y: 100,
radius: 5 + (30 * Math.random()), // Radius will be between 5 and 35
a: -5 + (10 * Math.random()), // Value of a will be between -5 and 5
b: -5 + (10 * Math.random()), //value of b will be between -5 and 5
color: cl[e]
}
ball.push(f);
}
}
function main() {
cxt.clearRect(0, 0, w, h);
player(p);
for (i = 0; i < n; i++) {
draw(ball[i]);
}
var l = 0
for (i = 0; i < n; i++) {
move(ball[i], l);
l++;
}
movePlayerWithMouse();
count();
requestAnimationFrame(main);
}
function draw(d) {
cxt.save();
cxt.translate(0, 0);
cxt.fillStyle = d.color;
cxt.beginPath();
cxt.arc(d.x, d.y, d.radius, 0, 2 * Math.PI);
cxt.fill();
cxt.restore();
}
function move(m, index) {
m.x += m.a;
m.y += m.b;
check(m);
testCollision(m, index);
}
function check(m) {
if ((m.x + m.radius) > w) { // Collision with the right wall
m.a = -m.a;
m.x = w - m.radius;
} else if ((m.x - m.radius) < 0) { // Collision with the left wall
m.a = -m.a;
m.x = m.radius;
}
if ((m.y + m.radius) > h) { // Collision with the top wall
m.b = -m.b;
m.y = h - m.radius;
} else if ((m.y - m.radius) < 0) { // Collision with the bottom surface
m.b = -m.b;
m.y = m.radius;
}
}
function player(p) {
cxt.save();
cxt.translate(0, 0);
cxt.fillStyle = p.color;
cxt.fillRect(p.x, p.y, p.length, p.breath);
cxt.restore();
}
// For testing the collision
function test(rx, ry, rw, rh, cx, cy, cr) {
var x0 = cx;
var y0 = cy;
if (x0 < rx) {
x0 = rx;
}
if (x0 > (rx + rw)) {
x0 = rx + rw;
}
if (y0 < ry) {
y0 = ry;
}
if (y0 > (ry + rh)) {
y0 = ry + rh;
}
return (((cx - x0) * (cx - x0) + (cy - y0) * (cy - y0)) < (cr * cr));
}
function testCollision(v, index) {
if (test(p.x, p.y, p.breath, p.length, v.x, v.y, v.radius)) {
ball.splice(index, 1); // Splice starts deleting the elements of array from the index given in the first parameter
// and the second parameter accepts the number of array elements to be deleted
}
}
function count() {
cxt.save();
if (ball.length == 0) {
cxt.fillText("You win", 20, 20);
} else {
cxt.fillText(ball.length, 20, 20);
}
cxt.restore();
}
#style {
border: 2px dotted black;
}
<body onload='init();'>
<div>
<canvas id='style' height='400' width='400'>
Your browser does not support canvas...
</canvas>
</div>
</body>
There is an error in your code as you are removing the object from array, but not reducing the n so just update the following:
function testCollision(v, index) {
if (test(p.x, p.y, p.breath, p.length, v.x, v.y, v.radius)) {
ball.splice(index, 1);
n--;
// Splice starts deleting the elements of array from the index given in the first parameter
// and the second parameter accepts the no. of array elements to be deleted
}
}

Why does the ball in pong get stuck at the bottom?

I recently made a JS Pong game. It works well, but the ball rarely gets stuck at the bottom or top. It looks like it is halfway through the wall and constantly bouncing. Video of the issue happening. You can try the game here. I do not know why this issue is happening because the logic seems right and works 90% of the time correctly. Here are the main two functions of my program:
function moveAll() {
if (showingWinScreen) {
return;
}
computerMovement();
ballX += ballSpeedX;
ballY += ballSpeedY;
if (ballY <= 10) {
ballSpeedY = -ballSpeedY;
} else if (ballY >= HEIGHT - 10) {
ballSpeedY = -ballSpeedY;
}
if (ballX >= WIDTH - 10) {
if ((ballY > paddleY) && (ballY < paddleY + 100)) {
ballSpeedX = -ballSpeedX;
var deltaY = ballY - paddleY - 50;
ballSpeedY = deltaY / 5;
} else {
player1Score++;
ballReset();
}
} else if (ballX <= 10) {
if ((ballY > mouseY - 50) && (ballY < mouseY + 50)) {
ballSpeedX = -ballSpeedX;
deltaY = ballY - mouseY;
ballSpeedY = deltaY / 6;
} else {
player2Score++;
ballReset();
}
}
}
function drawAll() {
if (showingWinScreen) {
colorRect(0, 0, WIDTH, HEIGHT, "black");
canvas.fillStyle = "yellow";
canvas.fillText("Click to continue!", 300, 300);
if (player1Score == WINNING_SCORE) {
canvas.fillText("You won!", 360, 500);
} else if (player2Score == WINNING_SCORE) {
canvas.fillText("The computer beat you!", 280, 500);
}
return;
}
colorRect(0, 0, WIDTH, HEIGHT, "black");
drawNet();
makeCircle(ballX, ballY, 10, 0, Math.PI * 2, "red");
colorRect(790, paddleY, 10, 100, "cyan");
colorRect(0, mouseY - 50, 10, 100, "yellow");
canvas.fillStyle = "white";
canvas.fillText(player1Score + " " + player2Score, 360, 100);
}
Thank you for your help!
I think there's only one case in which this could happen: when, in a colliding frame, you decrease the speed.
When the speed remains the same, no matter what, your ball will always bounce back to the previous' frames position:
var cvs = document.querySelector("canvas");
var ctx = cvs.getContext("2d");
var balls = [
Ball(50, 50, 0, 5, 5, "red"),
Ball(100, 50, 0, 5, 10, "blue"),
Ball(150, 50, 0, 5, 15, "green"),
Ball(200, 50, 0, 5, 20, "yellow")
];
var next = () => {
updateFrame(balls);
drawFrame(balls);
}
var loop = () => {
requestAnimationFrame(() => {
next();
loop();
});
}
next();
function Ball(x, y, vx, vy, r, color) {
return {
x: x,
y: y,
vx: vx,
vy: vy,
r: r,
color: color
}
};
function updateBall(b) {
b.x += b.vx;
b.y += b.vy;
if (b.y <= b.r ||
b.y >= cvs.height - b.r) {
b.vy *= -1;
}
};
function drawBall(b) {
ctx.beginPath();
ctx.fillStyle = b.color;
ctx.arc(b.x, b.y, b.r, 0, 2 * Math.PI, false);
ctx.fill();
}
function updateFrame(balls) {
balls.forEach(updateBall);
}
function drawFrame(balls) {
ctx.clearRect(0, 0, cvs.width, cvs.height);
balls.forEach(drawBall);
};
<canvas width="300" height="150" style="background: #454545"></canvas>
<button onclick="next()">next</button>
<button onclick="loop()">run</button>
But when the speed changes, things get stuck:
var cvs = document.querySelector("canvas");
var ctx = cvs.getContext("2d");
var balls = [
Ball(50, 50, 0, 10, 5, "red"),
Ball(100, 50, 0, 10, 10, "blue"),
Ball(150, 50, 0, 10, 15, "green"),
Ball(200, 50, 0, 10, 20, "yellow")
];
var next = () => {
updateFrame(balls);
drawFrame(balls);
}
var loop = () => {
requestAnimationFrame(() => {
next();
loop();
});
}
next();
function Ball(x, y, vx, vy, r, color) {
return {
x: x,
y: y,
vx: vx,
vy: vy,
r: r,
color: color
}
};
function updateBall(b) {
b.x += b.vx;
b.y += b.vy;
if (b.y <= b.r ||
b.y >= cvs.height - b.r) {
b.vy *= -0.5;
}
};
function drawBall(b) {
ctx.beginPath();
ctx.fillStyle = b.color;
ctx.arc(b.x, b.y, b.r, 0, 2 * Math.PI, false);
ctx.fill();
}
function updateFrame(balls) {
balls.forEach(updateBall);
}
function drawFrame(balls) {
ctx.clearRect(0, 0, cvs.width, cvs.height);
balls.forEach(drawBall);
};
<canvas width="300" height="150" style="background: #454545"></canvas>
<button onclick="next()">next</button>
<button onclick="loop()">run</button>
In your case, I'm thinking this can only happen when there's a paddle collision AND a wall collision simultaneously.
A quick-to-implement solution would be to check if the new position is valid before translating the ball position. If you don't want the precise location, you can place the ball at the point of collision. Note that this will produce a slightly off frame.
E.g.:
var newY = ballY + ballSpeedY;
// Top wall
if(newY <= 10) {
ballY = 10;
ballSpeedY = -ballSpeedY;
}
// Bottom wall
else if(newY >= HEIGHT-10){
ballY = HEIGHT - 10;
ballSpeedY = -ballSpeedY;
}
// No collision
else {
ballY = newY;
}
Update: a more detailed description of what can happen
Let's say your ball collides with the top border of your canvas and with your paddle in the same frame.
First, you move the ball to the colliding position: ballY += ballSpeedY; Say your ballY is 4, and your ballSpeedY is -5, you'll position the ball to -1, inside the wall.
If this were to be the only collision, you should be okay. You flip the speed (ballSpeedY = -ballSpeedY), so in the next frame, your ball should be back at -1 + 5 = 4, so ballY will be 4 again, and your ball will move towards 4 + 5 = 9 in the next frame.
Now a problem arises, when in the -1 positioned frame, you collide with the paddle as well! When the paddle hits the ball, you modify the ballspeed: ballSpeedY = deltaY / 5;. If this turns out to be < 1, your ball won't be able to exit the wall in the next frame. Instead of -1 + 5 = 4, your ball will, for example, move to: -1 + 0.5 = -0.5.
Now, your ball won't be able to get back in to play, since the next frame will, again, calculate a collision and flip the speed. This results in the bouncy, trembling effect you see when the ball gets stuck.
A naive but pretty decent solution, is to only update the position of the ball to a valid position. I.e.: never to a colliding coordinate.
var animate = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60)
};
var canvas = document.createElement("canvas");
var width = 400;
var height = 600;
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
var player = new Player();
var computer = new Computer();
var ball = new Ball(200, 300);
var keysDown = {};
var render = function () {
context.fillStyle = "#FF00FF";
context.fillRect(0, 0, width, height);
player.render();
computer.render();
ball.render();
};
var update = function () {
player.update();
computer.update(ball);
ball.update(player.paddle, computer.paddle);
};
var step = function () {
update();
render();
animate(step);
};
function Paddle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.x_speed = 0;
this.y_speed = 0;
}
Paddle.prototype.render = function () {
context.fillStyle = "#0000FF";
context.fillRect(this.x, this.y, this.width, this.height);
};
Paddle.prototype.move = function (x, y) {
this.x += x;
this.y += y;
this.x_speed = x;
this.y_speed = y;
if (this.x < 0) {
this.x = 0;
this.x_speed = 0;
} else if (this.x + this.width > 400) {
this.x = 400 - this.width;
this.x_speed = 0;
}
};
function Computer() {
this.paddle = new Paddle(175, 10, 50, 10);
}
Computer.prototype.render = function () {
this.paddle.render();
};
Computer.prototype.update = function (ball) {
var x_pos = ball.x;
var diff = -((this.paddle.x + (this.paddle.width / 2)) - x_pos);
if (diff < 0 && diff < -4) {
diff = -5;
} else if (diff > 0 && diff > 4) {
diff = 5;
}
this.paddle.move(diff, 0);
if (this.paddle.x < 0) {
this.paddle.x = 0;
} else if (this.paddle.x + this.paddle.width > 400) {
this.paddle.x = 400 - this.paddle.width;
}
};
function Player() {
this.paddle = new Paddle(175, 580, 50, 10);
}
Player.prototype.render = function () {
this.paddle.render();
};
Player.prototype.update = function () {
for (var key in keysDown) {
var value = Number(key);
if (value == 37) {
this.paddle.move(-4, 0);
} else if (value == 39) {
this.paddle.move(4, 0);
} else {
this.paddle.move(0, 0);
}
}
};
function Ball(x, y) {
this.x = x;
this.y = y;
this.x_speed = 0;
this.y_speed = 3;
}
Ball.prototype.render = function () {
context.beginPath();
context.arc(this.x, this.y, 5, 2 * Math.PI, false);
context.fillStyle = "#000000";
context.fill();
};
Ball.prototype.update = function (paddle1, paddle2) {
this.x += this.x_speed;
this.y += this.y_speed;
var top_x = this.x - 5;
var top_y = this.y - 5;
var bottom_x = this.x + 5;
var bottom_y = this.y + 5;
if (this.x - 5 < 0) {
this.x = 5;
this.x_speed = -this.x_speed;
} else if (this.x + 5 > 400) {
this.x = 395;
this.x_speed = -this.x_speed;
}
if (this.y < 0 || this.y > 600) {
this.x_speed = 0;
this.y_speed = 3;
this.x = 200;
this.y = 300;
}
if (top_y > 300) {
if (top_y < (paddle1.y + paddle1.height) && bottom_y > paddle1.y && top_x < (paddle1.x + paddle1.width) && bottom_x > paddle1.x) {
this.y_speed = -3;
this.x_speed += (paddle1.x_speed / 2);
this.y += this.y_speed;
}
} else {
if (top_y < (paddle2.y + paddle2.height) && bottom_y > paddle2.y && top_x < (paddle2.x + paddle2.width) && bottom_x > paddle2.x) {
this.y_speed = 3;
this.x_speed += (paddle2.x_speed / 2);
this.y += this.y_speed;
}
}
};
document.body.appendChild(canvas);
animate(step);
window.addEventListener("keydown", function (event) {
keysDown[event.keyCode] = true;
});
window.addEventListener("keyup", function (event) {
delete keysDown[event.keyCode];
});
http://jsfiddle.net/kHJr6/2/

Categories