Question

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;
Était-ce utile?

La 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.

Autres conseils

Change var e = ... in line 2 to e = ...

Try splitting up the problem by putting a breakpoint on switch (key) and looking at key and e, or writing console.log("E: " + e + " KEY: " + key) if you are not familiar with your debugger yet.

I'm not sure if it's necessary - probably not - but I'm paranoid about these things, so to be on the safe side I'd push the else if back to not have a new line between it and the if statement it's connected to.

You are creating a variable e with the code:

var e = window.event ? event : e ;

Which exists in the batupdate function's scope. You are also passing a parameter into that function with is labelled e.

Basically you are using the same name for 2 different things, which is problematic. Try this instead:

e = window.event ? event : e ;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top