Enemys aren't moving to player. Is there something wrong with my code?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jhale
extends KinematicBody2D

var Player = null
var move = Vector2.ZERO
var speed = 500

func _physics_process(delta):
	move = Vector2.ZERO
	if Player != null:
		move = position.direction_to(Player.positon) * speed
		move = Vector2.ZERO
	move = move.normalized()
	move = move_and_collide(move)
func _on_Area2D_body_entered(body):
	if body != self:
		Player = body
func _on_Area2D_body_exited(body):
	Player = null
:bust_in_silhouette: Reply From: kidscancode

There are several things wrong with your movement code:

  1. Don’t normalize move(). That makes it very small and cancels out your speed.

  2. Don’t assign the returned value of move_and_collide() to move. The return from move_and_collide() is a KinematicCollision2D object.

  3. Use delta in your movement: move_and_collide(move * delta)

If it still doesn’t work, you may not be detecting the player. Put a print(body.name) in your body_entered callback and confirm that it’s happening.

I don’t agree with 1):

normalizing should be done, but multiply with the speed AFTER the normalization.

I also think move_and_slide should be replaced with move_and_slide. Then no delta and assigning to move is correct.

whiteshampoo | 2020-06-24 07:07

Normalizing and multiplying by speed was already done. direction_to() returns a normalized vector. Doing it again is pointless.

kidscancode | 2020-06-24 08:08

oh, you are right. i confused direction_to and subtracting the vectors. sorry

whiteshampoo | 2020-06-24 09:50