-
Notifications
You must be signed in to change notification settings - Fork 6
/
rotatingsquare.cpp
62 lines (51 loc) · 1.72 KB
/
rotatingsquare.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
#include "rotatingsquare.h"
#include <math.h>
#include <QDebug>
RotatingSquare::RotatingSquare(float x, float y, float rotation, float size, float xVel, float yVel, float rotationVel)
{
this->x = x;
this->y = y;
this->rotation = rotation;
this->size = size;
this->xVel = xVel;
this->yVel = yVel;
this->rotationVel = rotationVel;
this->aabb = new QRectF(0,0,0,0);
this->lastTime = QDateTime::currentMSecsSinceEpoch();
// When rotated on a 45 degree angle the size becomes the dist between two diagonals of the square
this->rotatedSizeIncrease = sqrt(size*size + size*size) - size;
}
RotatingSquare::~RotatingSquare()
{
delete aabb;
}
void RotatingSquare::updateAABB()
{
float amountRotated = abs(abs(fmod(rotation, 90.0f)) - 45.0f) / 45.0f;
amountRotated = 1.0f - amountRotated;
float calcSize = size + rotatedSizeIncrease*amountRotated;
this->aabb->setRect(x-calcSize/2,y-calcSize/2,calcSize,calcSize);
}
void RotatingSquare::update(float containerWidth, float containerHeight)
{
updateAABB();
// calculate seconds elapsed since last frame
qint64 now = QDateTime::currentMSecsSinceEpoch();
float elapsedSecs = ((float)(now - lastTime))/1000.0f;
lastTime = now;
if(elapsedSecs > 1.0f)
elapsedSecs = 1.0f;
// adjust position & rotation based on velocity & elapsed time
x += xVel * elapsedSecs;
y += yVel * elapsedSecs;
rotation += rotationVel * elapsedSecs;
// bounce off walls
if(aabb->x() < 0 && xVel < 0)
xVel *= -1;
if(aabb->right() > containerWidth && xVel > 0)
xVel *= -1;
if(aabb->y() < 0 && yVel < 0)
yVel *= -1;
if(aabb->bottom() > containerHeight && yVel > 0)
yVel *= -1;
}