Reducing rotational speed of a cube using JS - javascript

I am trying to solve a javascript puzzle.
Draw a 3D ​Cube wireframe and rotate it along ​the​ ax​es​ that passes through its center. The rotating object should decelerate at a rate of ‘X’ degrees/sec​^​2 before it comes to a standstill.
​ ​
The object should respond as follows to the following user inputs
Swipe
​/Drag​
: Accelerates or decelerates the rotating object as per the difference in velocity
​ between​
​
rotation and swipe with the friction factor Y.
Touch
​/Click​
generates friction that should decelerate the rotation further by a Y (friction factor)
This is the code I have written
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="1000" height="1000"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.translate(200,200);
var x1,x2,y1,y2,tempx,tempy,up=false,down = false,inter, interval;
function line(context, p1,p2) {
context.beginPath();
context.moveTo(p1.x, p1.y);
context.lineTo(p2.x, p2.y);
context.closePath();
context.stroke();
}
function project() {
ctx.clearRect(-500, -500, canvas.width, canvas.height);
for(var i=0;i<edges.length;i++)
{
// var x1 = vertices[edges[i][0]][0];
// var y1 = vertices[edges[i][0]][1];
// var x2 = vertices[edges[i][1]][0];
// var y2 = vertices[edges[i][1]][1];
// var z1 = vertices[edges[i][0]][3];
// var z2 = vertices[edges[i][1]][3];
// vertices[edges[i][0]][0] = x1 + 20;
// vertices[edges[i][0]][1] = y1 + 20;
// vertices[edges[i][1]][0] = x2 + 20;
// vertices[edges[i][1]][1] = y2 + 20;
line(ctx,{x:vertices[edges[i][0]][0],y:vertices[edges[i][0]][1]}, {x:vertices[edges[i][1]][0],y:vertices[edges[i][1]][1]});
}
}
function rep()
{
rotateX(tempy/3000);
rotateY(tempx/3000);
project();
}
function stop()
{
console.log(inter);
inter += 0.5;
rotateX(tempy/3000);
rotateY(tempx/3000);
project();
clearInterval(interval);
interval = setInterval(stop, inter);
}
var vertices = [[-100,-100,-100],[-100,-100,100],[-100,100,-100], [-100,100,100],[100,-100,-100],[100,-100,100],[100,100,-100],[100,100,100]];
var edges =[[0,1],[1,3],[3,2],[2,0],[4,5],[5,7],[7,6],[6,4],[0,4],[1,5],[2,6],[3,7]];
var rotateX = function(theta) {
var sina = Math.sin(theta);
var cosa = Math.cos(theta);
for (var i=0; i<vertices.length; i++) {
var vertice = vertices[i];
var y = vertice[1];
var z = vertice[2];
vertice[1] = y * cosa - z * sina;
vertice[2] = z * cosa + y * sina;
}
};
var rotateY = function(theta) {
var sina = Math.sin(theta);
var cosa = Math.cos(theta);
for (var i=0; i<vertices.length; i++) {
var vertice = vertices[i];
var x = vertice[0];
var z = vertice[2];
vertice[0] = x * cosa - z * sina;
vertice[2] = z * cosa + x * sina;
}
};
var rotateZ = function(theta) {
var sina = Math.sin(theta);
var cosa = Math.cos(theta);
for (var i=0; i<vertices.length; i++) {
var vertice = vertices[i];
var x = vertice[0];
var y = vertice[1];
vertice[0] = x * cosa - y * sina;
vertice[1] = y * cosa + x * sina;
}
};
rotateZ(60);
rotateY(60);
rotateZ(60);
project();
canvas.addEventListener("mousedown",function(event)
{
old = Date.now();
x1 = event.clientX;
y1 = event.clientY;
down = true;
},false);
canvas.addEventListener("mouseup",function(event)
{
up = true;
newt = Date.now();
dt = newt - old;
x2 = event.clientX;
y2 = event.clientY;
dx = Math.sqrt(Math.pow((x2-x1),2)-Math.pow((y2-y1),2));
inter = (dx / dt) * 2;
//console.log(inter);
tempx = x2 - x1;
tempy = y2 - y1;
interval = setInterval(rep, inter);
// console.log("x1:" + x1 +" y1:" + y1 + "x2:" + x2 + "y2:" + y2);
},false);
canvas.addEventListener("mousemove",function(event)
{
if(down){
newt = Date.now();
dt = newt - old;
x2 = event.clientX;
y2 = event.clientY;
// console.log("x1:" + x1 +" y1:" + y1 + "x2:" + x2 + "y2:" + y2);
rotateX((y2-y1)/3000);
rotateY((x2-x1)/3000);
project();
}
},false);
canvas.addEventListener("click",function(event)
{
if(down)
{
down = false;
}
if(up)
{
clearInterval(interval);
interval = setInterval(stop, inter);
up = false;
}
},false);
// canvas.addEventListener("swipe",function)
</script>
<body>
</html>
I want to stop the cube by slowing the rotation speed linearly and stop. How to improve my code for that

