SFML community forums

Help => Graphics => Topic started by: Jan666 on June 14, 2022, 11:57:12 am

Title: floatrect move with a Sprite?
Post by: Jan666 on June 14, 2022, 11:57:12 am
Hello,
I have following problem:
I have an enemySprite who has a floatrect, a hitbox for the Player, that reduce his health when he collide with. But when the enemy move this floatrect stand still, any idea how to "parenting" this floatrect to the enemySprite when moves?
Title: Re: floatrect move with a Sprite?
Post by: Hapax on June 14, 2022, 07:34:02 pm
Change the position of the float rect whenever the position of the sprite is changed.

You can do this manually or maybe encapsulate in a class to do it automatically.
e.g.
(incomplete, obviously)
class Enemy
{
  sf::Sprite sprite;
  sf::FloatRect hitbox;

  setPosition(sf::Vector2f newPosition)
  {
    sprite.setPosition(newPosition);
    hitbox.x = newPosition.x;
    hitbox.y = newPosition.y;
  }
}

Then it's just, for example:
Enemy enemy;
// ...
enemy.setPosition({ 200.f, 150.f });

Of course, if the float rectangle is not exactly the same co-ordinate, you'll also need to offset those values.