Enemy AI Teleports to player whenever in range

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

Hey there,
I’m trying to get the enemy to chase the player whenever your in it’s range, however it just’s teleports to the player right now.

Here is my enemy code for now:

extends KinematicBody2D

const GRAVITY = 80
const SPEED = 300
const FLOOR = Vector2(0, -1)

var velocity = Vector2()
var direction = 1

onready var player = get_parent().get_node("Player")
onready var dir = Vector2(sign(player.position.x - position.x), 0)

func _ready():
   pass

func _physics_process(delta):	
   velocity.x = SPEED * direction
   velocity.y = GRAVITY
   velocity = move_and_slide(velocity, FLOOR)

if is_on_wall():
	direction = direction * -1
	$Sprite/BottomRayCast.position.x *= -1
	
if $Sprite/BottomRayCast.is_colliding() == false:
	direction = direction * -1
	$Sprite/BottomRayCast.position.x *= -1	

#Enemy Attack range (Player body enter and exit)

func _on_Area2D_body_entered(body):
    if body == player:
	    $Sprite.modulate.r += 10
	    player.emit_signal("damage_taken")

func _on_Area2D_body_exited(body):
    if body == player:
	    $Sprite.modulate.r -= 10

#Enemy Chase range

func _on_ChaseRange_body_entered(body):
    if body == player:
	    move_and_collide(dir * SPEED)

What am I doing wrong?

Hi,
should dir not been constantly recalculated (and normalized) and in relation to the enemy?

klaas | 2020-08-26 07:38

I have no idea how to do that x)

Pneuma | 2020-08-26 08:12

in _physics_process …

dir = global_transform.origin.direction_to ( player.global_transform.origin )

this calculates an normalized directional vector from self(enemy) to the player

klaas | 2020-08-26 10:13

This does seem to work better however the teleporting is still happening. Also, when the player is to the right of the enemy and going left, the enemy teleports to the left instead of towards the player.

Pneuma | 2020-08-26 11:00

set a breakpoint and “step into” and analyse the properties of the objects … this issue cant be too serious

klaas | 2020-08-26 11:07