Follow mouse position acts weird

Godot Version

4.3

Question

Hi! I’m new to Godot, I’ve been creating a 2D multiplayer game, I have 11 CharacterBody2D and I want to move them by selecting one, clicking somewhere in the terrain and make it go there. Everything is working except that the selected character goes “near” the mouse, it has an offset, you can see it in the picture, here it’s some of the code for the CharacterBody2D:

extends CharacterBody2D

var speed = 150

var mouse_over = false
var selected = false
var move = false
#sync
var sync_pos : Vector2:
	set(value):
		sync_pos = value
		processed_pos = false
var processed_pos : bool
	
func setMultiplayerAuthority(value):
	$MultiplayerSynchronizer.set_multiplayer_authority(value)

func is_local_authority():
	return $MultiplayerSynchronizer.get_multiplayer_authority() == multiplayer.get_unique_id()
	
func _ready() -> void:
	input_pickable = true
	mouse_entered.connect(_on_mouse_entered)
	mouse_exited.connect(_on_mouse_exited)
	
func _process(delta):
	if is_local_authority():
		look_at(get_global_mouse_position())
		# go to position
		if move:
			var dir = position.direction_to(get_global_mouse_position())			
			velocity = speed * dir.normalized()
			if position.distance_squared_to(get_global_mouse_position()) > 1:
				move_and_slide()
		processInput(delta)
	else:
		if not processed_pos:
			position = sync_pos
			processed_pos = true

	sync_pos = position
	
func setPosition(pos):
	position = pos
	print(position)

func getPosition():
	return position

func processInput(delta):
	if Input.is_action_just_released("LClick"):
		if mouse_over:
			selected = true
			print("selected")
		elif selected:
			move = true
			selected = false

func _on_mouse_entered() -> void:
	if is_local_authority():
		mouse_over = true

func _on_mouse_exited() -> void:
	if is_local_authority():
		mouse_over = false

I think you have to use the player’s global_position instead of just position. That should hopefully fix the offset.

Oh man, noob mistake, that solved it, thank you so much!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.