0

This is a sprinting function for a game, if the player has greater then 0% spring left then he can sprint, if it is at 0% the player cannot sprint. If the player is not sprinting then the sprint % will start to regenerate.

The problem: When the player hits 0% sprint the player is still able to sprint.

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++;
            }
        }
    }
}
Max Mcgregor
  • 101
  • 9
  • 1
    The only thing I can think of is that the last condition, that increments the `runDuration` is being called. And the very next tick, it continues to sprint. So what you get is a sprint, walk, sprint, walk, ..., sort of cycle. – Obicere Apr 30 '17 at 01:55

1 Answers1

1

Obicere is right that you are either sprinting, or you're alternately sprinting and not sprinting, giving a half-speed sprint. There's various ways to fix this. I'd suggest only recharging your sprint when you're not moving. You can do this using a boolean to keep track of whether you've moved this frame, or simply by using else-if to change your middle block of code to:

    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++;
    }

Note the new elses, and the final clause on the end which is moved up from the bottom of your code.

Neil Brown
  • 3,558
  • 1
  • 27
  • 36