Topic was automatically imported from the old Question2Answer platform.
Asked By
Emerald_Gunther
Hello I have been attempting to make a simple game that moves the player object to the mouse but have been having some trouble:
extends CharacterBody2D
func _ready():
pass
func _physics_process(delta):
look_at(get_global_mouse_position())
var speed = 500
var mouse_pos = get_global_mouse_position()
if Input.is_action_pressed("move_to_mouse"):
velocity = position.direction_to(mouse_pos) * speed
else: velocity = Vector2.ZERO
move_and_slide()
I have been using the above code but instead of moving the player to the mouse like I intended it to, it is moving to the lower right of the player and then just bugging out. I can move it around it just never reaches the mouse and it is super slow when it is already at the lower right of the player.
Does any one know how to fix this. Thanks.
On its own, the code looks fine but you mentioned that it moves to the lower-right of the player so I suspect some parent-child hijinks where the child is moving correctly, as far as its parent nodes allow (ish, that is with scaling, etc).
What’s the hierarchy look like?
spaceyjase | 2023-04-11 14:39
Hello I was able to fix the issue by centering the player using
var mouse_pos = get_global_mouse_position() - Vector2(450,300)
I have no idea why I have to subtract that high to center the player but it works.
My hierarchy though is
Node2D → CharacterBody2D → Sprite2D and CollisionShape2D
My sprite is scaled down to .25 if that has something to do with it. Thanks
var mouse_pos = get_global_mouse_position() - Vector2(50,50) #Center the player
velocity = position.distance_to(mouse_pos) * position.direction_to(mouse_pos) #Move
move_and_slide()
When you say bugging out I think you mean it vibrates this can be fixed by multiplying with distance_to.When your player is close distance_to will become 0 so it will not vibrate.
For fixing moving to the wrong position like to the lower right you have to subtract the center point of your player shape from the mouse position.
Thanks for the help I got it working. For whatever reason this line was not working:
did you multiply this with your speed variable ? If you did can you try it without it ? I tried to replicate your problem but i couldnt. The only thing I found is using high values like 500 breaks this line and sets your node position to NaN but if you use lower numbers it works fine. I cant think of anything else.