简体   繁体   English

用JavaScript中的单箭头键连续移动

[英]Continuous movement with single arrow key press in JavaScript

I'am designing a pacman like game for my webtech course assignment,but if can't seem to figure out how to keep the pacman moving with a single arrow press in a particular direction and when another arrow key is pressed move the pacman in that direction continuously?? 我正在为我的网络技术课程设计一个类似pacman的游戏,但是,如果似乎无法弄清楚如何使pacman沿单个箭头方向向特定方向移动,并在按下另一个箭头键时移动pacman方向不断? It seems to me setInterval has to be used for this purpose but I don't know how would that work...please help. 在我看来setInterval必须用于此目的,但我不知道该如何工作...请帮助。 I'am using switch case as follows for the movement: 我正在使用开关盒,如下所示:

  switch (event.keyCode) {
    case 37:

        inter=setInterval(leftArrowPressed(),50); //Move Left function call
        break;
    case 39:
        inter=setInterval(rightArrowPressed(),50); //Move Right function call
        break;
    case 38:
        inter=setInterval(upArrowPressed(),50); //Move Up function call
        break;
    case 40:
        inter=setInterval(ownArrowPressed(),50); //Move Down function call
        break;
    default:
        alert("Invalid Key pressed");
        break;
}

} }

 function leftArrowPressed() //Left Arrow
{      
document.getElementById("player").style.transform="rotateY(180deg)";
var newleftA = leftA - 5;
var z = newleftA / d;
m = Math.floor(z);

if(parseInt(document.getElementById("player").style.left)<=0)
    {
        document.getElementById("player").style.left= 555 +'px';
        document.getElementById("player").style.top= 180 +'px';
        document.getElementById("player").width.width= 614 +'px';
        document.getElementById("player").style.height= 239 +'px';
    }
if ((a[divTop][m]) == 1 || (a[divBottom][m] == 1)) {
    /*alert("Hit obstacle");*/
    ;

} else {
    document.getElementById("player").style.left = newleftA + 'px';
    /*cell.style.backgroundImage="";*/
}

} }

     function upArrowPressed() //Up Arrow
   {
   document.getElementById("player").style.transform = "rotate(270deg)";
var newtopA = topA - 5;
var z = newtopA / d;
m = Math.floor(z);

if ((a[m][divLeft] == 1) || (a[m][divRight] == 1)) {
    /*alert("Hit obstacle");*/
    ;

} else {
    document.getElementById("player").style.top = newtopA + 'px';
}

} }

   function rightArrowPressed() //Right Arrow
     {
  document.getElementById("player").style.transform = "rotate(0deg)";
var newrightA = rightA + 5;
var z = newrightA / d;
m = Math.floor(z);

if(parseInt(document.getElementById("player").style.left)>=545)
    {
        document.getElementById("player").style.left= 0 +'px';
        document.getElementById("player").style.top= 180 +'px';
        document.getElementById("player").width.width= 54 +'px';
        document.getElementById("player").style.height= 239 +'px';
    }
if ((a[divTop][m] == 1) || (a[divBottom][m] == 1)) {
   /* alert("Hit obstacle");*/

} else {
    document.getElementById("player").style.left =       parseInt(document.getElementById("player").style.left) + 5 + 'px';
}

} }

    function downArrowPressed() // Down Arrow
    {
     document.getElementById("player").style.transform = "rotate(90deg)";
var newbottomA = bottomA + 5;
var z = newbottomA / d;
m = Math.floor(z);
if ((a[m][divLeft] == 1) || (a[m][divRight] == 1)) {
   /* alert("Hit obstacle");*/

} else {
    document.getElementById("player").style.top =  parseInt(document.getElementById("player").style.top) + 5 + 'px';
}

} }

Dont call the movement functions from the keyboard events. 不要从键盘事件中调用移动功能。

Use the key up and key down events to just record the key events 使用按键上升和按键下降事件仅记录按键事件

const keys = {};
function keyEventHandler(event){
    keys[event.code] = event.type === "keydown";
    event.preventDefault();
}
window.addEventListener("keydown",keyEventHandler);
window.addEventListener("keyup",keyEventHandler);

