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

2016/8/17

life counter problem

christ christ

2016/8/17

#
i am trying to make the Tank actor lose a life when it hits the enemy actor. when it reaches 0 lives it should disappear. Therefore it should take 3 separate hits from the enemy for the tank to die; not 1 !, for some reason the code doesn't work and I think when the enemy touches the actor it takes 3 lives away immediately, is there anyway I can modify the code to make it only take one life at a time? here's the code for the health/life: private int health = 3; if (isTouching(enemy.class)) { health--; } if (health == 0) { getWorld().removeObject(this); }
danpost danpost

2016/8/17

#
christ wrote...
i am trying to make the Tank actor lose a life when it hits the enemy actor. when it reaches 0 lives it should disappear. Therefore it should take 3 separate hits from the enemy for the tank to die; not 1 !, for some reason the code doesn't work and I think when the enemy touches the actor it takes 3 lives away immediately
It is not that it takes 3 lives away immediately. It is taking one life at a time for 3 consecutive act cycles. This is because the enemy continues to touch the tank for a considerable length of time (computer-wise, 3 act cycles is about 0.055 seconds in a normal speed scenario). You can add a field to track the touching state so you can detect changes in that state instead of just checking the current state. It can be a boolean or possibly an Object reference field. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// with instance fields
private boolean touchingEnemy;
private int health = 3;
 
// you could have
if (touchingEnemy != isTouching(enemy.class)) // changing state
{
    touchingEnemy = !touchingEnemy; // change field value
    if (touchingEnemy)
    {
        health--;
        if (health == 0)
        {
            getWorld().removeObject(this);
        }
    }
}
With this, the touching state will have to be removed before lives are decreased again..
You need to login to post a reply.