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

yesterday

Stopping a walking soundloop upon death

Sendaris8 Sendaris8

yesterday

#
I have the following code for a character controlled by the user so that when he is walking the "dirt_walking" sound plays in a loop and stops when he stops walking. However, when the character gets eaten by a wolf or bear while walking, the walking sound continues in the loop. I've been struggling to have it stop upon the character's death for several days, so if anyone has a suggestion, feel free to share. Thanks.
GreenfootSound walkSound = new GreenfootSound("dirt_walking.mp3");
    public void move()
    {
        if (isTouching(Bear.class) || isTouching(Wolf.class))
        {
            walkSound.stop();
            return;
        }
        String[] keys = {"down", "up", "right", "left"};
        int[][] deltas = {{0, 2}, {0, -2}, {2, 0}, {-2, 0}};
        String[] images = {null, null, "Guy.png", "Guy.mirror.png"};

        boolean isMoving = false;

        for (int i = 0; i < keys.length; i++) {
            if (Greenfoot.isKeyDown(keys[i])) {
                int dx = deltas[i][0];
                int dy = deltas[i][1];

                if (images[i] != null) {
                    setImage(images[i]);
                }

                setLocation(getX() + dx, getY() + dy);
                if (hitObjects()) {
                    setLocation(getX() - dx, getY() - dy); //action-reaction
                }

                isMoving = true;
            }
        }
        if (isMoving)
        {
            if (!walkSound.isPlaying())
            {
                walkSound.playLoop();
            }
        }
        else
        {
            walkSound.stop(); 
        }
    }  
Super_Hippo Super_Hippo

yesterday

#
I guess the issue is that the wolf/bear removes the character from the world, so its act method of the character isn’t executed anymore. Try to stop the sound right before removing the object.
danpost danpost

yesterday

#
As a continuation of the post made by Super_Hippo, best may be to add a simple method to the Guy class for when it dies. Call this new method from wolf/bear classes to "kill" him:
public void die() {
    walkSound.stop();
    getWorld().removeObject(this);
}
Sendaris8 Sendaris8

yesterday

#
I've already tried it making a seperate 'die' method, as well as a seperate boolean and stopping the sound before the actor gets removed, but the loop always continues. What do you mean by 'call this new method from wolf/bear classes'?
danpost danpost

22 hours ago

#
Sendaris8 wrote...
What do you mean by 'call this new method from wolf/bear classes'?
I mean add the "new method" above, die(), to your Guy class. Then you can use something like the following in the Bear and Wolf classes:
Guy guy = (Guy)getOneIntersectingObject(Guy.class);
if (guy != null) guy.die();
You need to login to post a reply.