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

2017/10/8

Help with intersecting objects

xusui xusui

2017/10/8

#
Basically, I want it so when the class, "Body", intersects an object, to play a specific sound (each obstacle has a different sound)
private String sound; 
    private static boolean hit;
    public Obstacle(String soundName)
    {
        sound = soundName;
    }

    public void act() 
    {
        intersect();
    }    

    public void intersect() {
        Object body = getOneIntersectingObject(Body.class);
        if (body != null && !hit) {
            hit = true;
            setImage("block-light.png");
            Greenfoot.playSound(sound);
        } else if(body == null) {
            setImage("block.png");
            hit = false;
        }
    } 
Whenever the "Body" class intersects an obstacle, it loops the sound until the Body is NOT touching the obstacle. How do I fix this?
danpost danpost

2017/10/8

#
Instead of saving the String filename of the sound, save a GreenfootSound object for better control. Change line 1 to this:
GreenfootSound sound;
and change the constructor (lines 3 through 6) to this:
public Obstacle(String soundName)
{
    sound = new GreenfootSound(soundName);
}
Now you can change line 18 to this:
sound.play();
Each time you execute the 'Greenfoot.playSound' method, a new GreenfootSound object is created to be played -- and you have no control over that object. With the change above, only one GreenfootSound object is ever created, so (a) if it is not playing, it will start; and (b) if it is already playing, it will just continue to play until it is done. Also, you have full control over that GreenfootSound object.
xusui xusui

2017/10/8

#
Thank you, danpost. This helped a ton!
You need to login to post a reply.