Mouse pointer code problem?

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

Hi everyone, I have a problem with the code regarding “making the object move towards the mouse pointer”. I followed the tutorial on godot official documentation but it didn’t work. So I decided to do it without following the documentation but the problem is that when I click to make the object go to a given position, the object goes in that direction but it doesn’t stop. Here is the code:

var dir = Vector2()
var speed = 200

func _input(event):
if event is InputEventMouseButton:
dir = position.direction_to(event.position)

func _physics_process(delta):
move_and_slide(dir * speed)

:bust_in_silhouette: Reply From: exuin

First off, I’m pretty sure that the official tutorial should work. Did you add “click” to the InputMap in the project settings?

Second, the official tutorial has a check that makes it stop moving once it gets close enough to the target. You don’t have a target, only a direction, so there is no way to stop the object. I think you should try going through the official tutorial again.

In the official tutorial I saw that the object stops (the thing that doesn’t work for me) when it stops moving towards a point indicated by the mouse pointer! However it seemed strange to me too that an official tutorial code doesn’t work.

Peppe | 2021-06-22 06:38

:bust_in_silhouette: Reply From: wyattb

You can do something like this:

func _input(event):
	if event is InputEventMouseButton and event.pressed:
		target = event.position

func _physics_process(delta):
	if target != Vector2.ZERO and target != position:
		position=position.move_toward(target, velocity.length())