Why the position of RigidBody2D gets reset after mouse released

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

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
    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

A suggestion for improving your code (once you figure out your problem :wink: ). 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.

Ertain | 2021-02-16 22:20

:bust_in_silhouette: Reply From: GreasyMcBeef

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:

After switching to global_transform, 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 global_transform. Still being confused, but you did make my day. Thanks!

joshua7v | 2021-02-17 03:44