How do i make it so a sprite moves when clicked with mouse

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

I am making a game where you clean trash out of space. I want to make it so that when you click the trash it moves to a randomly different place each time clicked with the mouse

make new node with type texture button

megatron | 2023-03-14 06:08

attach newly created node with script (create new script)

megatron | 2023-03-14 07:12

select newly created node, select node tab (at right upper corner of the screen, right of inspector tab)

megatron | 2023-03-14 09:04

select pressed(), then select connect
type _on_pressed, below receiver method
select connect

megatron | 2023-03-14 09:05

open node script, select all, and copy-paste code below:

extends TextureButton

var screen_width = 1152
var screen_height = 648


func _on_pressed():
	var random = RandomNumberGenerator.new()
	var new_position = Vector2(random.randf_range(0, screen_width), random.randf_range(0, screen_height))
	position = new_position

megatron | 2023-03-14 09:08

select run button to try if its working

megatron | 2023-03-14 09:12

:bust_in_silhouette: Reply From: Merlin1846

Here’s some pseudo-code, although I would highly recommend you attempt to do this you’re self if you haven’t by now due to its simplicity.

 func _input(event):
      if event.is_action_mouse_click():
           if get_local_mouse_position() == position:
                position = Vector2(rand_range(0, 512), rand_range(0, 512))

If you want to make it move smoothly consider using a physics body if that’s what you want, or take a look at the lerp() function which can be called on almost anything that has a value.

Do note that this code requires that you’re mouse is perfectly on the node and it would be better to use a button or a distance() function.