Make characterbody2d push characterbody2d

I have a characterbody2d enemy that charges at the characterbody2d player, but when they contact, the enemy just stops at the player. How do I make it so that the enemy can actually push the player around?

(How to make CharacterBody2D push another CharacterBody2D?
Here’s a different forum post with the same idea but they don’t link the video they are referring to and I don’t think replacing the player with a rigid body is a good idea.)

With CharacterBody2D you need to manually adjust its velocity, so you need to check the collision and change the velocity of the pushed object based on that collision, ideally along its normal vector.
See here my little demo, you probably need to adjust the values to make it feel right, but the gist is there.

This is the scene tree:

This is the script on the Player node (the one pushing):

extends CharacterBody2D

const SPEED: float = 200.0
func _physics_process(delta: float) -> void:
	var direction: Vector2 = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
	velocity = direction * SPEED
	move_and_slide()

This is the script on the Enemy node (the one being pushed):

extends CharacterBody2D

func _physics_process(delta: float) -> void:
	velocity = Vector2.ZERO
	for index in get_slide_collision_count():
		var collision: KinematicCollision2D = get_slide_collision(index)
		if collision.get_collider().name == "Player":
			velocity = collision.get_normal() * collision.get_collider_velocity().length()
	move_and_slide()
1 Like