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

2015/11/17

How to run the method every other time

XxCelosiaxX XxCelosiaxX

2015/11/17

#
Hello I'm new at green foot and need some help I want to code it so that a sound is play every other click. How would I do that? here is what I have so far. I think you should set a variable to hold a count so when the sound play time will be 1. I'm just kind of confuse.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void sound()
    {
       MouseInfo mouse = Greenfoot.getMouseInfo();
       GreenfootSound gfs1 = new GreenfootSound("Beep.wav");
       int time = 0;
       if (Greenfoot.mouseClicked(this))
        {
            if (mouse.getButton() == 1)    // Left mouse pressed?
            {
                gfs1.play();
                time = time + 1;
            }
        }
    }
ElNo ElNo

2015/11/17

#
Hi, you have the right idea using a variable to hold record of your clicks. But to keep your value of time even after the sound-method is finished, you have to declare it as an attribute / instance-variable. (I would declare the gfs1 as an attribute too.) Then you have to check if your timer is 0 (= play sound) or not (= don't play sound). And you have to increase or decrease your timer so it will switch between the values 0 and 1. (Instead of a integer you could also use a boolean if your timer only switchen between two values.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private GreenfootSound gfs1 = new GreenfootSound("Beep.wav");
private int time = 0;
 
public void act()
{
    sound();
}
 
public void sound()
    {
       MouseInfo mouse = Greenfoot.getMouseInfo();
       if (Greenfoot.mouseClicked(this))
        {
            if (mouse.getButton() == 1)    // Left mouse pressed?
            {
                if(time == 0)
                {
                    gfs1.play();
                    time = time + 1;
                }
                else
                {
                    time = time - 1;
                }
            }
        }
    }
XxCelosiaxX XxCelosiaxX

2015/11/17

#
Thank you very much!
You need to login to post a reply.