camera_system.cpp 2.34 KB
Newer Older
1
2
3
4
5
6
#include "camera_system.hpp"

#include <mirrage/ecs/components/transform_comp.hpp>

namespace phase_shifter::gameplay {

Florian Oetke's avatar
Florian Oetke committed
7
8
	using mirrage::ecs::components::Transform_comp;

Tim Scheiber's avatar
Tim Scheiber committed
9
10
	Camera_system::Camera_system(mirrage::util::Message_bus& bus, mirrage::ecs::Entity_manager& entity_manager)
	  : _mailbox(bus), _entity_manager(entity_manager)
11
12
13
	{
		_entity_manager.register_component_type<Viewtarget_comp>();
		_entity_manager.register_component_type<Spring_comp>();
Tim Scheiber's avatar
Tim Scheiber committed
14
15
16
17
18
19
20
21
22
		_entity_manager.register_component_type<Shake_comp>();

		_mailbox.subscribe_to([&](Screen_shake_msg& e) {
			for (auto& shake : _entity_manager.list<Shake_comp>()) {
				shake.intesity = e.intensity;
				shake.duration = e.duration;
				shake.time_remaining = e.duration;
			}
		});
23
24
25
	}

	void Camera_system::update(mirrage::util::Time dt)
26
	{
Tim Scheiber's avatar
Tim Scheiber committed
27
28
29
30
		_mailbox.update_subscriptions();

		for(auto&& [transform, viewtarget, spring, shake] :
		    _entity_manager.list<Transform_comp, Viewtarget_comp, Spring_comp, Shake_comp>()) {
31
			auto target_facet = _entity_manager.get(viewtarget.target);
32
33

			if(target_facet.is_some()) {
34
35
				auto target_transform =
				        target_facet.get_or_throw().get<mirrage::ecs::components::Transform_comp>();
36
37

				if(target_transform.is_some()) {
38
					auto      target_position  = target_transform.get_or_throw().position;
39
40
41
42
43
44
45
					glm::vec3 offset           = viewtarget.offset;
					glm::vec3 dest_pos         = {target_position.x + offset.x,
                                          target_position.y + offset.y,
                                          target_position.z + offset.z};
					float     damping_constant = 2 * sqrtf(spring.spring_constant);
					glm::vec3 damping_force    = -damping_constant * spring.velocity;

Florian Oetke's avatar
Florian Oetke committed
46
47
48
					glm::vec3 spring_force = spring.spring_constant * (dest_pos - transform.position);
					glm::vec3 acceleration = (spring_force + damping_force) / spring.mass;
					spring.velocity += dt.value() * acceleration;
Tim Scheiber's avatar
Tim Scheiber committed
49
50
51
52
53
54
55
					spring.position += dt.value() * spring.velocity;
					transform.position = spring.position;
					if (shake.time_remaining > 0) {
						glm::vec3 shake_direction = glm::normalize(glm::vec3{std::rand(), 0, std::rand()});
						transform.position += shake.intesity * (shake.time_remaining / shake.duration) * shake_direction;
						shake.time_remaining -= dt.value();
					}
Florian Oetke's avatar
Florian Oetke committed
56
					transform.direction(-offset);
57
58
59
60
				}
			}
		}
	}
61
} // namespace phase_shifter::gameplay