How to Set and Restrict the Camera 2d Boundary in Godot Game engine


I have been learning and practicing Godot game engine by watching free high quality video series from HeartBeast. I really want you to go and watch this RPG tutorial series to learn practical fundamentals of Godot engine. In part-20 of the series we learned about setting up camera and make camera follow the player around the level. It is very easy in Godot.

Above tutorial video lets you learn to easily setup player Camera2D. One thing was missing and I took a challenge exercise where camera stops following the player when player is near the edge or boundary of the level. Currently camera moves with player and vast empty space is visible when player is near boundary of the level.

My solution is based on existing type of game world I am working with.

My world has TileMaps. Entities like dirt, cliffs, walls etc are layered with TileMap. The boundaries in my level are layered with TileMap. Level of my game has cliff on the boundaries. I want camera to avoid following the player near the boundaries. Bounds of limitation that camera going to use will be based on size of TileMap rendering cliffs. Code script is attached to the root of scene. Lets dive on code

onready var cliffTileMap = $DirtCliffTileMap
onready var camera = $Camera2D

func _ready():

func set_camera_limits():
    var map_limits = cliffTileMap.get_used_rect()
    var map_cellsize = cliffTileMap.cell_size
    camera.limit_left = map_limits.position.x * map_cellsize.x
    camera.limit_right = map_limits.end.x * map_cellsize.x
    camera.limit_top = map_limits.position.y * map_cellsize.y
    camera.limit_bottom = map_limits.end.y * map_cellsize.y
Node for 2D tile-based maps. Tilemaps use a TileSet which contain a list of tiles (textures plus optional collision, navigation, and/or occluder shapes) which are used to create grid-based maps.

Code brief:

  • First we get rectangle bounds of TileMap, this bounds will be calculated based on tiles that are used. Left side of bounds will be the tile space that has been used in very left. Same goes for rest of the directions.
  • Rect2 get_used_rect ( )
    Returns a rectangle enclosing the used (non-empty) tiles of the map.

  • Next we need pixels value to assign the limits of Camera. TileMap deals with cells or tiles. We need to calculate pixels from sizes of cells. Left boundary pixel will be size-of-cell times the origin of Rect. Right boundary will be size-of-cell times postion-of-last-cell in horizontal axis. So on.
  • We set Camera limits when our world is ready with nodes on _ready function.

More Articles

Recommended posts