🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Pong Paddle Movement

Started by
3 comments, last by 8Observer8 4 years, 9 months ago

Hi all, im new and learning JS and trying to build pong. im following a tutorial but trying to change it.

 

the line im stuck on is trying to move the paddle when the mouse moves

 


document.body.addEventListener("mousemove", mouseMoveHandler);

function mouseMoveHandler(event) {
    //console.log(event);
    player.setY(event.clientY - player.getHeight() /2);
}

This works with the assumption that my canvas takes up the entire screen

the tutorial has the canvas full browser, mine is only 800 x 400 and is centered.

how can i get this to only moe and register when im on the canvas? at the moment i can enter the browser and it starts moving even though my mouse is nowhere near it.

----------------------------------------------------------------------

 

Fixed it

 

i have a div the same size as the canvas called holder  so i did:


holder.addEventListener("mousemove", mouseMoveHandler);

function mouseMoveHandler(event) {
    //console.log(event);
    holder.style.cursor = "none";
    player.setY(event.clientY - player.getHeight() *2 );
}

 

Advertisement

You can add the listener to the canvas element itself, there's no need to wrap it in a container.

However, this requires the player to keep the mouse pointer within this area or your input will freeze. This quickly becomes annoying, especially when you hide the cursor. So generally it would be better to handle input on the document level.

Alternatively you could capture the mouse, but I'm not sure how well supported that is nowadays.

On 10/23/2019 at 5:45 AM, maknib said:

Hi all, im new and learning JS and trying to build pong.

This tutorial is awesome for beginners:

2D breakout game using pure JavaScript
https://developer.mozilla.org/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript

Post your examples on https://next.plnkr.co/ Plunker is one of the best Playgrounds where you can keep a few files. JSFiddle and CodePen are not allow to keep a few JS files.

This topic is closed to new replies.

Advertisement