Implementing Camera Pan in Critters



Camera Pan




Speaking about another thing I never paid attention to in my 2D game prototypes, camera movement and camera view ranks just around the top. Next to the UI. They're friends in fact.

When implementing parallax scrolling and even when playing with the top down tiled based programs I coded, the idea of camera control was always there, but as my prototypes never did move above, well the prototypes phase, I never really needed a true camera view and control.
Until I started playing with the Critters Level design that is. And the first design decision was:
Levels will be larger than device max resolution. So no more cheating and moving level layers at different speeds, It's time for a serious 2D Camera implementation.

So what does camera object needs to properly function? Not much as it turns out. It needs CameraView rectangle, UpdateCamera function, x and y relative to mouse motion and current level's width and height to make sure camera view stays in bound of the level and that's it.

In our main loop, we now listen to the  SDL_MOUSEMOTION and update out global variables based on the received event. For camera, we are especially interested in the sdlEvent_.motion.xrel and sdlEvent_.motion.yrel variables because they track the relative motion in their respective directions. We need these values because in our case the Camera is moved by holding the right mouse button. Or in Android case a multi touch gesture.
We also, call Camera's UpdateCamera from this event.

Our UpdateCamera function is simple.

If right click is pressed / multi touch 
  If we are moving camera right  (-xrel)
    subtract xrel from camera.x
 else we are moving camera left (xrel)
     subtract xrel from camera.x

Do the same when moving camera up and down and in the end do the checks to not let the camera leave the level rectangle.

Sample code:


Example Camera Movement

  
The other thing that needed work was my Level drawing function.

Until now, the level just drew all its elements directly on screen, but with camera, this changes a little. So instead of the screen, we now render to texture and then clip the camera_view to the screen.
To do that we must first create a blank SDL_Texture the size of the level with the SDL_TEXTUREACCESS_TARGET parameter set. Once this is done we can now use this new texture as a giant screen and just draw the entire level as we would normally but this time using  SDL_SetRenderTarget.

At this point we have entire level drawn on the specified texture and now we just need to show the specified camera rectangle on screen and that's it.
Camera Panning complete.

Example SDL_SetRenderTarget




 If you're interested in Critters or find this blog moderately interesting,
You can follow me on Twitter for news and updates
https://twitter.com/CrittersDev






Comments

Popular posts from this blog

Trouble in Qt Paradise

Programming UI for Critters

Of Loot Bombs and Sticky Walls