Object not moving with this simple code (2d) godot4.0

Godot Version

4.0

Question

I used a script from a short tutorial on youtube and adapted it for my uses. My sprite should follow my cursor slowly and glide back to 0, 0 when my cursor is “out of bounds”. For some reason the sprite just refuses to move when I add the clauses and putting a while(true) just makes it freeze. attachments below

extends CharacterBody2D

func _physics_process(_float):
	var mouse_pos = get_global_mouse_position()
	#while true:
	if position && mouse_pos <= Vector2(772, 636) && position && mouse_pos >= Vector2(84, 148):
		var v : Vector2 = get_global_mouse_position() - global_position
		velocity = v
		move_and_slide()
	else:
		position = position.move_toward(Vector2(0, 0), 1 * 11)

(yes, the script is attached to the characterBody2D(my root))
(my starting position is within these conditions. (0,0))

Why are you checking position twice? And why are you checking if position is not Vector2(0, 0)?

A while loop inside the PhysicsProcess makes no sense, as it always runs every physics frame anyway. Some of the conditional checks would always return true, for example: position && mouse_pos

Here’s the script corrected, with an export value added for the speed at which the object should move.

extends CharacterBody2D

@export var speed = 200  # Speed for moving towards the mouse

func _physics_process(delta):
	var mouse_pos = get_global_mouse_position()
	var viewport_size = get_viewport().size

	# Follow the mouse when inside the viewport
	if mouse_pos.x >= 0 and mouse_pos.x < viewport_size.x and mouse_pos.y >= 0 and  mouse_pos.y < viewport_size.y:
		var direction = (mouse_pos - global_position).normalized()
		velocity = direction * speed
		move_and_slide()
	else:
		# Move back towards the origin
		var direction_to_origin = (Vector2.ZERO - global_position).normalized()
		velocity = direction_to_origin * speed 
		move_and_slide()
1 Like