Reputation: 1165
I have been trying to fix this problem for about an hour or more... But couldn't find any usefull answers. I am trying to place a sprite on the center of the window, but it shows up on TOP_LEFT. Here is the constructor for my class and as you can see I am dividing surface.width and surface.height by 2
Spaceship::Spaceship(sf::RenderWindow& game_window){
auto surface = game_window.getSize();
signed int ss_x = surface.x/2;
signed int ss_y = surface.y/2;
int ss_width = 128;
int ss_height = 128;
int ss_radius = ss_width/2;
}
///////////////////////////////////////////
// For displaying the sprite on window //
///////////////////////////////////////////
void Spaceship::drawsprite(sf::RenderWindow& game_window){
sf::Texture ship;
if (!ship.loadFromFile(resourcePath() + "space-shuttle-64.png")) {
return EXIT_FAILURE;
}
sf::Sprite ss_sprite(ship);
ss_sprite.setPosition(ss_x, ss_y);
game_window.draw(ss_sprite);
}
I have also tried with:
auto surface = game_window.RenderWindow::getSize();
signed int ss_x = surface.x/2;
signed int ss_y = surface.y/2;
but that didn't help either.
I have tried to print the variables which are defined inside the constructor and I got 0 on all of them. So my problems seems to be the accessing problem. but there were no errors or warnings that have told me that.
this is the header file:
#ifndef Spaceship_hpp
#define Spaceship_hpp
#include <iostream>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <stdio.h>
using namespace std;
class Spaceship {
public:
Spaceship();
Spaceship(sf::RenderWindow&);
~Spaceship();
void moveship(char);
void drawsprite(sf::RenderWindow&);
private:
signed int ss_x, ss_y;
unsigned int ss_speed;
int ss_width, ss_height, ss_radius;
};
#endif /* Spaceship_hpp */
Upvotes: 0
Views: 2327
Reputation: 2533
You are not initialising your attributes in your constructor correctly.
Spaceship::Spaceship(sf::RenderWindow& game_window){
auto surface = sf::VideoMode::getDesktopMode();
signed int ss_x = surface.width/2;
signed int ss_y = surface.height/2;
int ss_width = 128;
int ss_height = 128;
int ss_radius = ss_width/2;
}
should be
Spaceship::Spaceship(sf::RenderWindow& game_window){
auto surface = sf::VideoMode::getDesktopMode();
ss_x = surface.width/2;
ss_y = surface.height/2;
ss_width = 128;
ss_height = 128;
ss_radius = ss_width/2;
}
Declaring variables in the body of the class means they are seen globally by the class, if you redeclare a variable in the constructor, it will take over the role from the global variable. This is called variable shadowing. All modifications to the variable will work, but once you leave the scope of your constructor/function/method, then you lose the information since your attribute variable wasn't modified.
More on scopes: http://en.cppreference.com/w/cpp/language/scope
More on variable shadowing: https://en.wikipedia.org/wiki/Variable_shadowing?oldformat=true
Upvotes: 1