Can't set RigidBody2d position from a panel

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

I have a panel with a button and a script:

extends Panel

func _on_SetButton_pressed() -> void:
	get_node("../../Fish").position = Vector2(0,0)

The panel is in a Canvas Layer called “HUD” which it’s in the node called “Main”, i want to access to the node called “Fish” (the player, witch it’s a RigidBody2d) and set it’s position to 0,0 for example, but it isn’t working.

Main Tree

:bust_in_silhouette: Reply From: DaddyMonster

Rigidbodies are your access to Godot’s physics engine. That means that their movement is handled by the engine and you provide the forces. Directly setting the position puts you in conflict with the engine for handling the objs position and isn’t how you should do things.

If you do want to reposition, the answer is to turn off the physics engine by changing its “mode” to kinematic (the enum = 3) and she’s all yours and then reset once you’re done.

Let me know if you want to specific code to do this but it’s literally a case of addressing the object and changing the “mode” value.

Hope that helps.

I tried this:

extends Panel

func _on_SetButton_pressed() -> void:

The function _set_pos on

func _set_pos(pos):
    position = pos
    mode = MODE_RIGID

It doesn’t work, it only prints “Done”, it works only if I set the default mode of the Rigid Body2d to be kinematic (but then he can’t move until the func _set_pos is called) or calling $Fish.position = Vector2(0,0) in the node “Main”.

VitusVeit | 2022-01-03 11:40

Try mode = RigidBody2D.MODE_KINEMATIC instead.

DaddyMonster | 2022-01-03 19:21

Thanks! It worked! I noticed if I set the mode of the RigidBody2d to Kinematic, then set the position, and immediately after setting the mode to Rigid it doesn’t work. But if I add a yield of 0.1 second timer before setting the mode to rigid it works. I guess it’s a problem with the physics frame.

VitusVeit | 2022-01-03 19:56

Oh brilliant, great to hear! Yes sorry, I was thinking that but I got distracted and forgot to say… The engine communication with the happens once a frame so you need a fraction of a second.

Good luck with your project!

DaddyMonster | 2022-01-03 20:04