Jump to content

  • Log In with Google      Sign In   
  • Create Account


MichaelStahre

Member Since 13 Dec 2011
Offline Last Active Dec 14 2011 04:38 PM

Posts I've Made

In Topic: SDL - Camera Movement

13 December 2011 - 07:55 AM

This isn't really an SDL-specific solution, but when drawing with any library you'll always be specifying where on the screen you want to draw.

As I only have square-drawing SDL code lying around, I'll throw you an example where the player is drawn on the screen in the form of a small, black square.

Here, position is a struct containing the x-position and the y-position of the player.

    SDL_Rect player_rect = {position.x, position.y, 30, 30};
    SDL_FillRect(screen, &player_rect, SDL_MapRGB(screen->format, 0x00, 0x00, 0x00));


If you then want a camera, then one simple solution is to have a camera struct that's just like the position struct and use that as an offset.
    SDL_Rect player_rect = {position.x - camera.x, position.y - camera.y, 30, 30};
    SDL_FillRect(screen, &player_rect, SDL_MapRGB(screen->format, 0x00, 0x00, 0x00));


If you always subtract the position you want to draw to with the position of the camera whenever you draw something, including the stage geometry, then you can just move the camera and everything else will be properly offset.
If moving the player then also moves the camera then the player is free to move throughout the stage and will always be drawn at the same position relative to the camera while the rest of the stage will stay put.


There are better and/or more sophisticated solutions, but that should probably serve your most basic needs.
I don't know if SDL has any built-in camera functionality, but I know there are frameworks that do (such as XNA, where SpriteBatch can take the camera offset as a parameter.)

PARTNERS