docsReading time: 2 minutes
General
Basics
- Getting Started
- Game API
- Input API
- Configuration
- Tile Maps
- Resource Management
- Entity Framework
- Control Entities
- User Interface
- utiLITI
- Deployment
- Savegames
- Libraries and Tools
- Glossary
Advanced
- The Particle System
- Dynamic Lighting
- Static Lighting
- Performance Optimization
- Custom MapObjectLoaders
- String Localization
- Object Serialization
- Utility Classes
- Network Communication
- Advanced Entity Knowledge
Tutorials
Custom MapObjectLoaders
MapObjectLoaders convert MapObjects from your Tiled map into game entities. Create custom loaders when you define new entity types.
How MapObjectLoaders Work
- Map is loaded from .tmx file
- Each MapObject has a
typeproperty - Registered loader matching the type is invoked
- Loader creates entity/entities and adds to environment
Creating a Custom Loader
public class ChestLoader extends MapObjectLoader {
public ChestLoader() {
super("CHEST"); // MapObject type this loader handles
}
@Override
public Collection<IEntity> load(Environment environment, IMapObject mapObject) {
Collection<IEntity> entities = new ArrayList<>();
// Validate map object
if (mapObject.getType() == null || !mapObject.getType().equals("CHEST")) {
return entities;
}
// Create entity from map object
Chest chest = new Chest();
chest.setLocation(mapObject.getLocation());
chest.setWidth(mapObject.getWidth());
chest.setHeight(mapObject.getHeight());
chest.setMapId(mapObject.getId());
chest.setName(mapObject.getName());
// Read custom properties
boolean locked = mapObject.getBoolValue("locked", false);
String lootTable = mapObject.getStringValue("lootTable", "default");
chest.setLocked(locked);
chest.setLootTable(lootTable);
entities.add(chest);
return entities;
}
}Registering Loaders
Register before loading maps:
public static void main(String[] args) {
Game.init(args);
// Register custom loaders BEFORE loading environment
Environment.registerMapObjectLoader(new ChestLoader());
Environment.registerMapObjectLoader(new PortalLoader());
Resources.load("game.litidata");
Game.world().loadEnvironment("level1");
Game.start();
}Reading Map Object Properties
@Override
public Collection<IEntity> load(Environment environment, IMapObject mapObject) {
// Basic properties
String name = mapObject.getName();
int id = mapObject.getId();
Point2D location = mapObject.getLocation();
double width = mapObject.getWidth();
double height = mapObject.getHeight();
// Custom properties (from Tiled Properties panel)
String value = mapObject.getStringValue("myProperty");
int count = mapObject.getIntValue("count", 0);
float speed = mapObject.getFloatValue("speed", 1.0f);
boolean enabled = mapObject.getBoolValue("enabled", true);
// Using constants
String sprite = mapObject.getStringValue(MapObjectProperty.SPRITE);
// ...
}See Also
- Map Objects – MapObject overview
- Custom Properties – Property configuration
- Default Entity Types – Built-in types
Last updated 2 weeks ago
Feedback / Collaborate
