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

Author Topic: sf::FloatRect.intersects doesn't work, but sf::FloatRect.contains does...?  (Read 2787 times)

0 Members and 1 Guest are viewing this topic.

smguyk

  • Jr. Member
  • **
  • Posts: 79
    • View Profile
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?

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
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.
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

smguyk

  • Jr. Member
  • **
  • Posts: 79
    • View Profile
Thank you!

You're right, it was the dimensions_ which I forgot to set. It's working now

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
You're welcome. Glad I could help  :)
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

 

anything