Skip to main content
GameDev.net gamedev.net
🔒 Locked

Pong Paddle Movement

Started by NibzAU Oct 23, 2019 at 1:45 AM 3 replies 2.5k views
Original Post
NibzAU
NibzAU

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 );
}


Prototype
Prototype

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.

8Observer8
8Observer8

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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.