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

2014/1/21

Play random sounds when hit an object.

sanjo94 sanjo94

2014/1/21

#
Hello people i have 3 soundeffects. if an object hits an other object it must play 1 of the 3 sounds randomly. thanks
danpost danpost

2014/1/21

#
Use a random number with either a switch statement, or a compound if-else statement, or an array for the sound file names as String objects or for the GreenfootSound objects.
sanjo94 sanjo94

2014/1/21

#
Thankyou danpost. i tried with this and it works:
1
2
3
4
5
6
7
8
9
10
11
12
  if( object != null)
{  
int rand = Greenfoot.getRandomNumber(2);
       if(rand == 0)
            {
                Greenfoot.playSound("gered.wav");
            }
            else if(rand == 1)
            {
                Greenfoot.playSound("gered1.wav");
            }
}
deathburrito16 deathburrito16

2014/1/21

#
the variable rand isn't really necessary, you know.
sanjo94 sanjo94

2014/1/22

#
Hi, I did not knew that actually. Can you show me how to do it without using the variable rand. Thankyou
danpost danpost

2014/1/22

#
sanjo94 wrote...
Can you show me how to do it without using the variable rand.
1
2
3
4
5
6
7
8
9
10
11
if (object != null)
{  
    if (Greenfoot.getRandomNumber(2) == 0)
    {
        Greenfoot.playSound("gered.wav");
    }
    else
    {
        Greenfoot.playSound("gered1.wav");
     }
}
With only two possibilities, if not the one, then the other (no need for the 'if' after the 'else'). Even with more than two possible sounds, you can avoid the 'rand' variable:
1
2
3
4
5
6
7
8
9
if (obect != null)
{
    switch(Greenfoot.getRandomNumber(3))
    {
        case 0:  Greenfoot.playSound("gered.wav"); break;
        case 1:  Greenfoot.playSound("gered1.wav"); break;
        case 2:  Greenfoot.playSound("gered2.wav"); break;
    }
}
sanjo94 sanjo94

2014/1/22

#
Thankyou for you reply. Because of u i know more about those methodes.
RyanOseris RyanOseris

2015/7/16

#
I tried putting this in but its says for object no symbol
danpost danpost

2015/7/16

#
@RyanOseris, please do not revive old discussion threads. Rather, start a new one. At any rate 'object' was assigned a value prior to the code given -- probably by way of using the 'getOneIntersectingObject' method:
1
Actor object = getOneIntersectingObject(<< class name >>);
You need to login to post a reply.