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

2012/8/14

removing enemy life

davemib123 davemib123

2012/8/14

#
Hi im trying to make a reference to the enemy class so when the bullet makes impact a life is removed. So far I have: I have this written in my main enemy class:
 public void takeLife(){
        life = life - 1;
    }
The hunter enemy I have given it a life of 100 using a constructor:
    public Hunter() {
        this.life = 100;
    }    
the bullet uses getOneIntersectingObject to check collision with the hunter using:
 Actor collided2 = getOneIntersectingObject(Hunter.class);
        if (collided2 != null){
            getWorld().addObject(new explosionLarge(), getX(), getY());
            City cityWorld = (City) getWorld();  // get a reference to the world
            // getWorld().removeObject(collided);
            Counter counter = cityWorld.getCounter();  // get a reference to the counter
            counter.add(20);
            getWorld().removeObject(this);
            return;
        }
I used the howto-1 tutorial for the counter, but wasnt too sure how to reference the enemy class.
davmac davmac

2012/8/14

#
If you change the first line of your collision check code to:
Hunter collided2 = (Hunter) getOneIntersectingObject(Hunter.class);
Then collided2 is a reference to the enemy object that the bullet has collided with; you can then insert a line such as:
collided2.takeLife();
... at the appropriate place.
davemib123 davemib123

2012/8/14

#
thanks davmac, works great. Question- why would you use
Hunter collided2
instead of
Actor collided2
davmac davmac

2012/8/14

#
Because the "takeLife" method is defined in Hunter, but not in Actor. If you leave it as an Actor reference, you will get an error when you try and call the takeLife method - the compiler isn't smart enough to figure out that the object is actually an instance of Hunter.
davemib123 davemib123

2012/8/14

#
ah rite :) thanks for the info
You need to login to post a reply.