SFML community forums

Help => Graphics => Topic started by: hdsiria on November 19, 2023, 07:52:37 pm

Title: How to set Sprite collision size different from texture size
Post by: hdsiria on November 19, 2023, 07:52:37 pm
when I set the sprite texture size with
sprite.setTextureRect(sf::IntRect(0, 0, 64, 64));
its collision size is set as well, so when I call Sprite.getGlobalBounds () I get that size, but I want the collision size to be less than the texture size, What should be done
Title: Re: How to set Sprite collision size different from texture size
Post by: Hapax on November 20, 2023, 02:52:40 pm
How you calculate collision is up to you so you can modify the rectangle given by getGlobalBounds before using it in collision calculations. You can, in face, use an entirely different rectangle or even a completely different shape; you just need to able to know which one you are using for which graphic.

A basic example of the first method to "shrink" the rectangle:
sf::IntRect spriteBounds{ sprite.getGlobalBounds(); };
const sf::Vector2i spriteBoundsShrinkMargin{ 2, 1 }; // shrink bounds rectangle by removing 2 pixels from each horizonal edge (left and right) and 1 pixel from each vertical edge (top and bottom)
spriteBounds.left += spriteBoundsShrinkMargin.x;
spriteBounds.top += spriteBoundsShrinkMargin.y;
spriteBounds.width -= spriteBoundsShrinkMargin.x * 2;
spriteBounds.height -= spriteBoundsShrinkMargin.y * 2;

// use spriteBounds to calculate collisions
Title: Re: How to set Sprite collision size different from texture size
Post by: hdsiria on November 23, 2023, 03:47:16 pm
As a game engine, why doesn't sfml sprite have a configurable collision size?
Title: Re: How to set Sprite collision size different from texture size
Post by: Hapax on November 23, 2023, 03:57:35 pm
I think there has been some misconception.

SFML is not a game engine nor does it really do collision (other than calculating if an AABB is overlapping another AABB).

The good thing about SFML is that it gives you the tools to write your own engine however you want it.

Or, you could just write a game and the engine comes with it...