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

2013/1/18

Repeating missile shot, delayed.

Mindlezs Mindlezs

2013/1/18

#
I want to the missile to be added to the world every 2000 milliseconds. I wrote this to do it:
if(Greenfoot.isKeyDown("space"))
        {
            if(shoot)
            {
                world.addObject(missile,getX()+25,getY());
                delay = timer+1000;
                shoot = false;
            }
        }
        if(delay <= timer)
        {
            shoot = true;
        }
I know its already simple, but is there a way to simplify it further?
Mindlezs Mindlezs

2013/1/18

#
shoot is obviously a boolean set to true from start. timer is set to the currenttimemillis
danpost danpost

2013/1/18

#
In this case, I believe it would be better to use game time instead of real time for the delay between shots. The coding is also fairly straight-forward. Where you are using two 'int's and one 'boolean' for real-time coding, it only uses one 'int' for game-time coding.
// instance int field
private int timer=0;
// in act method or a method it calls
if(timer>0)timer--;
if(timer==0 && Greenfoot.isKeyDown("space"))
{
    getWorld().addObject(new Missle(), getX()+25, getY());
    timer=120; // about two seconds
}
Notice in line 7, we are creating a new missle about every 2 seconds (as long as the 'space' key is pressed).
Mindlezs Mindlezs

2013/1/18

#
That 120 being abou two seconds is depending on the act speed, right? Thats not an issue, I'm just curious since I'm weighing which of the two counters i should use.
danpost danpost

2013/1/18

#
That is correct. However, no matter the speed that the scenario is set, if you get the delay to a suitable value, then changing the speed of the scenario should not alter the suitability of the rate because we would be using game-time.
Mindlezs Mindlezs

2013/1/18

#
Great, i get it. Thanks :D
You need to login to post a reply.