Tuto tiny-ecs demo Part 5 tiny-ecs System

From GiderosMobile
Revision as of 06:41, 21 December 2023 by MoKaLux (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

System

It is time to create our first System.

In the systems folder "_S", create a file called "sDrawable.lua" for example. This will be the System responsible for drawing entities:

SDrawable = Core.class()

function SDrawable:init(xtiny) -- tiny function
	xtiny.system(self) -- called only once on init (no update)
end

function SDrawable:filter(ent) -- tiny function
	return ent.spritelayer and ent.sprite
end

function SDrawable:onAdd(ent) -- tiny function
	ent.sprite:setPosition(ent.x, ent.y)
	ent.spritelayer:addChild(ent.sprite)
end

function SDrawable:onRemove(ent) -- tiny function
	ent.spritelayer:removeChild(ent.sprite)
end

In the init function we create a system based on tiny-ecs (not tiny-ecs world).

This system will only be called once on initialization.

The filter function allows to call the system on entities with a specific id. Here the system will execute on all entites with a spritelayer id AND a sprite id (cf: Entity).

The onAdd function tells the system what to do when an entity is added to the system. Here we tell the system to set the position of the entity and to add the entity to a sprite layer. The parameters like x, y position, sprite layer are stored in the entity itself.

The onRemove function tells the system what to do when an entity is removed from the system. Here we tell the system to remove the entity from the entity sprite layer.

That's it, we created our first System, easy!

World addSystem

Now we need to add our System to tiny-ecs world.

Please go to the "LevelX.lua" file and complete the code as follow:

	-- ...
	-- tiny-ecs
	self.tiny = require "classes/tiny-ecs"
	self.tiny.tworld = self.tiny.world()
	-- the player (xspritelayer, x, y)
	self.player1 = EPlayer1.new(self.camera, 12*16, 10*16)
	self.tiny.tworld:addEntity(self.player1)
	-- add 1 system to tiny-ecs
	self.tiny.tworld:addSystem(SDrawable.new(self.tiny))
	-- ...

Like addEntity, addSystem only adds one system at a time.

As we will be adding more systems, I prefer using the following tiny-ecs add syntax:

	-- ...
	-- add systems to tiny-ecs
	self.tiny.tworld:add(
		SDrawable.new(self.tiny)
	)
	-- ...

When a system doesn't work, make sure it was added to tiny-ecs world!

You can run the project and now the player1 should appear in Level1!

Next?

In the next part, we will create a Component for our player1 entity.


Prev.: Tuto tiny-ecs demo Part 4 tiny-ecs Entity
Next: Tuto tiny-ecs demo Part 6 tiny-ecs Component


Tutorial - tiny-ecs demo