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

2017/9/20

Help with counter variable

lucytorres12 lucytorres12

2017/9/20

#
Hi, i'm a mexican high school programation student so i apologize for any grammar errors that might occur. For my first greenfoot project i'm making a little game. When an enemy touches the hero, one unit is subtracted from a counter variable. When the variable value is 0 then the game stops. Well, that's what me and my classmate wanted to do, but we can't manage to make it work. When the hero is touched by an enemy the game stops automatically. Can anyone help us? we don't know what's wrong.
public class Eleven extends Actor
{
    int deathcount=3;
    /**
     * Act - do whatever the Eleven wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        followMouse();
        regenerate();
        death();
    }    
    private void followMouse()
    {
        MouseInfo mi = Greenfoot.getMouseInfo();
        if (mi != null) setLocation(mi.getX(), mi.getY());
    }
    public void regenerate()
    {
        if (isTouching(Villain1.class)){
            deathcount-=1;
            setLocation(400,400);
        }
    }
    public void death()
    {
        if (deathcount == 0){
            Greenfoot.stop();
        }
    }
}
danpost danpost

2017/9/20

#
Since the villain remains touching the hero for multiple act cycles, the 'deathcount' will drop to zero (from 3) in about 0.05 seconds. You will have to keep track of the state that the hero is touching a villain (so that you can place another condition on dropping the value of 'deathcount' . It can be a boolean value or a reference to the villain that is currently touching the hero. If you have multiple villains, a reference field is preferable.
You need to login to post a reply.