How to push a RigidBody2D with a CharacterBody2D

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

Hello,
I want to make a top-down shooter with boxes you can push around in Godot 4.
But the Character Body 2D can’t push my box and just stops.
I use the move and slide function.
And my RigidBody2D is not static, gravity still works.

Thank you for your answer!

3 Likes
:bust_in_silhouette: Reply From: Adam_S

Hi, I’m not quite sure, but it looks like the CharacterBody2D can’t move RigidBodys on its own.

You can do it manually, here is an example:

var force = 1000

if $CharacterBody2D.move_and_slide(): # true if collided
	for i in $CharacterBody2D.get_slide_collision_count():
		var col = $CharacterBody2D.get_slide_collision(i)
		if col.get_collider() is RigidBody2D:
			col.get_collider().apply_force(col.get_normal() * -force)

Thx for this! After I learnt enough GDScript to implement, worked perfectly. In case anyone else is as n00b as me, I added a new node under my CharacterController2D (my top level) called “Pusher” and added this as a script:

extends Node2D

@export var pushForce = 500

@export var bodyPath: NodePath = ".."

@onready var body: CharacterBody2D = get_node(bodyPath)

func _physics_process(_delta):
	if body.move_and_slide(): # true if collided
		for i in body.get_slide_collision_count():
			var col = body.get_slide_collision(i)
			if col.get_collider() is RigidBody2D:
				col.get_collider().apply_force(col.get_normal() * -pushForce)

HTH :slight_smile:

Arakade | 2023-03-07 00:26

2 Likes