CharacterBody2D enemy in platform game, stick to walls, ceiling

Godot Version

4.4

Question

I feel like this should be fairly easy to implement but struggling none the less.

I’m working on a 2D platform game and trying to script an enemy (maggot) that can walk along platforms but can walk up walls, along ceilings etc. Basically it ‘sticks’ to the platform, no matter what.

The enemy is a CharacterBody2D and I thought I’d be able to do something like this:

	for i in get_slide_collision_count():
		var collision = get_slide_collision(i)
		var collision_normal = collision.get_normal()
		
		# If surface normal is different to maggot normal, rotate
		if maggot_normal != collision_normal:
			rotation = collision_normal.angle() + PI / 2
			maggot_normal = collision_normal

Basically get the collision normal, rotate the maggot so it’s always ‘pointing in the right direction’ and then just move forward (+x axis). But it struggles when it hits a 90 corner, basically keeps flipping back and forth as it collides with the wall and floor.

Is there a ‘standard technique’ for what I’m trying to achieve?

You might consider running a path2d around your platform, and using that…