Schamph Schamph - 3 years ago 118
Java Question

Why is it adding more than 1 to my speed control?

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()



setLocation(getX() ,getY() -speed);

setLocation(getX() ,getY() +speed);


if(speed<10) speed++;


if(speed>0) 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.

Answer Source

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(speed<10 && !adjustedSpeed) speed++;
      adjustedSpeed = true;

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

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

    } else {

      adjustedSpeed = false

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download