-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayer.cpp
More file actions
264 lines (230 loc) · 9.78 KB
/
Copy pathPlayer.cpp
File metadata and controls
264 lines (230 loc) · 9.78 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#include <iostream>
#include "Player.hpp"
#include <SFML/Window/Keyboard.hpp>
#include <SFML/Graphics.hpp>
#include "Constants.hpp"
Player::Player(sf::Vector2f startPosition)
: texture{},
sprite( // Create a player sprite
[this]() {
if (!texture.loadFromFile("assets/images/playerSpritesheet.png"))
throw std::runtime_error("Failed to load sprite sheet");
return sf::Sprite(texture);
}()
),
heartSprite( // Create a player sprite
[this]() {
if (!heartFull.loadFromFile("assets/images/HeartFull.png"))
throw std::runtime_error("Failed to load health textures");
return sf::Sprite(heartFull);
}()
),
playerCollider(playerCollider) // Store reference to collider
{
// Create player collider
playerCollider = { Vec2(startPosition.x, startPosition.y), { Vec2(-50, -50), Vec2(50, 50) } };
// Set start position of player
sprite.setPosition(startPosition);
// Size of textures in the spritesheet
spriteSize = PLAYER_SPRITE_SIZE;
// Colour tint of character
baseColour = PLAYER_BASE_COLOUR;
// Set up sprite
sprite.setOrigin({spriteSize / 2.0f, (spriteSize + spriteSize / 2) / 2.0f});
sprite.setTexture(texture);
sprite.setTextureRect({{485, 1}, {spriteSize, spriteSize}});
sprite.setScale({0.8f,0.8f});
// Set health textures
heartSprite.setScale({0.2f, 0.2f});
if (!heartFull.loadFromFile("assets/images/HeartFull.png") || !heartEmpty.loadFromFile("assets/images/HeartEmpty.png")) {
throw std::runtime_error("Failed to load health textures");
}
// Set health
maxHealth = PLAYER_MAX_HEALTH;
health = PLAYER_MAX_HEALTH;
// Set gold
gold = 0;
// Default movement speed
verticalSpeed = PLAYER_V_SPEED;
horizontalSpeed = PLAYER_H_SPEED;
movement = {horizontalSpeed, 0};
moving = false;
// Timer for animations and delays
timer = PLAYER_TIMER;
timerMax = PLAYER_TIMER_MAX;
// When x coordinates have reached the final column
finalColumn = PLAYER_FINAL_COLUMN;
finalRow = PLAYER_FINAL_ROW;
// Coordinates for current texture in spritesheet
auto coords = playerAnimationTable.at({Action::Standing, Direction::South});
textureX = coords.xStart;
textureY = coords.yStart;
}
// Take damage until no health left, with a 1 second delay between damage
void Player::takeDamage(int amount) {
if (damageClock.getElapsedTime() >= damageCooldown) {
health -= amount;
damageClock.restart();
}
}
// Heal player until max health
void Player::heal(int amount) {
health += amount;
if (health > maxHealth) health = maxHealth;
}
void Player::addGold(int amount) {
gold += amount;
}
bool Player::spendGold(int amount) {
if (gold >= amount) {
gold -= amount;
return true;
}
return false;
}
void Player::setGold(int amount) {
gold = amount;
}
void Player::handleInput() {
auto pressed = [&](sf::Keyboard::Scancode key1, std::optional<sf::Keyboard::Scancode> key2 = std::nullopt) {
if (sf::Keyboard::isKeyPressed(key1)) return true;
if (key2 && sf::Keyboard::isKeyPressed(*key2)) return true;
return false;
};
// Set up possilbe key combinations to related directions and movement values
struct InputMapping {
bool condition;
Direction dir;
sf::Vector2f baseMovement;
};
std::vector<InputMapping> mappings = {
{ (pressed(sf::Keyboard::Scan::Right, sf::Keyboard::Scan::D) && pressed(sf::Keyboard::Scan::Up, sf::Keyboard::Scan::W)), Direction::NorthEast, { horizontalSpeed / 1.5f, -verticalSpeed / 1.5f } },
{ (pressed(sf::Keyboard::Scan::Right, sf::Keyboard::Scan::D) && pressed(sf::Keyboard::Scan::Down, sf::Keyboard::Scan::S)), Direction::SouthEast, { horizontalSpeed / 1.5f, verticalSpeed / 1.5f } },
{ (pressed(sf::Keyboard::Scan::Left, sf::Keyboard::Scan::A) && pressed(sf::Keyboard::Scan::Up, sf::Keyboard::Scan::W)), Direction::NorthWest, { -horizontalSpeed / 1.5f, -verticalSpeed / 1.5f } },
{ (pressed(sf::Keyboard::Scan::Left, sf::Keyboard::Scan::A) && pressed(sf::Keyboard::Scan::Down, sf::Keyboard::Scan::S)), Direction::SouthWest, { -horizontalSpeed / 1.5f, verticalSpeed / 1.5f } },
{ pressed(sf::Keyboard::Scan::Right, sf::Keyboard::Scan::D), Direction::East, { horizontalSpeed, 0.0f } },
{ pressed(sf::Keyboard::Scan::Up, sf::Keyboard::Scan::W), Direction::North, { 0.0f, -verticalSpeed } },
{ pressed(sf::Keyboard::Scan::Down, sf::Keyboard::Scan::S), Direction::South, { 0.0f, verticalSpeed } },
{ pressed(sf::Keyboard::Scan::Left, sf::Keyboard::Scan::A), Direction::West, { -horizontalSpeed, 0.0f } }
};
bool moved = false;
for (auto& m : mappings) {
if (m.condition) {
moved = true;
moving = true;
currentDirection = m.dir;
movement = m.baseMovement;
timer += 0.08f;
// Play movement animation
if (timer >= timerMax) {
Action action = sprinting ? Action::Sprint : Action::Jog; // Check if sprinting or jogging
auto coords = playerAnimationTable.at({action, currentDirection});
animate(coords.xStart, coords.xEnd, coords.yStart, coords.yEnd);
if (sprinting) movement *= 4.0f; // Increase movement speed if sprinting
textureX += spriteSize; // Increment through textures
timer = 0.0f;
}
sprite.move(movement); // Move player
break;
}
}
if (!moved) {
movement = {0.0f, 0.0f};
moving = false;
}
// If space pressed then attack and change to attack animation
if (pressed(sf::Keyboard::Scan::Space)) {
attacking = true;
timer += 0.08f;
if (timer >= timerMax) {
auto coords = playerAnimationTable.at({Action::Attack, currentDirection});
animate(coords.xStart, coords.xEnd, coords.yStart, coords.yEnd);
textureX += spriteSize;
timer = 0.0f;
}
} else {
attacking = false;
}
}
// Reusable function for animating player
void Player::animate(int xStart, int xEnd, int yStart, int yEnd) {
// If current texture coordinates outside of expected values then use start coordinates
if(textureY == yStart) {if(textureX < xStart) {textureX = xStart; textureY = yStart;}} // If column is before start of anim
if(textureY == yEnd) {if(textureX > xEnd) {textureX = xStart; textureY = yStart;}} // If column is past end of anim
if(textureY < yStart || textureY > yEnd) {textureX = xStart; textureY = yStart;} // If row is before or after anim
if(textureY != yStart && textureY != yEnd) {textureX = xStart; textureY = yStart;} // Row value is invalid
// If x is at final column, switch to next row
if (textureX > finalColumn) { textureX = 0; textureY += spriteSize;}
// If y is at final row, then use start coordinates
if (textureY > finalRow) {textureX = xStart; textureY = yStart;}
// If x value is valid, then change current sprite texture coordinates
if (textureX <= finalColumn) {
sprite.setTextureRect({{textureX, textureY}, {spriteSize, spriteSize}});
}
}
// Sprint movement boolean, to be called true from main when user double tabs movement keys
void Player::sprint(bool sprint) {
if (sprint) {
sprinting = true;
} else {
sprinting = false;
}
}
// Checking for changes to player
void Player::update(float deltaTime) {
// If player is not moving then change player to standing pose
if (moving == false && attacking == false) {
auto coords = playerAnimationTable.at({Action::Standing, currentDirection});
textureX = coords.xStart; textureY = coords.yStart;
sprite.setTextureRect({{textureX, textureY}, {spriteSize, spriteSize}});
}
// Indicate damage by turning sprite red
if (damageClock.getElapsedTime() >= damageCooldown - sf::seconds(0.7f)) {
sprite.setColor(baseColour);
} else {
sprite.setColor(sf::Color::Red);
}
// Sync sprite with collider
sprite.setPosition(toSF(playerCollider.pos));
}
// For drawing player in main
// Draw shadow seperately
void Player::drawShadow(sf::RenderWindow& window) {
// Add shadow under character
sf::CircleShape shadow(spriteSize / 5.f);
shadow.setFillColor(sf::Color(0, 0, 0, 100));
shadow.setOrigin({spriteSize / 2.0f, (spriteSize + spriteSize / 2) / 2.0f});
shadow.setScale({1.0f, 0.4f});
sf::Vector2f position = sprite.getPosition();
shadow.setPosition({position.x + spriteSize / 3.18f, position.y + spriteSize / 2.6f});
window.draw(shadow);
}
// Draw player sprite
void Player::draw(sf::RenderWindow& window) {
window.draw(sprite);
}
// Draw user interface features
void Player::drawUI(sf::RenderWindow& window, const sf::View& camera) {
const sf::Font font("assets/fonts/MagicSchoolOne.ttf");
// Set up UI
// Draw health bar at top left of camera
sf::Vector2f cameraLocation = camera.getCenter() - (camera.getSize() / 2.f);
for (int i = 0; i < maxHealth; ++i) {
heartSprite.setTexture(i < health ? heartFull : heartEmpty);
heartSprite.setPosition({
cameraLocation.x + 10.f + i * 60.f,
cameraLocation.y + 10.f
});
window.draw(heartSprite);
}
// Draw gold text at top-right
sf::Text goldText(font, "Gold: " + std::to_string(Player::getGold()), 44); // Set text string, font, character size
goldText.setFillColor(sf::Color::Yellow);
sf::FloatRect textBounds = goldText.getLocalBounds();
goldText.setOrigin(textBounds.size);
goldText.setPosition({
cameraLocation.x + camera.getSize().x - 10.f,
cameraLocation.y + 37.f
});
window.draw(goldText);
}