#Issue with TextureButton drag & drop not consistently instantiating scene on TileMapLayer

3 messages · Page 1 of 1 (latest)

little grail
#
  1. A UI scene
  2. A character scene
  3. A Node2D that contains both the UI and a TileMapLayer node

In the UI scene, I have a TextureButton with an Area2D as its child node. The TextureButton has a script that basically does this:

When I press and drag the TextureButton over the TileMapLayer (which is in a specific group), the Area2D detects when the TileMapLayer body enters, and then the TextureButton should instantiate the character scene on a specific cell of the TileMapLayer.

The problem is: while the Area2D correctly detects the TileMapLayer, most of the time the TextureButton (which has a Sprite2D showing a card) doesn't instantiate the character scene. I have to drag the card (TextureButton) multiple times for the character scene to finally instantiate.

Hope this makes sense 😅

#

Here's my code:

#

extends TextureButton

var card_is_pressed:bool = false
var card_was_pressed:bool = true
var default_pos:Vector2
var last_valid_road:TileMapLayer = null
@onready var road_area:Area2D = $Area2D
var orc = preload("res://Godot Archives/Entities/o_warrior.tscn")

func _ready() -> void:
default_pos = self.global_position
connect("button_down", _on_card_pressed)
connect("button_up", _on_card_released)
road_area.connect("body_entered", road_entered)
road_area.connect("body_exited", road_exited)

func _process(delta: float) -> void:
pass

func road_entered(body:Node2D):
if body.is_in_group("road"):
last_valid_road = body

func road_exited(body:Node2D):
if body == last_valid_road:
last_valid_road = null

func _gui_input(event: InputEvent) -> void:
if card_is_pressed and event is InputEventScreenDrag:
self.global_position += event.position

func _on_card_pressed():
card_is_pressed = true

func _on_card_released():
card_is_pressed = false

if last_valid_road:
    #var bottom_pos = global_position + Vector2(0, size.y / 2)
    var local_pos = last_valid_road.to_local(global_position)
    var card_pos = last_valid_road.local_to_map(local_pos)
    var data:TileData = last_valid_road.get_cell_tile_data(card_pos)
    
    if data:
        var can_put:bool = data.get_custom_data("path")
        if can_put:
            if not card_is_pressed:
                var orc_warrior = orc.instantiate()
                last_valid_road.add_child(orc_warrior)
                var orc_pos = last_valid_road.local_to_map(orc_warrior.global_position)
                
                orc_warrior.position = last_valid_road.map_to_local(card_pos) 
                self.queue_free()
    
else:
        self.global_position = default_pos