2013-05-31 3 views
0

Я пытаюсь создать платформу, и у меня есть работа, прыжок и двойной прыжок. Теперь моя проблема в том, что я хочу, чтобы игрок нажал кнопку перехода, а герой прыгнул только один раз, а не постоянно прыгал. Если я удерживаю кнопку «вверх», он будет продолжать прыгать, чего я не хочу, я просто хочу, чтобы он выполнял прыжок один раз, даже если ключ все еще удерживается. Я хочу то же самое для двойного прыжка, как я могу это сделать.AS3: только одно нажатие клавиши

package 
{ 
    import flash.display.MovieClip; 
    import flash.events.Event; 
    import flash.events.KeyboardEvent; 
    import flash.ui.Keyboard; 

    public class Player extends MovieClip 
    { 
     //Player run speed setting 
     var RunSpeed:Number = 8; 
     //Player key presses 
     var RightKeyPress:Boolean = false; 
     var LeftKeyPress:Boolean = false; 
     var UpKeyPress:Boolean = false; 
     //Jump variables 
     var Gravity:Number = 1.5; 
     var JumpPower:Number = 0; 
     var CanJump:Boolean = false; 
     var DoubleJump:Boolean = false; 

     public function Player() 
     { 
      // constructor code 
      stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyPressed); 
      addEventListener(Event.ENTER_FRAME,Update); 
      stage.addEventListener(KeyboardEvent.KEY_UP,KeyReleased); 
     } 

     function KeyPressed(event:KeyboardEvent) 
     { 
      //When Key is Down 
      if (event.keyCode == 39) 
      { 
       RightKeyPress = true; 
      } 

      if (event.keyCode == 37) 
      { 
       LeftKeyPress = true; 
      } 

      if (event.keyCode == 38) 
      { 
       UpKeyPress = true 

      } 
     } 

     function Update(event:Event) 
     { 
      //Adding gravity to the game world 
      JumpPower += Gravity; 
      //if player is more than 300 on the y-axis 
      if (this.y > 300) 
      { 
       //Player stays on the ground and can jump 
       JumpPower = 0; 
       CanJump = true; 
       DoubleJump = false; 
      } 

      //If player is on floor and right key is pressed then run right 
      if ((RightKeyPress && CanJump)) 
      { 
       x += RunSpeed; 
       gotoAndStop('Run'); 
       scaleX = 1; 
      } 
      else if ((LeftKeyPress && CanJump)) 
      { 
       //Otherwise if on floor and left key is pressed run left 
       x -= RunSpeed; 
       gotoAndStop('Run'); 
       scaleX = -1; 
      } 
      else if ((UpKeyPress && CanJump)) 
      { 
       //Otherwise if on floor and up key is pressed then jump 
       JumpPower = -15; 
       CanJump = false; 
       gotoAndStop('Jump'); 
       DoubleJump = true; 
      } 

      //If on floor and right and up key are pressed then jump 
      if ((RightKeyPress && UpKeyPress && CanJump)) 
      { 
       JumpPower = -15; 
       CanJump = false; 
       gotoAndStop('Jump'); 
       DoubleJump = true; 
      } 

      //If on floor and left and up key are pressed then jump 
      if ((LeftKeyPress && UpKeyPress && CanJump)) 
      { 
       JumpPower = -15; 
       CanJump = false; 
       gotoAndStop('Jump'); 
       DoubleJump = true; 
      } 

      //If jumped and right key is pressed then move right 
      if ((RightKeyPress && CanJump == false)) 
      { 
       x += RunSpeed; 
       scaleX = 1; 
      } 
      else if ((LeftKeyPress && CanJump == false)) 
      { 
       //Otherwise if jumped and left key is pressed then move left 
       x -= RunSpeed; 
       scaleX = -1; 
      } 

      //If in air and able to doublejump and pressed up key, then double jump 
      if (UpKeyPress && DoubleJump && JumpPower > -2) 
      { 
       JumpPower = -13; 
       DoubleJump = false; 
       gotoAndStop('DoubleJump'); 
      } 

      //If on floor and no key is presses stay idle 
      if ((!RightKeyPress && !LeftKeyPress && CanJump)) 
      { 
       gotoAndStop('Idle'); 
      } 

      this.y += JumpPower; 
     } 

     function KeyReleased(event:KeyboardEvent) 
     { 
      if (event.keyCode == 39) 
      { 
       event.keyCode = 0; 
       RightKeyPress = false; 
      } 

      if (event.keyCode == 37) 
      { 
       event.keyCode = 0; 
       LeftKeyPress = false; 
      } 

      if (event.keyCode == 38) 
      { 
       event.keyCode = 0; 
       UpKeyPress = false; 
      } 
     } 
    } 
} 
+0

Вы пробовали поставить точку перерыва, где происходит двойной прыжок? Мне кажется, что логика с логическим состоянием должна работать корректно, но вы по какой-то причине должны быть в этом блоке неоднократно? Попробуйте отслеживать логические значения в ключевых точках функции «Обновить». – shaunhusain

+0

@shaunhusain: точка останова? Я новичок в AS3, поэтому пока не знаю многого, но я быстро учусь. – user2350724

+0

Нет проблем, проверьте эту ссылку http://www.adobe.com/devnet/flash/articles/flash_as3_debugging.html или просто пойдите в Google немного, кажется, вторая половина этой статьи может быть полезна, но она длинная. – shaunhusain

ответ

2

Я подозреваю, что то, что происходит в том, что, как только значение у вашего игрока удовлетворяет условию if (this.y > 300) вы дающую ему снова прыгать, так до тех пор, пока ключ удерживается он прыгает, потому что UpKeyPress && CanJump оба истинны ,

Я думаю, что делает что-то вроде следующего могли бы получить ближе лет ваш ответ ...

В функции Update:

function Update(event:Event) 
{ 
    //Adding gravity to the game world 
    JumpPower += Gravity; 
    //if player is more than 300 on the y-axis 
    if (this.y > 300) 
    { 
     //Player stays on the ground and can jump 
     JumpPower = 0; 
     // Do not allow another jump until the UpKey is pressed 
     //CanJump = true; 
     //DoubleJump = false; 
    } 
    ... 

Затем в Keypressed функции:

function KeyPressed(event:KeyboardEvent) 
{ 
    //When Key is Down 
    if (event.keyCode == 39) 
    { 
     RightKeyPress = true; 
    } 

    if (event.keyCode == 37) 
    { 
     LeftKeyPress = true; 
    } 

    if (event.keyCode == 38) 
    { 
     UpKeyPress = true 
     // Do not allow another jump until the UpKey is pressed 
     if (this.y > 300) 
     { 
      CanJump = true; 
      DoubleJump = false; 
     } 
    } 
} 

Я также предлагаю вторую рекомендацию shaunhusain установить точки останова и получить удобство с кодом отладки.

+3

Для дальнейшего использования есть класс клавиатуры, который перечисляет некоторые из ключей, поэтому вы можете заменить 38 Keyboard.UP. – Rich

Смежные вопросы