Skip to content

Components

Giacomo Cavalieri edited this page Oct 14, 2021 · 5 revisions

Defining custom components

A component is simply a case class extending the Component trait, e.g.

case class Position(x: Double, y: Double) extends Component
case class Color(r: Int, g: Int, b: Int) extends Component

Adding components to entities

Once you have a component you can add it to an entity by writing:

import dev.atedeg.ecscala.given

object Example with ECScalaDSL {
  val world = World()
  val addedEntity = world hasAn entity withComponent Position(1, 1)
  // or addedEntity addComponent Position(1, 1)
  // or addedEntity += Position(1, 1)
}

To add more components at once you can write:

import dev.atedeg.ecscala.given

object Example with ECScalaDSL {
  val world = World()
  val addedEntity = world hasAn entity withComponents (Position(1, 1) &: Color(255, 0, 0))
}

The &: is used to build a CList (i.e. a list of components).

At any given time, a component must be assigned to at most one entity: trying to assign the same component to more than one entity will result in a runtime error:

val position = Position(1, 1)
entity1 += position
entity2 += position // Error

In addition, an Entity can have at most one Component per type:

entity += Position(1, 1)
entity += Position(10, 10) // Overrides the previously added component
entity getComponent[Position] // -> Position(10, 10)

Removing components from entities

In order to remove a component assigned to an entity you can write:

import dev.atedeg.ecscala.given

object Example with ECScalaDSL {
  val world = World()
  val position = Position(1, 1)
  val addedEntity = world hasAn entity withComponent position
  remove[Position] from addedEntity
  // or remove (position) from addedEntity
  // or addedEntity -= position
  // or addedEntity.removeComponent(position)
  // or addedEntity.removeComponent[Position]
}

Getting components from entities

To get a specific component from an entity you can use getComponent which will return an Option with the component of the specified type:

entity += Position(1, 1)
entity getComponent[Position] // Some(Position(1, 1))
entity getComponent[Velocity] // None