SFML community forums

Help => Graphics => Topic started by: smguyk on October 09, 2014, 07:05:15 pm

Title: sf::FloatRect.intersects doesn't work, but sf::FloatRect.contains does...?
Post by: smguyk on October 09, 2014, 07:05:15 pm
In my 2D platformer I am passing the player's current view to the entity manager, so I only draw the entities that are currently in view.

I pass the following sf::FloatRect (currentView_ is just an sf::View):
sf::FloatRect(
  currentView_.getCenter().x - currentView_.getSize().x / 2,
  currentView_.getCenter().y - currentView_.getSize().y / 2,
  currentView_.getSize().x,
  currentView_.getSize().y
)

When I then use sf::FloatRect.intersects it doesn't draw the entities, but when I use sf::FloatRect.contains it draws them just fine.

void EntityManager::drawEntities(sf::RenderTarget &renderTarget, sf::FloatRect &rect) {
  // Doesn't work:
  for (std::vector<Entity>::iterator i = entities_.begin(); i != entities_.end(); ++i) {
    if (rect.intersects(i->getRect()) {
      renderTarget.draw(*i);
    }
  }

  // Works:
  for (std::vector<Entity>::iterator i = entities_.begin(); i != entities_.end(); ++i) {
    if (rect.contains(i->getRect().left + i->getRect().width / 2, i->getRect().top + i->getRect().height / 2)) {
      renderTarget.draw(*i);
    }
  }
}

In case it's needed, the function getRect() returns the entity's float rect:

sf::FloatRect Entity::getRect() {
  return sf::FloatRect(position_.x, position_.y, dimensions_.x, dimensions_.y);
}

The problem with it not working is that I don't want to check if only the entity's center is within the current view, but rather if ANY POINT of the entity's rect is.

Could someone please help me?
Title: Re: sf::FloatRect.intersects doesn't work, but sf::FloatRect.contains does...?
Post by: Hapax on October 09, 2014, 09:10:20 pm
It looks like it should work.
I think you should confirm for certain that getRect() is returning exactly what you expect it to, especially those "dimensions_".
The reason I say about this is that even if your getRect() is returning all zeroes, the "center" point that you are calculating is at (0, 0) and therefore still within the view's rect. However, if the width and height of the rect are zero, there is nothing to intersect. Namely, the right and bottom are never greater than the top-left of the view.
Title: Re: sf::FloatRect.intersects doesn't work, but sf::FloatRect.contains does...?
Post by: smguyk on October 09, 2014, 09:49:48 pm
Thank you!

You're right, it was the dimensions_ which I forgot to set. It's working now
Title: Re: sf::FloatRect.intersects doesn't work, but sf::FloatRect.contains does...?
Post by: Hapax on October 09, 2014, 11:52:43 pm
You're welcome. Glad I could help  :)