Game Development Reference
In-Depth Information
Although this could be done with if statements, as the complexity of the system
increases these statements would become increasingly complex. A better solution
is to use a clamp function, which takes a value and restricts it to be between a
minimum and maximum value. In this case, we want the camera's x-position to
be equal to the player's x-position, with a minimum valid value of half the screen
width and a maximum valid value of the center of the final background.
Once we have the position of the camera, we can then determine which back-
groundsarevisiblebasedonthecamera.Finally,allthesprites,includingtheback-
grounds, can be drawn with an offset based on this camera position.
Click here to view code image
// camera.x is player.x as long as its clamped
within the valid range
camera.x = clamp( player.x , screenWidth / 2,
hCount * screenWidth -
screenWidth / 2)
Iterator i = bgSpriteList .begin()
while i != bgSpriteList .end()
Sprite s = i .value()
// find the first bg image to draw
if ( camera.x - s.x ) < screenWidth
// Image 1: s.x = 0, camera.x = 480,
screenWidth/2 = 480
// 0 - 480 + 480 = 0
draw s at ( s.x - camera.x + screenWidth /2, 0)
// draw the bg image after this, since it
might also be visible
i ++
s = i .value()
draw s at ( s.x - camera.x + screenWidth /2, 0)
break
end
i ++
loop
This provided code implements scrolling where the camera and player can move
forward and backward through the level, as in games such as Super Mario World .
Search WWH ::




Custom Search