-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.cpp
104 lines (96 loc) · 2.15 KB
/
player.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
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
#include "player.h"
player::player()
{
playerX = playerY = pVelX = pVelY = 0;
}
player::~player()
{
playerTexture.free();
}
void player::handleEvent(SDL_Event& e)
{
if( e.type == SDL_KEYDOWN && e.key.repeat == 0)
{
switch(e.key.keysym.sym)
{
case SDLK_w:
pVelY -= PLAYER_VEL;
break;
case SDLK_s:
pVelY += PLAYER_VEL;
break;
case SDLK_a:
pVelX -= PLAYER_VEL;
break;
case SDLK_d:
pVelX += PLAYER_VEL;
break;
}
}
else if(e.type == SDL_KEYUP && e.key.repeat == 0)
{
switch(e.key.keysym.sym)
{
case SDLK_w:
pVelY += PLAYER_VEL;
break;
case SDLK_s:
pVelY -= PLAYER_VEL;
break;
case SDLK_a:
pVelX += PLAYER_VEL;
break;
case SDLK_d:
pVelX -= PLAYER_VEL;
break;
}
}
}
void player::move()
{
playerX += pVelX;
playerY += pVelY;
if((playerX < 0) || (playerX + PLAYER_WIDTH > SCREEN_WIDTH))
{
playerX -= pVelX;
}
if((playerY < 0) || (playerY + PLAYER_HEIGHT > SCREEN_HEIGHT))
{
playerY -= pVelY;
}
}
void player::loadPlayer(SDL_Renderer* renderer)
{
playerTexture.loadFromFile( "images/sprites/tree1.png",renderer );
}
void player::render(SDL_Renderer* renderer)
{
playerTexture.render(playerX,playerY,NULL,0.0,NULL,SDL_FLIP_NONE,renderer);
}
void player::freePlayer()
{
playerTexture.free();
}
void player::setCamera(SDL_Rect& camera)
{
camera.x = (playerCollisionBox.x + PLAYER_WIDTH/2) - SCREEN_WIDTH/2;
camera.y = (playerCollisionBox.y + PLAYER_HEIGHT/2) - SCREEN_HEIGHT/2;
//make sure player doesn't leave top or left side of screen
if(camera.x < 0)
{
camera.x = 0;
}
if(camera.y < 0)
{
camera.y=0;
}
//screen width,height should be replaced by level width, height.
if(camera.x>SCREEN_WIDTH-camera.w)
{
camera.x=SCREEN_WIDTH-camera.w;
}
if(camera.y>SCREEN_HEIGHT-camera.h)
{
camera.y=SCREEN_HEIGHT-camera.h;
}
}