CocosCreator

 onLoad: function () {
  

       cc.eventManager.addListener({

键盘事件类型

            event: cc.EventListener.KEYBOARD,
             
            onKeyPressed: this.onKeyPressed.bind(this), bind方法会创建一个新函数,称为绑定函数.
            onKeyReleased: this.onKeyReleased.bind(this)
        }, this.node);
    },


    

    onKeyPressed: function (keyCode, event) {
        switch (keyCode) {
            case cc.KEY.d:
                this.direction = 1;
                if (!this.jumping) this.player.play("run");    
                break;
            case cc.KEY.a:
                this.direction = -1;
                if (!this.jumping) this.player.play("run");   
                break;
            case cc.KEY.j:
                if (!this.jumping || this.jumpCount < 30) {
                    this.jumping = true;
                    this.speed.y = this.jumpSpeed;
                    this.jumpCount++;
                    this.jumpCount < 2 ? this.player.play("jump") : this.player.play("twiceJump");
                }
                break;
        }
    },

    onKeyReleased: function (keyCode, event) {
         switch (keyCode) {
            case cc.KEY.d:
                if (this.direction == 1) {
                    this.direction = 0;
                }
                break;
            case cc.KEY.a:
                if (this.direction == -1) {
                    this.direction = 0;
                }
                break;
         }
    },

猜你喜欢

转载自blog.csdn.net/qq_41939248/article/details/80410800