I’m new to godot and I have a problem

Godot Version

4.2.2

I studied programming 20 years ago, but I only now decided to return and try again due to personal problems.

I generally don’t ask for help, I prefer to study to understand the subject, but I find myself stuck.

I’ve been studying Godot for a month and a half, and I’ve already understood almost the entire program, but the language, despite being easy to understand, is difficult to write. I’ve been trying to do simple logic for two weeks, but nothing I try works.
The funniest part is that I’m stuck in what I swore would be the easiest part… :sweat_smile:

What I’m trying to do is simple: I have a button and when I click it I instantiate an object (which must follow the mouse pointer) and I duplicate it in my scene. In other words, it is a builder like Cities Skylines but 2D.

I’ve tried over 20 different codes but none of them worked…here’s the current code:

Contol–
–Button

extends Button

var object_scene: PackedScene = preload(“res://scenes/Buildings/build_01.tscn”)
var object_to_duplicate: Node2D = null

func _on_pressed():
if object_to_duplicate == null:
object_to_duplicate = object_scene.instantiate()
object_to_duplicate.global_position = get_global_mouse_position()
get_tree().root.add_child(object_to_duplicate)

else:
	var new_object = object_to_duplicate.duplicate()
	new_object.global_position = get_global_mouse_position()
	get_tree().root.add_child(new_object) 

func _process(delta):
if object_to_duplicate != null:
object_to_duplicate.global_position = get_global_mouse_position()

The problem with this code is:

  • The object is created but does not correctly follow the mouse cursor.
  • The object is not duplicated on the screen.

If anyone could please help me I would appreciate it…without understanding how this works my project simply ends here…

Thanks.

Is the sprite in the scene you preload centered? That may be the problem.

This only fix the object not correctly follow the mouse cursor.
Thanks :hugs:

Now i need to know how duplicate this object…i try i few changes on the button script but doesn’t work either…now my code is this:

extends Button

var object_scene: PackedScene = preload(“res://scenes/Buildings/build_01.tscn”)
var object_to_duplicate: Node2D = null

func _on_pressed():
var object_to_duplicate = object_scene.instantiate()
object_to_duplicate.global_position = get_global_mouse_position()
add_child(object_to_duplicate)

	var new_object = object_to_duplicate.duplicate()
	new_object.global_position = get_global_mouse_position()
	add_child(new_object)

What is the intention of this code? Because this will duplicate the node and put in the same place as the first one so nothing will change

Ok…soo can you help me understand how to fix it ?

The intention is a object placement…like a builder game…I have a button and when I click it I instantiate an object and I duplicate it in my map.

Here a video of whats is happening…

extends Node2D

# O objeto que vc planeja criar
var object_scene: PackedScene = preload("res://color_rect.tscn")
# A instancia do objeto criado
var new_object: Node

func _ready():
	# Começa como falso pq vc n precisa dele funcionando enquanto não
	# tiver criando algo
	set_process(false)


func _process(delta: float) -> void:
	# Seta a posição do seu objeto para a posição do mouse, questões 
	# de centralização vão variar de acordo com o objeto sendo mexido
	# no seu caso vai ser bom ter uma função que retorne o tamanho do objeto
	# sendo criado pra setar um offset, como eu sei que o tamanho do node
	# então uso ele diretamente
	new_object.global_position = get_global_mouse_position() - (Vector2(40, 40)/2)


func _unhandled_input(event: InputEvent) -> void:
	# Se o evento for um clique do mouse
	if event is InputEventMouseButton:
		# Se new_object não for nulo, o clique for do botão esquerdo do mouse 
		# e se for pressionado, desliga _process e deixa o node parado na 
		# posição do mouse
		if new_object and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
			# Aqui uso modulate pq estou simulando o objeto com
			# um node do tipo ColorRect, pra o seu caso vc deve criar uma 
			# função no objeto pra avisar quando ele esta na posição final 
			# caso vc queira que ele troque de cor ou qualquer outra ação
			new_object.modulate = Color.WHITE
			# Desliga o _process pra não mexer mais o node
			set_process(false)
			new_object = null


func _on_button_pressed() -> void:
	# Instancia seu novo objeto e garante que vc tem uma referencia dele,
	# não precisa duplicar o node
	new_object = object_scene.instantiate()
	# Aqui estou usando add_child direto só pra exemplo mesmo, mas o ideal
	# é vc ter um node exclusivamente pra segurar todos as construções
	add_child(new_object)
	# Isso aqui é só pra ele mudar de cor enquanto movo, vc n vai usar essa
	# linha abaixo
	new_object.modulate = Color.YELLOW
	# Essa vc precisa, vai ligar o callback _process para mexer seu novo objeto
	set_process(true)

2 Likes

It worked !!! Thank you very much. And thank you very much for the explanations. I will study to understand better. Again thank you very much :hugs: