Search code examples
javascriptonkeypresspong

Javascript Pong Game Moving Bats


I'm currently on a Pong game tutorial, with Javascript. I'm at the point where I need to make the 2 bats move, by pressing certain keys. The bats should move when I press K, M, A or Z. But they are not moving at all. My IDE says 'variable e hides argument'. This is the code I'm using at the moment:

batupdate = function(e) {   
var e = window.event ? event : e;

if (e.keyCode) 
{ 
    key = e.keyCode; 
}

else if (typeof (e.which) != 'undefined') 
{ 
    key = e.which; 
}

switch (key) 
{
    case (122):
        BatL.move(1);
        break;
    case (97):
        BatL.move(-1);
        break;
    case (107):
        BatR.move(-1);
        break;
    case (109):
        BatR.move(1);
        break;
}
}

document.onkeypress = batupdate;

Solution

  • The problem doesn't lie in the code you have shown us. You can see this here: http://jsfiddle.net/K6MRu/

    I took out the Bat[LR].move() calls because we don't have their implementation and replaced them with alerts showing the same data. You'll see that it it works just fine. This means the problems has to be in the value of the BatL and/or BatR variables or the implementation of the move() function.

    The message your IDE is giving is not actually a problem at all, as it just means you can't access something you aren't trying to access. You can make the message go away by removing the var in var e = window.event ? event : e; as others have suggested and I would recommend doing so, but it won't solve the problem of your bats not moving.