C++ how to prevent import loops - c++

I am a bit in the dark for the moment so I am trying stack overflow. My problem is that I have a classed named ‘Scene’ which will have a map of ‘GameObject’. The problem is that these GameObject need to use some function from there scene so I create a Scene* that is assigned to the main scene. The problem with this case is that I a in a loop where I import Scene which include GameObject which include Scene (and it goes on). If you think 5isnis not clear feel free to comment I will give more detail or edit this post thx.
Scene.h
class Scene
{
public:
sf::RenderWindow* window;
_Manager manager;
sf::Color backgroundColor;
std::string name;
std::map<std::string, GameObject*> gameObjects;
Scene();
Scene(std::string name);
virtual void Start() = 0;
virtual void Update() = 0;
virtual void Draw() = 0;
void _Update();
};
GameObject.h
class GameObject : public Object
{
private:
Scene* scene;
std::vector<Component*> components;
public:
Transform* transform = new Transform;
void AddComponent(Component* component);
Component* GetComponent(std::string type);
GameObject* Find();
void Instantiate(GameObject* gm, Transform* transform);
void Start();
void Update();
};

For those who got the same problem i just forgot you can do forward declaration and when you need to use the full class just import the files you need in the .cpp file of your class.

Related

SFML- Missing ';' before identifier

I want Player to create an object of the class Bullet.
Result:
syntax error : missing ';' before identifier 'bullet'
From what i've can find about the issue is that the Bullet class isn't known to the compiler at that point,
how do i make it known?
Player class
class Player :public Entity{
private:
float velocity;
Sprite titleSprite;
Texture titleTexture;
Sprite playerSprite;
Texture playerTexture;
Bullet bullet; // <-----------
public:
virtual void draw(RenderTarget& target, RenderStates states)const;
virtual void update(float dt);
void movePlayer(float offset);
Sprite getPlayerSprite()const;
Sprite getTitleSprite()const;
Bullet getBullet();
Player();
virtual ~Player();
};
Bullet class
#include "Player.h"
class Bullet : public Entity{
private:
Sprite bulletSprite;
Texture bulletTextucre;
public:
void shootBullet(float offset);
Sprite getBulletSprite()const;
Sprite getBulletTexture();
void setBulletSprite(Sprite bulletSprite);
virtual void draw(RenderTarget& target, RenderStates states)const;
virtual void update(float dt);
Bullet();
virtual ~Bullet();
};
Looks like Bullet class doesn't include Entity.h
#include Bullet.h header inside the Player header file.
And remove #include "Player.h" from the Bullet header if you're not using anything from that class.

C++ creating an instance of a class

class Game {
private:
string title;
bool running;
State currentState;
public:
sf::RenderWindow window;
void setup();
void run();
};
I have a variable called currentState. This is State:
#ifndef STATE_HPP
#define STATE_HPP
using namespace std;
class State {
private:
public:
void start();
void update();
void render();
};
#endif
And then I have a class called PlayState, which inherits State:
#ifndef PLAY_STATE_HPP
#define PLAY_STATE_HPP
#include <SFML/Graphics.hpp>
#include "Game.hpp"
#include "State.hpp"
using namespace std;
class PlayState : public State {
private:
sf::CircleShape shape;
Game game;
public:
PlayState();
void start();
void update();
void render();
};
#endif
On my Game.cpp, I am creating currentState, by doing:
currentState = PlayState();
The problem is, though, that it's not working. currentState.update() is state.update(). It seems that I am not overriding the State methods when I create PlayState.
Here's PlayState.cpp:
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <stdio.h>
#include "PlayState.hpp"
PlayState::PlayState() {
printf("heyyy\n");
}
void PlayState::start() {
shape.setRadius(100.f);
shape.setOrigin(20.0f, 20.0f);
shape.setFillColor(sf::Color::Green);
}
void PlayState::update() {
sf::Event event;
while (game.window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
game.window.close();
//running = false;
}
}
printf("here\n");
}
void PlayState::render() {
printf("here\n");
game.window.clear();
game.window.draw(shape);
game.window.display();
}
Any ideas about how I can 'override' those methods? Thank you.
EDIT
I had to make State.cpp functions virtual so that they can be overriden.
I also had to define State *currentState as a pointer and create PlayState with "currentState = new PlayState();".
Also, now I access .update and .draw with ->update() and ->draw().
Two problems. As #McAden said, the functions in State that are to be overridden in PlayState need to be marked virtual. The other problem is that the data member currentState in Game has type State. When you assign an object of type PlayState to it, it gets the State part of the PlayState object, but not the derived parts. This is called "slicing". To prevent it, make currentState a pointer to State, and when you create that PlayState object, assign its address to the Game object's currentState.
What you're looking for is the concept of virtual functions.
Wikipedia entry
State needs:
virtual void update();
PlayState needs:
void update();
You need to make your function's with the virtual modifier ie.
virtual void Update();
When calling currentState->Update() this will call the topmost overridden function, if you desire to call any of the parent classes functions inside of the classes methods simply specify ie. State::Update(); when calling the function.