<html>
<body>
<canvas id="myCanvas" width="1000" height="1000"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.translate(200,200);
var x1,x2,y1,y2,tempx,tempy,up=false,down = false,inter, interval;
function line(context, p1,p2) {
context.beginPath();
context.moveTo(p1.x, p1.y);
context.lineTo(p2.x, p2.y);
context.closePath();
context.stroke();
}
function project() {
ctx.clearRect(-500, -500, canvas.width, canvas.height);
for(var i=0;i<edges.length;i++)
{
line(ctx,{x:vertices[edges[i][0]][0],y:vertices[edges[i][0]][1]}, {x:vertices[edges[i][1]][0],y:vertices[edges[i][1]][1]});
}
}
function rep()
{
rotateX(tempy/1000);
rotateY(tempx/1000);
project();
}
function stop()
{
console.log(inter);
inter += 0.5;
rotateX(tempy/1000);
rotateY(tempx/1000);
project();
clearInterval(interval);
interval = setInterval(stop, inter);
}
var vertices = [[-100,-100,-100],[-100,-100,100],[-100,100,-100], [-100,100,100],[100,-100,-100],[100,-100,100],[100,100,-100],[100,100,100]];
var edges =[[0,1],[1,3],[3,2],[2,0],[4,5],[5,7],[7,6],[6,4],[0,4],[1,5],[2,6],[3,7]];
var rotateX = function(theta) {
var sina = Math.sin(theta);
var cosa = Math.cos(theta);
for (var i=0; i<vertices.length; i++) {
var vertice = vertices[i];
var y = vertice[1];
var z = vertice[2];
vertice[1] = y * cosa - z * sina;
vertice[2] = z * cosa + y * sina;
}
};
var rotateY = function(theta) {
var sina = Math.sin(theta);
var cosa = Math.cos(theta);
for (var i=0; i<vertices.length; i++) {
var vertice = vertices[i];
var x = vertice[0];
var z = vertice[2];
vertice[0] = x * cosa - z * sina;
vertice[2] = z * cosa + x * sina;
}
};
var rotateZ = function(theta) {
var sina = Math.sin(theta);
var cosa = Math.cos(theta);
for (var i=0; i<vertices.length; i++) {
var vertice = vertices[i];
var x = vertice[0];
var y = vertice[1];
vertice[0] = x * cosa - y * sina;
vertice[1] = y * cosa + x * sina;
}
};
rotateZ(60);
rotateY(60);
rotateZ(60);
project();
canvas.addEventListener("mousedown",function(event)
{
old = Date.now();
x1 = event.clientX;
y1 = event.clientY;
down = true;
},false);
canvas.addEventListener("mousemove",function(event)
{
if(down){
newt = Date.now();
dt = newt - old;
x2 = event.clientX;
y2 = event.clientY;
// console.log("x1:" + x1 +" y1:" + y1 + "x2:" + x2 + "y2:" + y2);
rotateX((y2-y1)/1000);
rotateY((x2-x1)/1000);
project();
}
},false);
canvas.addEventListener("click",function(event)
{
if(down)
{
down = false;
}
if(up)
{
clearInterval(interval);
interval = setInterval(stop, inter);
up = false;
}
},false);
</script>
<body>

Related

rotation of a 3d cube relative to a specific point on the canvas

