Class: BeltsEngine::Ecs::EntityManager

Inherits:
Hash
  • Object
show all
Defined in:
lib/belts_engine/ecs/entity_manager.rb

Instance Method Summary collapse

Constructor Details

#initialize(game) ⇒ EntityManager

Returns a new instance of EntityManager.



3
4
5
6
# File 'lib/belts_engine/ecs/entity_manager.rb', line 3

def initialize(game)
  @game = game
  @next_id = 0
end

Instance Method Details

#add_components(id, components) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/belts_engine/ecs/entity_manager.rb', line 21

def add_components(id, components)
  entity = self[id]
  entity.merge!(**components)

  @game.collections.values.each do |collection|
    collection.add_entity(entity)
  end
end

#destroy(id) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/belts_engine/ecs/entity_manager.rb', line 43

def destroy(id)
  @game.collections.values.each do |collection|
    collection.remove_entity(id)
  end

  self.delete(id)
end

#destroy_allObject



51
52
53
54
55
# File 'lib/belts_engine/ecs/entity_manager.rb', line 51

def destroy_all
  keys.each do |id|
    destroy(id)
  end
end

#instantiate(prefab_class, position = Vec3.zero, rotation = Vec3.zero, scale = Vec3.one) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/belts_engine/ecs/entity_manager.rb', line 8

def instantiate(prefab_class, position = Vec3.zero, rotation = Vec3.zero, scale = Vec3.one)
  id = @next_id
  entity = self[id] = Entity.new(id)
  @next_id += 1

  components = Marshal.load(Marshal.dump(prefab_class.to_s.constantize.components)) # deep copy
  components[:transform].position = position if position
  components[:transform].rotation = rotation if rotation
  add_components(id, components)

  id
end

#remove_components(id, keys) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/belts_engine/ecs/entity_manager.rb', line 30

def remove_components(id, keys)
  entity = self[id]

  keys.each do |key|
    entity.delete(key)
  end

  @game.collections.values.each do |collection|
    collection.remove_entity(id)
    collection.add_entity(entity)
  end
end