Rigidbody drag with unexpected results

Godot Version

4.2.2

Question

` Hi all, I’m having problems with drag & drop rigibodies.
I’m using this project as a template (not mine): GitHub - godotrecipes/rigidbody_drag_drop

video of my tests: Test - Album on Imgur

When the rigid body bump into a wall i want it to stop moving, not glitching through.
Same with the collision with oher bodies, as shown in the video, if I push hard enough I can make the other bodies fall trough the walls.

Any idea how to fix this?

Thanks in advance `

Instead of setting the position of the rigidbody directly, you could apply a force each frame to move it toward the mouse. This way, it would not go into the wall because Godot can push the rigidbody away.

1 Like

I tried to apply an impulse, but i get this behaviour: the ball orbits around the cursor

I modified the function process physics like this:

func _physics_process(delta):
	if held:
		apply_impulse(global_position.direction_to(get_global_mouse_position()) * 10)

Also when the object is picked up I don’t freeze it anymore, otherwise the impulse would have no effect

Impulses should only be applied once, like for a jump ability. Forces, on the other hand, are applied over multiple frames.

To make the ball stop oscillating, you’ll also need a damping force. You can achieve this by adding the two forces:

extends RigidBody2D

@export var spring_constant: float = 100
@export var damping_constant: float = 5

func _physics_process(delta):
	var mouse_position = get_viewport().get_mouse_position()
	
	var displacement_to_mouse = mouse_position - global_position

	var spring_force = displacement_to_mouse * spring_constant
	var damping_force = -linear_velocity * damping_constant
		
	apply_force(spring_force + damping_force)
2 Likes

Thank you, this works nicely :grin:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.