+1 vote

I'm making a system where once the player enters within the radius of the Enemy, the enemy chases them and attacks them.

Upon running this code, instead of chasing them, the Enemy moves to a spot diagonal of the player and moves along with the player's movement.

How come they aren't actually chasing the player? I suspect that it has to do something with the velocity of the enemy, though, I'm not sure what the root cause of this is.

extends KinematicBody2D

const initialX = 150
const destinationX = 650

var velocity = Vector2()
var speed = 200
var wentToFinalPos = false
var detectedPlayer = false
var playerPosition = Vector2()
onready var player = get_parent().get_node("Player")

func _process(_delta):
    playerPosition = player.global_position

    if (detectedPlayer == false):
        if (wentToFinalPos == false):
            velocity = Vector2(1, 0)

            if (floor($".".position.x) >= destinationX):
                wentToFinalPos = true   
            velocity = Vector2(-1, 0)

            if (floor($".".position.x) <= initialX):
                wentToFinalPos = false
        velocity = (playerPosition - position)

    velocity = move_and_slide(velocity.normalized() * speed)

func _on_Detection_body_entered(body):
    if (body == player):
        detectedPlayer = true
Godot version 3.3.0
in Engine by (22 points)

Try using their global positions instead of their local positions? If their parent isn't at 0,0 that might be the cause of the offset.

Even with global positions, it doesn't work.

1 Answer

+1 vote
Best answer

I figured it out myself! The issue is that for some reason, the "points" (or whatever y'all call them) on the player and the enemy's KinetaticBody2Ds aren't the same (or similar) to make the enemy chase the player, otherwise, it ends up in a different location that is NOT the player's location.

I made another test program while trying to figure out the issue myself is to show you how the issue is caused:

Figure 1
Figure 1: The setup that causes the issue

Figure 2
Figure 2: The setup that has the enemy go after the player, not in a random position far away from the player

Apologies for wasting anyone's time trying to answer this question :/

by (22 points)
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.