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

2016/4/19

Trouble with health deduction

StoveAteMe StoveAteMe

2016/4/19

#
Hey guys, so I wanted my controllable class (savior) to be able to endure 4 separate intersecting encounters with my rocket class. The idea is that, the savior's initial health is 100, and you lose 25 every time the savior comes into contact with the rocket. But when I test this out, my savior object disappears on the first interaction.
public class Savior extends Actor
{
    /**
     * Act - do whatever the Savior wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    
    int health = 100;
    public void act() 
    {
        
        if(Greenfoot.isKeyDown("a")){
  
            move(-3);
    }    
    if(Greenfoot.isKeyDown("d")) {
            move(3);

       }
    if(Greenfoot.isKeyDown("w")) {
           getWorld().addObject(new Missile(), this.getX(), this.getY());
        
    }
    Hit();
    if( health == 0) {
        getWorld().removeObject(this);
    }

  }
  
  public void Hit()
  {
    Actor rocket; 
    rocket = getOneObjectAtOffset(0, 0, Rocket.class);
      if(isTouching(Rocket.class)) {
          getWorld().removeObject(rocket);
          health = health - 25;
        }
    
    
  }


}
danpost danpost

2016/4/19

#
The problem is due to the fact that you are using two different collision methods in your Hit method (namely 'getOneObjectAtOffset' and 'isTouching'. The first one is more limited than the second one and will be 'null' for multiple act methods while the other one returns 'true'. So, nothing is removed from the world and health is decreased four times, to zero, on four consecutive act cycles. There is another collision method you could use to fix this. Instead of using the 'getOneObjectAtOffset' method, and since you do not need a reference to any rocket unless you are actually touching one, you can remove the rocket with the 'removeTouching' method. This will remove one anytime the 'isTouching' method returns a true value:
public void Hit()
{
    if (isTouching(Rocket.class)) {
        removeTouching(Rocket.class);
        health = health - 25;
        if (health == 0) {
            getWorld().removeObject(this);
        }
    }
}
Remove lines 25 through 27 from the class code above. You only need to check the value of 'health' when it decreases (not every act cycle), so I added that to the 'Hit' method where it should go.
You need to login to post a reply.