SPARK  0.1.0
A general purpose game engine written in C++.
Loading...
Searching...
No Matches
Transform.h
1#pragma once
2
3#include "spark/core/Component.h"
4#include "spark/core/Export.h"
5#include "spark/core/GameObject.h"
6
7#include "spark/math/Vector2.h"
8
9#include "glm/matrix.hpp"
10#include "glm/gtc/matrix_transform.hpp"
11
12#define GLM_ENABLE_EXPERIMENTAL
13#include "glm/gtx/quaternion.hpp"
14
15namespace spark::core::components
16{
20 class SPARK_CORE_EXPORT Transform final : public Component
21 {
22 DECLARE_SPARK_RTTI(Transform, Component)
23
24 public:
25 math::Vector2<float> position = {0.f, 0.f};
26 float rotation = 0;
27 math::Vector2<float> scale = {1.f, 1.f};
28
29 public:
30 explicit Transform(GameObject* parent)
31 : Component(parent) {}
32
33 friend bool operator==(const Transform& lhs, const Transform& rhs) { return lhs.position == rhs.position; }
34 friend bool operator!=(const Transform& lhs, const Transform& rhs) { return !(lhs == rhs); }
35
40 glm::mat4 matrix() const
41 {
42 glm::mat4 matrix(1.f);
43
44 // Apply local transform
45 matrix = glm::translate(matrix, {gameObject()->transform()->position.x, gameObject()->transform()->position.y, 0.f});
46 matrix = glm::rotate(matrix, gameObject()->transform()->rotation, {0.0f, 0.0f, 1.0f});
47 matrix = glm::scale(matrix, {gameObject()->transform()->scale.x, gameObject()->transform()->scale.y, 1.0f});
48
49 // Apply parent transforms
50 const GameObject* parent = gameObject()->parent();
51 while (parent)
52 {
53 const Transform& parent_transform = *parent->transform();
54 matrix = glm::translate(matrix, {parent_transform.position.x, parent_transform.position.y, 0.f});
55 matrix = glm::rotate(matrix, parent_transform.rotation, {0.0f, 0.0f, 1.0f});
56 matrix = glm::scale(matrix, {parent_transform.scale.x, parent_transform.scale.y, 1.0f});
57 parent = parent_transform.gameObject()->parent();
58 }
59
60 return matrix;
61 }
62 };
63}
64
65IMPLEMENT_SPARK_RTTI(spark::core::components::Transform)
A component that can be attached to a GameObject to provide additional functionality.
Definition Component.h:20
GameObject * gameObject()
Gets the GameObject that the component is attached to.
Definition Component.cpp:19
A GameObject is any object in the game. It contains a list of components that provides functionality ...
Definition GameObject.h:26
A component that stores the position of a game object.
Definition Transform.h:21
glm::mat4 matrix() const
Gets the transformation matrix of the transform.
Definition Transform.h:40
A vector with two components.
Definition Vector2.h:13