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

2015/2/5

Help taking away health from enemy

DarkGhost DarkGhost

2015/2/5

#
Hi, I'm trying to get it so that the enemy has 20 health and the bullet takes away 5 each time it hits and when the health reaches 0 the enemy dies, but I can't figure out how to get this to work.. My code so far Bullet:
public class Bullet1 extends Cymeriadau
{
    private int direction, speed;
    public Bullet1(int dir)
    {
        direction = dir;
        speed = 15;
    }

    public void act()
    {
        setRotation(direction);
        move(speed);
        if( atWorldEdge() ) {
            getWorld().removeObject(this);
        }
    }

    public void hitEnemy() {
        RahikiLvl1 enemy = (RahikiLvl1) getOneObjectAtOffset(0, 0, RahikiLvl1.class);
        if (enemy != null) {
            enemy.setHealth(-1);
            getWorld().removeObject(this);
        }

    }
}
Enemy: public class RahikiLvl1 extends Cymeriadau { private int shotTimer = 0; private int direction = 1; private int speed = 2; private int topY = 100; private int lowerY = 550; private int health = 20; public void setHealth(int points) { health += points; } public int getHealth() { return health; } public void act() { if (shotTimer >0) { shotTimer = shotTimer -1;} else { getWorld().addObject(new Bullet2(getRotation()), getX(), getY()); shotTimer = 100; } { setLocation(getX(), getY() + (direction * speed)); if(getY() < topY) { direction = 1; } if(getY() > lowerY) { direction = -1; } } if (health <0) { getWorld().removeObject(this); } } } Player Shooting code:
        if (shotTimer >0) {
            shotTimer = shotTimer -1;}
        else if (Greenfoot.isKeyDown("space") )
        {
            getWorld().addObject(new Bullet1(getRotation()), getX(), getY());
            shotTimer = 10;
        }
danpost danpost

2015/2/5

#
The code for your 'hitEnemy' method will not execute unless it is called from somewhere with:
hitEnemy();
This should probably be placed in your act method. You cannot, however, execute both the code in this method and your 'atWorldEdge' check during the same act cycle. That is, if one removes the bullet from the world, the other check will fail. You can avoid this by either forcing an exit from the act method by adding a 'return' statement after removing the actor or by checking to ensure the actor is still in the world before running the other check by checking that the 'getWorld' method does not return a 'null' value ( 'if (getWorld() != null)' ).
DarkGhost DarkGhost

2015/2/5

#
Great that worked brilliantly! Thank you! :)
You need to login to post a reply.