C++ SFML Sprite not drawing, however no errors occur - c++

I've been trying to make a sprite display in C++ SFML but with the use of classes. However, when I compile and run the program, nothing appears: there are no errors either.
(The only thing that happens in main is that a 'Game' object is created)
Game.h
#ifndef GAME_H
#define GAME_H
#include <SFML/Graphics.hpp>
#include "Player.h"
class Game
{
public:
Game();
private:
//Variables
sf::RenderWindow _mainWindow;
enum _gameState { Playing, Paused, Splash, Menu };
//Methods
void gameLoop();
};
#endif // GAME_H
Game.cpp
#include "Game.h"
#include "Player.h"
Game::Game() {
//Variables
_mainWindow.create(sf::VideoMode(960, 640), "Game", sf::Style::Titlebar | sf::Style::Close);
_mainWindow.setFramerateLimit(60);
//Start Game Loop
gameLoop();
}
void Game::gameLoop() {
Player player;
while(_mainWindow.isOpen()) {
sf::Event ev;
while(_mainWindow.pollEvent(ev)) {
if(ev.type == sf::Event::Closed)
_mainWindow.close();
if(ev.type == sf::Event::KeyPressed) {
if(ev.key.code == sf::Keyboard::Escape)
_mainWindow.close();
}
}
//Draw Stuff
_mainWindow.clear(sf::Color::White);
player.drawSprite(_mainWindow);
_mainWindow.display();
}
}
Player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <SFML/Graphics.hpp>
#include <iostream>
class Player
{
public:
Player();
void drawSprite(sf::RenderWindow& window);
private:
bool loadSprite();
sf::Texture _playerTexture;
sf::Sprite _playerSprite;
};
#endif // PLAYER_H
Player.cpp
#include "Player.h"
#include "Game.h"
Player::Player()
{
if(!Player::loadSprite()){
return;
}
}
bool Player::loadSprite() {
sf::Texture _playerTexture;
if(!_playerTexture.loadFromFile("img/darkguy.png", sf::IntRect(32,32,32,32))) {
std::cout << "Failed to load player image" << std::endl;
return false;
} else {
sf::Sprite _playerSprite;
_playerSprite.setTexture(_playerTexture);
}
return true;
}
void Player::drawSprite(sf::RenderWindow& window) {
//sprite.setTextureRect(sf::IntRect(10, 10, 32, 32));
window.draw(_playerSprite);
std::cout << "Sprite Drawn Successfully" << std::endl;
}

