5
\$\begingroup\$

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?

\$\endgroup\$
  • 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
2
\$\begingroup\$

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.

\$\endgroup\$

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.