Using certain methods, I drew a 3D cube.
My task is to rotate it around the z axis. I also need to rotate the cube relative to the coordinates (0,0,0) (on my canvas, these will be the coordinates (150,150,0)). Now it rotates correctly, but only changes its angle relative to the 'top left corner of my canvas'.
I think the solution to my problem is as follows:
To rotate the cube relative to the given coordinates, the cube must first be translated to the negative coordinates of this point, and by changing the angle, it must be translated back, but only to the positive coordinates of this point.
In my case the pseudo code would be like this:
// if I want to flip the cube around the coordinates (150,150,0) (this is the center of my canvas), then I need to do the following
translate(-150,-150,0);
rotate();
translate(150,150,0);
In the commented parts of the code, I tried to do this, but when I translate the cube, it gets stuck somewhere in the corner and I don't know how to fix it.
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
function randomColor() {
return "rgb(" + randInt(0,255) + "," + randInt(0,255) + "," + randInt(0,255) + ")";
}
function ctg(x) {
return 1 / Math.tan(x);
}
function draw() {
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
let canvasWidth = 300;
canvas.width = canvas.height = canvasWidth;
function drawUW() {
context.lineWidth = 0.1;
context.beginPath();
context.moveTo(0,canvas.height/2);
context.lineTo(canvas.width,canvas.height/2);
context.moveTo(canvas.width/2,0);
context.lineTo(canvas.width/2,canvas.height);
context.stroke();
}
function updateCanvas() {
context.clearRect(0,0,canvas.width,canvas.height);
drawUW();
}
let x = 50, y = 50, z = 50;
let d = 100;
let x0 = canvas.width/2;
let y0 = canvas.height/2;
let x1 = x0+x;
let y1 = y0;
let x2 = x0;
let y2 = y0-y;
let x3 = x0+x;
let y3 = y0-y;
// x' = xd/(z+d)
// y' = yd/(z+d)
let x0p=x0*d/(z+d);
let y0p=y0*d/(z+d);
let x1p=x1*d/(z+d);
let y1p=y1*d/(z+d);
let x2p=x2*d/(z+d);
let y2p=y2*d/(z+d);
let x3p=x3*d/(z+d);
let y3p=y3*d/(z+d);
function getWalls() {
wall01 = [[x0,x2,x3,x1],[y0,y2,y3,y1]];
wall02 = [[x0p,x2p,x2,x0],[y0p,y2p,y2,y0]];
wall03 = [[x0p,x2p,x3p,x1p],[y0p,y2p,y3p,y1p]];
wall04 = [[x1p,x3p,x3,x1],[y1p,y3p,y3,y1]];
wall05 = [[x2,x2p,x3p,x3],[y2,y2p,y3p,y3]];
wall06 = [[x0,x0p,x1p,x1],[y0,y0p,y1p,y1]];
}
function drawWall(wall) {
context.fillStyle = randomColor();
context.strokeStyle = "black";
context.lineWidth = 0.5;
context.beginPath();
context.moveTo(wall[0][0],wall[1][0]);
context.lineTo(wall[0][1],wall[1][1]);
context.lineTo(wall[0][2],wall[1][2]);
context.lineTo(wall[0][3],wall[1][3]);
context.lineTo(wall[0][0],wall[1][0]);
context.fill();
context.stroke();
}
function rotatePoint(x,y,z,fi) {
fi*=Math.PI/180;
arr = [x,y,z,1];
newX = 0;
newY = 0;
newZ = 0;
tx = -150, ty = -150, tz = -150;
arrTranslate = [
[1,0,0,tx],
[0,1,0,ty],
[0,0,1,tz],
[0,0,0,1]
];
// z
arrRotate = [
[Math.cos(fi),-Math.sin(fi),0,0],
[Math.sin(fi),Math.cos(fi),0,0],
[0,0,1,0],
[0,0,0,1]
];
// translate
// for (let i = 0; i < arr.length; i++) {
// newX += arr[i] * arrTranslate[0][i];
// newY += arr[i] * arrTranslate[1][i];
// newZ += arr[i] * arrTranslate[2][i];
// }
//rotate
for (let i = 0; i < arr.length; i++) {
newX += arr[i] * arrRotate[0][i];
newY += arr[i] * arrRotate[1][i];
newZ += arr[i] * arrRotate[2][i];
}
tx = 150, ty = 150, tz = 150;
// translate
// for (let i = 0; i < arr.length; i++) {
// newX += arr[i] * arrTranslate[0][i];
// newY += arr[i] * arrTranslate[1][i];
// newZ += arr[i] * arrTranslate[2][i];
// }
x = newX;
y = newY;
z = newZ;
return [newX,newY,newZ];
}
function rotatePoints(fi) {
x0 = rotatePoint(x0,y0,z,fi)[0];
y0 = rotatePoint(x0,y0,z,fi)[1];
x1 = rotatePoint(x1,y1,z,fi)[0];
y1 = rotatePoint(x1,y1,z,fi)[1];
x2 = rotatePoint(x2,y2,z,fi)[0];
y2 = rotatePoint(x2,y2,z,fi)[1];
x3 = rotatePoint(x3,y3,z,fi)[0];
y3 = rotatePoint(x3,y3,z,fi)[1];
x0p = rotatePoint(x0p,y0p,z,fi)[0];
y0p = rotatePoint(x0p,y0p,z,fi)[1];
x1p = rotatePoint(x1p,y1p,z,fi)[0];
y1p = rotatePoint(x1p,y1p,z,fi)[1];
x2p = rotatePoint(x2p,y2p,z,fi)[0];
y2p = rotatePoint(x2p,y2p,z,fi)[1];
x3p = rotatePoint(x3p,y3p,z,fi)[0];
y3p = rotatePoint(x3p,y3p,z,fi)[1];
}
let inFi = document.getElementById("fi");
inFi.addEventListener("change", updateImage);
function updateImage() {
rotatePoints(inFi.value);
getWalls();
updateCanvas();
drawWall(wall06);
drawWall(wall04);
drawWall(wall03);
drawWall(wall02);
drawWall(wall05);
drawWall(wall01);
}
updateImage();
}
<body onload="draw();">
<canvas id="canvas"></canvas>
<div><input type="number" id="fi" value="0"></div>
</body>

Draw Heart using JavaScript in any postion(X,Y)