You are declaring a new, local _playerSprite here:
} else {
sf::Sprite _playerSprite;
_playerSprite.setTexture(_playerTexture);
}
instead, use the existing class member:
} else {
_playerSprite.setTexture(_playerTexture);
}
You may want to drop the first line from this code as well, same issue:
bool Player::loadSprite()
{
sf::Texture _playerTexture; // <--- local redeclaration

From my memories: the texture must be a member of your class; it must exist while you are using it. In your code, _playerTexture is destroyed at the end of loadSprite(). Same problem for _playerSprite.
Edit:
You don't have to re-declare the member of your class in your methods :
bool Player::loadSprite() {
sf::Texture _playerTexture;
if(!_playerTexture.loadFromFile("img/darkguy.png", sf::IntRect(32,32,32,32))) {
std::cout << "Failed to load player image" << std::endl;
return false;
} else {
sf::Sprite _playerSprite;
_playerSprite.setTexture(_playerTexture);
}
return true;
}
Should be:
bool Player::loadSprite() {
if(!_playerTexture.loadFromFile("img/darkguy.png", sf::IntRect(32,32,32,32))) {
std::cout << "Failed to load player image" << std::endl;
return false;
} else {
_playerSprite.setTexture(_playerTexture);
}
return true;
}
(PS: Your code doesn't respect the SRP (Single Responsability Principle), Player doesn't have to display itself.)

you are drawing but not displaying the sprite for that do this
void Player::drawSprite(sf::RenderWindow& window) {
//sprite.setTextureRect(sf::IntRect(10, 10, 32, 32));
window.draw(_playerSprite);
std::cout << "Sprite Drawn Successfully" << std::endl;
//this is the display function
window.display()
}

Related

Why is my SFML sprite not showing texture?

I'm trying to create a game. I have a class GameObjects that many classes will inherit from. The class GameObject has a draw method that takes the window address to the display. Why does the sprite show up without the texture when displayed like this?
This is the texture, more of a placeholder. I was able to load it in other files directly creating the sprite and drawing it.
Here is my main.cpp
#include <iostream>
#include "Game.h"
int main()
{
//window setup
Game game;
//Initialize game
game.start();
return 0;
}
Here is my Game.h
#pragma once
#include "GameObject.h"
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
class Game
{
private:
//window variables
int w_width;
int w_height;
sf::RenderWindow window;
sf::Event ev;
bool isRunning;
std::vector<GameObject> o_vector;
void initVariables();
void initWindow();
void initObjects();
void drawObjects();
public:
void start();
void run();
void input();
void update();
void render();
};
And Game.cpp
#include "Game.h"
#include "GameObject.h"
void Game::start()
{
this->initVariables();
this->initWindow();
this->initObjects();
this->run();
}
//Initializations
void Game::initVariables()
{
isRunning = true;
//window variables
w_width = 1280;
w_height = 720;
}
void Game::drawObjects()
{
for (int o_count = 0; o_count < o_vector.size(); o_count++)
{
o_vector.at(o_count).draw(window);
}
}
void Game::initWindow()
{
//window creation
window.create(sf::VideoMode(w_width, w_height), "The Dungeon Crawler", sf::Style::Titlebar | sf::Style::Close | sf::Style::Resize);
}
void Game::initObjects()
{
GameObject baseObject;
o_vector.push_back(baseObject);
}
void Game::run()
{
while (isRunning)
{
input();
update();
render();
}
}
void Game::input()
{
while (window.pollEvent(ev))
{
switch (ev.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
switch (ev.key.code)
{
case sf::Keyboard::Escape:
window.close();
break;
case sf::Keyboard::A:
break;
}
}
}
}
void Game::update()
{
}
void Game::render()
{
window.clear(sf::Color(0, 0, 128));
drawObjects();
window.display();
}
Here is GameObject.h
#pragma once
#include <vector>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
class GameObject
{
private:
std::string name;
std::vector<int> o_position;
std::vector<int> o_size;
std::string t_path;
sf::Sprite o_sprite;
sf::Texture o_texture;
void initVariables();
public:
//Constructors & Destructors
GameObject();
~GameObject();
//Getters
std::vector<int> getPos();
std::vector<int> getSize();
sf::Sprite getSprite();
//Setters
void setPos(std::vector<int>pos_in);
void setSize(std::vector<int> size_in);
//Graphics
void draw(sf::RenderWindow &displayWindow);
};
And GameObject.cpp
#include "GameObject.h"
GameObject::GameObject()
{
initVariables();
}
GameObject::~GameObject()
{
}
void GameObject::initVariables()
{
o_position = { 0,0 };
o_size = { 64,64 };
t_path = "Resources/EmptySquare.png";
if (!o_texture.loadFromFile(t_path))
{
std::cout << "Failed to load" << std::endl;
return;
}
o_sprite.setTexture(o_texture);
}
std::vector<int> GameObject::getPos()
{
return o_position;
}
std::vector<int> GameObject::getSize()
{
return o_size;
}
sf::Sprite GameObject::getSprite()
{
return o_sprite;
}
void GameObject::setPos(std::vector<int> pos_in)
{
o_position = pos_in;
}
void GameObject::setSize(std::vector<int> size_in)
{
o_size = size_in;
}
void GameObject::draw(sf::RenderWindow &displayWindow)
{
displayWindow.draw(o_sprite);
}
Thank you for any help!
the problem is this line in Game::initObjects()
GameObject baseObject;
o_vector.push_back(baseObject);
you creata a copy of GameObject.
so it will make a copy of o_sprite.
the o_sprite copies the texture pointer.
after this function ends, the texture pointer is no longer valid.
sf::Sprite has the member const Texture* m_texture; and when calling sf::Sprite::setTexture(const Texture& texture) this member m_texture will in fact point to the texture. That texture will be destructed after initObjects() ends, and your element at position 0 will have a o_sprite.m_texture that points to this destructed object. SFML/Sprite.hpp
you could define the correct operator=(GameObject) that implements the correct sprite copy - or in this case simply say:
void Game::initObjects()
{
o_vector.resize(1);
}
resize will call the constructor of GameObject and you will have no copies and therefore dangling pointers.
Another way would be for you to allocate game object on the heap and store a pointer to it in the vector. This way you will avoid the cost of copying.
To make these changes, declare baseObject as private member of Game class and in initObjects method allocate it on the heap.
class Game
{
private:
GameObject *baseObject;
std::vector<GameObject *> o_vector;
};
void Game::initObjects()
{
baseObject = new GameObject;
o_vector.push_back(baseObject);
}
void Game::drawObjects()
{
for (int o_count = 0; o_count < o_vector.size(); o_count++)
{
o_vector.at(o_count)->draw(window); // use -> operator to call draw
}
}
PS: Instead of raw pointer, you can also use C++11 smart pointer.

Sprite not showing sfml

I want to display my player in the window but my player sprite is not showing in the window. I am new to c++. I want to learn classes, inheritence, composition, etc in this way.I have 3 files Player.cpp, Game.cpp and main.cpp. I am using main.cpp to call Game.cpp using a fuction called Run().
Got nothing to try.
Player.cpp
#include "Player.hpp"
#include "string.h"
#include <iostream>
void Player::initPlayer()
{
const char* playerTexturePath = "/Users/don/Desktop/sfmlgames/game1/img/MCmid.png";
if(!mPlayerTexture.loadFromFile(playerTexturePath))
{
std::cout << "mPlayerTexturePath not found!!" << std::endl;
}
mPlayerSprite.setTexture(mPlayerTexture);
mPlayerSprite.setPosition(100.f, 100.f);
mPlayerSprite.setScale(1.f, 1.f);
}
void Player::draw_player(sf::RenderWindow &win)
{
win.draw(mPlayerSprite);
}
Game.cpp
#include "Game.hpp"
#include <iostream>
Player player1;
//Constructor: Create a window and Player
Game::Game() : mWindow(sf::VideoMode(640, 480), "Game")
{
//Frame rate 60
mWindow.setFramerateLimit(60);
player1.initPlayer();
}
//Game loop
void Game::Run()
{
while(mWindow.isOpen())
{
render();
events();
update();
}
}
void Game::events()
{
sf::Event event;
while (mWindow.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
mWindow.close();
}
}
}
void Game::update()
{
}
void Game::render()
{
mWindow.clear(sf::Color::Red);
player1.draw_player(mWindow);
mWindow.display();
}
main.cpp
#include "Game.hpp"
int main()
{
Game game;
game.Run();
}
I don't think I will need to give code to hpp files.
The problem was with image I dont know why. I used another image and it worked fine.

