I am working on creating a game that has to do with objects(circles) falling from the top of the canvas. I have these circles randomly generating at x coordinates and then falling at a constant rate. I am trying to write a collision algorithm but cannot seem to access the x coordinates or width/height of the circles that are falling.
This is how I created the circles and put them in an array. var projectiles = [] was declared at the top of my code already
function spawnEnemies()
{
var g1 = new createjs.Graphics();
g1.beginStroke('white').beginFill('red').drawCircle(Math.floor(Math.random() * 650) + 50, 50, 20);
var e = new createjs.Shape(g1);
projectiles.push(e);
stage.addChild(e);
}
This is my collision algorithm where I am trying to access the x and y coordinates of the circles and also retrieve their width and height. I used console.log to check and see what values are being returned. For p.x the value 0 is returned every time and p.width returns NaN. I am confused why p.x and p.width are not working.
function checkCollision()
{
for (i = 0; i < projectiles.length; i++) {
var p = projectiles[i];
if((p.x + width) < ship.x)
{
hit = false;
}
else if(p.x > (ship.x + ship.image.width))
{
hit = false;
}
else if(p.y > (ship.y + ship.image.height))
{
hit = false;
}
else if((p.y + p.height) < ship.y)
{
hit = false;
}
else
{
hit = true;
console.log(p.x);
}
}
The x
and y
properties of a Shape
can be used to translate it. In your code, you instead leave them as the default (0) and draw the circle at a specific location in the Shape's canvas.
If you want the x
to reflect the location of the circle, consider changing spawnEnemies
to always draw the circle at the Shape's origin, then setting its x
to the desired location.
g1.(...).drawCircle(0, 50, 20);
var e = new createjs.Shape(g1);
e.x = Math.(...);