0
\$\begingroup\$

I want to use sf::View in SFML in order to change the position of the view, such that the player sprite is always in the center of the screen. Thus I want to write a function which allows me to input a set of coordinates and thus center the screen around those coordinates. In addition I want to be able to set a limit to this, such that when the player reaches the side of the map, that axis of the camera stops following the player, as it has reached a "limit". How do I achieve this?

Thank you in advance.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You have to check if the player is too close to a side and move the view accordingly. If he is too much on one side then you don't center the view on him anymore.

Here is an example of how I would do it. (I haven't tested it)

//View is your current view.
//Position is the position you want to center the view on.
//Size is the size of your "area".

void move_view(View &view, sf::Vector2f size ,sf::Vector2f position)
{
    if (position.x > size.x-view.getSize().x/2)//on the right side
    {
        position.x  = size.x-view.getSize().x/2;
    }
    if  (position.x < view.getSize().x/2)//on the left side
    {
        position.x  = view.getSize().x/2;
    }
    //same for up and down
    //...
    view.setCenter(position);
}
\$\endgroup\$
3
  • \$\begingroup\$ What do position and size refer to? \$\endgroup\$
    – Yaxlat
    Feb 15, 2015 at 16:06
  • \$\begingroup\$ Sorry, I edited. \$\endgroup\$
    – Heckel
    Feb 15, 2015 at 16:09
  • \$\begingroup\$ I managed to come up with a slightly different version using view.reset, because I plan on using zoom in the future, and that makes things easier. However I tested your version, and it works so I'll accept it. \$\endgroup\$
    – Yaxlat
    Feb 15, 2015 at 16:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .