#Handling hover on Tilemap individual tiles

2 messages · Page 1 of 1 (latest)

quaint rose
#

Hi, I'm trying to wrap my head around Tilemaps and I'm trying to do something as simple as modifying a tile when my house is hovering it. I've read the documentation and fiddled around and came out with this solution that works. However it feels clunky and I was wondering if there is a better approach. Any recommendation welcome, thank you 🙂

class_name Arena extends TileMap

const OUT_OF_ZONE: Vector2i = Vector2i(-1, -1)

var has_hover: bool = false
# Default value outside of the tilemap
var hover_tile: Vector2i = OUT_OF_ZONE
var last_hover_tile: Vector2i = OUT_OF_ZONE

func _unhandled_input(event: InputEvent):
    if not event is InputEventMouseMotion:
        return

    var mouse_pos: Vector2 = get_global_mouse_position()
    var tile_pos: Vector2i = local_to_map(mouse_pos)
    var tile_data: TileData = get_cell_tile_data(1, tile_pos)

    var previous_has_hover = has_hover
    last_hover_tile = hover_tile
    if tile_data != null:
        has_hover = true
        hover_tile = tile_pos
    else:
        has_hover = false
        hover_tile = OUT_OF_ZONE

    # Notify only when a change occurred
    if previous_has_hover != has_hover or last_hover_tile != hover_tile:
        notify_runtime_tile_data_update(1)


func _use_tile_data_runtime_update(layer: int, coords: Vector2i) -> bool:
    return layer == 1 and (coords == hover_tile or coords == last_hover_tile)


func _tile_data_runtime_update(_layer: int, coords: Vector2i, tile_data: TileData) -> void:
    tile_data.modulate = Color.RED if coords == hover_tile else Color.WHITE
quaint rose
#

Actually I found a weird bug while doing more tests. I have an array of highlighted nodes and I use it like that :

func _tile_data_runtime_update(layer: int, coords: Vector2i, tile_data: TileData) -> void:
    print("Updating tile data ", coords)
    print(highlighted_tiles)
    if layer != 1:
        return
    
    if coords in highlighted_tiles:
        tile_data.modulate = Color.GREEN
    elif coords == hover_tile:
        tile_data.modulate = Color.RED 
    else:
        tile_data.modulate = Color.WHITE

So I can have both a hover tile and a fixed list of highlighted tiles. But I have this weird bug, if I hover on a x value equal or lower than one of the highlighted tiles, it resets its modulate, even if I didn't get called on its coordinates 😬