SFML Window not responding to inputs

I recently started working on SFML. I just created a window then later started to separating my main code. First i wrote a window class.
Nothing special, just draws my window and prints mouse coordinates.
#include "Window.hpp"
#include <iostream>
Window::Window()
{
SetWindow(800,600, "JUST SFML");
}
void Window::SetWindow(unsigned int width, unsigned int height, sf::String title)
{
m_sfmlWindow.create(sf::VideoMode(width, height), title);
}
void Window::StartDrawing()
{
m_sfmlWindow.clear();
}
void Window::EndDrawing()
{
m_sfmlWindow.display();
}
bool Window::isClosed()
{
return !m_sfmlWindow.isOpen();
}
void Window::EventControl()
{
sf::Event event;
while (m_sfmlWindow.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
m_sfmlWindow.close();
}
if (event.type == sf::Event::MouseMoved)
{
std::cout << event.mouseMove.x << " , " << event.mouseMove.y << std::endl;
}
}
}
void Window::Draw(sf::Drawable& shape)
{
m_sfmlWindow.draw(shape);
}
Everything worked perfectly.
Then i tought i need a GameManager class that i can just use in my main class.
#include "GameManager.hpp"
GameManager::GameManager()
{
m_shape.setRadius(30.0f);
m_shape.setFillColor(sf::Color::Magenta);
m_incVal = 1.0f;
m_posX = 10.0f;
m_frameRate = 1.0f / 60.0f;
}
GameManager::~GameManager()
{
}
void GameManager::InputControl()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
m_incVal = 1.0f;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
m_incVal = -1.0f;
}
}
void GameManager::UpdateScene()
{
if (m_deltaTime.asSeconds() >= m_frameRate)
{
m_posX += m_incVal;
m_shape.setPosition(m_posX, 300);
m_deltaTime -= sf::seconds(m_frameRate);
}
}
void GameManager::DrawScene()
{
m_window.StartDrawing();
m_window.Draw(m_shape);
m_window.EndDrawing();
}
void GameManager::RestartClock()
{
m_deltaTime += m_clock.restart();
}
bool GameManager::isFinished()
{
return m_window.isClosed();
}
It was perfectly working when i use window object, later i've changed to gamemanager it start being not responding.. I can get keyboard inputs but not mouse move coordinates. Where am i make it wrong?
#include <SFML/Graphics.hpp>
#include "GameManager.hpp"
#include "Window.hpp"
int main()
{
GameManager gameManager;
while (!gameManager.isFinished())
{
gameManager.InputControl();
gameManager.UpdateScene();
gameManager.DrawScene();
gameManager.RestartClock();
}
/*
sf::CircleShape shape(100.0f);
shape.setFillColor(sf::Color::Magenta);
shape.setOutlineThickness(5.0f);
shape.setOutlineColor(sf::Color::White);
Window window;
while (!window.isClosed())
{
window.EventControl();
window.StartDrawing();
window.Draw(shape);
window.EndDrawing();
}
*/
return 0;
}
In order to receive events (such as the mouse moving), you need to call pollEvents on the window.
In your commented code, you were doing this through your Window::EventControl() method. Your new GameManager class isn't calling this, however, so you aren't receiving any events.