Inheriting base class, defining the base class' prototype method but calling child class' method from third object

I have a class called "Game", with prototypes functions "Update" and "Draw" but they're not defined. It's up to the object inheriting the "Game" object to override them. Is this possible?
Contents of "Game.h"
class Game // does it have to abstract/virtual?
{
public:
//General stuff for all games here
}
void Update(Game *game) = 0; // or make it virtual in someway
Contents of "MyGame.h"
#include "Game.h"
class MyGame : public Game
{
public:
// General stuff for my game
}
void Update(MyGame *game);
// Contents of "MyGame.cpp"
#include "MyGame.h"
void Update(MyGame *game) // does it have to be overriden/overloaded?
{
}
// Contents of "GameManager.h"
#include "Game.h"
class GameManager
{
public:
Game *game;
}
void Update(GameManager *manager);
// Contents of "GameManager.cpp"
#include "Game.h"
void Update(GameManager *manager)
{
Update(manager->game);
}
The key is the last method:
Why can't GameManager call MyGame Update() method when GameManager's Game object = MyGame and not Game?
Define Draw and Update as virtual methods in the base class Game.
class Game
{
public:
virtual void Draw() {};
};
class MyGame : public Game
{
public:
virtual void Draw() {}
};
void callDraw(Game* game)
{
game->Draw();
}
//...
Game* game = new MyGame;
callDraw(game);
The last call will call the method in MyGame although it's called on a Game pointer.

Create a sprite from a class that inherits CCSprite

I have a Balloon class (see this) that inherits from CCSprite. I have given it properties like balloonSpeed and balloonStrength. I seem to be having problems in it, though.
What I want to do is that when I make an instance of the Balloon class, I want it to do the following:
Give it a texture (a PNG file of a balloon).
Set properties like balloonSpeed and balloonStrength.
Add actions to make it move and accept touch input.
When the object is touched, I want to:
Count if # of taps = balloonStrength. if so, destroy Balloon.
I have done a simpler version of this where a Balloon object is destroyed when it is touched. I want to apply OOP and custom classes here but I can't seem to get the right way of doing it.
Thanks in advance.
then the h file should looks like below:
#include "cocos2d.h"
using namespace cocos2d;
class Balloon : public cocos2d::CCSprite, public CCTargetedTouchDelegate {
public:
float balloonSpeed;
int balloonStrength;
int numberOfTaps;
virtual void onEnter();
virtual void onExit();
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
};
and in your touch method:
bool Balloon::ccTouchBegan(CCTouch* touch, CCEvent* event){
CCPoint touchLocation = this->getParent()->convertTouchToNodeSpace(touch);
if (CCRect::CCRectContainsPoint(this->boundingBox(), touchLocation)) {
this->numberOfTaps++;
if(this->balloonStrength == this->numberOfTaps){
this->removeFromParentAndCleanup(true);
}
}
return true;
}
you can use it after you add the blueBalloon as a child of a layer or node as below:
blueBalloon->balloonSpeed = 2.0f;
blueBalloon->numberOfTaps = 0;
blueBalloon->balloonStrength = 5;

i need help implementing my event manager and engine system (SDL && C++)

