使用箭头键移动javascript字符

Moving a javascript character with the arrow keys

本文关键字:移动 javascript 字符      更新时间:2023-09-26

我正在用javascript编写一个RPG游戏,我希望我的主角在按下箭头键或wasd键时移动。我有生成他的代码,但我应该如何定义他的位置,以便他在按下上述键时移动?

function mainchar(){
    var mainchar = new Image();
    mainchar.src = /*I'll add this soon*/;
    mainchar.style.top = /*What should I put here?*/;
    mainchar.style.left = /*What should I put here?*/;
    mainchar.style.position = "absolute";
    document.body.appendChild( mainchar );
}

使用:http://help.dottoro.com/ljaffqqe.php

使用正确的按键代码捕捉按键向上/向下。

然后将mainchar.style.top设置为您希望将其移动到的位置…

例如

  1. 检测密钥
  2. 按下正确的键时
  3. 更新了mainchar.stlye.top