The library I am using (SDL2) only supports drawing to int positions. I am currently storing my objects positions as double, and would like to render them. Should I round the value to int, i.e. 0.5 => 1, or simply cast it to int, i.e. 0.5 => 0?

  • 3
    \$\begingroup\$ As long as your rendered positions aren't negative, then rounding is the same as casting/truncating after adding 0.5 - so you'd get the same rendered result with either method as if your camera/viewpoint were nudged by half a pixel while using the other method. Does that distinction matter? \$\endgroup\$ – DMGregory Mar 18 '17 at 16:47

Maybe this answer will not suit your question, but I assume that you want to have float movement precision even when SDL rectangles support only integer values.

One of the tricks you can do is to have a float/double variables to track some kind of "virtual" position in your world. In your case it means having a struct SDL_Rect and some float vector. For example:

//Custom made generic type
Vector2<float> _position;

//SDL struct
SDL_Rect _rect;

void Object::init(float x, float y,SDL_texture* text)
    _position.x = x;
    _position.y = y;

    _rect.x = (int)x;
    _rect.y = (int)y;

    _texture = text;

And then the update function would look like this:

void Object::update(float deltaTime){

    _position.x += 5.0f * deltaTime;
    _position.y += 5.0f * deltaTime;

    _rect.x = (int)_position.x;
    _rect.y = (int)_position.y; 

That way you don't lose the movement precisions the floats have. Then you can use this position vector also for collision checks, where instead of checking SDL_Rects (in case of Rectangular collision) you check their position vectors+dimensions.

| improve this answer | |

There's a simple way to render a rectangle with floating point coordinates but for some reason it's documentation is not available on the wiki. A commit was done to add this feature on October 22, 2018.

SDL_FRect box = {11.5, 1.2, 10.5, 11.252};
SDL_RenderFillRectF(renderer, &box);

A simple demonstration of how it can be used for rendering.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.