Positioning a RigidBody2D in an Area2D body_entered signal handler

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

Hi,

I’ve a layout-x-y-centered control with a RidigBody2D child with a linear_velocity.
This body pauses when the tree gets paused.
When this body enters an Area2D it should be repositioned to the x-y-center.

When the tree gets paused it works. The body is centered. But after unpausing, it looks like the body is back at the old position. Like warping.

func _integrate_forces(state):
	if restart:
		restart = false
		stopMoving(state)
		startup()
		get_tree().paused = false # switch to check for paused position

func startup():
	var rnd = RandomNumberGenerator.new()
	rnd.randomize()
	
	var force_x = (rnd.randi_range(1, 2) * 2 - 3) * difficulty
	var force_y = (rnd.randi_range(1, 2) * 2 - 3) * 2 * difficulty
	linear_velocity.x = force_x
	linear_velocity.y = force_y

func stopMoving(state: Physics2DDirectBodyState):
	get_tree().paused = true
	state.linear_velocity = Vector2(0, 0)
	position = Vector2(0, 0)

func _on_RightWall_body_entered(body):
	restart = true

func _on_LeftWall_body_entered(body):
	restart = true

Why this doesn’t work as expected?

:bust_in_silhouette: Reply From: kidscancode

You’re correct to be using _integrate_forces() to affect the RigidBody2D without breaking physics, however, just as you use the state to change linear_velocity, you must also use it to set the position. This is done via the state.transform:

state.transform.origin = Vector2()

Ok. Thx. I’ve breen pretty sure, that I’ve already tried that call before without success. But maybe somehow different. You’re right, now this works.

arlecchino | 2019-03-23 10:25