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

2015/11/16

How to set a random "time" when an sprite is clicked

axxv axxv

2015/11/16

#
I couldn't word it in the title properly but I need help for making an actor stay at frame for a random amount of time when clicked. Whenever I use Greenfoot.delay(), it delays my whole scenario but I just want that specific actor to say in a frame for a random amount of time. What can I use instead of the Greenfoot.delay()?
public void mouseClick()
    {
        if(Greenfoot.mouseClicked(this))
        {
           setImage("wake.png");
           GreenfootImage image = getImage();
           image.scale(image.getWidth() + 100, image.getHeight() + 100);
           Greenfoot.delay(Greenfoot.getRandomNumber(50));
        }
    }
ElNo ElNo

2015/11/16

#
Hi, you could give this actor an attribute wait (Integer) and initialize it with 0. When there is a mouseClick you set it to the number of round yout actor should wait. In yout act-method you include an if-statement which will contain everything that is in your act-method right now (or that part that should not be executed while it is supposed to wait):
if (wait == 0)
{
    // your code in te act-method that should be delayed
}
else
{
   wait--;
}
This way your actor will have to wait until its wait-counter is back to 0 after the specified number of "run-rounds" .
danpost danpost

2015/11/16

#
axxv wrote...
What can I use instead of Greenfoot.delay()?
You can use an instance field of int type as a timer. Set its to a random value when the object is clicked and the image is changed. Add a method to run the timer (decrease its value if greater than zero) and reset the image when it is exhausted (the value becomes zero). Code it so that it only reset the image on the act cycle that the timer goes from one to zero -- do not have the image repeatedly set to the actor cycle after cycle. Call the method from the 'act' method.
axxv axxv

2015/11/18

#
thank you so much for the help!!!
You need to login to post a reply.