How to delete and add tiles if they exited the screen?

Godot Version :smiley:

4.3

Question(Important):exclamation:

for performance, i really want to know how to make tiles of the tilemap get deleted if they exit the screen and if they are in the screen the tiles are visible again.but i dont know how to make/code it.

if you know the answer, pls reply i will really appreciate it :smiley:

forget about it i discovred it by myself.for thoose who have the same problem you just have to paste this code to your tilemap script:

extends TileMap

var camera_rect: Rect2 # Stores the camera’s visible area
static var cell_size: Vector2 = Vector2.ZERO # Static variable for cell size
var original_tiles: Dictionary = {} # Dictionary to store original tile data (for restoration)

Called once when the scene starts

func _ready() → void:
cache_original_tiles()
cell_size = cell_size # Cache the cell size for future use

Cache all original tiles in the TileMap

func cache_original_tiles() → void:
for tile_position: Vector2i in get_used_cells(0): # Use layer 0 as the default
original_tiles[tile_position] = get_cell_source_id(0, tile_position)

Update camera rect and manage tile visibility every frame

func _process(_delta: float) → void: # Prefix unused parameter
update_camera_rect()
manage_tile_visibility()

Update the camera’s visible area

func update_camera_rect() → void:
var camera: Camera2D = get_viewport().get_camera_2d() # Assumes you have a Camera2D
if camera:
var screen_size: Vector2 = get_viewport().get_visible_rect().size
camera_rect = Rect2(camera.global_position - screen_size / 2, screen_size)

Show or delete tiles based on visibility

func manage_tile_visibility() → void:
var visible_cells: Array[Vector2i] = get_visible_cells(camera_rect)

# Iterate through only the cached tiles
for tile_position: Vector2i in original_tiles.keys():
	var tile_is_visible: bool = tile_position in visible_cells
	var tile_is_set: bool = get_cell_source_id(0, tile_position) != -1

	# Update visibility only if necessary
	if tile_is_visible and not tile_is_set:
		show_tile(tile_position)
	elif not tile_is_visible and tile_is_set:
		hide_tile(tile_position)

Get visible tiles based on the camera’s rect

func get_visible_cells(rect: Rect2) → Array[Vector2i]:
var visible_cells: Array[Vector2i] =
var min_pos: Vector2i = (rect.position / cell_size).floor()
var max_pos: Vector2i = ((rect.position + rect.size) / cell_size).ceil()

# Populate the visible cells
for x: int in range(min_pos.x, max_pos.x):
	for y: int in range(min_pos.y, max_pos.y):
		visible_cells.append(Vector2i(x, y))

return visible_cells

Show tile at a specific position

func show_tile(tile_position: Vector2i) → void:
set_cell(0, tile_position, original_tiles[tile_position])
print(“Tile restored at:”, tile_position)

Hide tile at a specific position

func hide_tile(tile_position: Vector2i) → void:
set_cell(0, tile_position, -1)
print(“Tile removed at:”, tile_position)