Question

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.

Was it helpful?

Solution

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.

  • drawBullet uses x and y that aren't defined. Use spaceShip.x and spaceShip.y instead.
  • newBullet uses angle, which isn't defined anywhere
  • newBullet tried to use the movebullet function. It should be moveBullet
  • drawImage needs an image, canvas, or video element - it doesn't take a URL.

Edit(2): More fixes There are still several problems to fix.

  • One is that you still haven't changed the call to ctx.drawImage to pass an image element rather than a URL.
  • Another is your move function is multiplying the x and y values by the speed. That means that as soon as the bullet moves, it is off the screen.
  • A third problem is that the 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top