Now we have switches, let's create doors !
Now that I can control objects with switches, I can create doors, that can be open/closed with switches.
Here is the code of ObstacleDoor.java :
public class ObstacleDoor extends Obstacle{
private float speed = 5;
private Vector2 initialPosition, finalPosition;
public ObstacleDoor(World world, OrthographicCamera camera, MapObject rectangleObject) {
super(world, camera, rectangleObject);
//Motion speed
if(rectangleObject.getProperties().get("Speed") != null){
speed = Float.parseFloat((String) rectangleObject.getProperties().get("Speed"));
}
initialPosition = new Vector2(posX, posY);
if(width > height)
finalPosition = new Vector2(posX + Math.signum(speed) * 1.9f*width, posY);
else
finalPosition = new Vector2(posX, posY + Math.signum(speed) * 1.9f*height);
}
@Override
public BodyType getBodyType(){
return BodyType.KinematicBody;
}
@Override
public void active(){
if(active)
body.setLinearVelocity( Math.signum(speed) * (initialPosition.x - body.getPosition().x) * speed,
Math.signum(speed) * (initialPosition.y - body.getPosition().y) * speed
);
else
body.setLinearVelocity( Math.signum(speed) * (finalPosition.x - body.getPosition().x) * speed,
Math.signum(speed) * (finalPosition.y - body.getPosition().y) * speed
);
}
@Override
public void activate(){
active = !active;
}
}
About this code :
- ObstacleDoor is a subclass of Obstacle.
- First I read check in the Properties of the TiledMapObject for the opening speed value.
- Then I set the closed and open positions of the door.
- Finally, the active() function move the door to the open/closed position according to the value of the boolean active.
The following is straightforward, if you followed this devlog :
The TiledMapReader.java need to recognize the ObstacleDoor in the map :
for (RectangleMapObject rectangleObject : objects.getByType(RectangleMapObject.class)) {
if(rectangleObject.getProperties().get("Type") != null){
...
//Doors
else if(rectangleObject.getProperties().get("Type").equals("Door")){
ObstacleDoor obstacle = new ObstacleDoor(world, camera, rectangleObject);
obstacles.add(obstacle);
}
...
}
}
And here is the result !
