-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsprite.cpp
More file actions
65 lines (56 loc) · 2.04 KB
/
sprite.cpp
File metadata and controls
65 lines (56 loc) · 2.04 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
#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, float scale):
Drawable(n, pos, vel, scale),
image( img ),
worldWidth(Gamedata::getInstance().getXmlInt("world/width")),
worldHeight(Gamedata::getInstance().getXmlInt("world/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")),
Gamedata::getInstance().getXmlFloat(name+"/scale")
),
image( ImageFactory::getInstance().getImage(name) ),
worldWidth(Gamedata::getInstance().getXmlInt("world/width")),
worldHeight(Gamedata::getInstance().getXmlInt("world/height"))
{ }
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() ) );
}
}