0 votes

What I want to achieve is: while holding down the mouse, create an instance of an object and display it on screen, move mouse(while holding down left button) will move that object, release button will drop the object(rigidbody with gravity). Current situation: basically works, but the object will go back to the click position after releasing mouse button. I have no idea why.

func _physics_process(delta):
    var scene = preload("res://a-scene.tscn")
    if Input.is_action_just_pressed("click"): # mouse down
        node = scene.instance() # node is a rigid body
        node.can_sleep = false
        add_child(node)
    if Input.is_action_pressed("click"):: # mouse holding down
        node.position.x = get_local_mouse_position().x
    if Input.is_action_just_released("click"): # mouse up
        print('release')
in Engine by (15 points)

A suggestion for improving your code (once you figure out your problem ;) ). Place this code, var scene = preload("res://a-scene.tscn"), outside of the _physics_process() (near the top of the script). This may help with performance.

1 Answer

+1 vote
Best answer

You have to modify the global transform to move a RigidBody2D yourself. Any changes to their position values get reset by the engine each timestep. You might get some use out of this, since I think it accomplishes what you're going for:
https://kidscancode.org/godot_recipes/physics/rigidbody_drag_drop/

by (84 points)
selected by

After switching to globaltransform, it works. I want to read more about "Any changes to their position values get reset by the engine each timestep." I checked the docs of RigidBody2D, it says I should not set position directly but does not mention globaltransform. Still being confused, but you did make my day. Thanks!

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.