简体   繁体   中英

Moving a javascript character with the arrow keys

I'm writing an RPG game in javascript, and I want my main character to move when youi press the arrow keys or the wasd keys. I have code to generate him, but how should I define his postion so he moves when the aforementioned keys are pressed?

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

Use: http://help.dottoro.com/ljaffqqe.php

To capture when the keyup / keydown using the correct key code.

Then set mainchar.style.top to where ever you want it to be moved to...

eg

  1. Detect Key
  2. When correct key is pressed
  3. Updated mainchar.stlye.top

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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