Hi I’m a newbie to programming, I am trying to create a movement system with a mouse. When the player left clicks the sprite moves and when the player left clicks again the sprite stops at the mouse’s position. How can I achieve this?
This is my current code that has the sprite following the mouse’s position:
@export var speed = 200
var mouse_position = null
func _physics_process(_delta):
velocity = Vector2(0,0)
mouse_position = get_global_mouse_position()
var direction = (mouse_position - position).normalized()
velocity = (direction * speed)
move_and_slide()
look_at(mouse_position)
You can get left mouse click by using _input method like this
func _input(event):
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
print("Left mouse button clicked")
Currently you are using mouse_position = get_global_mouse_position() inside _physics_process, so that means that your mouse_position will update every physics frame.
You probbably want to move that under mouse click?
I added your code after the physics process function. The game registers the left click’s input, but the sprite is not stopping at the mouse’s position
Did I input mouse_position = get_global_mouse_position() correctly?
func _input(event):
mouse_position = get_global_mouse_position()
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
print("Left mouse button clicked")
If I place mouse_position = get_global_mouse_position() under any other If statement listed in input function, I get an error in the direction variable in the physics process function
Did you remove mouse_position = get_global_mouse_position()
from _physics_process?
Also move mouse_position under print like this:
func _input(event):
if event is InputEventMouseButton:
if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
print("Left mouse button clicked")
mouse_position = get_global_mouse_position()
I placed this code in and it works, however it wasn’t what I was trying to achieve. The sprite follows and stops at the point where the mouse clicked. The sprite doesn’t follow the cursor. What I’m trying to achieve is when the player left clicks the sprite moves and when the player left clicks again the sprite stops at the mouse’s position