Problems after teleporting RigidBody2D

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

I’m making a angrybirds styled game, where the player launches a rock from a slingshot that collides with other objects.
One of these objects is another slingshot, where the rock can be launched again.
It’s composed by an Area2D with a pretty big collision radius, and when the rock hits it, it’s supposed to teleport the rock to the center of the slingshot object and let the player launch it again.
The rock is a RigidBody2D, and at the moment this is the code I use to teleport it to the center of the slingshot:

func _integrate_forces(state):
    if current_slingshot != null and in_slingshot:
		self.position = current_slingshot.position
		self.sleeping = true

This does teleport the rock to the center of the slingshot, but when I launch it again with apply_impulse(), the rock is launched from the position where it first collided with the slingshot, and not from its center.
What am I doing wrong?

:bust_in_silhouette: Reply From: kidscancode

You cannot move a rigid body with position.

You are correct that you need to use _integrate_forces(), but any physics changes must be made to the Physics2DDirectBodyState - the state in the callback.

func _integrate_forces(state):
    if current_slingshot != null and in_slingshot:
        var new_transform = state.get_transform()
        new_transform.origin = current_slingshot.position
        state.set_transform(new_transform)
        self.sleeping = true

More information here: Godot 3.0: Rigid Bodies · KCC Blog

Thanks. It’s working now.

Torgo | 2018-04-30 14:34