Difference Between SDL_Rect
and SDL_FRect
in SDL2
What's the difference between SDL_Rect
and SDL_FRect
? When should I use floats?
Both SDL_Rect
and SDL_FRect
are fundamental SDL types used to represent rectangular areas, but they differ in the data type they use for storing coordinates and dimensions.
SDL_Rect
The SDL_Rect
struct uses integers (int
) for its members:
typedef struct SDL_Rect {
int x, y; // Position of the top-left corner
int w, h; // Width and Height
} SDL_Rect;
Because it uses integers, SDL_Rect
is primarily suited for situations where positions and sizes align perfectly with the pixel grid of the screen or a surface. This makes it ideal for:
- Defining the exact pixel boundaries for UI elements like buttons or panels.
- Specifying source or destination rectangles for blitting operations (
SDL_BlitSurface
) where pixel precision is required. - Working directly with screen coordinates or surface coordinates, which are inherently integer-based.
SDL_FRect
The SDL_FRect
struct, introduced later in SDL's development, uses floating-point numbers (float
) for its members:
typedef struct SDL_FRect {
float x, y; // Position of the top-left corner
float w, h; // Width and Height
} SDL_FRect;
Using floats allows SDL_FRect
to represent positions and dimensions with sub-pixel precision. This is particularly useful for:
- Physics simulations where objects move smoothly and don't necessarily align to pixel boundaries frame-by-frame.
- Representing positions in a "world coordinate" system that might be scaled or scrolled, where calculations naturally result in floating-point values.
- Smoother animations and movement, as positions can be updated by fractional amounts each frame.
When to Use Which?
- Use
SDL_Rect
when dealing directly with screen/surface pixels, integer-based UI layouts, or functions that specifically require integer coordinates (likeSDL_FillRect
used in this lesson). - Use
SDL_FRect
when you need sub-pixel precision, typically for game object positions, physics, or representing geometry in a coordinate system independent of the final pixel grid. You might store your object's primary position as anSDL_FRect
and convert it to anSDL_Rect
only when needed for rendering functions that require integers.
SDL provides functions to work with both types, and sometimes you might need to convert between them (often involving simple casting or rounding).
We explore SDL_FRect
and the concepts of floating-point coordinates, world space vs. screen space, and camera implementation in more detail later in the course.
Rectangles and SDL_Rect
Learn to create, render, and interact with basic rectangles using the SDL_Rect
and SDL_Color
types.