Then in the main game loop just check for the keys to move and do what ever action needs down when they are down. 然后在主游戏循环中,只需检查按键是否移动,然后在按下时进行所有需要按下的操作即可。

//call from Main loop once every frame
function doPlayerMove(){
    if(keys.ArrowLeft){
          // move left
    }
    if(keys.ArrowRight){
          // move right
    }
    if(keys.ArrowDown){
          // move down
    }
    if(keys.ArrowUp){
          // move up
    }
}

Example of a main loop and keyboard handler 主循环和键盘处理程序的示例

 var createImage=function(w,h){var i=document.createElement("canvas");i.width=w;i.height=h;i.ctx=i.getContext("2d");return i;} var canvas = createImage(512,200); var ctx = canvas.ctx; document.body.appendChild(canvas); var player = { controls : { up : "ArrowUp", left : "ArrowLeft", right : "ArrowRight", down : "ArrowDown", }, x : 100, y : 100, dx : 0, dy : 0, dir : 0, doMove(){ var k = this.controls; this.dy = 0; this.dx = 0; if(keys[k.up]){ this.dy = -2; this.dir = Math.PI * 1.5; } if(keys[k.down]){ this.dy = 2; this.dir = Math.PI * 0.5; } if(keys[k.left]){ this.dx = -2; this.dir = Math.PI * 1; } if(keys[k.right]){ this.dx = 2; this.dir = Math.PI * 0; } this.x = (this.x + canvas.width + this.dx) % canvas.width; this.y = (this.y + canvas.height + this.dy) % canvas.height; }, draw(){ var open = Math.abs(Math.sin(globalTime/200)); ctx.fillStyle = "yellow"; var x,y; x = Math.cos(this.dir) * -6; y = Math.sin(this.dir) * -6; ctx.beginPath(); ctx.moveTo(this.x + x,this.y + y); // move back of mouth away from circle center ctx.arc(this.x,this.y,20,open + this.dir, this.dir + Math.PI * 2 - open); ctx.fill(); } } const keys = {}; function keyEventHandler(event){ keys[event.code] = event.type === "keydown"; keys.firstKeyPressed = true; event.preventDefault(); } document.addEventListener("keydown",keyEventHandler); document.addEventListener("keyup",keyEventHandler); canvas.addEventListener("click",function(){keys.focus = true;}); /** SimpleUpdate.js begin **/ // short cut vars var w = canvas.width; var h = canvas.height; var cw = w / 2; // center var ch = h / 2; var globalTime; ctx.font = "16px arial"; ctx.textAlign = "center"; // main update function function update(timer){ globalTime = timer; ctx.setTransform(1,0,0,1,0,0); // reset transform ctx.globalAlpha = 1; // reset alpha ctx.fillStyle = "black"; ctx.fillRect(0,0,w,h); if(!keys.focus){ ctx.fillStyle = "Yellow"; ctx.fillText("Click to get focus.",256,16); }else if(!keys.firstKeyPressed ){ ctx.fillStyle = "Yellow"; ctx.fillText("Use arrow keys to move.",256,16); } player.doMove(); player.draw(); requestAnimationFrame(update); } requestAnimationFrame(update); 

One way to approach this would be to : 解决此问题的一种方法是:

  • have the state stored somewhere that records which arrow buttons has been pressed 将状态存储在某个位置,该状态记录了已按下的箭头按钮

  • update the position of PacMan depending on state 根据状态更新PacMan的位置

Store state change: 商店状态变更:

var direction = 'right';  // this is declared outside the function that alters it

window.addEventListener("keyup", changeState(event));

function changeState(event){
  switch (event.key) {
    case 37:
        direction = 'left';
        break;
    case 39:
        direction = 'right';
        break;
    case 38:
        direction = 'up';
        break;
    case 40:
        direction = 'down';
        break;
    default:
        alert("Invalid Key pressed");
        break;
  }
}

You can then have a function called by an interval that checks this stored button press value and then invokes the appropriate function to move your PacMan character: 然后,您可以有一个由间隔调用的函数,该函数检查此存储的按钮按下值,然后调用适当的函数来移动您的PacMan字符:

var intervalUpdateState = setInterval(movePacMan, 200);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM