Write a new system
Updated: Oct 16, 2024
The core of Spatial SDK’s computation is its components. Systems function every tick, typically involving one or more entity queries and modifications to component data.
To construct a new system, follow these steps:
Begin by defining your class. Spatial SDK Systems utilize com.meta.spatial.core.System
. The header should be as follows:
class UpAndDownSystem() : SystemBase() {
Override the execute function. This function operates every tick, and you’ll use it for the operations you wish to perform:
The following steps outline an example where specific entities are queried and caused to move upward until a certain point, at which they return to their initial location in a continuous loop.
Create a query to pull data from the data model. The following query examines all entities with an UpAndDown
component and a Transform
:
val q = Query.where { has(UpAndDown.id, Transform.id) }
for (entity in q.eval()) {
Run an operation on the entity to change the data and establish the new component:
for (entity in q.eval()) { // the line from earlier
val transform = entity.getComponent<Transform>()
transform.transform.t.y += (0.2f)
transform.transform.t.y %= 1
entity.setComponent(transform)
}
The entire system construction process is combined as follows:
//UpAndDownSystem.kt
class UpAndDownSystem() : SystemBase() {
override fun execute() {
val q = Query.where { has(UpAndDown.id, Transform.id) }
for (entity in q.eval()) {
val transform = entity.getComponent<Transform>()
transform.transform.t.y += (0.2f)
transform.transform.t.y %= 1
entity.setComponent(transform)
}
}
}
Register your system.
//MyActivity.kt
systemManager.registerSystem(UpAndDownSystem())
Your code will run the execute function every tick.