CharacterBody2d & RigidBody2D Interaction

Godot Version

4.2.1

Question

Hello all,

I came across a helpful youtube video about this:

The video suggests that a simple solution for this interaction is to make collision layers where the CharacterBody doesn’t detect the RigidBody but the RigidBody does detect the CharacterBody. Like the video suggests, this achieves good but not great interaction between the nodes - the RigidBody can easily be pushed through walls, etc.

The 2nd solution offered is to make both the CharacterBody and RidigBody detect each other with collision layers and add in this code on the CharacterBody script:

(general movement script above)
move_and_slide()

for i in get_slide_collision_count():
var collision = get_slide_collision(i)
if collision.get_collider() is RigidBody2D:
var push_force = 400
collision.get_collider().apply_central_impulse(collision.get_normal() * push_force)

However, I implemented the 2nd solution and still get some weird interactions. I was able to figure out that Godot is detecting the player as is_on_floor when it’s on top of the ball. So I think perhaps the push_force is applied to the ball while the player is on top of the ball so it carries the player with the ball (or something along those lines). I tried something like the code below, which seems to still yield unwanted interactions:

if collision.get_collider() is RigidBody2D:
if is_on_floor():
position.y = position.y - 5
velocity.x = 0
#print(velocity)
var push_force = 400
collision.get_collider().apply_central_impulse(-collision.get_normal() * push_force)

Here’s a video of the issue:

Does anyone know a solution for this?

Keep a layer for the ground or floor only, give another layer for the ball, and remove the ball’s layer from Floor Layers in the inspector.

Basically, find and un-toggle the layer of the ball in the Floor Layers.

thanks! I figured out a workaround with code and changing the Max Angle of the Floor property on the player (CharacterBody2D) to 0 degrees, but that’s a much simpler fix!

Um, this solution will be unstable if the player is exactly on top of the ball, the “floor” (which is the ball) angle will be 0 in this case.

As you have said, the core of this problem is that Godot is detecting the player on top of the ball as on the floor. So the solution is to give the ball a layer other than the ground’s layer. Don’t worry about this, almost every game will separate the layers for each type of object.

makes sense, and yes I’m using your solution now. Thanks!

Hi there, thanks for the video, you made my day.

1 Like