C++/SFML Graphing Application-Repeating Texture/Sprite

I was taking up the challenge of creating a program to use for graphing simple math equations using C++ and the SFML 2.3.2. graphics library, and I've got the graph paper texture rendering fine. However, the problem I've had is getting it to repeat itself as I scroll around.
I was using sf::View to get it to pan, and it works well, but as soon as it pans outside the pre-defined size of the sprite it's just a blank background.
I thought of trying to determine when I'm outside the bounds of the sprite, and then expanding the size of the sprite or moving it, but then drawings (such as a graph) won't persist if the sprite is changed/reset.
What I need to know is how to create a background of a texture, in this case graphing paper, that will tile/repeat in every direction, and allow drawings to be made on top of it that persist if they move off screen.
Code is below:
GraphPaper.h:
#pragma once
#include "stdafx.h"
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";
};
GraphPaper.cpp: This is where I create and load the needed sprite and texture.
I set the texture to repeat inside the "load(string filename)" method, but that only affects it within the bounds set by the sprite's rectangle.
#include "GraphPaper.h"
GraphPaper::GraphPaper() : isLoaded(false)
{
load(file);
assert(isObjectLoaded());
}
GraphPaper::~GraphPaper() {};
void GraphPaper::load(std::string filename)
{
if (texture.loadFromFile(filename) == false)
isLoaded = false;
else
{
texture.setRepeated(true);
sprite.setTexture(texture);
//Huge size to at least make it look like it's infinite,
//but a temporary solution.
sprite.setTextureRect(sf::IntRect(0,0,10000,10000));
isLoaded = true;
}
}
bool GraphPaper::isObjectLoaded()
{
return isLoaded;
}
sf::Sprite GraphPaper::getSprite()
{
return sprite;
}
MainWindow.h:
#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;
};
MainWindow.cpp: This is what handles all the drawing, and, at the moment, all input processing. "start()" is simply called from the main method.
#include "MainWindow.h"
#include "GraphPaper.h"
#include "stdafx.h"
void MainWindow::start()
{
sf::RectangleShape rectangle = sf::RectangleShape(sf::Vector2f(120, 50));
rectangle.setFillColor(sf::Color(0,0,0));
mainWindow.create(sf::VideoMode(1024, 768, 32), "Test");
sf::View view(sf::FloatRect(0,0,1000,600));
mainWindow.setView(view);
leftMousePressed, rightMousePressed, isExiting = false;
sf::Event currentEvent;
mainWindow.clear(white);
mainWindow.draw(paper.getSprite());
mainWindow.display();
while (!isExiting)
{
while (mainWindow.pollEvent(currentEvent))
{
switch (currentEvent.type)
{
case sf::Event::MouseMoved:
{
if (rightMousePressed == true)
{
std::cout << "Mouse Panned\n";
}
if (leftMousePressed == true)
{
std::cout << "Mouse is Drawing\n";
}
break;
}
case sf::Event::MouseButtonPressed:
{
std::cout << "Mouse Pressed\n";
mouseX = currentEvent.mouseButton.x;
mouseY = currentEvent.mouseButton.y;
if (currentEvent.mouseButton.button == sf::Mouse::Left)
{
leftMousePressed = true;
}
else if (currentEvent.mouseButton.button == sf::Mouse::Right)
{
rightMousePressed = true;
}
break;
}
case sf::Event::MouseButtonReleased:
{
std::cout << "Mouse Released\n";
if (currentEvent.mouseButton.button == sf::Mouse::Left)
{
leftMousePressed = false;
}
else if(currentEvent.mouseButton.button == sf::Mouse::Right)
{
rightMousePressed = false;
}
break;
}
case sf::Event::KeyPressed:
{
if (currentEvent.key.code == sf::Keyboard::Escape)
{
close();
}
//No right movement yet, was testing.
else if (currentEvent.key.code == sf::Keyboard::Left)
{
moveCamera(currentEvent);
}
break;
}
case sf::Event::Closed:
{
close();
break;
}
}
}
}
}
void MainWindow::moveCamera(sf::Event key)
{
std::cout << "Inside moveCamera\n";
//No right movement yet, was testing.
//Movement is also hardcoded for testing as well.
view.move(100, 0);
mainWindow.setView(view);
mainWindow.clear(white);
mainWindow.draw(paper.getSprite());
mainWindow.display();
std::cout << "Leaving moveCamera\n";
}
void draw()
{
//mainWindow.draw();
}
void MainWindow::close()
{
std::cout << "Closing...\n";
mainWindow.close();
isExiting = true;
}

