I'm creating a mini game using Raphael elements that is meant to create a pop-up when the player bumps with the "bullet", and so far the code works accordingly if I create each elements normally. For example, this:
let playerCircle = paper.circle(100, 3*pHeight/10, 15).attr({
"fill": "black"
});
let enemyShip = paper.circle(100, 100, 15).attr({
"fill": "red",
"stroke": "black",
});
However, I want the "enemyShip" to spawn on clicking of the player circle, and I have this current code:
let spawnEnemy = function(ev){
let posX = random(pWidth, pWidth+30);
let posY = random(0, 3*pHeight/5-30);
let enemyShip = paper.circle(posX, posY, 15).attr({
"fill": "red",
"stroke": "black",
});
enemyShip.animate({
"cx": posX-pWidth-60,
}, 1000, "linear", function(){enemyShip.remove()})
};
When I do this however, it results in "Uncaught Reference Error: enemyShip is not defined", any way I can fix this?
Not sure if this information would help, but this is the code to register the collision:
let collision = function(a, b){
a = {
"x": a.attr("cx"),
"y": a.attr("cy"),
};
b = {
"x": b.attr("cx"),
"y": b.attr("cy"),
};
let d = distance(a, b);
if (d < playerCircle.attr("r") + enemyShip.attr("r")){
alert("hi");
};
};
It's probably a scope issue. If you declare enemyShip outside of the spawnEnemy function, it will probably work. as collision can't know about that variable as it is.
I'd also change your collision function a little, and make it work for any 2 object/entities, so instead of it being forced to use playerCircle and enemyShip, just use a & b and its attributes and not have any hardcoded references in that function.