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

Author Topic: floatrect move with a Sprite?  (Read 538 times)

0 Members and 1 Guest are viewing this topic.


  • Jr. Member
  • **
  • Posts: 64
    • View Profile
floatrect move with a Sprite?
« on: June 14, 2022, 11:57:12 am »
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?


  • Hero Member
  • *****
  • Posts: 3138
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: floatrect move with a Sprite?
« Reply #1 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.
(incomplete, obviously)
class Enemy
  sf::Sprite sprite;
  sf::FloatRect hitbox;

  setPosition(sf::Vector2f 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.
Selba Ward - SFML drawables
Kairos - Timing Library
Rectangular Boundary Collision - Rectangular SAT Collision

Hapaxia Links