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

2013/6/28

isDead boolean

davemib123 davemib123

2013/6/28

#
Hi, i'm setting up a dead method for my hero. I have this before the constructor:
private boolean isDead;
This in the constructor:
isDead = false;
The act method:
public void act() 
    {
        
        if (isDead = false){
            checkKeys();
        boundary();
            if(!checkGround())    
            {    
                fall(); 
            }   
            else  
            {  
                isJumping = false;  
            }  
        }
        else if (isDead = true){
            
            dead();
        }
    }
The dead method:
    public void dead()
    {
        isDead = true;
        Levels L = (Levels)getWorld();
        Counter lifeCounter = L.getLifeCounter();

        if (lifeCounter.getValue() <= 0)
        {
            getWorld().addObject(new Dead(), getX(),getY());
            getWorld().removeObject(this);
        }
    }
Problem is when I compile, Mario has the dead value set to true. How do I change it to false? I thought setting it with the constructor would do it? The sourcecode is available here: http://www.greenfoot.org/scenarios/8881
danpost danpost

2013/6/28

#
Looks like your main problem is with your equality operator, which should be two equal signs (not one). Your 'if' statements should be like the following:
if (isDead == true)
// or just
if (isDead) // since it holds a boolean value
By using only one equal sign, you are actually setting 'isDead' to true in:
if (isDead = true)
and then because it is true it calls the 'dead' method.
davemib123 davemib123

2013/6/28

#
thanks danpost. That works great. I've tried to set it, that when the life is 0 to remove Mario. However the number keeps decrementing and Mario is not removed, the dead method is the same as described above.
danpost danpost

2013/6/29

#
I do not see where the value of the lifecounter is decremented.
Gevater_Tod4711 Gevater_Tod4711

2013/6/29

#
I think the problem is that the value of isDead is set to true when the method dead is executed and the method dead is executed when the value of isDead is true. So if you don't do anything first the method will never be executed and mario will never be removed. Maybe you should check if the value of the lifecounter is null or even smaler that null and then execute the method dead and not if isDead has the value true.
davemib123 davemib123

2013/6/29

#
I need further elaboration on this.
danpost danpost

2013/6/30

#
The problem Gevater_Tod4711 noticed was that line 3 of the 'dead' method does not reset the value of 'isDead' back to 'false', like to should.
davemib123 davemib123

2013/6/30

#
Thanks Danpost & Gevater_Tod4711. Problem sorted :)
You need to login to post a reply.