-
Notifications
You must be signed in to change notification settings - Fork 1
/
PlayState.cpp
109 lines (91 loc) · 2.73 KB
/
PlayState.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
105
106
107
108
109
#include "PlayState.h"
#include "TextureManager.h"
#include "Game.h"
#include "InputHandler.h"
#include <iostream>
const string PlayState::s_playID = "PLAY";
using namespace std;
PlayState::PlayState()
{
//ctor
}
void PlayState::update()
{
//input behaviour
if(TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE))
{
TheGame::Instance()->getStateMachine()->pushState(new PauseState());
}
//update GameObjects
for(int i = 0; i < m_gameObjects.size(); i++)
{
m_gameObjects[i]->update();
}
//Collision detection
if(checkCollision(dynamic_cast<SDLGameObject*>(m_gameObjects[0]), dynamic_cast<SDLGameObject*>(m_gameObjects[1])))
{
TheGame::Instance()->getStateMachine()->pushState(new GameOverState());
}
}
void PlayState::render()
{
for (int i = 0; i < m_gameObjects.size(); i++)
{
m_gameObjects[i]->draw();
}
}
bool PlayState::onEnter()
{
if(!TheTextureManager::Instance()->load("img/helicopter.png","helicopter", TheGame::Instance()->getRenderer())) //can't load images
{
return false;
}
if(!TheTextureManager::Instance()->load("img/helicopter2.png", "helicopter2", TheGame::Instance()->getRenderer()))
{
return false;
}
GameObject* player = new Player (new LoaderParams(100, 100, 128, 55, 5, "helicopter"));
GameObject* enemy = new Enemy (new LoaderParams(500, 100, 128, 55, 5, "helicopter2"));
m_gameObjects.push_back(player);
m_gameObjects.push_back(enemy);
cout << "Entering PlayState" << endl;
return true;
}
bool PlayState::onExit()
{
for (int i = 0; i < m_gameObjects.size(); i++) //clear all existing gameObjects
{
m_gameObjects[i]->clean();
}
m_gameObjects.clear(); //clear vector
//clean textures
TheTextureManager::Instance()->clearFromTextureMap("helicopter");
cout << "exiting PlayState " << endl;
return true;
}
string PlayState::getStateID() const
{
return s_playID;
}
bool PlayState::checkCollision(SDLGameObject* p1, SDLGameObject* p2)
{
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
//Calculate sides of rect b
leftA = p1->getPosition().getX();
rightA = p1->getPosition().getX() + p1->getWidth();
topA = p1->getPosition().getY();
bottomA = p1->getPosition().getY() + p1->getHeight();
//Calculate sides of rect b
leftB = p2->getPosition().getX();
rightB = p2->getPosition().getX() + p2->getWidth();
topB = p2->getPosition().getY();
bottomB = p2->getPosition().getY() + p2->getHeight();
//check collision
if (bottomA <= topB or topA >= bottomB or rightA <= leftB or leftA >= rightB) //no collision
return false;
else
return true;
}