Search code examples
jquerypong

How do I set a movement limit in jquery?


I'm trying to create pong, and I've created all the html, css, and js for the paddles to move, but how do i keep them from moving from outside of the predetermined border that I've set?

This is the code for the right paddle's existence in js, using jquery.

var rightBoard = GameItem("#rightBoard");
  rightBoard.x = BOARD_WIDTH - $('#rightBoard').width()

And this is the movement code.

var keycode = event.which;
    if (keycode === KEY.DOWNARROW) {
      rightBoard.velocityY = 5;
    }if (keycode === KEY.UPARROW) {
      rightBoard.velocityY = -5; 
    }

How can I set a limit so it won't move past a certain point? I'm stuck on this, as it's one of my first projects. Thanks for the help.


Solution

  • Everytime you move the paddle, either during setting the velocity or at the place where you actually add the velocities to your paddle position, Check if the newly updated position will be inside or outside bounds. If it is inside, then only update the actual position.

    var keycode = event.which;
        if (keycode === KEY.DOWNARROW) {
          if(rightBoard.y + 5 < BOARD_HEIGHT - Paddle_Height)
               rightBoard.velocityY = 5;
          else
               rightBoard.velocityY = 0;
        }if (keycode === KEY.UPARROW) {
          if(rightBoard.y - 5 > 0)
               rightBoard.velocityY = -5;
          else
               rightBoard.velocityY = 0;
        }
    

    Here I am assuming that paddle's origin is set at the top left corner.