0 votes

I have a tilemap that is generated in a Level Scene in which my player can move just fine and collision detection works just fine too. Now I wanted to add an enemy that will chase the player inside the Level and tried all kinds of different A.I.s for it and it never works. The Enemy never follows the player until it is ther. At first it usually runs away, once the distance gets big enough the enemy changes direction but does not come close to the player. Here is my current code for the enemy.

extends KinematicBody2D

var speed = 100
var player
onready var attackRay = $AttackCollider

func _ready():
    player = get_node("/root/Player")

var velocity = Vector2()

func _physics_process(delta):           
    velocity = position.direction_to(player.position) * speed

In case it matters here is my Player Code

extends KinematicBody2D

signal exitLevel

export var speed = 200

func _physics_process(delta):
    var velocity = Vector2() 
    if Input.is_action_pressed("ui_right"):
        velocity.x += 1
    if Input.is_action_pressed("ui_left"):
        velocity.x -= 1
    if Input.is_action_pressed("ui_down"):
        velocity.y += 1
    if Input.is_action_pressed("ui_up"):
        velocity.y -= 1
    if velocity.length() > 0:
        velocity = velocity.normalized() * speed


Any tips or help in figuring out why this basic AI is not working is greatly appreciated. I use Godot 3.2 btw.

asked May 1 in Engine by cgill95 (12 points)

1 Answer

0 votes

I've used your code as is, and it works for me. The enemy follows the player and sticks with it.
Do some printing of what the enemy is tracking and make sure it is the player node that it's following.

answered May 1 by deaton64 (1,201 points)

Thanks for checking out that it works. I found the error but not the solution yet. The player prints out its position correctly aligned with the Main Scene. When printing out the player position in the enemy it starts at 0,0 and changes relative to that. So there is always a difference between what the enemy thinks the players position is and the actual position of the player. also this explains why the enemy always runs towards the top right from the start. How can I access the correct position from the player object in the enemy code?

Is your enemy scene somehow a child of the player scene?

What you could do, is create a Global singleton script add variable for player.

Then in the player script do this:

func _ready():
    Global.player = self

and in the enemy script do this:

func _ready():
    player = Global.player

Then you will know that enemy does have the Player object.

If that doesn't work, zip your code up somewhere and I'd be happy to take a look.

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 How to use this Q&A? before posting your first questions.