9. Mouse controls
This is the 9th step out of 10 of the Gamedev Canvas tutorial.
The game itself is actually finished, so let's work on polishing it up. We already have the keyboard controls, but we could easily add mouse controls too. It's even easier: all we need is the listener for the mouse move event:
document.addEventListener("mousemove", mouseMoveHandler, false);
We can update the paddle position based on the pointer coordinates, the handler function is doing exactly that:
function mouseMoveHandler(e) { var relativeX = e.clientX - canvas.offsetLeft; if(relativeX > 0 && relativeX < canvas.width) { paddleX = relativeX - paddleWidth/2; } }
If the relativeX
(the relative position of the pointer on the Canvas) is greater than zero and lower than the Canvas width, which means the pointer is within the Canvas boundaries, then the paddleX
position (anchored on the left edge of the paddle) will be set to the relativeX
value minus half the width of the paddle.
The paddle will follow the position of the mouse cursor, but we're restricting the movement to the size of the Canvas, so it won't disappear on either sides of it completely.
{{JSFiddleEmbed("https://jsfiddle.net/end3r/L3gngab5/","","320")}}
Exercise: adjust the boundaries of the paddle movement, so the whole paddle will be visible on both edges of the Canvas instead of only the half of it.
Now, you can get back to this tutorial's index page or continue to the last, tenth chapter: Finishing up.