-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsprite.cpp
79 lines (68 loc) · 2.33 KB
/
sprite.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
73
74
75
76
77
78
79
#include <cmath>
#include <random>
#include <functional>
#include "sprite.h"
#include "gameData.h"
#include "imageFactory.h"
Vector2f Sprite::makeVelocity(int vx, int vy) const {
float newvx = Gamedata::getInstance().getRandFloat(vx-50,vx+50);;
float newvy = Gamedata::getInstance().getRandFloat(vy-50,vy+50);;
newvx *= [](){ if(rand()%2) return -1; else return 1; }();
newvy *= [](){ if(rand()%2) return -1; else return 1; }();
return Vector2f(newvx, newvy);
}
Sprite::Sprite(const string& n, const Vector2f& pos, const Vector2f& vel,
const Image* img):
Drawable(n, pos, vel),
image( img ),
worldWidth(Gamedata::getInstance().getXmlInt("view/width")),
worldHeight(Gamedata::getInstance().getXmlInt("view/height"))
{ }
Sprite::Sprite(const std::string& name) :
Drawable(name,
Vector2f(Gamedata::getInstance().getXmlInt(name+"/startLoc/x"),
Gamedata::getInstance().getXmlInt(name+"/startLoc/y")),
Vector2f(
Gamedata::getInstance().getXmlInt(name+"/speedX"),
Gamedata::getInstance().getXmlInt(name+"/speedY"))
),
image( ImageFactory::getInstance().getImage(name) ),
worldWidth(Gamedata::getInstance().getXmlInt("view/width")),
worldHeight(Gamedata::getInstance().getXmlInt("view/height"))
{ }
Sprite::Sprite(const Sprite& s) :
Drawable(s),
image(s.image),
worldWidth(Gamedata::getInstance().getXmlInt("view/width")),
worldHeight(Gamedata::getInstance().getXmlInt("view/height"))
{ }
Sprite& Sprite::operator=(const Sprite& rhs) {
Drawable::operator=( rhs );
image = rhs.image;
worldWidth = rhs.worldWidth;
worldHeight = rhs.worldHeight;
return *this;
}
inline namespace{
constexpr float SCALE_EPSILON = 2e-7;
}
void Sprite::draw() const {
if(getScale() < SCALE_EPSILON) return;
image->draw(getX(), getY(), getScale());
}
void Sprite::update(Uint32 ticks) {
Vector2f incr = getVelocity() * static_cast<float>(ticks) * 0.001;
setPosition(getPosition() + incr);
if ( getY() < 0) {
setVelocityY( std::abs( getVelocityY() ) );
}
if ( getY() > worldHeight-getScaledHeight()) {
setVelocityY( -std::abs( getVelocityY() ) );
}
if ( getX() < 0) {
setVelocityX( std::abs( getVelocityX() ) );
}
if ( getX() > worldWidth-getScaledWidth()) {
setVelocityX( -std::abs( getVelocityX() ) );
}
}