-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathenemy.cpp
More file actions
88 lines (79 loc) · 1.58 KB
/
enemy.cpp
File metadata and controls
88 lines (79 loc) · 1.58 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
#include "enemy.hpp"
Enemy::Enemy(SDL_Surface* display, Foreground* foreground)
{
this->display = display;
this->foreground = foreground;
this->sprite = NULL;
px = 0;
py = 0;
vy = 0;
vx = 16;
width = height = 0;
animation_time = 0;
death_animation = 0;
}
Enemy::~Enemy()
{
if(sprite != NULL)
SDL_FreeSurface(sprite);
}
bool Enemy::loadSprite(std::string filename, int width, int height)
{
this->width = width;
this->height = height;
if(sprite != NULL)
SDL_FreeSurface(sprite);
if((sprite = IMG_Load(filename.c_str())) != NULL)
return true;
else
return false;
}
void Enemy::setMapPosition(int x, int y)
{
px = x * 256;
py = y * 256;
}
int Enemy::update()
{
if(!death_animation)
{
// gravity
vy = vy >= 64 ? 64 : vy + 16;
while(foreground->collision(px/16, (py+vy)/16, width, height))
{
if(vy > 0)
{
vy--;
} else {
vy = 8;
}
}
py += vy;
// horizontal movement
if(foreground->collision((px+vx)/16, py/16, width, height))
vx = -vx;
px += vx;
} else {
if(death_animation-- == 1)
return -1;
else
return 1;
}
return 0;
}
void Enemy::draw(int x, int y)
{
if(animation_time++ > 15)
animation_time = 0;
SDL_Rect src = { death_animation ? 64 : (animation_time > 7 ? 16 : 0) + (vx > 0 ? 32 : 0), 0, 16, 16 };
SDL_Rect dst = { px/16 - x, py/16 - y, 16, 16 };
SDL_BlitSurface(sprite, &src, display, &dst);
}
void Enemy::hit()
{
death_animation = 32;
}
Box Enemy::getBbox()
{
return Box(px / 16, px / 16 + width, py / 16, py / 16 + height);
}