-1
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)


public class Turtle extends Actor
{
    /**
     * Act - do whatever the Turtle wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    int laufmenge;

    public void act() 
    {



        if(Greenfoot.isKeyDown("left")){
            move(-speed);
        }

        if(Greenfoot.isKeyDown("right")){
            move(speed);
        }

        if(Greenfoot.isKeyDown("up")){
            setLocation(getX() ,getY() -speed);
        }

        if(Greenfoot.isKeyDown("down")){
            setLocation(getX() ,getY() +speed);
        }        

        if(Greenfoot.isKeyDown("x")){

         if(speed<10) speed++;
        }

        if(Greenfoot.isKeyDown("y")){

           if(speed>0) speed--;
        }

        System.out.println(speed);
    }    

    private int speed=1;
}

This is code from Greenfoot because i am currently trying to learn coding. I cant understand why when i execute the programm and control the speed he is changing the value by more than one. I guess it will be an easy question. And is it possible to put the increase and decrease of the speed on one button with two letters like the >< key? i didnt work in my case.

aydinugur
  • 1,208
  • 2
  • 14
  • 21
Schamph
  • 13
  • 3
  • Please, format the code properly. Also, under what circumstances your "speed" is changing by more then 1? Have you tried to debug your code yourself? – Sergei Sirik Sep 29 '17 at 22:20
  • yes i tried but greenfoot have not the best debugger.. there is not even one. He is only showing syntax errors. I checked the code with the System.out.println to show be the change of the value when i press x or y but it is changing with more than one then. Mostly 4 or 5 more. – Schamph Sep 29 '17 at 22:23
  • How many times is the ``act`` method executed? – f1sh Sep 29 '17 at 22:23

1 Answers1

2

This happens because act() is called in rapid succession. Even if you just press and release x, act() will have run several times while the key is down, and therefore updated the speed several times.

To avoid that, you can track whether or not you've adjusted the speed since the first time you noticed that the button was pressed.

For example, you can have a private bool adjustedSpeed = false; in your class, and then do:

    if(Greenfoot.isKeyDown("x")){

      if(speed<10 && !adjustedSpeed) speed++;
      adjustedSpeed = true;

    } else if(Greenfoot.isKeyDown("y")){

      if(speed>0 && !adjustedSpeed) speed--;
      adjustedSpeed = true;

    } else {

      adjustedSpeed = false

    }
that other guy
  • 116,971
  • 11
  • 170
  • 194