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

Author Topic: How to set Sprite collision size different from texture size  (Read 1071 times)

0 Members and 1 Guest are viewing this topic.

hdsiria

  • Newbie
  • *
  • Posts: 23
    • View Profile
How to set Sprite collision size different from texture size
« 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

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: How to set Sprite collision size different from texture size
« Reply #1 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
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

hdsiria

  • Newbie
  • *
  • Posts: 23
    • View Profile
Re: How to set Sprite collision size different from texture size
« Reply #2 on: November 23, 2023, 03:47:16 pm »
As a game engine, why doesn't sfml sprite have a configurable collision size?

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: How to set Sprite collision size different from texture size
« Reply #3 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...
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*