Why isn't the Rigidbody 2d following the mouse with the code below?

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

func _on_Area2D_input_event(viewport, event, shape_idx):

if event is InputEventMouseButton:

if event.is\_pressed():

	selected = true


	mode =RigidBody2D.MODE\_STATIC			


	selected = false

	mode = RigidBody2D.MODE\_RIGID

func _physics_process(delta):

currentpos = get_global_position()

if selected == true:

var position = get\_position()

var angletomouse = position.angle\_to(get\_global\_mouse\_position())

var directionfm = Vector2(cos(angletomouse), sin(angletomouse))

add\_central\_force(directionfm \* movespeed)


\#global\_position = get\_global\_mouse\_position()


selected = false

I followed a tutorial for the selection bit but the bit I run in the physics process is mine. At the moment it just accelerates off to the right until I click again. I think I know why the acceleration thing is happening (because I’m adding a force every frame?) but I don’t know why it isn’t going towards the mouse. Let me know if I need to clarify anything, and any help is much appreciated!

a simple

var direction = position.direction_to( get_global_mouse_position() )
set_axis_velocity ( direction * speed )

should do the trick.

Try to avoid euler math, always go with vector math!

P.S. providing proper formated code in your question will encurage more users to have a look into it.

klaas | 2020-09-02 09:36

Thank you so much!! I’ve spent so long trying to get this to work!! I really appreciate it! Thank you!! Do you have any idea how to stop it vibrating when it gets to the mouse position?

SuperSopwith | 2020-09-02 13:20

to stop the vibration you have to make some sort of dead-zone

var damping = 0.95
var dist = position.distance_to( get_global_mouse_position() )  #get the distance from sprite to pointer
if dist > 10.0: #do it only if the distance is bigger than 10 (or whatever)
    var direction = position.direction_to( get_global_mouse_position() )
    set_axis_velocity ( direction * min(speed,dist.length * damping) ) #dont overshot ... take smaller speed or distance apply some damping

this is some code of the top of my head … so i dont know if this fixes this issue

klaas | 2020-09-03 10:23