summaryrefslogtreecommitdiff
path: root/sim/src/TurretControl.cpp
blob: b5527fc3914dfdc0188a152d3dc2559abc717976 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <kurator/sim/TurretControl.h>

#include <entt/entity/registry.hpp>
#include <entt/signal/dispatcher.hpp>

#include <kurator/sim/components.h>
#include <kurator/sim/events.h>
#include <kurator/universe/TurretType.h>


namespace kurator
{
namespace sim
{


void
TurretControl::update(entt::registry& registry, entt::dispatcher& dispatcher, const float dt)
{
	auto view = registry.view<TurretControl, universe::TurretType>();
	for (auto&& [entity, control, def] : view.each()) {
		if (!registry.valid(control.owner)) {
			registry.destroy(entity);
			continue;
		}
		const auto& [state, transform] = registry.get<AIState, Transform>(control.owner);  // no checks
		if (!registry.valid(state.target))
			continue;
		if (control.reload > 0.0)
			control.reload -= dt;
		if (control.rounds < 1 && control.reload <= 0.0)
			control.rounds = def.rounds;
		if (control.delay > 0.0)
			control.delay -= dt;
		if (control.rounds > 0 && control.delay <= 0.0) {
			auto& target_points = registry.get<HitPoints>(state.target);
			const auto& target = registry.get<Transform>(state.target);
			const auto distance = transform.position.distance(target.position);
			if (distance > def.optimal_range * 2.5)
				continue;
			const auto damage = def.effective_damage(distance);
			if (damage > 0.0) {
				target_points.health -= damage;
				dispatcher.trigger(Hit{damage, control.owner, state.target});
			}
			control.delay = def.rate_of_fire;
			if (--control.rounds < 1)
				control.reload = def.reload;
		}
	}
}


}  // namespace sim
}  // namespace kurator