blob: c52807a1118eead3246d2d5459f1a8ac4a7aebf6 (
plain) (
blame)
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
|
#include "sprite.h"
#include <SDL_image.h>
#include <fstream>
#include <list>
#include <regex>
#include "util.h"
Sprite::Sprite(std::string_view filename, Renderer& renderer) {
std::ifstream datafile(filename.data());
if (!datafile.is_open()) {
throw std::invalid_argument(std::string("Could not find sprite datafile: ") + std::string(filename));
}
char ch;
std::string imagename;
datafile >> imagename;
textureId_ = renderer.loadImageFromFile(imagename);
datafile >> size_.w();
datafile >> ch; //,
datafile >> size_.h();
std::string animLine;
std::getline(datafile, animLine); // blank
while (std::getline(datafile, animLine)) {
std::regex re(R"(([a-z]+)\[([a-z_]+)\]: ([0-9,]+))");
std::smatch m;
std::regex_match(animLine, m, re);
std::vector<int> frames;
auto framestrs = splitStr<std::list<std::string>>(m[3], ",");
for (const std::string& f : framestrs) {
frames.push_back(std::stoi(f));
}
int animId = animations_.size();
animations_.push_back(std::move(frames));
Direction dir = directionFromString(std::string(m[2]));
stateDirToAnim_[m[1]][dir] = animId;
}
updateAnimation();
}
void Sprite::setDirection(Direction dir) {
if (curDir_ != dir) {
curDir_ = dir;
updateAnimation();
}
}
void Sprite::setState(std::string state) {
if (state_ != state) {
state_ = state;
updateAnimation();
}
}
void Sprite::updateAnimation() {
curAnim_ = stateDirToAnim_[state_][curDir_];
curFrame_ = 0;
}
void Sprite::tickAnim() {
curFrame_++;
if (curFrame_ >= animations_[curAnim_].size()) {
curFrame_ = 0;
}
}
|