SFML community forums

Help => General => Topic started by: Uk Marine on March 02, 2014, 11:06:31 am

Title: Newbie Question: How to set an object's position to the middle of the screen?
Post by: Uk Marine on March 02, 2014, 11:06:31 am
Hi everyone, can anyone tell me how to calculate both x and y values of a circle to set its position to the center of the screen? i tried dividing the screen resolution by /2 but it didn't seem to work, can someone please remind me how to do this? Thank you.

mWindow(sf::VideoMode(1280 , 800)
{
   mPlayer.setRadius(40.f);
   mPlayer.setPosition(640.f , 400.f);
   mPlayer.setFillColor(sf::Color::Blue);
}

Result:

(http://s30.postimg.org/7k3a7x82l/Close_enough.jpg) (http://postimg.org/image/7k3a7x82l/)
Title: Re: Newbie Question: How to set an object's position to the middle of the screen?
Post by: Barlog on March 02, 2014, 11:22:12 am
You should use
setOrigin(x,y) (http://www.sfml-dev.org/documentation/2.1/classsf_1_1Transformable.php#a56c67bd80aae8418d13fb96c034d25ec) to center origin point of a sprite. Set it to half of a size of a sprite;
Or you need to subtract half of width and height of sprite from sprite position each time you reposition your sprite;
Title: Re: Newbie Question: How to set an object's position to the middle of the screen?
Post by: Hapax on March 02, 2014, 11:22:29 am
mPlayer.setOrigin(mPlayer.getRadius(), mPlayer.getRadius());
Title: Re: Newbie Question: How to set an object's position to the middle of the screen?
Post by: Nexus on March 02, 2014, 11:23:55 am
Unless otherwise specified, you set the left-upper corner of an object with setPosition(). As mentioned by Tirion Helkaraxe, you should set the origin to the center. In the case of a sf::CircleShape, the origin is simply at position (radius, radius).
Title: Re: Newbie Question: How to set an object's position to the middle of the screen?
Post by: Uk Marine on March 02, 2014, 12:02:15 pm
Thanks for your answers guys, the mPlayer.setOrigin(mPlayer.getRadius(), mPlayer.getRadius()); worked, but why did we do (mPlayer.getRadius(), mPlayer.getRadius) twice?
Title: Re: Newbie Question: How to set an object's position to the middle of the screen?
Post by: Nexus on March 02, 2014, 12:05:22 pm
X and Y components of the origin. The radius is a scalar, the origin a vector.
Title: Re: Newbie Question: How to set an object's position to the middle of the screen?
Post by: Hapax on March 02, 2014, 12:05:35 pm
Thanks for your answers guys, the mPlayer.setOrigin(mPlayer.getRadius(), mPlayer.getRadius()); worked, but why did we do (mPlayer.getRadius(), mPlayer.getRadius) twice?
The default origin is the top-left of the boundary box of the circle. To get the origin into the centre, you need to move it radius to the right, and radius down.
Title: Re: Newbie Question: How to set an object's position to the middle of the screen?
Post by: Uk Marine on March 02, 2014, 12:08:03 pm
Thank you guys so much, really appreciate your help.