0 votes

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():

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

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?

in Engine by (32 points)

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

I have no idea how to do that x)

in physicsprocess ...

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

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

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.

set a breakpoint and "step into" and analyse the properties of the objects ... this issue cant be too serious

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.