Greenfoot - isKeyDown() 似乎保持其价值

Greenfoot - isKeyDown() seems to hold its value

这是一个游戏的冲刺功能,如果玩家剩余的电量大于0% spring那么他可以冲刺,如果是0%则玩家不能冲刺。如果玩家没有冲刺,那么冲刺百分比将开始恢复。

问题: 当玩家达到 0% 冲刺时,玩家仍然可以冲刺。

public class User extends Characters
{
    private int walk = 3;
    private int run = 10;
    private int speed = walk;

    private boolean isRunning = false;
    private int runDuration = 100;
    private int baseRunDuration = 100;
    private int runCoolDown = 300;


    public void act() 
    {
        playerMove();
    }

    //Contains movement inputs as well as run imputs
    void playerMove(){
        getWorld().showText("Run Duration: " + runDuration, 100, 100);

         if(Greenfoot.isKeyDown("w") ){
            setLocation(getX(), getY()-speed);
        }
        if(Greenfoot.isKeyDown("a")){
            move(-speed);
        }
        if(Greenfoot.isKeyDown("s")){
            setLocation(getX(), getY()+speed);
        }
        if(Greenfoot.isKeyDown("d")){
            move(+speed);
        }

        if(Greenfoot.isKeyDown("shift") && runDuration > 0){

            if(runDuration > 0){
                isRunning = true;
                speed = run;
                runDuration--;


            }
        }
       else{
                speed = walk;
                isRunning = false;
        }

        if(isRunning == false){
            if(runDuration < baseRunDuration){
                runDuration++;
            }
        }
    }
}

Obicere 是正确的,您要么在冲刺,要么在冲刺和不冲刺之间交替进行,即半速冲刺。有多种方法可以解决此问题。我建议您只在不动时为冲刺充电。您可以使用布尔值来跟踪您是否移动了此帧,或者只需使用 else-if 将中间代码块更改为:

    if(Greenfoot.isKeyDown("w") ){
        setLocation(getX(), getY()-speed);
    }
    else if(Greenfoot.isKeyDown("a")){
        move(-speed);
    }
    else if(Greenfoot.isKeyDown("s")){
        setLocation(getX(), getY()+speed);
    }
    else if(Greenfoot.isKeyDown("d")){
        move(+speed);
    }
    else if(runDuration < baseRunDuration){
         runDuration++;
    }

注意新的 else,以及从代码底部向上移动的最后一个子句。