I have seen a good animation in codepen.io Link Here . Its really amazing. But instead of red-arrow i thought to change it to Heart(Love symbol). So i started to debug the code and i found the function drawArrow, where they are drawing the arrow. There i have tried to implement heart draw(got the code from here).
var ctx = _pexcanvas.getContext("2d");
var d = 20; //The Size of the hearting
var k =150; // The Position of the heart
ctx.moveTo(k, k + d / 4);
ctx.quadraticCurveTo(k, k, k + d / 4, k);
ctx.quadraticCurveTo(k + d / 2, k, k + d / 2, k + d / 4);
ctx.quadraticCurveTo(k + d / 2, k, k + d * 3/4, k);
ctx.quadraticCurveTo(k + d, k, k + d, k + d / 4);
ctx.quadraticCurveTo(k + d, k + d / 2, k + d * 3/4, k + d * 3/4);
ctx.lineTo(k + d / 2, k + d);
ctx.lineTo(k + d / 4, k + d * 3/4);
ctx.quadraticCurveTo(k, k + d / 2, k, k + d / 4);
But while using the above code i can't change the starting position of the heart, means if i increase the K value its placing the heart in the linear position(Like heart will appear only in the linear scope of (-x,y) to (x,-y)),
But i like to place to heart in anywhere in the screen, but i can't achieve it. Give me right direction to fix it.
Note: I am not an JavaScript Dev, i have a basic knowledge in java.
Thanks in advance.
You just need to add the new function to draw hearts instead of arrow, the solution you are referred will draw a stable heart.
Width and height can be use as per your requirement.
Add the following function:
function drawHeart(fromx, fromy, tox, toy,lw,hlen,color) {
var x = fromx;
var y = fromy;
var width = lw ;
var height = hlen;
ctx.save();
ctx.beginPath();
var topCurveHeight = height * 0.3;
ctx.moveTo(x, y + topCurveHeight);
// top left curve
ctx.bezierCurveTo(
x, y,
x - width / 2, y,
x - width / 2, y + topCurveHeight
);
// bottom left curve
ctx.bezierCurveTo(
x - width / 2, y + (height + topCurveHeight) / 2,
x, y + (height + topCurveHeight) / 2,
x, y + height
);
// bottom right curve
ctx.bezierCurveTo(
x, y + (height + topCurveHeight) / 2,
x + width / 2, y + (height + topCurveHeight) / 2,
x + width / 2, y + topCurveHeight
);
// top right curve
ctx.bezierCurveTo(
x + width / 2, y,
x, y,
x, y + topCurveHeight
);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
Below is the working solution for same.
"use strict"
var stage = {
w:1280,
h:720
}
var _pexcanvas = document.getElementById("canvas");
_pexcanvas.width = stage.w;
_pexcanvas.height = stage.h;
var ctx = _pexcanvas.getContext("2d");
var pointer = {
x:0,
y:0
}
var scale = 1;
var portrait = true;
var loffset = 0;
var toffset = 0;
var mxpos = 0;
var mypos = 0;
// ------------------------------------------------------------------------------- Gamy
function drawArrow(fromx, fromy, tox, toy,lw,hlen,color) {
var dx = tox - fromx;
var dy = toy - fromy;
var angle = Math.atan2(dy, dx);
ctx.fillStyle=color;
ctx.strokeStyle=color;
ctx.lineCap = "round";
ctx.lineWidth = lw;
ctx.beginPath();
ctx.moveTo(fromx, fromy);
ctx.lineTo(tox, toy);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(tox, toy);
ctx.lineTo(tox - hlen * Math.cos(angle - Math.PI / 6), toy - hlen * Math.sin(angle - Math.PI / 6));
ctx.lineTo(tox - hlen * Math.cos(angle)/2, toy - hlen * Math.sin(angle)/2);
ctx.lineTo(tox - hlen * Math.cos(angle + Math.PI / 6), toy - hlen * Math.sin(angle + Math.PI / 6));
ctx.closePath();
ctx.stroke();
ctx.fill();
}
function drawHeart(fromx, fromy, tox, toy,lw,hlen,color) {
var x = fromx;
var y = fromy;
var width = lw ;
var height = hlen;
ctx.save();
ctx.beginPath();
var topCurveHeight = height * 0.3;
ctx.moveTo(x, y + topCurveHeight);
// top left curve
ctx.bezierCurveTo(
x, y,
x - width / 2, y,
x - width / 2, y + topCurveHeight
);
// bottom left curve
ctx.bezierCurveTo(
x - width / 2, y + (height + topCurveHeight) / 2,
x, y + (height + topCurveHeight) / 2,
x, y + height
);
// bottom right curve
ctx.bezierCurveTo(
x, y + (height + topCurveHeight) / 2,
x + width / 2, y + (height + topCurveHeight) / 2,
x + width / 2, y + topCurveHeight
);
// top right curve
ctx.bezierCurveTo(
x + width / 2, y,
x, y,
x, y + topCurveHeight
);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
var colors = ['#1abc9c','#1abc9c','#3498db','#9b59b6','#34495e','#16a085','#27ae60','#2980b9','#8e44ad','#2c3e50','#f1c40f','#e67e22','#e74c3c','#95a5a6','#f39c12','#d35400','#c0392b','#bdc3c7','#7f8c8d'];
ctx.clearRect(0,0,stage.w,stage.h);
for (var i =0;i<200;i++) {
var angle = Math.random()*Math.PI*2;
var length = Math.random()*250+50;
var myx=360+Math.sin(angle)*length;
var myy=360-Math.cos(angle)*length;
drawArrow(myx,myy,myx+length/6*Math.sin(angle),myy-length/6*Math.cos(angle),length/30,length/30,'#c0392b');
}
var explode = new Image();
explode.src = canvas.toDataURL("image/png");
ctx.clearRect(0,0,stage.w,stage.h);
for (var i =0;i<200;i++) {
var angle = Math.random()*Math.PI-Math.PI/2;
var length = Math.random()*480+50;
var myx=stage.w/2+Math.sin(angle)*length;
var myy=stage.h-Math.cos(angle)*length;
drawArrow(myx,myy,myx+length/6*Math.sin(angle),myy-length/6*Math.cos(angle),length/30,length/30,'#2c3e50');
}
var explodeb = new Image();
explodeb.src = canvas.toDataURL("image/png");
ctx.clearRect(0,0,stage.w,stage.h);
ctx.fillStyle = "rgba(236,240,241,1)";
ctx.fillRect(0,0,stage.w,stage.h);
for (var i =0;i<200;i++) {
var angle = Math.random()*Math.PI/Math.PI*180;
var length = Math.random()*250+50;
var myx=Math.random()*stage.w;
var myy=Math.random()*stage.h;
drawArrow(myx,myy,myx+length/6*Math.sin(angle),myy-length/6*Math.cos(angle),length/30,length/30,colors[Math.floor(Math.random()*colors.length)]);
}
ctx.fillStyle = "rgba(236,240,241,0.9)";
ctx.fillRect(0,0,stage.w,stage.h);
var back = new Image();
back.src = canvas.toDataURL("image/png");
var angle=0;
var ai = true;
var ait = 0;
var btm=0;
var bullets = [];
function Bullet() {
this.x=stage.w/2-Math.sin(angle)*150;
this.y=stage.h-Math.cos(angle)*150;
this.r=angle;
}
var enemies = [];
function Enemy() {
this.r = Math.random()*Math.PI/(2.5/2)-Math.PI/2.5;
this.dis = Math.random()*1280+720;
this.x=stage.w/2-Math.sin(this.r)*this.dis;
this.y=stage.h-Math.cos(this.r)*this.dis;
}
for(var i=0;i<10;i++) {
enemies.push(new Enemy());
enemies[i].x += Math.sin(enemies[i].r)*300;
enemies[i].y += Math.cos(enemies[i].r)*300;
}
var explosions = [];
function Explosion(x,y,ty) {
this.x=x;
this.y=y;
this.t=30;
this.ty=ty;
}
var eturn = 0;
var cold = [];
function enginestep() {
ctx.drawImage(back,0,0);
if (!ai&&ait<Date.now()-3000) {
ai = true;
}
btm++;
if(btm>8){
btm=0;
bullets.push(new Bullet());
}
for (var i=0;i<bullets.length;i++) {
bullets[i].x -= Math.sin(bullets[i].r)*20;
bullets[i].y -= Math.cos(bullets[i].r)*20;
drawArrow(bullets[i].x+Math.sin(bullets[i].r)*50,bullets[i].y+Math.cos(bullets[i].r)*50,bullets[i].x,bullets[i].y,8,8,'#2980b9');
if(bullets[i].x<-100||bullets[i].x>stage.w+100){
bullets.splice(i,1);
}
if(bullets[i].y<-100||bullets[i].y>stage.h+100){
bullets.splice(i,1);
}
}
for(var i=0;i<enemies.length;i++) {
enemies[i].x += Math.sin(enemies[i].r)*3;
enemies[i].y += Math.cos(enemies[i].r)*3;
drawHeart(enemies[i].x-Math.sin(enemies[i].r)*100,enemies[i].y-Math.cos(enemies[i].r)*100,enemies[i].x,enemies[i].y,15,15,"#c0392b");
if (enemies[i].y>stage.h) {
enemies[i] = new Enemy();
explosions.push(new Explosion(stage.w/2,stage.h,2));
shake = true;
shaket=0;
}
for (var b=0;b<bullets.length;b++) {
var dx = enemies[i].x-bullets[b].x;
var dy = enemies[i].y-bullets[b].y;
var dis = dx*dx+dy*dy;
if (dis<20*20) {
explosions.push(new Explosion(enemies[i].x,enemies[i].y,1));
enemies[i] = new Enemy();
bullets.splice(b,1);
}
}
}
if (ai) {
for(var l=0;l<enemies.length;l++) {
var dx = enemies[l].x-stage.w/2;
var dy = enemies[l].y-stage.h;
var dis = Math.floor(Math.sqrt(dx*dx+dy*dy));
var val1 = 100000+dis;
var val2 = 1000+l;
cold[l]=val1+'x'+val2;
}
cold.sort();
eturn = parseInt(cold[0].slice(8,11));
if (parseInt(cold[0].slice(1,6))<800) {
angle += (enemies[eturn].r-angle)/8;
}
} else {
var dx = pointer.x-stage.w/2;
var dy = pointer.y-stage.h;
angle = Math.atan(dx/dy);
}
drawArrow(stage.w/2,stage.h,stage.w/2-Math.sin(angle)*150,stage.h-Math.cos(angle)*150,30,20,'#2c3e50');
for(var e=0;e<explosions.length;e++) {
if (explosions[e].ty==1) {
var myimg = explode;
ctx.globalAlpha=1-(explosions[e].t/stage.h);
ctx.drawImage(myimg,explosions[e].x-explosions[e].t/2,explosions[e].y-explosions[e].t/2,explosions[e].t*stage.w/stage.h,explosions[e].t);
ctx.globalAlpha=1;
} else {
var myimg = explodeb;
ctx.globalAlpha=1-(explosions[e].t/stage.h);
ctx.drawImage(myimg,explosions[e].x-explosions[e].t*stage.w/stage.h/2,stage.h-explosions[e].t,explosions[e].t*stage.w/stage.h,explosions[e].t);
ctx.globalAlpha=1;
}
}
for(var e=0;e<explosions.length;e++) {
explosions[e].t += 20;
if (explosions[e].t>stage.h) {
explosions.splice(e,1);
}
}
}
// ------------------------------------------------------------------------------- events
// ------------------------------------------------------------------------------- events
// ------------------------------------------------------------------------------- events
// ------------------------------------------------------------------------------- events
function toggleFullScreen() {
var doc = window.document;
var docEl = doc.documentElement;
var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
if(!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
requestFullScreen.call(docEl);
}
else {
cancelFullScreen.call(doc);
}
}
function motchstart(e) {
mxpos = (e.pageX-loffset)*scale;
mypos = (e.pageY-toffset)*scale;
}
function motchmove(e) {
mxpos = (e.pageX-loffset)*scale;
mypos = (e.pageY-toffset)*scale;
pointer.x = mxpos;
pointer.y = mypos;
ai = false;
ait = Date.now();
}
function motchend(e) {
}
window.addEventListener('mousedown', function(e) {
motchstart(e);
}, false);
window.addEventListener('mousemove', function(e) {
motchmove(e);
}, false);
window.addEventListener('mouseup', function(e) {
motchend(e);
}, false);
window.addEventListener('touchstart', function(e) {
e.preventDefault();
motchstart(e.touches[0]);
}, false);
window.addEventListener('touchmove', function(e) {
e.preventDefault();
motchmove(e.touches[0]);
}, false);
window.addEventListener('touchend', function(e) {
e.preventDefault();
motchend(e.touches[0]);
}, false);
// ------------------------------------------------------------------------ stager
// ------------------------------------------------------------------------ stager
// ------------------------------------------------------------------------ stager
// ------------------------------------------------------------------------ stager
function _pexresize() {
var cw = window.innerWidth;
var ch = window.innerHeight;
if (cw<=ch*stage.w/stage.h) {
portrait = true;
scale = stage.w/cw;
loffset = 0;
toffset = Math.floor(ch-(cw*stage.h/stage.w))/2;
_pexcanvas.style.width = cw + "px";
_pexcanvas.style.height = Math.floor(cw*stage.h/stage.w) + "px";
_pexcanvas.style.marginLeft = loffset +"px";
_pexcanvas.style.marginTop = toffset +"px";
} else {
scale = stage.h/ch;
portrait = false;
loffset = Math.floor(cw-(ch*stage.w/stage.h))/2;
toffset = 0;
_pexcanvas.style.height = ch + "px";
_pexcanvas.style.width = Math.floor(ch*stage.w/stage.h) + "px";
_pexcanvas.style.marginLeft = loffset +"px";
_pexcanvas.style.marginTop = toffset +"px";
}
}
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};})();
function sfps(iny) {
return(Math.floor(smoothfps)/60*iny);
}
var timebomb=0;
var lastCalledTime;
var fpcount = 0;
var fpall = 0;
var smoothfps = 60;
var thisfps = 60;
function fpscounter() {
timebomb ++;
if (!lastCalledTime) {
lastCalledTime = Date.now();
return;
}
var delta = (Date.now()-lastCalledTime)/1000;
lastCalledTime = Date.now();
var fps = 1/delta;
fpcount ++;
fpall += fps;
if (timebomb>30) {
thisfps = parseInt(fpall/fpcount*10)/10;
fpcount = 0;
fpall = 0;
timebomb = 0;
}
}
var shake = false;
var shaket = 0;
function animated() {
requestAnimFrame(animated);
if (shake) {
var trax = Math.random()*60-30;
var tray = Math.random()*60-30;
ctx.translate(trax,tray);
}
// fpscounter();
//ctx.clearRect(0,0,_pexcanvas.width,_pexcanvas.height);
enginestep()
// ctx.fillStyle='#8e44ad';
// ctx.font = "24px arial";
// ctx.textAlign = "left";
// ctx.fillText(thisfps,20,50);
// smoothfps += (thisfps-smoothfps)/100;
// ctx.fillText(cold[0].slice(1,6),20,80);
// ctx.beginPath();
// ctx.arc(pointer.x, pointer.y, 50, 0, Math.PI*2,false);
// ctx.closePath();
// ctx.fill();
if (shake) {
ctx.translate(-trax,-tray);
shaket ++;
if (shaket>20) {
shaket=0;
shake=false;
}
}
}
_pexresize();
animated();
body {background:#000000;margin:0;padding:0}
canvas {background:#ecf0f1;}
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Pex.Js Engine">
<meta name="author" content="Ahmad Faisal Jawed">
<title>Arrows</title>
</head>
<body onresize='_pexresize()'>
<canvas id='canvas' width=1280 height=720></canvas>
</body>
</html>

Why does algebra.js fail to solve for y

On website https://omegalords.ga/world/test.html, I have a code that calculates 1 unit towards a target. In the code the slope is 1. so the x and y of the next spot to jump to should be the same. Why does it at some point change and the 2 coordinates. I have ran the numbers, but it doesn't work properly. Could someone explain hwy?
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var findDis = function(x1,y1,x2,y2){
//Finds distance rounded to the nearest 1000th
return Math.trunc(((Math.sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)))*1000))/1000
}
var findIntersections = function(b,a,m,r){
var Fraction = algebra.Fraction;
var Expression = algebra.Expression;
var Equation = algebra.Equation;
var coords = {
l:[],
g:[]
}
//b^2 - 2bx + x^2 - 2bm^2x + b^2m^2 - r^2
var sl = algebra.parse(Math.pow(b,2)+" - "+2*b+"x + x^2 + "+Math.pow(m,2)+"x^2 -" + 2 * b * Math.pow(m,2) + "* x + " + Math.pow(b,2) * Math.pow(m,2) + " - " + Math.pow(r,2));
var sr = algebra.parse("0")
var eq = new Equation(sl, sr);
//Solves for x rounded to the nearest 1000
coords.l.push(Math.trunc((eq.solveFor("x")[0]*1000))/1000);
coords.g.push(Math.trunc((eq.solveFor("x")[1]*1000))/1000);
//Solves for y
coords.l.push(Math.trunc((coords.l[0] * m + a - (b * m))*1000)/1000);
coords.g.push(Math.trunc((coords.g[0] * m + a - (b * m))*1000)/1000);
return JSON.stringify(coords);
}
var findSlope = function(x1,y1,x2,y2){
//Finds Slope rounded to the nearest 1000th
return Math.trunc(((y1-y2)/(x1-x2))*1000)/1000;
}
var getRandomInt = function(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
var wolves = [];
var deers = [];
var deer = function(x,y){
this.x = x;
this.y = y;
this.hp = 100;
this.size = 10;
this.hunger = 0*%;
this.preyTypes = [grass];
this.predatorTypes = [wolves];
deers.push(this);
}
var wolf = function(x,y){
this.x = x;
this.y = y;
this.hp = 100;
this.size = 10;
this.hunger = 0 * %;
wolves.push(this);
this.preyTypes = [deers]
}
wolf.prototype.move = function(){
this.nearbyPredators = [];
this.nearbyPrey = [];
//finds all nearby prey
for(var j = 0;j<this.preyTypes.length;j++){
for(var i = 0;i < this.preyTypes[j].length;i++){
if(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y) < 40){
this.nearbyPrey.push(this.preyTypes[j][i]);
}else{
console.log(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y))
}
}
}
//If there are no nearby prey, move randomly
if(this.nearbyPrey.length === 0){
wolf.x += getRandomInt(-8,9)
wolf.y -= getRandomInt(-9,8);
//If there is only one nearby prey, move towards it
}else if(this.nearbyPrey.length === 1){
this.nearestPrey = this.nearbyPrey[0]
var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y);
console.log(slope);
var coords = JSON.parse(findIntersections(this.x,this.y,slope,1));
console.log(coords);
var ldis = findDis(this.x,this.y,coords.l[0],coords.l[1]);
var gdis = findDis(this.x,this.y,coords.g[0],coords.g[1]);
console.log(ldis,gdis)
if(ldis > gdis){
this.x = coords.l[0]
this.y = coords.l[1]
console.log(this.x,this.y)
}else {
this.x = coords.g[0]
this.y = coords.g[1]
console.log(this.x,this.y)
}
//If there is more than 1, find the nearest prey and move towards it
}else {
for(var i = 0; i < this.nearbyPrey.length; i++){
this.tempDis = getDis(this.x,this.y,this.nearbyPrey[i].x,this.nearbyPrey[i].y)
if(typeof this.nearestPrey == 'undefined'){
this.nearestPrey = {
prey:this.nearbyPrey[i],
distance:this.tempDis
}
this.tempDis = undefined
}else {
if(this.tempDis > this.nearestPrey.distance){
this.nearestPrey = {
prey:this.nearbyPrey[i],
distance:this.tempDis
}
}
}
}
var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y)
var coords = JSON.parse(findIntersections(this.nearestPrey.x,this.nearestPrey.y,slope,1));
var ldis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.l[0],coords.l[1]);
var gdis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.g[0],coords.g[1]);
if(ldis > gdis){
this.x = coords.l[0]
this.y = coords.l[1]
}else {
this.x = coords.g[0]
this.y = coords.g[1]
}
}
}
wolf.prototype.bite = function(prey){
prey.hp -= this.strength;
this.hunger += 40 * %
console.log(this.hunger);
console.log(this.nearestPrey.hp)
}
new wolf(100,100)
new deer(80,80);
var init = function(){
ctx.translate(0.5, 0.5);
ctx.lineWidth = .5
window.setInterval(draw,1000);
}
var draw = function(){
ctx.clearRect(0,0,canvas.width,canvas.height)
wolves[0].move();
for(var i=0;i<wolves.length;i++){
ctx.beginPath();
ctx.arc(deers[0].x,deers[0].y,10,0,2*Math.PI);
ctx.stroke();
ctx.beginPath()
ctx.arc(wolves[i].x,wolves[i].y,10,0,2*Math.PI);
ctx.stroke();
}
}
init()
</script>

