0

您可以分配 A 键以在我的 Flash 游戏中移动我的角色,如果可以的话怎么做?

     playerOne.y = mouseY;
}

function movePlayerTwo(evt:KeyboardEvent):void {
    if(evt.keyCode == Keyboard.UP) { playerTwo.y = playerTwo.y - 20; }
    if(evt.keyCode == Keyboard.DOWN) { playerTwo.y = playerTwo.y + 20; }
}
4

2 回答 2

0

On a listener

stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);

and

stage.addEventListener(KeyboardEvent.KEY_UP, onUp);

you simply listen if ANY key is pressed. In the handlers onDown() and onUp() you need to check witch key was actually pressed. Usually it's done with a switch to keep the code tidy. Here's an example:

private function onDown(e:Event):void
{
   switch(e.keyCode)
   {
      case 65: // this is the keycode for key "a"
      keyAPressed = true;
      break;
   }
}

For movement it's a good idea to make a few variables, like

private var isMoving:Boolean = false;
private var leftPressed:Boolean = false;
private var rightPressed:Boolean = false;
private var goingLeft:Boolean = false;

with this you can have better controls with a loop like this:

private function movementLoop():void
{
   if (! isMoving)
   return; // if the char's not moving it's safe to return the function
   if (goingLeft)
   x -= movementSpeed;
   else
   x += movementSpeed;
}

You can use this site to check the keyCodes for every button: http://www.kirupa.com/developer/as3/using_keyboard_as3.htm

As you can see from this example the movement are handled on a loop that can be called by a timer or ENTER_FRAME event, not from the press of a button. It's important for many reasons, few of them are:

  • You're not spamming the movement command by holding the key down.
  • Your keyboard handler is smaller and cleaner to read and extend with new implementation
  • You can make a NPC move with same methods by modifying the isMoving and direction variables
  • Same as above goes to sending this data to server in multiplayer games
  • If you press both left and right, the variables can switch direction of the movement, not try to move the player both left and right.

Hope I could answer your question.

Good luck!

于 2013-08-13T06:30:40.743 回答
0

密钥的 ASCII 值为A65:

if(evt.keyCode === 65)
{
    // Do movement.
}

你可以在这里查找其他一些。

于 2013-08-12T23:02:26.467 回答