How can I create touch-able Sprites only using code?

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

I have about 100 sprites on screen, and I want to touch/click them individually, and I need to create them only using script, not with the editor.

I’ve tried using

TouchScreenButton

InputEventScreenTouch

Control

ColorRect

Area2D

Here is my code:

    var click_dummy = ColorRect.new()
    click_dummy.color = Color(0,1,0,0.2)
    click_dummy.rect_size = Vector2(50,50)
    click_dummy.rect_position = Vector2(pt[0]-25,pt[1]-25)
    click_dummy.set_script(touchscript)
    card_node.add_child(click_dummy)
    click_dummy.name = 'click'+str(card_id)+'_'+str(i)

    var scale = 0.7 * rng.randf_range(0.75, 1.0)
    var angle = rng.randf_range(0,180)

    var spr = Sprite.new()
    spr.scale = Vector2(scale,scale)
    spr.rotate(angle)
    spr.position = Vector2(pt[0],pt[1])
    spr.texture = load("res://jfsdlfhsdjo")

Here is the touchscript script:

extends ColorRect
#extends Sprite
#extends Control
#extends TouchScreenButton

func _ready():
    pass
func _process(delta):
    pass

#func _input_event(event):
func _input(event):
    if event is InputEventScreenTouch or event is InputEventMouseButton:
#        if event.is_pressed():
        print(event.position)
        print(get_name())

Clicking/touching fires the event on all the sprites I have, while I just want to fire the event on the one I touch/click.

:bust_in_silhouette: Reply From: wyattb

Can you show how you have your input and event code setup?

I’ve edited my question.

jokoon | 2021-06-17 14:18

Make your area2d/sprite a separate empty scene and add the event script to it. You can then check the name of what was clicked.

extends Area2D

func _on_Area2D_input_event(viewport: Node, event: InputEvent, shape_idx: int) -> void:
	if (event is InputEventScreenTouch or event is InputEventMouseButton) and event.is_pressed():
		print(name)
		pass # Replace with function body.

on your main app, load the empty scene and then customize accordingly.

extends Node2D

var rng = RandomNumberGenerator.new()

func _on_Button_pressed() -> void:

	rng.randomize()
	var scene = load("res://Testing/SpritesTest/ScriptsTest.tscn")
	var click_dummy = scene.instance()
	add_child(click_dummy)
	var spr=Sprite.new()
	spr.texture=load("res://icon.png")
	click_dummy.add_child(spr)
	var i=rng.randi_range(1,1000)
	var j=rng.randi_range(1,1000)
	click_dummy.name = 'click'+str(i,j)
	click_dummy.position=Vector2(i % 500,j % 500)
	print(click_dummy.position," ",click_dummy.name)	
	pass # Replace with function body.

wyattb | 2021-06-17 16:59