I have a working code that wraps all the stuff in anonymous function, to avoid pollute global namespace. But it still containing too many global variables, so, i am trying to clean it in some way. This is now:
(function() {
...
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
function drawPaddle() {
ctx.beginPath(); // Draw paddle
ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath(); // end draw
}
})();
In the draw() function"Main", i have a conditional statement to check the relative movement of the paddle:
function draw() {
...
// here i'm clearing canvas after each frame draw
//here are calls to other functions.
if(rightPressed && paddleX < canvas.width-paddleWidth) {
paddleX += 7;
}
else if(leftPressed && paddleX > 0) {
paddleX -= 7;
}
}
I had try to move all the stuff on a class(this will be a edit to add MyclassPaddle). Related functions are:
keyDownHandler();
KeyUpHandler();
drawPaddle();
// the if statement to check movement of paddle.
The problem now is when i try no move the if to an isolated function the 'global' variables isn't updated, so the paddle can't move. I want to move all related variables but i'm not finding the right way.
namespace.variable