SFML community forums

Help => General => Topic started by: codelyoko373 on August 20, 2017, 11:16:11 pm

Title: Strange Sprite Offset
Post by: codelyoko373 on August 20, 2017, 11:16:11 pm
I'm attempting to recreate Space Invaders using SFML and I'm currently working on the menu.

I wanted to add two sprites to the menu but I'm having lots of problems trying to get the sprites into position.
This is the code I'm using to create one of the sprites as well as set it's position and origin (I commented out the other sprite for testing reasons):
invader2 = new MenuInvader();
   invader2->setScale(5.0f, 5.0f);
   invader2->setOrigin(invader2->getGlobalBounds().width / 2, invader2->getGlobalBounds().height / 2);
   invader2->setPosition(window->getSize().x / 2, window->getSize().y / 2);

This is what it looks like in Game:
(https://image.prntscr.com/image/ZIhaGub2S02AOhuW6yLISw.png)
For some reason the sprite is far off the screen and the only way I can fix this is by scaling the sprite back down to it's original size but even if I do that, there is still this strange offset from the centre of the screen which is where I want the sprite to be:
(https://image.prntscr.com/image/3gCP-AGsS8e41catsQA0Iw.png)

Does anyone know what's going on?
Title: Re: Strange Sprite Offset
Post by: AlejandroCoria on August 21, 2017, 01:01:48 am
With (window->getSize().x / 2, window->getSize().y / 2) you are creating a position in window coordinates. You have to use mapPixelToCoords (https://www.sfml-dev.org/documentation/2.4.2/classsf_1_1RenderTarget.php#a2b0cab0e4c6af29d4efaba149d28116d) to convert it into world coordinates.
Title: Re: Strange Sprite Offset
Post by: codelyoko373 on August 21, 2017, 01:37:14 am
That didn't work, The sprite is still in the same place.

Did I do it wrong?
invader2 = new MenuInvader();
   invader2->setScale(1.0f, 1.0f);
   invader2->setOrigin(invader2->getGlobalBounds().width / 2, invader2->getGlobalBounds().height / 2);
   invader2->setPosition(window->mapPixelToCoords(sf::Vector2i(window->getSize().x / 2, window->getSize().y / 2)));
Title: Re: Strange Sprite Offset
Post by: AlejandroCoria on August 21, 2017, 02:31:01 am
Now I see you're using getGlobalBounds instead of getLocalBounds. The origin is calculated in local coordinates and the scale of 5 causes it to be in the wrong position.
Title: Re: Strange Sprite Offset
Post by: codelyoko373 on August 21, 2017, 02:51:08 am
Is there a way to fix this?
Title: Re: Strange Sprite Offset
Post by: AlejandroCoria on August 21, 2017, 06:06:38 am
Maybe I was not clear with my message (English is not my main language) but you should replace getGlobalBounds with getLocalBounds.