如果对象到达页面上的某个点,如何使对象停止?

时间:2015-06-25 08:45:44

标签: javascript jquery collision-detection webpage game-physics

我正在制作一个游戏,您可以在某个区域内移动,但问题是您可以在我希望玩家进入的区域之外自由移动。我有什么方法可以做到这一点,如果玩家到达页面上某个他不能再移动的坐标?

我将其编码,以便每次按下任何箭头键时,玩家将向所选方向移动16px。

<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>

我试了但是没有用,有什么建议吗?

1 个答案:

答案 0 :(得分:0)

首先需要定义区域是什么(假设X和Y的下限为0):

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

您可以测试移动是否会将玩家抛出您定义的区域之外。

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