Trying to draw my player and move him

I am working on a little project where I am trying to get a player in my 2D view (actually a circle) and let him move left to right, up and down flawless, also I want to be able to press 2 keys at ones so he moves sideways or something like that.
Also i want to be able to shoot with the player in a certain direction in a later state of the project (it could be important as of now)
I am doing this project because I want to learn how C++ OOP works.
The structure im having in my mind is simple :
Main > (Creates) > GameWindow
Main > (creates) > EntityManager > (creates) > Player
Player > (creates via) > EnitityManager > Gun
Gun > (Creates via) > EntityManager > Bullet
Player can :
Walk up/down/left/right
Shoot.
So to get to the code, This is what I have in my FirstGame.cpp
#include "stdafx.h"
#include "GameWindow.h"
#include "EntityManager.h"
int main()
{
// Create an entity manager
EntityManager::Instance();
// Display the window
GameWindow::Instance().Run();
}
in my GameWindow.h I have :
#pragma once
#include <SFML/Graphics.hpp>
using namespace sf;
class GameWindow
{
public:
static GameWindow& Instance()
{
static GameWindow instance;
return instance;
}
RenderWindow& GetRenderWindow();
void Run();
private:
static const int DEF_WIDTH = 1366;
static const int DEF_HEIGHT = 720;
GameWindow();
GameWindow(const GameWindow&);
GameWindow& operator=(const GameWindow&);
~GameWindow();
string windowTitle;
int windowWidth;
int windowHeight;
void Initialize();
void DisplayWindow();
void CheckWindowEvent();
};
and in my GameWindow.cpp
#include "StdAfx.h"
#include "GameWindow.h"
#include "Player.h"
#include "SFML\Graphics.hpp"
RenderWindow renderWindow;
Event eventSF;
GameWindow::GameWindow()
{
Initialize();
}
GameWindow::~GameWindow()
{
}
void GameWindow::Initialize()
{
// Set width & height to default settings
windowWidth = DEF_WIDTH;
windowHeight = DEF_HEIGHT;
// Create the render window
renderWindow.create(VideoMode(windowWidth, windowHeight), windowTitle, Style::Titlebar | Style::Close | Style::Resize);
Cmd::WriteLine("GameWindow Initialized!");
}
RenderWindow& GameWindow::GetRenderWindow()
{
return renderWindow;
}
void GameWindow::Run()
{
// Loop until window has closed
while (renderWindow.isOpen())
{
// Check current window events
CheckWindowEvent();
// Display window
DisplayWindow();
}
}
void GameWindow::DisplayWindow()
{
// Display the render window
renderWindow.clear();
renderWindow.display();
}
void GameWindow::CheckWindowEvent()
{
Event _event;
while (renderWindow.pollEvent(_event))
{
// Request for closing the window
if (_event.type == Event::Closed)
renderWindow.close();
}
}
and in my EntityManager.h I got :
#pragma once
#include "Entity.h"
#include "Player.h"
class EntityManager
{
public:
static EntityManager& Instance()
{
static EntityManager instance = EntityManager();
return instance;
}
private:
EntityManager();
~EntityManager();
void Initialize();
};
and my EntityManager.cpp
#include "StdAfx.h"
#include "EntityManager.h"
#include "GameWindow.h"
#include "Player.h"
EntityManager::EntityManager()
{
Initialize();
}
EntityManager::~EntityManager()
{
}
void EntityManager::Initialize()
{
Player::Create();
}
and now the Player.h
#pragma once
#include <SFML/Graphics.hpp>
#include "Entity.h"
using namespace sf;
class Player: Entity
{
public:
Player();
~Player();
void GotDamage(int damage);
static void Create();
void Draw();
void Shoot();
void Move(float x, float y);
void Controls(Event _eventSF);
private:
string name;
int health;
Event eventSF;
CircleShape playerVisual;
protected:
void Initialize() override;
};
and last the Player.cpp
#include "StdAfx.h"
#include "Player.h"
#include "GameWindow.h"
#include <SFML/Graphics.hpp>
Player::Player()
{
}
Player::~Player()
{
}
void Player::Create()
{
Player player;
player.Initialize();
player.Draw();
player.Controls(player.eventSF);
}
void Player::Initialize()
{
CircleShape playerVisual(50);
playerVisual.setPosition(800, 450);
playerVisual.setFillColor(sf::Color(100, 250, 50));
Entity::Initialize();
}
void Player::Controls(sf::Event _eventSF)
{
while(GameWindow::Instance().GetRenderWindow().isOpen())
{
while(GameWindow::Instance().GetRenderWindow().pollEvent(_eventSF))
{
switch(_eventSF.type)
{
case sf::Event::KeyPressed:
if (_eventSF.key.code == sf::Keyboard::Up)
{
Move(0,-1);
}
if (_eventSF.key.code == sf::Keyboard::Down)
{
Move(0,1);
}
if (_eventSF.key.code == sf::Keyboard::Left)
{
Move(-1,0);
}
if (_eventSF.key.code == sf::Keyboard::Right)
{
Move(1,0);
}
if (_eventSF.key.code == sf::Keyboard::BackSpace)
{
GotDamage(20);
}
break;
}
}
}
cout << " Checking Controls " << endl;
}
void Player::Move(float _x, float _y)
{
cout << "Move Player " << endl;
playerVisual.move(_x, _y);
Draw();
}
void Player::GotDamage(int _damage)
{
//for some reason health is -858993460
cout << "Your current health is " << Player::health << " you received " << _damage << " damage now you have " << Player::health - _damage << " health left. " << endl;
health -= _damage;
}
void Player::Draw()
{
cout << "Draw Player" << endl;
CircleShape visual(50);
playerVisual.setPosition(800, 450);
playerVisual.setFillColor(sf::Color(100, 250, 50));
GameWindow::Instance().GetRenderWindow().draw(visual);
}
I know it is a lot but I hope someone can help me.
To repeat my goal :
I am trying to get my player to be drawn on the screen and let him move sideways and if possible diagonal.
Thanks in advance!
To add onto KeyHeart's answer.
I hacked up your code a bit and managed to get it working.
Keep in mind the scope of your variables. There's CircleShape playerVisual(50) in Player::Initialize() which is a local variable, but you already have a CircleShape playerVisual inside Player.h! So the former is unnecessary. Likewise in Player::Create() you create a local player object.
I don't have a full copy of your code, so I assume what you plan on doing is having EntityManager handle all existing entities, such as the player. Therefore you should have Player player declared in the EntityManager's header file. Thus calling the constructor, which I have taken everything from Player::Create() and placed it into Player::Player(). And this player will exist for lifespan of EntityManager.
The order in which you should be updating the buffer is:
renderWindow.clear()
renderWindow.draw()
renderWindow.display()
As you have it now, you draw() then clear() effectively displaying nothing.
There are many approaches, but the simplest would be adding a call to Player::Draw() in GameWindow::DisplayWindow(). Though GameWindow will need a player object to call Draw().
Regarding moving the player. Player::Controls contains what may be an infinite loop in a sense. The line while (GameWindow::Instance().GetRenderWindow().isOpen()) will continue to loop as long as the window is open thus can block anything else from updating, such as drawing.
Shouldn't you be drawing playerVisual rather than visual which exists locally inside the Player::Draw() function?
Also shouldn't you call Player::Draw() in GameWindow::Run(), since you call GameWindow::DisplayWindow() which will update the screen. Calling Player::Draw() in Player::Move() limits drawing of the sprite only to when it moves. The results of this would be the sprite existing only in frames in which it moves otherwise an empty canvas.