Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags
(2 edits)

Losing condition : Major Tom gets crushed !

OK now we have these nice pistons, Major Tom can get crushed by them, making the player lose the game.

Detecting the event "Tom gets crushed" happens in the ContactListener we set in the GameScreen, to detect collisions between bodies.

Remember, the ContactListener has 4 methods :

  1. beginContact
  2. endContact
  3. preSolve
  4. postSolve

The one that interests us here is the postSolve method. The postSolve method gives us access to the impulse that a body undergoes after a collision. The idea is that the more the hero is crushed, the higher the impulse he undergoes. Thus, if the impulse exceeds a predetermined value, the hero dies.

Here is the code of the postSolve method of the ContactListener in the GameScreen.java :

public void postSolve(Contact contact, ContactImpulse impulse) {
                Body bodyA = contact.getFixtureA().getBody();
                Body bodyB = contact.getFixtureB().getBody();
                
                //Hero death by crushing
                if(bodyA.getUserData().equals("Tom") || bodyB.getUserData().equals("Tom")){ 
                    for(int i = 0; i < impulse.getNormalImpulses().length; i++){
                        if(impulse.getNormalImpulses()[i] > GameConstants.CRUSH_IMPULSE){
                            System.out.println("Oh noes ! Major Tom has been crushed !!");
                        }
                    }
                }
            }

About this code :

  • First we check if Major Tom is involved in the collision that has been detected
  • The we check if one of the impulses exceeds the max value we put in the GameConstants.java. One of the impulses ? Yes, when you have a collision between two bodies, each of the bodies undergoes an impulse, therefore, for one collision, two impulses.
  • If one of the impulse exceeds the threshold, we print a message in the console.
Don't foget to add this line in the GameConstants.java :
public static float CRUSH_IMPULSE = 300;

The value of 300 is completely arbitrary. I'll probably change it when the time of fine tuning comes.


And here is the result ! Simple, isn’t it ?


Notice : The code I put in the postSolve will also detect any collision that produces an impulse that exceeds the threshold, for example if the hero flies at very high speed and hit a wall. I could make a condition that the hero dies only if he is crushed by a piston, but I like the idea that he could die by a high-speed collision, that would add challenge to the game. So for now, I stick with that code.