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

2017/12/3

Ships must take three hits before exploding

massivassl massivassl

2017/12/3

#
Hello again. I am making progress in my 1v1 player ship game, but now i've run into another problem I already found a way to make ships explode on contact with the bullets, but the ships are supposed to take three hits before exploding.
public void die()
    {  int t=0; //this serves as a hit counter. if you are hit three times, your ship is suppose to explode
       if (canSee (P2Bullet.class))
       {
          eat (P2Bullet.class);
          t++;//adds a hit to your counter
       }
       
       else if (canSee (P2Bullet.class) && t==3)
       {
          getWorld().addObject (new Explosion(), getX(), getY());//replaces the ship actor with an explosion actor
          getWorld().removeObject(this);//removes your ship from the game
        }
    }
i've tested this, but the result is that the ship just takes an infinite amount of hits. the second if statement doesn't seem to execute
danpost danpost

2017/12/3

#
massivassl wrote...
the result is that the ship just takes an infinite amount of hits. the second if statement doesn't seem to execute
That is because 't' is declared and set to zero at the beginning of the method. No wonder it never gets a value of 3. Also, 't' is not retained once the method has finished executing (it is just re-declared the next time it executes). Move 'int t=0;' to outside the method.
massivassl massivassl

2017/12/3

#
danpost wrote...
Move 'int t=0;' to outside the method.
i tried that. int t is now outside the die() method.
 int t=0;
    
    public void die()
    {  
       if (canSee (P2Bullet.class))
       {
          eat (P2Bullet.class);
          t++;//adds a hit to your counter
       }
       
       else if (canSee (P2Bullet.class) && t==3)
       {
          getWorld().addObject (new Explosion(), getX(), getY());//replaces the ship actor with an explosion actor
          getWorld().removeObject(this);//removes your ship from the game
        }
    }
same problem, or should t this time be a public or public static int?
Super_Hippo Super_Hippo

2017/12/3

#
Line 11 should be
if (t==3)
or it will never be executed. And the } in line 9 should be in the end instead so it isn't checked all the time.
private int t=0;

public void die()
{  
    if (canSee(P2Bullet.class))
    {
        eat(P2Bullet.class);
        t++;//adds a hit to your counter
        if (t==3)
        {
            getWorld().addObject(new Explosion(), getX(), getY());//replaces the ship actor with an explosion actor
            getWorld().removeObject(this);//removes your ship from the game
        }
    }
}
massivassl massivassl

2017/12/3

#
Ah I see. Thanks a lot, dan and hippo.
You need to login to post a reply.