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

2020/4/20

Making the hearts disappear (Lives) HELP PLEASE

xlama xlama

2020/4/20

#
This is for a project, and I'm kinda new to programming so I'm having lots of problems. I'm making a car game and I wanted to add 3 lives, which disappear each time the player's car bumps into a roadcar. I've added 3 objects at the top of the screen, and I've only managed to make 1 heart disappear if the car collides. The other 2 remain in place.
public void checkCollision()
    {
       Actor collided = getOneIntersectingObject(RoadCar.class);
           if(collided != null) {
              
        Greenfoot.playSound("Explosion.wav");
         getWorld().removeObjects(getWorld().getObjectsAt(487, 23, Lives.class));
         
          
        
 
}
That's the car's method. And I've added 3 objects in CarWorld. addObject(new Lives(),574,23); addObject(new Lives(),531,23); addObject(new Lives(),487,23); Any kind of help would be appreciated xx.
danpost danpost

2020/4/20

#
Your code only removes a heart at a specific location (where only one heart will reside). You could have them adjust left if the location to their left opens up (provided there is a valid empty location to its left; that is, unless its x-coordinate is already 487, when you do not want it to move left from there). The following change, however, should suffice. Replace line 7 with the following:
int lives = getWorld().getObjects(Lives.class).size();
getWorld().removeObject(getWorld().getObjects(Lives.class).get(lives-1));
if (lives-1 == 0) Greenfoot.stop(); // or execute game over routine
The last line is needed as trying to remove another Lives object, when none remain, will cause a run-time error (indexOutOfBoundsException).
xlama xlama

2020/4/20

#
I tried that but it would just remove them all at once and stops the game.
xlama xlama

2020/4/20

#
public void checkCollision()
    {    int countColl=3;
       Actor collided = getOneIntersectingObject(RoadCar.class);
      
           if(collided != null) {
               countColl--;
             
        Greenfoot.playSound("Explosion.wav");
 
}
if (countColl == 2) {
    getWorld().removeObjects(getWorld().getObjectsAt(487, 23, Lives.class));
    
    
     } 
     
     if (countColl == 1) {
    getWorld().removeObjects(getWorld().getObjectsAt(531, 23, Lives.class));
    
     } 
    }

I've also tried adding a counter for each collision to try and see if it'll work but it still hasn't.
danpost danpost

2020/4/20

#
xlama wrote...
I tried that but it would just remove them all at once and stops the game.
Okay. Possible solutions are (1) you could just remove the car collided with; or (2) you could create another class to take the image of collided car and replace the car with it.
You need to login to post a reply.