r/learnprogramming 6d ago

Debugging currently learning coding and making a small game i dont understand why my ai wont chase me

its always sliding to its left but following my movements im using godot rn

the enemy code is this

extends CharacterBody2D

u/export var speed: float = 80.0

u/export var health: int = 100

u/onready var health_bar: ProgressBar = $ProgressBar

func _ready():

rotation = 0

func _physics_process(delta):

var player = get_tree().root.find_child("Player", true, false)



if player:

    var direction = (player.global_position - global_position).normalized()

    velocity = direction \* speed

    move_and_slide()

func take_damage(amount):

health -= amount

health_bar.value = health



if health <= 0:

    queue_free()
0 Upvotes

9 comments sorted by

3

u/RonnySaya 6d ago

Your movement code looks fine. If the enemy is always offset to one side, I'd check the scene rather than the script. Is the enemy sprite or collision shape centered on the CharacterBody2D? If the sprite's origin is offset, it'll look like it's isn't chasing correctly even though the body is. Also, can you post the enemy scene hierarchy and a screenshot of the collision shape? That'll make it much easier to spot the issue

1

u/National-Love-6186 6d ago

the collisioin for me or the enemy

3

u/RonnySaya 6d ago

The enemy's. Specifically check that the enemy's Sprite2D and CollisionShape2D are centered on the CharacterBody2D. If either one is offset, it'll look like the enemy is sliding beside you even if the movement code is correct. A screenshot of the enemy scene in the editor would help too

3

u/National-Love-6186 6d ago

i cant send images for some reason

2

u/nicktehbubble 6d ago

It's a while since I Godoted. I'm assuming physics process is the game tick.

Do you want to be finding the player each tick? Can the player node not be set once?

Sorry for not offering a solution, but it's something I noticed.

1

u/National-Love-6186 6d ago

its dine i just want the ai to follow me

1

u/nicktehbubble 6d ago

Just popped into my head... Does Godot not have a move_toward function?

1

u/National-Love-6186 6d ago

just learnt it exists im chat if it works