I’m new to coding and am trying to figure out how to make an NPC chase the player in a top-down 2d game. I’m trying to debug it but no matter what I change, the enemy just moves in 1 direction.
Here’s the code:
extends CharacterBody2D
@onready var player = $"../Player"
var speed = 100
func _physics_process(delta):
if Input.is_action_pressed("ui_accept"):
var direction = (player.position - position).normalized()
velocity = direction * speed
move_and_slide()
And incase it matters, the player being referenced is a CharacterBody2D
Using global_position isn’t changing it
Also, the function normalized() is spelled with a z and switching player.position and position in both variations only swaps the direction that they go in
It will only chase when holding the spacebar (“ui_accept”) is this intentional? It seems like this code should work, is there anything else altering velocity or using move_and_slide in the NPC script?
I’m using the Input.is_action_pressed just to debug, it would normally start chasing the player after they enter an area. Nothing else is altering the velocity inside the NPC script and what I sent is the entire script.
Also, to answer the edit in KingGD’s reply, removing the normalized just puts them at a specific distance to the bottom right of the player
Sounds like the Player and/or the Enemy has a visual offset. Make sure each scene has it’s sprite and collision at 0,0 (where the red and green lines intersect) relative to the root CharacterBody2D node.
I don’t know how I didn’t catch this, apparently I changed the position of the sprite and collisionshape instead of the characterbody, thanks
incase of needing the script if they have a problem, here is the final debug script:
extends CharacterBody2D
@onready var player = $“…/Player”
var speed = 100
func _physics_process(delta):
if Input.is_action_pressed(“ui_accept”):
var direction = (player.global_position - global_position).normalized()
velocity = direction * speed
move_and_slide()