0 votes

Am trying to ma the enemy follow the player,
but problem: I can refer to the player (or the player scene) in the script.
The Player and Enemy are both in the root folder
THIS IS MY CODE BELOW:

extends KinematicBody

var path = []
var path_node = 0

var speed = 10

onready var nav = get_parent()
onready var player = $"Player"

func _ready():
pass

func physicsprocess(delta):
if pathnode < path.size():
var direction = (path[path
node] - globaltransform.origin)
if direction.length() < 1:
path
node += 1
else:
moveandslide(direction.nomalized() * speed, Vector3.UP)

func moveto(targetpos):
path = nav.getsimplepath(globaltransform.origin, targetpos)
path_node = 0

func onTimertimeout():
move
to(player.global_transform.origin)

in Engine by (12 points)

1 Answer

0 votes

I think what you're suggesting should be possible. However, you don't want to use:

onready var player = $"Player"

Instead, I'd recommend the below approach:

  1. Create a function on your enemy named "setTarget" and have it take in a parameter called "target"
  2. When you create your enemy, get your player from there and call enemy.setTarget(player)
  3. In your enemy, only try to get a path to your player if the player is not null, and try until you have a target (Edit: updated format so it would not italicize stuff unintentionally.)

This is only one way to approach this. Another way I've done it is to use groups, where you put your player in a group, and then every enemy can get access to the player directly if they need it. I prefer the above though as it's more declarative.

by (108 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 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 webmaster@godotengine.org with your username.