How do I make an object stop if it reaches a certain point on a page?

2k Views Asked by At

I am making a game where you can move around in a certain area but the problem is that you can move freely outside the area I want the player to be in. Is there any way I can make it so that if the player reaches a certain coordinate on the page that he cant move any further?

I coded it so that everytime any of the arrow keys are pressed the player moves 16px to the direction chosen.

<script>
//pressing a key
$(document).keydown(function(e){

//sets variables
var position = $("#player").position();
var xLimit = 500;
var yLimit = 300;
var currentX = 0;
var currentY = 0;
var offset = 16;

//everytime user presses "left" key object "player" moves left 16 pixels.
switch(e.keyCode){
case 37: //left
$("#player").css('left', position.left - 16 + 'px');

function moveLeft() {
   if (currentX + offset <= xLimit) {
       currentX += offset;
   }
}
break;


//everytime user presses "up" key object "player" moves up 16 pixels.
case 38: //up
$("#player").css('top', position.top - 16 + 'px');

function moveUp() {
   if (currentX + offset <= xLimit) {
       currentX += offset;
   }
}
break;


//everytime user presses "right" key object "player" moves right 16 pixels.
case 39: //right
$("#player").css('left', position.left + 16 + 'px');

function moveRight() {
   if (currentX + offset <= xLimit) {
       currentX += offset;
   }
}
break;


//everytime user presses "down" key object "player" moves down 16 pixels.
case 40: //down
$("#player").css('top', position.top + 16 + 'px');
break;

function moveDown() {
   if (currentX + offset <= xLimit) {
       currentX += offset;
   }
}

}
});
</script>

I tried it but did not work, any suggestions?

1

There are 1 best solutions below

3
On

Your first need to define what is the area (let's say the lower limits for X and Y are 0) :

var position = $("#player").position();
var xLimit = 500;
var yLimit = 300;
var offset = 16;

You can test if the move will throw the player outside of the area you defined.

switch(e.keyCode){
   case 37: //left
       function moveLeft() {
          if (position.left - offset >= 0) {
              $("#player").css('left', position.left - offset + 'px');
          }
       }
       break;

   case 38: //up
       function moveUp() {
          if (position.top - offset >= 0) {
              $("#player").css('top', position.top - offset + 'px');
          }
       }
       break;

   case 39: //right
       function moveRight() {
          if (position.left + offset <= xLimit) {
              $("#player").css('left', position.left + offset + 'px');
          }
       }
       break;

   case 40: //down
       function moveDown() {
           if (position.top + offset <= yLimit) {
               $("#player").css('top', position.top + offset + 'px');
           }
       }
       break;
 }