This site requires JavaScript, please enable it in your browser!
Greenfoot back
Recorsi
Recorsi wrote ...

2017/9/20

how can i make an actor get slower and eventually stop?

Recorsi Recorsi

2017/9/20

#
Hi community, i made a spaceship that moves like that:
private void Bewegen()
   {
    

      if (Greenfoot.isKeyDown("a"))
       {
            turn(-4);
       } 
      if (Greenfoot.isKeyDown("d"))
       {
            turn(4);
       }
      if (Greenfoot.isKeyDown("w"))
       {
            move(-5);
       } 
}
but if i stop pressing "W" it comes instantly to a stop. how can i make it to get slower after releasing the button? right now it looks unnatural. thanks
danpost danpost

2017/9/20

#
First, you must make '5' (see line 15) a variable amount and 'w' should control the increasing value of that variable. Moving will be controlled by the value of the variable instead of by the state of any key. To make '5' a variable, give it a name ('speed' should suffice). The variable must be declared somewhere outside the method so that it exists for as long as the spaceship does:
private int speed = 0;
Line 13 through 16 can then be replaced with:
if (Greenfoot.isKeyDown("w"))
{
    speed++;
    /** optional follow-up (using a limit field */
    if (speed > limit) speed = limit;
}
move(-speed);
You now need an 'else' part to this 'if' block so that 'speed' can be decreased:
else if (speed > 0) speed--;
to slow down. You will find that the acceleration and deceleration of the spaceship will happen very quickly. To slow it down some, you can increase the limit and move a fraction of the value of 'speed':
move(-speed/20); // for example
You will also find that at lower speeds, the spaceship will tend to move in one of the four ordinal directions (up, down, left or right). This is because the spaceship is limited to where pixels are on the screen. Tracking the x and y coordinates of the spaceship more precisely it what is required to fix this. Everything involved here is what the SmoothMover class provides to an actor. You can import the class and have the class of the spaceship extend it. The lines of code above will need adjustment to accommodate the addition of the class.
Recorsi Recorsi

2017/9/21

#
Oh, sorry i didnt tell you but i already have smoothmover. i didnt know it would make a difference. What do i have to change in order to make it work with smoothmover? right now it says "cannot find symbol - variable limit"
danpost danpost

2017/9/21

#
I added that line as pseudo-code. But, if you do want to limit the speed, a constant double field with a more appropriate name, maybe MAX_SPEED, could be used:
private static final int MAX_SPEED = 10; // for example
Then, just replace 'limit' with 'MAX_SPEED'. Or, just replace 'limit' with the appropriate value ('10', as for in the example).
Recorsi Recorsi

2017/9/23

#
Thanks :)
You need to login to post a reply.