Animated Obstacles : Piston (2/2)
Making the TiledMapReader recognize the ObstaclePiston
Here is the updated code for TiledMapReader .java :
private OrthographicCamera camera; private World world; private MapObjects objects; public Array<Obstacle> obstacles; private Array<MapObject> pistons; public Hero hero; public TiledMapReader(final MyGdxGame game, TiledMap tiledMap, World world, OrthographicCamera camera){ this.camera = camera; this.world = world; hero = new Hero(world, camera, tiledMap); objects = tiledMap.getLayers().get("Objects").getObjects(); obstacles = new Array<Obstacle>(); pistons = new Array<MapObject>(); for (RectangleMapObject rectangleObject : objects.getByType(RectangleMapObject.class)) { if(rectangleObject.getProperties().get("Type") != null){ //End of the level if(rectangleObject.getProperties().get("Type").equals("Exit")){ Exit finish = new Exit(world, camera, rectangleObject); obstacles.add(finish); } //Light obstacles else if(rectangleObject.getProperties().get("Type").equals("Light")){ ObstacleLight obstacle = new ObstacleLight(world, camera, rectangleObject); obstacles.add(obstacle); } //Pistons else if(rectangleObject.getProperties().get("Type").equals("Piston")){ pistons.add(rectangleObject); } } else{ Obstacle obstacle = new Obstacle(world, camera, rectangleObject); obstacles.add(obstacle); } } //Pistons creation for(int i = pistons.size - 1; i > -1; i--){ if(pistons.get(i).getProperties().get("Group") != null){ for(int j = 0; j < pistons.size; j++){ if(Integer.parseInt(pistons.get(i).getProperties().get("Group").toString()) == Integer.parseInt(pistons.get(j).getProperties().get("Group").toString()) && i != j){ ObstaclePiston piston = new ObstaclePiston(world, camera, pistons.get(i), pistons.get(j)); obstacles.add(piston); pistons.removeIndex(i); pistons.removeIndex(j); i--; } } } else System.out.println("Piston creation failed"); } }Differences with the previous TiledMapReader.java :
- First, we create an Array : pistons = new Array<MapObject>
- In the for loop, we store every Rectangles which "Type" is Piston in the pistons Array.
- Outside the main for loop, we create another for loop dedicated to create ObstaclePiston : It will check if 2 objects in the pistons Array have the same "Group" number, create an ObstaclePiston from these 2 objects before removing them from the pistons Array and adding the newly create ObstaclePiston to the obstacles Array.
Finally, we need to run the active() method in the GameScreen
In the render() of the GameScree.java, we only need to add this lines :
for(Obstacle obstacle : mapReader.obstacles){ obstacle.active(); }
Here is a gif of the result :
Now that we have these ObstaclePiston, we need to create the losing condition "Hero gets crushed" !