-
Notifications
You must be signed in to change notification settings - Fork 20
Entity and Components (old)
Simon edited this page Sep 26, 2022
·
1 revision
To create and add entities to a world use the entity
function of the world. Let's create an entity with a PositionComponent
and SpriteComponent
:
data class Position(var x: Float = 0f, var y: Float = 0f)
data class Sprite(var texturePath: String = "")
fun main() {
val world = world {}
val entity: Entity = world.entity {
add<Position> { x = 5f }
add<Sprite>()
}
// if needed, you can already access the new entity within the entity{} block
val entity2 = world.entity { e ->
// e is the same as entity2
// this can be useful in some cases where you want to set the entity as
// custom 'userData' on certain third-party library objects directly
}
}
There might be situations where you need to execute a specific code when a component gets added or removed from an entity.
This can be done via ComponentListener
in Fleks. They are created in a similar way like systems meaning that they are created
by Fleks using dependency injection. The world
of a ComponentListener
is automatically available as a dependency like any ComponentMapper
.
Here is an example of a listener that reacts on add/remove of a Box2dComponent
and destroys the body
when the component gets removed from an entity:
data class Box2dComponent{
lateinit var body: Body
}
class Box2dComponentListener(
private val b2dWorld : com.badlogic.gdx.physics.box2d.World
) : ComponentListener<Box2dComponent> {
override fun onComponentAdded(entity: Entity, component: Box2dComponent) {
component.body = b2dWorld.createBody( /* body creation code omitted */ )
component.body.userData = entity
}
override fun onComponentRemoved(entity: Entity, component: Box2dComponent) {
component.body.world.destroyBody(body)
component.body.userData = null
}
}
fun main() {
val b2dWorld = com.badlogic.gdx.physics.box2d.World()
val world = world {
injectables {
add(b2dWorld)
}
components {
// register listener to the world
add<Box2dComponentListener>()
}
}
}
data class Box2dComponent{
lateinit var body: Body
}
class Box2dComponentListener : ComponentListener<Box2dComponent> {
private val b2dWorld : com.badlogic.gdx.physics.box2d.World = Inject.dependency()
override fun onComponentAdded(entity: Entity, component: Box2dComponent) {
component.body = b2dWorld.createBody( /* body creation code omitted */ )
component.body.userData = entity
}
override fun onComponentRemoved(entity: Entity, component: Box2dComponent) {
component.body.world.destroyBody(body)
component.body.userData = null
}
}
fun main() {
val b2dWorld = com.badlogic.gdx.physics.box2d.World()
val world = world {
injectables {
add(b2dWorld)
}
components {
// register component together with its listener to the world
add(::Box2dComponent, ::Box2dComponentListener)
}
}
}