-
I'm working on a game and have a problem with mouse position relative to screen, window and view
void Things::UpdateMousePos() // parent class to objects like buttons, texts etc.
{
this->mPosScreen = sf::Mouse::getPosition(); // working on fullscreen
this->mPosWindow = sf::Mouse::getPosition(); // not working
this->mPosView = this->window->mapPixelToCoords(sf::Mouse::getPosition(*this->window)); // crashing the game
}
I've searched quite a lot, but even the view tutorial on sfml site hasn't resolved it
-
Use a debugger to get a call stack of the crash.
Also your window should probably not be a pointer.
Personally, I would recommend to not use this-> to access member variables, especially if you also prefix those with m. It adds more "noise" and thus harder to read.
-
I used the debugger, and I got
#0 0x6e185ab0 sf::Window::getSystemHandle(this=0xbaadf00d) (D:\Programming\C++\Releases\_Sources\SFML\src\SFML\Window\Window.cpp:390)
error (segment fault)
Also deleted all pointers to window, but it still doesn't want to work
-
OK, I solved this problem by getting my mouse position from game state, not from the button's parent class.
Now my code looks like this:
if mouse is on a button:
bool SomeText::isMouseInvaded(sf::Vector2i mouse_position)
{
if ( mouse_position.x >= this->text.getPosition().x - textRect.width / 2 &&
mouse_position.x <= this->text.getPosition().x + textRect.width / 2 &&
mouse_position.y >= this->text.getPosition().y - textRect.height / 2 &&
mouse_position.y <= this->text.getPosition().y + textRect.height / 2 &&
this->if_halfed ) return true; //if_halfed means if origin is set in the middle or in the top-left corner
else if ( mouse_position.x >= this->text.getPosition().x &&
mouse_position.x <= this->text.getPosition().x + textRect.width &&
mouse_position.y >= this->text.getPosition().y + textRect.top &&
mouse_position.y <= this->text.getPosition().y + textRect.height + textRect.top &&
!this->if_halfed) return true;
else return false;
}
and a fragment from function checking that event:
if (this->things["QUIT_BUTTON"]->isClicked_Left(mPosWindow)) // quitting the game
this->quit = true;
-
this=0xbaadf00d
This is a special value to help debugging. This particular one means uninitialized memory allocated on the heap (to be verified, I just searched quickly).
So most likely you were allocating a new Things instance without initializing its window member to a valid sf::Window pointer.
-
Could this be the reason for using the same names for the window?
Things::Things(sf::RenderWindow* window)
{
this->window = window;
this->arial.loadFromFile("Fonts/arial.ttf"); // loading fonts
this->comicsans.loadFromFile("Fonts/comic.ttf");
this->ethnocen.loadFromFile("Fonts/ethnocen.ttf");
}