how can i make two objects belonging to the same array move independently of each other using javascript and the canvas tag?

I am trying to create a blackhole simulation, where all the balls that are outside of it go away from it at a given speed and those that fall on it are dragged towards the circle until they reach the center of it, where they would stop and disappear, here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>blackhole simulation escape velocity</title>
<script>
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var G = 6.67e-11, //gravitational constant
pixel_G = G / 1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
pixel_M = M / 1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3, // scaled radius
ccolor = 128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - 700) * (pos.x - 700)) + ((pos.y - 400) * (pos.y - 400)));
if (distance > pixel_Rs-5 ) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - 400, pos.x - 700);
var evelocity = Math.sqrt((2 * pixel_G * pixel_M) / (distance * 1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
} else {
var delta2 = new Vector2D (0,0);
var forceDirection2 = Math.atan2(pos.y - 400, pos.x - 700);
var g = (pixel_G*pixel_M)/(distance*distance*1e2);
delta2.x += Math.cos(forceDirection2)*g;
delta2.y += Math.sin(forceDirection2)*g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 1;
if (pos.x == 700 && pos.y == 400){
somethingMoved = false;
};
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init(event) {
canvas = document.getElementById("space");
ctx = canvas.getContext('2d');
blackhole = new Ball(pixel_Rs, { x: 700,
y: 400 }, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * 1400), Math.floor(Math.random() * 800));
circle = new Ball(5, vec2D, ccolor);
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
Ball.prototype.draw = function(ctx) {
var c=parseInt(this.color);
ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',1)';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
function onClick (){
canvas = document.getElementById ('space');
ctx = canvas.getContext ('2d')
canvas.addEventListener ("mousedown", init, false)
blackhole = new Ball (5, {x: 700,
y: 400 }, 0);
blackhole.draw (ctx) ;
}
window.onload = onClick;
</script>
<style>
body {
background-color:#021c36 ;
margin: 0px;
}
</style>
</head>
<body>
<canvas id = "space", width = "1400", height = "800">
</canvas>
</body>
</html>
Now as you can see, I created a second variable called delta2, but the problem is that it can't update the position of the circles, which in term makes it impossible to move the circle, can someone tell me what is wrong. Also, how can I make the big black circle after a certain amount of time, i know i probably should create a timer, but i don't know how they work
The gravity is too weak. I put a pseudo gravity to demonstrate.
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var bh = {
w:500,
h:300
};
bh.cx = Math.floor(bh.w/2);
bh.cy = Math.floor(bh.h/2)
var G = 6.67e-11, //gravitational constant
pixel_G = G / 1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
pixel_M = M / 1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3, // scaled radius
ccolor = 128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - bh.cx) * (pos.x - bh.cx)) + ((pos.y - bh.cy) * (pos.y - bh.cy)));
if (distance > pixel_Rs - 5) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - bh.cy, pos.x - bh.cx);
var evelocity = Math.sqrt((2 * pixel_G * pixel_M) / (distance * 1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
} else {
var delta2 = new Vector2D(0, 0);
var forceDirection2 = Math.atan2(pos.y - bh.cy, pos.x - bh.cx);
// FIX THIS!!!
var g = 1;//(pixel_G * pixel_M) / (distance * distance * 1e2);
delta2.x += Math.cos(forceDirection2) * g;
delta2.y += Math.sin(forceDirection2) * g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 1;
if (pos.x == bh.cx && pos.y == bh.cy) {
somethingMoved = false;
};
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init(event) {
canvas = document.getElementById("space");
canvas.width = bh.w;
canvas.height = bh.h;
ctx = canvas.getContext('2d');
blackhole = new Ball(5, { //pixel_Rs, {
x: bh.cx,
y: bh.cy
}, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * bh.w), Math.floor(Math.random() * bh.h));
circle = new Ball(5, vec2D, ccolor);
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
Ball.prototype.draw = function(ctx) {
var c = parseInt(this.color);
ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',1)';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
function onClick() {
canvas = document.getElementById('space');
ctx = canvas.getContext('2d')
canvas.addEventListener("mousedown", init, false)
blackhole = new Ball(5, {
x: bh.cx,
y: bh.cy
}, 0);
blackhole.draw(ctx);
}
window.onload = onClick;
body {
background-color: #021c36;
margin: 0px;
}
<canvas id="space" , width="700" , height="400"></canvas>

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