Problem in making an autotile system, any help?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Spu7Nix

So ive written a script to make an autotile feature for my 2d procedural terrain, but for some reason it doesnt work as intended. I want the tiles to tile seamlessly, so that the tile with the top edge is on the top, bottom right corner on the bottom right etc. Heres the code for the autotile:

  func update():
	var mappos = chunk.world_to_map(position)
	
	
	if tileAt(0, -1) == null: #UP
		
		if tileAt(-1, 0) == null: #TOP LEFT CORNER
			$spr.texture = preload("res://tiles/dirt/dirtTL.png")
		elif tileAt(1, 0) == null: #TOP RIGHT CORNER 
			$spr.texture = preload("res://tiles/dirt/dirtTR.png")
			
		else: #TOP (never gets to here for some reason)
			$spr.texture = preload("res://tiles/dirt/dirtT.png")
		
	elif tileAt(0, 1) == 1: #DOWN 
		
		if tileAt(-1, 0) == null: #BOTTOM LEFT CORNER
			$spr.texture = preload("res://tiles/dirt/dirtBL.png")
		elif tileAt(1, 0) == null: #BOTTOM RIGHT CORNER
			$spr.texture = preload("res://tiles/dirt/dirtBR.png")
			
		else:
			$spr.texture = preload("res://tiles/dirt/dirtB.png")
	elif tileAt(1, 0) != null: #RIGHT
		$spr.texture = preload("res://tiles/dirt/dirtR.png")
	elif tileAt(-1, 0) == null: #LEFT
		$spr.texture = preload("res://tiles/dirt/dirtL.png")
	else: #CENTER
		$spr.texture = preload("res://tiles/dirt/dirtC.png")



func tileAt(xoff, yoff):
	var mappos = chunk.world_to_map(position)
	if mappos.x + xoff > chunk.size.x - 1 or mappos.x + xoff < 0 or mappos.y + yoff > chunk.size.y - 1 or mappos.y + yoff < 0:
		
		return null
	else:
		return chunk.tiles[mappos.x + xoff][mappos.y + yoff]

(BTW chunk.tiles is a 2d array that stores the tile objects on their respective places in a 32x16 grid)
Here is the result i get when i run:
Here is the result i get when i run:

I’m probably stupid, but i have struggled with this for a couple of hours now. Anybody got any help?

EDIT: The problem in the image is basibly that none of the bottom tiles work, the right tile doesnt work, the top right corner replaces the top tile for some reason)

:bust_in_silhouette: Reply From: Calamander

I’m not sure what your textures look like, but if you want to take into account every surrounding tile you should probably not exclude its check from result after 1-2 "if"s,.
Try using “match” instead, check all 8 neighboring tiles, sum up results and only after that choose appropriate texture.
Also why do you need your own autotile when Godot already has one? It’s not perfect but looks enough for what is in your picture. There is no official documentation for it right now but you can find good ones on the web like this one