I am making a game and I am looking for some help with an elementary camera-following algorithm.
- Say we have a window which has the size of 320 by 480.
- We also have
a player with coordinates x,y. - The user can move the player with the
arrow keys. - The camera is following the player coordinates. [The camera coordinates are where the screen is]. So camera.x=player.x and camera.y=player.y
Now the problem that I am getting is : when the player reaches the end of the room,
I can see the ‘outside’ of the room. So ideally the camera should stop moving when it is approaching the end of the room.
I am not sure how to tackle this problem efficiently and this does seem like a common feature in games. Any help would be great.
My code, it doesnt work.. really at all, the view goes wacky randomly*:
#bi_currentwindow.layout.x = -(top left x corner of window)
#bi_currentwindow.layout.y = -(top left y corner of window)
#bi_bg_size= total room (or world) size
diff=(object.x-Window.size[0]/2)
if diff<0:
bi_currentwindow.layout.x = object.x+diff
else:
diff=(object.x+Window.size[0]/2)-bi_bg_size[0]
if diff<0:
bi_currentwindow.layout.x = -object.x+Window.size[0]/2.0
diff=(object.y-Window.size[1]/2)
if diff<0:
bi_currentwindow.layout.y = diff+Window.size[1]/2
else:
bi_bg_size=centralVarTransfer.bi_bg_size
diff=bi_bg_size[1]-(object.y+Window.size[1]/2)
if diff>0:
bi_currentwindow.layout.y = -object.y+Window.size[1]/2.0
I prefer to make the player center screen and move the background, whenever I do a 2D game. This allows you to do: If my rooms side is > or < my screen size, then move my screen so its side is equal to my screen size.
But if you have a camera and prefer to use that method:
The math should be pretty easy.
Something like:
my code might be a bit off (and only for one side of the room), but conceptually you are checking if your camera position modified by an offset (based on camera width or height) is greater or less than the room position modified by an offset (based on room width or height).
I find having 2 index cards and moving one around like the camera helps conceptualize the boundary conditions you are trying to code.