CharacterBody2D as a child, but parent should also move along

hi there,

i have a unit scene built with components, so i need my characterbody2d, which is responsible for the movement, to be a child of unit. tree looks like this:

Unit (parent)

  • CharacterBody2D (child, script attached)
  • other components

characterbody2d script:

@export var movement_speed : float
@export var movement_acceleration : float

func _physics_process(delta):
	if get_parent().is_in_group("Player"):
		velocity = lerp(velocity, get_input() * movement_speed, movement_acceleration * delta)
		move_and_slide()


func get_input():
	input.x = Input.get_action_strength("Right") - Input.get_action_strength("Left")
	input.y = Input.get_action_strength("Down") - Input.get_action_strength("Up")
	return input.normalized()

for now, only the characterbody2d moves, but not the whole scene. i need the unit to move along with characterbody2d.

so i added

get_parent().position += velocity * delta

after move_and_slide() but results in different movement. while characterbody2d and unit are same position at start, as soon as i move, the characterbody2d moves away (faster) for some reason. i can see that because i enabled visible collision shapes.

why and how could i fix that?

The reason the characterbody is moving away faster is because the movement of the parent gets applied to its children → the characterbody basically moves twice the amount.

I strongly suggest to put the characterbody2d as the root of the scene as this makes movement way easier.
You can still write the movement code in a child node and just reference the parent

2 Likes

thanks for the fast answer. that works. maybe there is another solution so i can keep my markup, but i will go along with this for now.

edit: i will go with this approach. thanks again!

1 Like

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