How to make an NPC go right when hitting a collisionshape2d

Godot 4.3

Hello! I’ve been trying this for a week and the resources I find don’t work, my deadline is running short and I’ve only got one week to figure this out left. Does anyone know how to make an NPC go the opposite direction when hitting a certain direction?

CODE:

extends CharacterBody2D

const jump_power = -900
const gravity = 50
const SPEED = 400

func _ready():
	velocity.y = gravity
	move(1, 200)

func _physics_process(_delta):
	pass

	move_and_slide()

func move(dir, speed):
	velocity.x = dir * speed

func _on_hitbox_body_entered(body):
	if body.is_in_group("collison_negitave"):
		move(1, 200)
	if body.is_in_group("collision_positive"):
		move(-1, 200)

You may have to show your scene tree? it seems like this sample should work if the hitbox touches a Static/Rigid/Character Body2D with the correct group. I notice the spelling is different in each group “collison_negitave” and “collision_positive” maybe there is a misspelling?

It could help to add print statements to see if this move function is really working.


It may be better to use collision data itself through get_last_slide_collision or looping through get_slide_collision. Something like this using linear algebra

if dir.dot(collision.get_normal()) > 0.5:
    dir.x *= -1

Did you connect the body collision signals correctly? Is the last function firing when you want it?
You can try adding print() statements in different parts of your code to see where it propagates.
And you have a typo in your “negative_collision” group name in the last function, which may also be the cause of your problem.

it’s telling me that the dot function does not exist and that collision is not declared in the current scope

dot is a Vector2 function, and you could get a collision value from get_slide_collision or get_last_slide_collision. That was not a full example, just the math if you are up for the rest of it.

gotcha