只有当按下左键时,玩家才会向左移动并且不会停止

Posted

技术标签:

【中文标题】只有当按下左键时,玩家才会向左移动并且不会停止【英文标题】:Only when the left button is pressed, the player moves left and does not stop 【发布时间】:2014-02-18 13:11:36 【问题描述】:

这是我的游戏的代码。我使用 Flash Develop 来编写代码是因为我发现 Flash Develop 更容易。

当我按右、上和下键时,我的播放器会根据指示移动。但是当按下左箭头键时,玩家会向左移动并且不会停止。

    package  

import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
/**
 * ...
 * @author Moynul Hussain
 */
public class main extends MovieClip

    //MainMenu

    //background
    public var back:MovieClip;

    public var leftPressed:Boolean = false;
    public var rightPressed:Boolean = false;
    public var upPressed:Boolean = false;
    public var downPressed:Boolean = false;

    public var xScrollSpeed:int = 10;
    public var yScrollSpeed:int = 10;



    public var mcPlayButton:MovieClip;

    public function main() 
    


    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
    stage.addEventListener(Event.ENTER_FRAME, loop);


    

    private function loop(e:Event):void 
    
        if (leftPressed)
        
            back.x += xScrollSpeed;
         
        else if (rightPressed)
        
            back.x -= xScrollSpeed;
        

        if (upPressed) 
           
        back.y += yScrollSpeed;

         
        else if (downPressed)
        
            back.y -= yScrollSpeed;
           
    



    function keyDownHandler(e:KeyboardEvent):void
        if (e.keyCode == 37)
        
        trace("left pressed");
        leftPressed = true;

         
        else if (e.keyCode == 39 )
        
        trace("right pressed");
        rightPressed = true;

         else if(e.keyCode == 38)
        trace("up pressed");
        upPressed = true;

         else if(e.keyCode == 40)
        trace("down pressed");
        downPressed = true;
        
        

    function keyUpHandler(e:KeyboardEvent):void
        if(e.keyCode == 37)
        trace("left released");
        upPressed = false;

         else if(e.keyCode == 39)
        trace("right released");
        rightPressed = false;

         else if(e.keyCode == 38)
        trace("up released");
        upPressed = false;

         else if(e.keyCode ==40)
        trace("down released");
        downPressed = false;
        
        


   

 

如果我的代码激怒了任何人,我非​​常抱歉,我从 Flash Develop 复制并粘贴到这里。

【问题讨论】:

【参考方案1】:

看起来你已经设置好了释放向上键:

if(e.keyCode == 37)
trace("left released");  // left
upPressed = false;       // up

【讨论】:

以上是关于只有当按下左键时,玩家才会向左移动并且不会停止的主要内容,如果未能解决你的问题,请参考以下文章

我的角色怎么能向左箭头键或右键的方向跳跃?

在使用 NVDA 等屏幕阅读器时,如何按向左或向右键?

PyAutoGUI 鼠标键盘方法记录

鼠标事件 滚轮事件

当我在 tkinter 游戏中按下一个键时,敌人会停止

Tkinter 按钮仅在单击左键时才会下沉