Constructor not drawing borders. (my mini game) - c++

I'm trying to make a mini game in c++ and i have encountered a problem. I am currently trying to make a board for my game and i've made a function to draw the borders but i don't want to call it, i want it to be called by the constructor.
Board.h :
class Board
{
public:
Board(Graphics& out_gfx);
private:
void DrawBoardBorder();
Graphics& in_gfx;
Color borderColor = Colors::MakeRGB(94,35,113);
};
Board.cpp :
Board::Board(Graphics & out_gfx)
:
in_gfx(out_gfx)
{
DrawBoardBorder();
}
The borders are drawn correctly if the function is moved to public and called with the help of the object, but the borders are not drawn if i let the constructor do the job. Why?

Related

TouchGFX widget visible on empty screen

I'm evaluating the TouchGFX tool additional to the STM32-Platform.
Everything works "fine", like the interaction with some hardware resources of the STM32F746G-Discovery board, but there is another issue.
I created a custom keyboard (as seen as in the TouchGFX examples), but even before I enter the last Screen, where it should be visible, it appears on the screen before.
I checked the View.hpp/.cpp and ViewBase.hpp/.cpp of both screens and I don't know why it is as it is.
Screen3View.hpp (Where the keyboard should be visible)
#ifndef SCREEN3VIEW_HPP
#define SCREEN3VIEW_HPP
#include <gui_generated/screen3_screen/Screen3ViewBase.hpp>
#include <gui/screen3_screen/Screen3Presenter.hpp>
#include <gui_generated/screen3_screen/Screen3ViewBase.hpp>
#include <gui/screen3_screen/Screen3Presenter.hpp>
#include <gui/common/CustomKeyboard.hpp>
#include <touchgfx/widgets/ButtonWithLabel.hpp>
class Screen3View : public Screen3ViewBase
{
public:
Screen3View();
virtual ~Screen3View() {}
virtual void setupScreen();
virtual void tearDownScreen();
protected:
CustomKeyboard keyboard;
};
#endif // SCREEN3VIEW_HPP
Screen3View.cpp
Screen3View::Screen3View()
{
keyboard.setPosition(16, 16, 400, 240);
add(keyboard);
}
Screen4View.hpp (where the keyboard should not be visible)
#ifndef SCREEN4VIEW_HPP
#define SCREEN4VIEW_HPP
#include <gui_generated/screen4_screen/Screen4ViewBase.hpp>
#include <gui/screen4_screen/Screen4Presenter.hpp>
class Screen4View : public Screen4ViewBase
{
public:
Screen4View();
virtual ~Screen4View() {}
virtual void setupScreen();
virtual void tearDownScreen();
protected:
};
#endif // SCREEN4VIEW_HPP
Screen4View.cpp
Screen4View::Screen4View()
{
}
all other.cpp of the TouchGFX files "say" the exact same thing.
Just Screen 3 should have this keyboard, and not Screen 4 too.
So if anybody has an idea why it is like that please answer. :)
Thank you very much.
When you "switch screens" in a TouchGFX application this new frame will be rendered to some framebuffer memory (the complexity of running a simulator vs target hardware with multiple framebuffers is irrelevant when it comes to explaining what you're seeing).
When you activate a screen that renders nothing (like Screen4 since it has no widgets) you're basically staring at the state of the framebuffer left by the previous frame (which was Screen3 with the Keyboard). Imagine if Screen4 was the first thing you were trying to render - Then you would just see garbage/uninitialized memory.
This is why you're seeing a Keyboard, even if it is not even a part of Screen4. Add a box to Screen4 covering the full dimensions of the canvas and you won't see the previous framebuffer state anymore. This would be the same for any widget.
If you compare the glass of the LCD to a window in your house, by adding a box you're basically closing the blinds to that window, now unable to see the "Keyboard" just on the other side.
zrrbyte's answer gives a nice explanation of why one would face the problem that the OP is facing. The solution given (forcing a background image on the screen) works, but an alternate solution is to fill the frame-buffer with some color. For STM32F746G-DISCO you would do it as follows:
Screen4View::Screen4View()
{
HAL::getInstance()->blitFill(0, 0, 0, 480, 272, 255);
}
This will basically force the entire LCD to be filled with black color.
The prototype for this function is in HAL.cpp:
virtual void blitFill(colortype color, uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint8_t alpha);
Practically, it won't make much of a difference whether you use zrrbyte's solution or mine - the performance for both solutions is similar.

Animation in a Qt 2D pathfinding game

I'm making a 2D grid based game in Qt.
When clicking on a square in a grid the player moves to that square following a path calculated with an A* algoritm. However I would like to be able to animate this. So instead of immediately going to the goal the player has to go from square (node) to square until it reaches the goal at a speed that the user can set.
Question: What is the easiest way to achieve this?
Personally, I'd design this similar to the following:
class Player : public QObject {
...
QPoint pos;
QList<QPoint> path;
QPropertyAnimation posAnimation;
};
Define pos as a Q_PROPERTY. This enables you to use QPropertyAnimation to define an animation on this value for animating the movement between two adjacent points. After the animation is done, take() one point from the path and reconfigure the animation, giving you an animation along the whole path.
Use a slot animationFinished() in the Player class to provide the next point to the animation.
To start such an animation, fill the path with the values (in a function move(QList<QPoint> path) or similar), set the values of the animation and start it.
These code snippets should help you:
// in constructor:
posAnimation.setPropertyName("pos");
posAnimation.setTargetObject(this);
connect(&posAnimation, SIGNAL(finished()), SLOT(animationFinished()));
// in the slot:
if(!path.empty()) {
posAnimation.setStartValue(pos());
posAnimation.setEndValue(path.takeFirst());
posAnimation.start();
}
To define pos as a property, you have to define two slots: A reading and a writing function, also known as a getter and a setter:
class Player : public QObject {
Q_OBJECT
Q_PROPERTY(QPoint pos READ pos WRITE setPos) // define meta-property "pos"
...
public slots:
QPoint pos() const; // getter
void setPos(QPoint p); // setter
private:
QPoint m_pos; // private member
};
QPoint Player::pos() const {
return m_pos;
}
void Player::setPos(QPoint pos) {
m_pos = pos;
}
The Q_PROPERTY line just declares a meta-property. This has nothing to do with C++, but Qt's meta object compiler parses this line and adds an entry to the internal property list. Then, you can say player->property("pos") to access the position instead of player->pos(). You may wonder why this is useful. It's useful whenever you only want to pass around a property name as a string, like to tell the QPropertyAnimation which property to animate. Another scenario is when using scripting like QML. Then you define properties all over your classes. You can read more about meta-properties in the Qt documentation: The Property System.
Take a look at the demo of the tower defense game Squaby made with the V-Play (v-play.net) engine. You can access the full source code here: Squaby.
V-Play provides you with game components for path finding and more (API reference).

Draw sprite in draw loop

Got a problem, when I am trying to draw a sprite in the draw loop it won't draw
In the constructor for this class I am setting the sprite.
Constructor I have:
texture.loadFromFile("img1.png");
sprite.setTexture(texture);
sprite and texture is in the header file
I did some experiments, and if I use texture.loadFromFile(); in the draw loop it works.
But then I have to "reload" the picture 60 times per second.
void PlayerReceiver::draw(sf::RenderWindow & rw){
//texture.loadFromFile("mario.png");
//std::cout<<texture.getSize().y<<std::endl;
rw.draw(sprite);
}
Thank you for answers.
Got a problem, when I am trying to draw a sprite in the draw loop it
won't draw In the constructor for this class I am setting the sprite.
From what I understand from this question, you want to load a texture and sprite inside a constructor and it's not working when you try to draw it from your draw loop.
I have a program which loads textures in the constructor and it runs fine, so what I would imagine is wrong (and I'm not sure since I don't see but six lines of your program in the above post) is that the texture and sprite objects are not defined on a class level.
Here's my header file for a texture object I'm using:
class GraphPaper
{
public:
GraphPaper();
~GraphPaper();
bool isObjectLoaded();
sf::Sprite getSprite();
private:
void load(std::string filename);
bool isLoaded;
sf::Texture texture;
sf::Sprite sprite;
const std::string file = "images/Graph-Paper.png";
};
The texture and sprite objects are listed on a class-wide level as private members and are accessed through getter methods.
And here's the constructor for that class (altered a bit to better match what you were wanting done):
#include "GraphPaper.h"
GraphPaper::GraphPaper() //: isLoaded(false)
{
if (texture.loadFromFile(file) == false)
isLoaded = false;
else
{
texture.setRepeated(true);
sprite.setTexture(texture);
isLoaded = true;
}
//load(file);
assert(isObjectLoaded());
}
After this I simply draw my "GraphPaper" object.
mainWindow.draw(paper.getSprite());
I already have access to it because I defined a "GraphPaper" object called "paper" in my MainWindow header file.
#pragma once
#include "GraphPaper.h"
#include "stdafx.h"
class MainWindow
{
public:
void close();
void start();
void moveCamera(sf::Event);
private:
bool leftMousePressed, rightMousePressed, isExiting;
int r, g, b, mouseX, mouseY;
GraphPaper paper;
const sf::Color white = sf::Color(255, 255, 255);
sf::RenderWindow mainWindow;
sf::View view;
};
Assuming this is what you are wanting to do, then your problem is likely in the header file. Any objects defined on a class level, once loaded, won't get destroyed until the class itself is destroyed. Maybe you need to make sure you aren't destroying the reference to the class that the constructor is in. For instance, if you create an instance of your class inside a loop, the moment that loop ends the class object will be destroyed.
Just a supposition: You have this in your construtor:
PlayerReceiver::PlayerReceiver()
{
sf::Texture texture;
texture.loadFromFile("img1.png");
sprite.setTexture(texture);
}
This way the texture object is destroyed right after the constructor ends. Both the sprite and the texture must be members of the class, so that they don't get destroyed until the player itself is destroyed.
If this is not your problem, then please post more code.

Pass argument to callback function COCOS2D Android

I've started working with cocos2d few days ago...and im working on small 2d game.
I figured out how to animate sprites. Now when sprite finished with animation I want it to be cleared from screen.
How to pass argument to callback function?
target.runAction(CCSequence.actions(repeatAnimation,
CCCallFuncND.action(this, "deleteTarget",target)));
Function is defined as:
public void deleteTarget(Object target)
It always gives me "NoSuchMethodException"...any idea?
Do it like this
CCCallFuncN ccfun = CCCallFuncN.action(this, "test");
public void test(Object sender) {
Do whatever you require
}

C++ / SDL encapsulation design help

So I am semi-new to C++, and completely new to SDL. Most of my conceptual knowledge of OOP comes from Java and PHP. So bear with me.
I am trying to work out some simple design logic with my program / soon to be side-scroller. My problem lies with trying to make my 'screen' layer (screen = SDL_SetVideoMode(...)) accessible to all my other classes; Hero class, background layer, enemies, etc. I have been loosely following some more procedural tutorials, and have been trying to adapt them to a more object oriented approach. Here is a little bit of what I have so far:
main.cpp
#include "Game.h"
#include "Hero.h"
int main(int argc, char* argv[])
{
//Init Game
Game Game;
//Load hero
Hero Hero(Game.screen);
//While game is running
while(Game.runningState())
{
//Handle Window and Hero inputs
Game.Input();
Hero.userInput();
//Draw
Game.DrawBackground();
Hero.drawHero();
//Update
Game.Update();
}
//Clean up
Game.Clean();
return 0;
}
As you can see, I have a Game class, and a Hero class. The Game class is responsible for setting up the initial window, and placing a background. It also updates the screen as you can see.
Now, since my Game class holds the 'screen' property, which is a handle for SDL_SetVideoMode, I am stuck passing this into any other class (ex: Hero Hero(Game.screen);) that needs to update to this screen... say via SDL_BlitSurface.
Now, this works, however I am getting the idea there has GOT to be a more elegant approach. Like possibly keeping that screen handler on the global scope (if possible)?
TLDR / Simple version: What is the best way to go about making my window / screen handler accessible to all my subsequent classes?
I like the way you are doing it.
Though rather than passing the screen reference I would pass a reference to a game itself. Thus each hero object knows which game it belongs too, it can then ask the game object for the screen as required.
The reason I would do this is so that in a few years when your game is a wide and successful product and you convert it for online-play you really need to do no work. The game server will be able to easily support multiple game objects, each game object hosting multiple hero objects. As each hero object wants to draw it asks the game for the screen abd updates the screen (the screen can now very from game object to game object and still work perfectly (as long as they have the same interface).
class Game
{
public:
Game(Screen& screen)
: screen(screen)
{}
virtual ~Game() {}
virtual Screen& screen() { return theGameScreen;}
void update() { /* Draw Screen. Then draw all the heros */ }
private:
friend Hero::Hero(Game&);
friend Hero::~Hero();
void addHero(Hero& newHero) {herosInGame.push_back(&newHero);}
void delHero(Hero& newHeor) {/* Delete Hero from herosInGame */}
// Implementation detail about how a game stores a screen
// I do not have enough context only that a Game should have one
// So theoretically:
Screen& theGameScreen;
std::vector<Hero*> herosInGame;
};
class Hero
{
public:
Hero(Game& game)
: game(game)
{game.addHero(*this);}
virtual ~Hero()
{game.delHero(*this);}
virtual void Draw(Screen& screen) {/* Draw a hero on the screen */}
private:
Game& game;
};
Main.
#include "Game.h"
#include "Hero.h"
int main(int argc, char* argv[])
{
//Init Game
Screen aScreenObject
Game game(aScreenObject);
//Load hero
Hero hero(game); // or create one hero object for each player
//While game is running
while(game.runningState())
{
//Handle Window and Hero inputs
Game.Input();
Hero.userInput();
//Update
Game.update();
}
//Clean up
// Game.Clean(); Don't do this
// This is what the destructor is for.
}
I don't know if it's elegant, but what I do for the side-scrolling game I'm making is to make a show() function in each class than draws to the screen, and passing the screen handle as a parameter. Then whenever I want to draw something to the screen I just do foo.show(screen). The screen handle is in main().
The first, and honestly, easiest solution, is to use a global variable. Yes, yes, yes, everyone says global variables are horrible, but in this situation, it's perfectly fine.
The other solution, which is a bit more work, but can result in somewhat more portable code, is to encapsulate your drawing functions into a single, static class. This way, you can draw to the screen directly without having to pass around a variable, or have to lie awake at night thinking the code review police will get you because you used a global variable. Plus, this can potentially make it easier if you ever decide to port your game to a new library. Some quick and dirty pseudocode:
class Drawing
public:
static void Draw(x, y, sdl_surface graphic, sdl_rect & clip=null);
static void init(sdl_surface & screen);
private:
sdl_surface screen;
void Drawing::Draw(x, y, sdl_surface graphic, sdl_rect & clip=null)
{
sdl_blit(x, y, graphic, clip);
}
void Drawing::init(sdl_surface & screen)
{
this.screen=screen;
}
It sounds like you're looking for a way to implement the Singleton design pattern, where you would have a single Screen object. If you know you're only ever going to have a single Screen object it should work fine.
In this case you would implement a static method on the Game class:
class Game
{
public:
static Game *GetTheSceenObject();
private:
static Screen *theScreen; // details of initialisation ommitted
}
that would return a pointer to the single Screen object.
If there is a possibility that you'll end up using multiple SDL screens, though, it may be worth creating a Draw() method in your Hero class that is responsible for drawing the hero on each of the Screens managed by the Game class by iterating through a list provided by the Game class.
That functionality could be contained in the methods of a common DrawableThingy class that Hero and Enemy are derived from.
Passing Game.screen around is more OO (though it might be better to have a getter function) than having one instance of it that can be accessed from any class, because if you have one global version, you can't have more than one Game.screen at any one time.
However if you know you'll only ever need one in the entire lifetime of the program, you might consider making Game::Screen() a public static function in the Game class that returns a private static member screen. That way, anyone can call Game::Screen() and get the screen.
Example (assuming ScreenType is the type of screen and that you store a pointer to it):
class Game {
public:
static ScreenType* Screen() {
if (!screen)
screen = GetScreenType(args);
return screen;
}
}
private:
// if you don't already know:
// static means only one of this variable exists, *not* one per instance
// so there is only one no matter how many instances you make
// the same applies to static functions, which you don't need an instance to call
static ScreenType* screen;
};
// and somewhere in a .cpp file
ScreenType* Game::screen = NULL;
// and you use it like this
ScreenType* scr = Game::Screen();
// use scr