Why does my Godot enemy move sideways instead of chasing the player?

0
0
Asked By MellowCedar42 On

I'm learning to code and building a small game in Godot. I'm trying to make an enemy chase the player, but the enemy always seems to slide to its left while still responding to my movement. The enemy is a CharacterBody2D, and I'm setting its velocity toward the player every physics frame with this code:

extends CharacterBody2D

@export var speed: float = 80.0
@export var health: int = 100
@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()

What could cause the enemy to appear to move sideways instead of directly toward the player?

2 Answers

Answered By CopperLynx18 On

Your chase logic does not need to be changed just because it runs in _physics_process. Finding the player every physics frame is acceptable for a small project, although storing a reference once would be cleaner later. First confirm that the node is really named Player and that the enemy and player are using the same coordinate space through global_position. If those are correct, the sideways appearance is most likely caused by the enemy's visual child being offset or rotated in the scene rather than by the velocity code.

Answered By QuietOrbit7 On

The movement calculation itself looks correct: it finds the vector from the enemy to the player, normalizes it, and moves in that direction. If the enemy follows you but appears to be offset or sliding to one side, check the enemy scene in the editor. Make sure the Sprite2D and CollisionShape2D are centered on the CharacterBody2D, and verify that neither child node has an unexpected position or rotation. A misplaced sprite can make the movement look wrong even when the CharacterBody2D is traveling correctly.

MellowCedar42 -

Do you mean I should check the collision shape for the player or for the enemy?

QuietOrbit7 -

Start with the enemy. Select its CharacterBody2D and make sure the sprite and collision shape are centered around its origin. You can also turn on visible collision shapes while running to compare the actual body position with what you see on screen.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.