-
Notifications
You must be signed in to change notification settings - Fork 2
/
Camera2D.cpp
72 lines (55 loc) · 1.83 KB
/
Camera2D.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "Camera2D.h"
namespace NeroEngine{
Camera2D::Camera2D() :_position(0.0f, 0.0f),
_cameraMatrix(1.0f),
_orthoMatrix(1.0f),
_scale(1.0f),
_needsMatrixUpdate(true),
_screenWidth(100),
_screenHeight(100)
{
}
Camera2D::~Camera2D()
{
}
void Camera2D::init(int screenWidth, int screenHeight){
_screenWidth = screenWidth;
_screenHeight = screenHeight;
_orthoMatrix = glm::ortho(0.0f, float(_screenWidth), 0.0f, float(_screenHeight));
}
void Camera2D::update(){
if (_needsMatrixUpdate){
glm::vec3 translate(-_position.x + _screenWidth / 2.0f, -_position.y + _screenHeight / 2.0f, 0.0f);
_cameraMatrix = glm::translate(_orthoMatrix, translate);
glm::vec3 scale(_scale,_scale,0.0f);
_cameraMatrix = glm::scale(glm::mat4(1.0f), scale) * _cameraMatrix;
_needsMatrixUpdate = false;
}
}
glm::vec2 Camera2D::convertScreenToWorld(glm::vec2 screenCoords){
//invert dir Y
screenCoords.y = _screenHeight - screenCoords.y;
//in the center
screenCoords -= glm::vec2(_screenWidth / 2, _screenHeight / 2);
//scala the coordnates
screenCoords /= _scale;
//translate with the camera position
screenCoords += _position;
return screenCoords;
}
bool Camera2D::isBoxiInView(const glm::vec2& position, const glm::vec2& dimensions){
glm::vec2 scaledScreenDimensions = glm::vec2(_screenWidth, _screenHeight) / (_scale);
float MIN_DISTANCE_X = dimensions.x / 2.0f + scaledScreenDimensions.x/2.0f;
float MIN_DISTANCE_Y = dimensions.y / 2.0f + scaledScreenDimensions.y/2.0f;
glm::vec2 centerPos = position + dimensions/2.0f;
glm::vec2 centerCameraPos = _position;
glm::vec2 distVec = centerPos - centerCameraPos;
float xDepth = MIN_DISTANCE_X - abs(distVec.x);
float yDepth = MIN_DISTANCE_Y - abs(distVec.y);
if (xDepth>0 && yDepth>0){
//Åöײ
return true;
}
return false;
}
}