Reputation: 11
So I have been coding a platformer for a project, and need to code an enemy.
I want to make the enemy attack when the player's position is in a certain range relative to the enemy's position.
Aside from this being sloppy AI that I'll fix later, I can't seem to find a way to access the position of the KinematicBody2D node I use for the player.
I've tried making a variable in the World node, and it won't access that.
Any suggestions would be appreciated
Upvotes: 1
Views: 17782
Reputation: 71
Not AI related, just global variables...
Follow Martin's answer to create a singleton where you put all variables you want shared by other scripts.
In my case (Globals.gd is one of the singletons - you may have more than one), my scripts use such variables like this:
onready var globals = get_node("/root/Globals")
func _ready() -> void:
globals.seqCC = 0
globals.trackDone = true
for i in globals.allTracksName.size():
$TracksList.add_item(globals.allTracksName[i])
globals.trackParts = ["RL"]
By the way... you may create 'global' functions, too... Just put their code in a singleton and you'll be able to call them from any other script. (I use this to keep all sound/music management in a separate, global, script I call from any other scene, for instance.)
Cheers...
Upvotes: 3
Reputation: 914
Instead of using a global variable, I suggest you add an Area2D
under the Enemy scene that represents the enemy's detection range for the Player. Then in your Enemy scene, connect the area_entered
or body_entered
(depending on your setup) to your Enemy script. It should generate a function that looks something like _on_area_entered()
. Then just start coding the Enemy attack there.
If you really want to use a global variable, then an alternative way to achieve that is to create a singleton / autoload. To do this, just create a script (that extends any Node) or a scene. Then go to Project Settings
> AutoLoad
and browse for the script / scene that you made. Finally, enter a Node name then press Add
.
What this will do is it will make your script a "variable" that can be accessed anywhere in your scripts. This is where you can start coding for Enemy and Player interactions.
Upvotes: 4