Trying to make a game. Not working out well

So here’s the code. I can’t print the player and if I could only do that I could decide the rest of the logic. The playerX variable is commented out of the code because if it becomes apart of the code, neither the ball or the player appears. I believe the ball is appearing where the player is supposed to. Even if this isn’t a codecademy exercise, I’d still love some help or advice on this. What am I doing wrong?

Ion Gamez
<style> 
* {
padding: 0;
margin: 0;
}
canvas { 
background: #eee;
display: block;
margin: 0 auto;
border-color: black;
border-style: solid;
border-radius: 20px;
border-width: 5px;
}


</style>

</head>

<canvas id="myCanvas" width="480" height="320"></canvas>

<script>
var playerHeight = 10;
var playerWidth = 75;
//var playerX = (canvas.width-playerWidth)/2;
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 20;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var rightPressed = false;
var leftPressed = false;


document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false); 


function keyDownHandler(e) {
 if(e.key == "Right" || e.key == "ArrowRight") {
    rightPressed = true;
}
 else if(e.key == "Left" || e.key == "ArrowLeft") {
    leftPressed = true;
}

}

function keyUpHandler(e) {
 if(e.key == "Right" || e.key == "ArrowRight") {
    rightPressed = false;
}
 else if(e.key == "Left" || e.key == "ArrowLeft") {
    leftPressed = false;
}

}

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}
 function drawPlayer() {
    ctx.beginPath();
    ctx.rect(playerX, canvas.height-playerHeight, playerWidth, playerHeight);
    ctx.fillStyle = "2700ff";
    ctx.fill();
    ctx.closePath();
} 

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  drawBall();
  drawPlayer();

  
 if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
  dx = -dx;
}

if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
  dy = -dy;
}

if(rightPressed) {
    playerX += 7;
    if (playerX + playerWidth > canvas.width){
        playerX = canvas.width - playerWidth;
    }
}
else if(leftPressed) {
    playerX -= 7;
    if (playerX < 0){
        playerX = 0;
    }
} 

x += dx;
y += dy;

}

setInterval(draw, 10);
</script>

Welcome back to the forums

The issue appears to boil down to using the wrong order when you’re declaring your variables:

You use canvas.width in the calculation to set the initial value of playerX before canvas is defined.

If you change the order of those two lines:
ball-bounce

2 Likes