RigidBody2D Drag Movement

Godot Version

4.7

Question

I’m making a game in which you have to move around objects(currently RigidBody2ds) to find food. Here’s my code thus far:

extends RigidBody2D



var is_dragging: bool = false
var offset_varible: Vector2 = Vector2.ZERO

#var snap: int = 50


func _ready() -> void:
	lock_rotation = true


func _process(delta: float) -> void:
	if is_dragging:
		global_position = get_global_mouse_position() - offset_varible
		apply_central_force(global_position)
	


func _on_button_button_down() -> void:
	is_dragging = true
	offset_varible = get_global_mouse_position() - global_position

func _on_button_button_up() -> void:
	is_dragging = false

The scene tree looks like this:

Chair(RigidBody2D) --↓
Sprite2D
-↓
Button(Button down and button up are connected from this node)
CollisionShape2D

The problem’s that the movement’s pretty buggy. If i move the mouse cursor too fast, it sometimes teleports back to the ground, moves around wildly, etc etc. Also, when i comes in contact with other rigid body 2ds, its a bit chaotic, so is there a way to make it so that RIgidBody2Ds never overlap with each other?
When the RigidBody is dragging, it ignore static bodies entirely and goes straight through them. Is there a way to fix that too?
Does anybody know how to fix this? Thank you so much

You will want to avoid setting global_position for rigid bodies. apply_central_force is a step in the right direction but giving it global_position doesn’t make much sense, you will want to calculate the difference from the object/offset to the mouse and apply a force relative to that and the object’s mass

func _process(delta: float) -> void:
	if is_dragging:
		var difference := get_global_mouse_position() - (offset_varible + global_position)
		# multiply this by a higher number to make it snappier
		apply_central_force(difference * mass * 2)

Thank you so much again! It works great