Rotating a sprite in SDL2?

Started by
1 comment, last by Sunsharior 9 years, 1 month ago

Can anyone that has ever done this please share how to do it? I'm looking at the LazyFoo tutorials and that code isn't working for me (using SDL_RenderCopyEx doesn't even draw the sprite). I want to rotate a sprite in real time based on where a specific object is. Is SDL even capable of doing this?

Advertisement

You can rotate a sprite using SDL2, based on whatever you feel like coding -- time passed, position of mouse cursor, etc.

If you're having problems with getting SDL_RenderCopyEx working, start there. It should work, so you're doing something wrong somewhere.

Hello to all my stalkers.

With this simple snipet, you will be able to draw a sprite.


// for this to work, i will assume you already have a SDL_Renderer and a SDL_Window.
SDL_Texture *texture = IMG_LoadTexture(renderer, "image.png");

// if the texture was loaded.
if(texture)
{
    SDL_Rect rect = {0, 0, 32, 32}; // the rect is where you wants the texture to be drawn (screen coordinate).
    SDL_Rect crop = {0, 0, 16, 16}; // the crop is what part of the image we want to display.

    float angle = 180.0f; // set the angle.
    SDL_Point center = {8, 8}; // the center where the texture will be rotated.
    SDL_RendererFlip flip = SDL_FLIP_NONE; // the flip of the texture.

    // now, try to draw something
    int result = SDL_RenderCopyEx(renderer, texture, &crop , &rect, angle, &center, flip);
    
    if(result!= 0)
        std::cout << SDL_GetError() << std::endl;
}
else
    std::cout << Error << "Couldn't render texture." <<  std::endl;

Using this example, you will draw an image rotated 180 degree.

It will be drawn at 0,0 with a width of 32 and a height of 32. The crop is 16x16 and the rotation is 180 that is centered at 8,8.

I hope this help.

If you have errors, feel free to post it.

This topic is closed to new replies.

Advertisement