Question

So I've been picking apart a javascript game tutorial and trying to create my own out of it, but I've run across a problem that I'm not sure how to deal with. Basically, the player can shoot upwards inside of a canvas by clicking, and I'm using a mousedown event in one of the update functions to achieve that. Every time this occurs, a little lazer missile should be created (a new instance of it is created and pushed onto an array, lazers). For testing purposes, I'm having the game print how many lazers are in this array, and it seems that every time the mouse is clicked (or down, rather), it adds around 20 lazers instead (and sometimes much, much more than that). This is the specific function:

 canvas.addEventListener('mousedown', function (e) {
        lazers.push(makeProjectile(position.x + width / 2, position.y - height / 2));
 });

I put the whole thing on jsfiddle as well: http://jsfiddle.net/cgC2z/3/

Keep in mind that this code is a bit messy and there may be hanging bits around. (Do feel free to comment on the way the game is being constructed, though, I would love any and all constructive criticism).

Was it helpful?

Solution

You are adding the event listener in the update function. Hence every update another event listener is being added. Then they are all being triggered at once, when clicking.

Simply move the event listeners out: http://jsfiddle.net/cgC2z/4/

canvas.addEventListener('mousemove', function (e) {
    var mousePos = getMousePos(canvas, e);
    position.x = mousePos.x;
    position.y = mousePos.y;
}, false);

canvas.addEventListener('mousedown', function (e) {
    lazers.push(makeProjectile(position.x + width / 2, position.y - height / 2));
});

function update(elapsed) {
    for (var i = 0; i < lazers.length; i++) {
        lazers[i].update(elapsed);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top