-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayer.cpp
More file actions
89 lines (78 loc) · 2.51 KB
/
Player.cpp
File metadata and controls
89 lines (78 loc) · 2.51 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "Player.h"
//--------------------------------------------------------------------------------------------------------------------
// Private function
//--------------------------------------------------------------------------------------------------------------------
void Player::initVariables()
{
this->movementSpeed = 10.f; // Initialize movement speed of player
}
void Player::initShape()
{
this->shape.setFillColor(sf::Color::Green);
this->shape.setSize(sf::Vector2f(50.f, 50.f));
}
//--------------------------------------------------------------------------------------------------------------------
// Constructors and Destructors
//--------------------------------------------------------------------------------------------------------------------
Player::Player()
{
this->shape.setPosition(0.f, 0.f);
this->initVariables();
this->initShape();
}
Player::~Player()
{
}
//--------------------------------------------------------------------------------------------------------------------
// Public functions
//--------------------------------------------------------------------------------------------------------------------
void Player::updateInput()
{
// Keyboard input
// Mleft
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
this->shape.move(-this->movementSpeed, 0.f);
}
// Right
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
this->shape.move(+this->movementSpeed, 0.f);
}
// Top
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
this->shape.move(0.f, -this->movementSpeed);
}
// Down
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
this->shape.move(0.f, +this->movementSpeed);
}
}
void Player::updateWindowBoundCollision(const sf::RenderTarget* target)
{
sf::FloatRect playerBounds = this->shape.getGlobalBounds();
//Left
if (playerBounds.left <= 0.f)
this->shape.setPosition(0.f, playerBounds.top);
//Right
else if (playerBounds.left + playerBounds.width >= target->getSize().x)
this->shape.setPosition(target->getSize().x - playerBounds.width, playerBounds.top);
//Top
if (playerBounds.top <= 0.f)
this->shape.setPosition(playerBounds.left, 0.f);
//Bottom
else if (playerBounds.top + playerBounds.height >= target->getSize().y)
this->shape.setPosition(playerBounds.left, target->getSize().y - playerBounds.height);
}
void Player::update(const sf::RenderTarget* target)
{
// Window bonds collision
this->updateWindowBoundCollision(target);
this->updateInput();
}
void Player::render(sf::RenderTarget* target)
{
target->draw(this->shape);
}