javascript 如何在W A S D上进行字符控制?

tquggr8v  于 2023-11-15  发布在  Java
关注(0)|答案(1)|浏览(89)

我做了鼠标控制,但是,当我使用onkeydown而不是onmousedown时,角色移动了几毫秒然后停止,当按钮被释放时,角色进入空闲动画。我如何修复它?
这是我向左和向右移动的代码:

const rightHandler = () => {
heroImg.style.transform = "scale(1,1)";
direction = "right";
spritePosition = spritePosition + 1;
imgBlockPosition = imgBlockPosition + 1;
if (spritePosition > 7) {
    spritePosition = 0;
}
heroImg.style.left = `-${spritePosition * 64}px`;
heroImg.style.top = '-64px';
imgBlock.style.left = `${imgBlockPosition * 7}px`;
}

const leftHandler = () => {
heroImg.style.transform = "scale(-1,1)";
direction = "left";
spritePosition = spritePosition - 1;
imgBlockPosition = imgBlockPosition - 1;
if (spritePosition < 7) {
    spritePosition = 13;
}
heroImg.style.left = `-${spritePosition * 64}px`;
heroImg.style.top = '-64px';
imgBlock.style.left = `${imgBlockPosition * 7}px`;
}

字符串
这是onmousedown和onmouseup的代码:

let onMouseDown = (event) => {
clearInterval(timer);
x = event.screenX;
timer = setInterval(() => {
    if (x > halfWidth) {
        direction = "right";
        rightHandler();
    }
    else {
        direction = "left";
        leftHandler();
    }
}, 100);
}

let onMouseUp = (event) => {
clearInterval(timer);
idleAnimation();
}


但是当我使用这个代码时:

let onKeyDown = (event) => {
clearInterval(timer);
var keyCode = event.keyCode;
timer = setInterval(() => {
    if (keyCode == 39) {
        direction = "right";
        rightHandler();
    }
    else if (keyCode == 37) {
        direction = "left";
        leftHandler();
    }
}, 100);
}

let onKeyUp = () => {
clearInterval(timer);
idleAnimation();
}


我的角色在几秒钟后停止移动。我需要改变什么?

mm5n2pyu

mm5n2pyu1#

如果你按住这个键,onpress会不断地触发,清除间隔然后设置间隔,在运行之前清除间隔,设置一个新的间隔,等等。
如果一个键被按下,使用布尔值来跟踪。如果它被按下,调用另一个递归调用它自己的方法。
另外,如果你想做动画,不要使用setInterval,因为在每次屏幕更新之间可能会发生几次计算,这会导致不稳定的动画,而应该使用requestAnimationFrame
下面是一个例子,它可以看起来像什么:

var keyPressed = -1;

const DIRECTIONS = {
  39: {direction: 1, name: "rightArrow"},
  37: {direction: -1, name: "leftArrow"}
}

let onKeyDown = (event) => {
  if (keyPressed == event.keyCode) { return }
  
  let keyCode = event.keyCode;
  
  if (DIRECTIONS[keyCode]) {
    move(DIRECTIONS[keyCode], keyCode);
  }
}

const move = (direction, keyCode) => {
  console.log(direction);
  
  if (keyCode == keyPressed) {
    requestAnimationFrame(() => move(direction, keycode));
  }
}

let onKeyUp = (event) => {
  keyPressed = -1;
}

document.addEventListener('keydown', onKeyDown);
document.addEventListener('keyup', onKeyUp);

个字符

相关问题