0 votes

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

Godot version v3.4.2.stable.official [45eaa2daf]
in Engine by (101 points)

1 Answer

+1 vote
Best answer

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.

by (1,697 points)
selected by

I tried this:

extends Panel

func _on_SetButton_pressed() -> void:

The function setpos on Fish.gd:

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 setpos is called) or calling $Fish.position = Vector2(0,0) in the node "Main".

Try mode = RigidBody2D.MODE_KINEMATIC instead.

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.

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!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.