I'm currently trying to modify this piece of code so that my player is able to shoot. I'm stuck where it is at the moment where the player doesn't actually shoot anything (no image is created on space click, though no error outlined), The missiles only need to travel upwards on my canvas. I would prefer if any answers to this question also give some form of learning as I'm interested in actually understanding how to implement this properly as to just needing some kind of quick fix.
When setInterval
calls moveBullet
, the this
value will not be the bullet, it will be window
. Try binding the function to the bullet using the following:
setInterval(bullets[bullets.length - 1].moveBullet.bind(bullets[bullets.length - 1]), 25);
see This link for more info.
Edit: updating with more fixes:
You should show the console in you browser (F12 in most browsers). This will list some errors you are having.
x
and y
that aren't defined. Use spaceShip.x
and spaceShip.y
instead.angle
, which isn't defined anywheremovebullet
function. It should be moveBullet
Edit(2): More fixes There are still several problems to fix.
render
function updates the entire background, which means that the bullet, even if it was drawn would immediately get overwritten. You should move the actual bullet drawing to the render function.I have updated your original JSFiddle with some of these fixes, enough to get it drawing (without erasing). You can find it here. I also changed it to just have 1 bullet per space press (to help with debugging).
At the moment, I just made it stop drawing the background, so that you can see the bullet, but you should look at moving the bullet drawing (not moving) to the render function.