i need help with my attempt at writing a reusable game engine. it's not the best engine, but i definitely think it will be reusable once i am done. i am not asking for code or to be spoonfed, but i am asking for some advice :-).
my current layout:
i have an engine class, a game class, and an event manager class. the engine class extends the event manager class, and the game class extends the engine class. here is my current code for these 3 classes (ignore the Graphics class--it is just a reusable class i use to avoid rewriting fullscreen, initialize, and resize screen functions).
ENGINE.HPP
#ifndef _ENGINE_HPP
#define _ENGINE_HPP
#pragma once
#include <SDL/SDL.h>
#include "event_manager.hpp"
enum
{
ENGINE_SUCCESS = 0,
ENGINE_INITIALIZATION_ERROR
};
class Engine : public EventManager
{
public:
Engine();
virtual ~Engine();
int exec();
void handle_event(SDL_Event *);
void update_engine();
virtual bool init();
virtual void render();
virtual void update();
virtual void clean();
bool running_;
};
ENGINE.CPP
#include "./engine.hpp"
Engine::Engine()
{
running_ = false;
}
Engine::~Engine()
{
}
int Engine::exec()
{
if (!init())
{
clean();
return ENGINE_INITIALIZATION_ERROR;
}
SDL_Event event;
while (running_)
{
while (SDL_PollEvent(&event))
handle_event(&event);
update();
render();
}
clean();
return ENGINE_SUCCESS;
}
void update_engine()
{
}
void handle_event(SDL_Event *event)
{
EventManager::handle_event(event);
}
bool init() {return true;}
void render() {}
void update() {}
void clean() {}
EVENT_MANAGER.HPP
#ifndef _EVENT_MANAGER_HPP
#define _EVENT_MANAGER_HPP
#pragma once
#include <SDL/SDL.h>
class EventManager
{
public:
EventManager();
virtual ~EventManager();
virtual void handle_event(SDL_Event *);
// events here
virtual void event_exit();
};
#endif
EVENT_MANAGER.CPP
#include "./event_manager.hpp"
EventManager::EventManager()
{
}
EventManager::~EventManager()
{
}
void EventManager::handle_event(SDL_Event *event)
{
switch (event->type)
{
case SDL_QUIT:
event_exit();
break;
}
}
void on_exit() {}
GAME.HPP
#ifndef _GAME_HPP
#define _GAME_HPP
#include "./engine.hpp"
#include "./entity.hpp"
#include "./graphics.hpp"
class Game : public Engine
{
public:
Game();
bool init();
void render();
void update();
void clean();
private:
Graphics g;
};
#endif
GAME.CPP
#include "./game.hpp"
int main(int argc, char **argv)
{
Engine engine;
return engine.exec();
}
Game::Game() {}
bool Game::init()
{
if (!g.init(800, 600, 32, g.screen_flags()))
{
return false;
}
SDL_WM_SetCaption("Title", NULL);
return true;
}
void Game::update()
{
Engine::update_engine();
}
void Game::clean()
{
SDL_FreeSurface(g.screen_);
SDL_Quit();
}
void Game::render()
{
SDL_Flip(g.screen_);
}
i am getting this error:
engine.cpp: In function ‘void handle_event(SDL_Event*)’:
engine.cpp:40: error: cannot call member function ‘virtual void
EventManager::handle_event(SDL_Event*)’ without object
why is this happening? shouldn't i be able to do EventManager:: if the I did
class Engine : public EventManager
???
that is the only error i get, i am sure it is something simple. now i need a little bit of advice.
instead of handling events like
void Engine::event_exit()
in the engine, i'd rather do it in the game class.
class Game : public Engine
void Game::event_exit()
if that doesn't make sense, notice how i made Engine extend EventManager, and my Game class extends Engine
class Engine : public EventManager
class Game : public Engine
would it work if i called the snippet above these ^ two snippets? i can't test it because i get that error.
Happens to the best of us, but I think it's just a matter of forgetting to specify namespaces. When you implement the functions in engine.cpp, you forgot to prepend Engine::, so the code should be:
void Engine::update_engine()
{
}
void Engine::handle_event(SDL_Event *event)
{
EventManager::handle_event(event);
}
It's a classic case of C++ error messages not really telling you the root of the error.
A short explanation, just in case:
The compiler tried to compile the function void handle_event(SDL_Event *event), and saw a call to a method EventManager::handle_event(event);. Since the compiler thought the function was not part of the Engine class, it would expect you to call the method of a particular instance of the EventManager class, i.e.
someEventManager->handle_event(event);
As soon as you specify that the implementation you wrote is that of a method, belonging to the class Engine, the compiler essentially deduces:
void Engine::handle_event(SDL_Event *event)
{
this->EventManager::handle_event(event);
}
And therefore is happy.