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

2013/5/21

Health

Gzuzfrk Gzuzfrk

2013/5/21

#
Is there a quick code to greenfoot to where if the player gets hit twice then the object will die? I want it to where you have to shoot the object twice then it will die.
danpost danpost

2013/5/21

#
That would depend on what you mean by 'quick code'. When an object needs multiple hits to die, normally an instance int field would be used to count the hits as they come. This would work fine for two hits, or even one (though, unnecessary; since there is no counting involved in the case of one). Two on the other hand, is kind of a special case; you can either count the two hits as they come or, as an alternative, you can use a boolean field to flag the first hit.
// using int field for any number of hits (starting at one)
int hitsToDie = /* some number */;
int hitsTaken = 0;
// method called when hit
public void hit()
{
    hitsTaken++;
    if (hitsTaken == hitsToDie) getWorld().removeObect(this);
}
// using a boolean when only two hits required to die
boolean hasTakenAHit;
// method called when hit
public void hit()
{
    if (hasTakenAHit) getWorld().removeObject(this);
    else hasTakenAHit = true;
}
Gzuzfrk Gzuzfrk

2013/5/21

#
Ok so I tried that and its not working for some reason Where would I put all of that with this code?
public void fireBallHit()
    {
        Actor b = getOneIntersectingObject(Alien.class);
        if(b != null)
        {
            getWorld().removeObject(b);
            getWorld().removeObject(this);
            
        }
    }
TheMissingKey TheMissingKey

2013/5/21

#
    public void fireBallHit()  
        {  
            Actor b = getOneIntersectingObject(Alien.class);  
            if(b != null)  
            {
                //here
                hitsTaken++;
                getWorld().removeObject(b);  
                getWorld().removeObject(this);  
                  
            }  
        }  
TheMissingKey TheMissingKey

2013/5/21

#
you also wouldn't remove the objects unless hitsTaken==hitsToDie, so take out the getWorld().removeObject(b); and if this is in the object to take damage's class, in the act method put a:
if(hitsTaken==hitsToDie)
{
    getWorld().removeObject(this);
}
and put the rest of the code in the act method in an:
if(this!=null)
{
    //all code in act method
}
danpost danpost

2013/5/21

#
private boolean hasTakenAHit;

public void fireBallHit()
{
    Actor b = getOneIntersectingObject(Alien.class);
    if (b != null) 
    {
        getWorld().removeObject(b);
        if (hasTakenAHit) getWorld().removeObject(this);
        hasTakenAHit = true;
    }
}
Gzuzfrk Gzuzfrk

2013/5/21

#
Thanks :) it's working now
You need to login to post a reply.