Pulling rigid bodies using spring joints

Godot Version

v4.5.stable.fedora [876b29033]

Question

I have a fallen log object that i want the player to be able to pull, and I believe the best way to do that is with DampedSpringJoint2D. I made the player a RigidBody2D, because i found it easier to make the player be able to push and pull other rigid bodies that way. Pushing works perfectly, while pulling seems to be really hard to do.

What i have tried is creating an area around the player. While the pull button is pressed, it will create a spring joint that connects to all rigid bodies in the area. This is the pull function:

func pull():
	if Input.is_action_pressed("pull"):
		for n in pull_area.get_overlapping_bodies().size():
			var body = pull_area.get_overlapping_bodies().get(n)
			var rope = DampedSpringJoint2D.new()
			add_child(rope)
			rope.node_a = self
			rope.node_b = body

pull() is called in _physics_process. It seems though that it’s not possible to connect the spring joint to self, as the game crashes with this error message:

E 0:00:02:206   pull: Invalid assignment of property or key 'node_a' with value of type 'RigidBody2D (player_rigid_body.gd)' on a base object of type 'DampedSpringJoint2D'.
  <GDScript Source>player_rigid_body.gd:59 @ pull()
  <Stack Trace> player_rigid_body.gd:59 @ pull()
                player_rigid_body.gd:22 @ _physics_process()

Have you tried hard-coding this? I.E., actually making one in the editor attached to the player and tried it to make sure you have everything setup correctly before attempting to do it in code?

node_a and node_b has to be a node_path, not the node itself. So use self.get_path() (if that works?) and body.get_path()

2 Likes

that way the player would only be able to pull one item at a time, and once i make a couple of smaller items i want the player to be able to pull as many as they can fit around themselves.

Thanks! The nodes a and b do use paths and not nodes, I guess I just missed that part. It works now!

I’m glad you found the problem, but you misunderstood what I was suggesting. If you had tried to do it through the editor, you would have learned how it worked, and then been able to replicate it in code. It’s a trouble-shooting process. I was not suggesting you hard code it and leave it that way. Just break the problem down into smaller parts.

1 Like