使元素表现出某种方式直到事件(制作pacman游戏)

时间:2015-12-01 16:32:50

标签: javascript jquery events

我在Javascript中制作pacman游戏作为练习。什么是一个好方法让角色无限期地向一个方向走,直到按下另一个键?

function Player(){

this.left = $('#pacMan').css('left');

this.leftMove = function(){

this.left = parseInt(this.left) - 20;  
$('#pacMan').animate({'left': this.left}, 100);   
};


//Pressing directional keys calls appropriate methods.

$('body').keydown(function(){
if (event.which === 39){
for (i=0; i<13; i++){
pacMan.rightMove();
}
}
if (event.which === 37){
pacMan.leftMove();
}
if (event.which === 38){
pacMan.topMove();
}
if (event.which === 40){
pacMan.bottomMove();
}

});*/

如何使元素继续移动方向,直到按下新键,它会向那个方向移动?

3 个答案:

答案 0 :(得分:1)

我倾向于用于此类问题的一般方法是让您的对象拥有changeXvx)和changeYvy)变量。然后在您的主游戏循环中,将对象的位置更改为变量:

this.left = parseInt(this.left) - this.vx;  
this.top = parseInt(this.top) - this.vy;  

在您的事件处理程序中,您可以根据要移动的位置设置vxvy的值。例如,设置vx = 10vy = 0会使每个循环向左移动10个单位。

if (event.which === 39) {
   //pacMan.leftMove();
   pacMan.vx = 10; pacMan.vy = 0;
}

玩家只需要一个move()函数,该函数将根据主循环中的值移动:

var timer = setInterval(function () {
  pacMan.move();
}, 50);

move()的位置:

this.move = function(){
  this.left = parseInt(this.left) - this.vx;  
  $('#pacMan').css({'left': this.left})
  this.top = parseInt(this.top) - this.vy;  
  $('#pacMan').css({'top': this.top});      
}

Working Example

答案 1 :(得分:0)

我建议使用setTimeout函数

setTimeout( function() {
    // leftMove, topMove, bottomMove, rightMove
    // if you press new key, you have to change direction
} , 1000 );
// 1000 moving delay 

答案 2 :(得分:0)

您可以使用window.setInterval执行此操作,这样的工作

var timer;
$('body').keydown(function () {
  var key = event.which;
  window.clearInterval(timer);
  timer = window.setInterval(function () {
    switch (key) {
    case 37:
      pacMan.leftMove();
      break;
    case 38:
      pacMan.topMove();
      break;
    case 39:
      pacMan.rightMove();
      break;
    case 40:
      pacMan.bottomMove();
      break;
    }
  }, 100);
});