Detecter

local Detecter = require('encompass').Detecter

A Detecter is an Engine which is responsible for reading the game world and producing Messages.

Detectors are defined by the Component prototype(s) they track, and the detect function they implement.

It is an anti-pattern to modify Entities or Components from inside a Detecter. Do not do this.

Function Reference

Detecter.define(name, component_types)
Arguments:
  • name (string) – The name of the Detecter.
  • component_types (table) – An array-style table containing Component types.

Defines a Detecter that will track Entities which contain _all_ of the given Component types.

Detecter:create_message(message_type, ...)
Arguments:
  • message_type (prototype) – A Message prototype.
  • ... – Alternating key and value arguments. The values should have types appropriate to their matching keys as defined by the Message prototype. If these do not match the Message prototype, an error will be thrown.
Returns:

An instantiated Message of the given prototype.

Detecter:detect(entity)
Arguments:
  • entity (Entity) – A reference to an entity which is tracked by the Detecter.

Every frame, this callback runs for each entity tracked by the Detecter. The programmer must override this callback or an error will be thrown.

Example

local TransformComponent = require("game.components.transform")
local VelocityComponent = require("game.components.velocity")
local MotionMessage = require("game.messages.motion")

local Detecter = require("encompass").Detecter
local MovementDetector = Detecter.define('MovementDetector', {
    TransformComponent, VelocityComponent
})

function MovementDetector:detect(entity)
    local transform_component = entity:get_component(TransformComponent)
    local velocity_component = entity:get_component(VelocityComponent)

    self:create_message(MotionMessage,
        'component',        transform_component,
        'x_velocity',       velocity_component.linear.x,
        'y_velocity',       velocity_component.linear.y,
        'angular_velocity', velocity_component.angular,
        'instant_linear',   false,
        'instant_angular',  false
    )
end

return MovementDetector