Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Strange Sprite Offset  (Read 3102 times)

0 Members and 1 Guest are viewing this topic.

codelyoko373

  • Newbie
  • *
  • Posts: 8
    • View Profile
Strange Sprite Offset
« 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:

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:


Does anyone know what's going on?

AlejandroCoria

  • Jr. Member
  • **
  • Posts: 68
    • View Profile
    • alejandrocoria.games
    • Email
Re: Strange Sprite Offset
« Reply #1 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 to convert it into world coordinates.

codelyoko373

  • Newbie
  • *
  • Posts: 8
    • View Profile
Re: Strange Sprite Offset
« Reply #2 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)));

AlejandroCoria

  • Jr. Member
  • **
  • Posts: 68
    • View Profile
    • alejandrocoria.games
    • Email
Re: Strange Sprite Offset
« Reply #3 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.

codelyoko373

  • Newbie
  • *
  • Posts: 8
    • View Profile
Re: Strange Sprite Offset
« Reply #4 on: August 21, 2017, 02:51:08 am »
Is there a way to fix this?

AlejandroCoria

  • Jr. Member
  • **
  • Posts: 68
    • View Profile
    • alejandrocoria.games
    • Email
Re: Strange Sprite Offset
« Reply #5 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.

 

anything