

Then, the function checks the distance of the skeleton from the player. This vector will be used to determine the distance from the player, and to set the direction of movement and the orientation of the skeleton. The first thing this function does is calculate the player’s position relative to the skeleton. Var player_relative_position = player.position - position

# Calculate the position of the player relative to the skeleton
CONSTRUCT 3 USE RANDOM FOR SPAWN CODE
Replace the function code with this: func _on_Timer_timeout(): The function to manage the timer signal will be automatically created. In the Node panel, double-click on timeout(), select the Skeleton node and press Connect. To do this, we need to connect the Timer timeout() signal to our script. Basically, we want to execute a function every time the timer is triggered. The randomize() method of RandomNumberGenerator use a time-based seed to initialize the random number generator.Īs we said earlier, we want to use the timer to periodically decide the behavior of the skeleton. Using the SceneTree root property, we get a reference to the root Viewport, to which we can request a node reference by passing its path to the get_node() function. The get_tree() function returns the current node hierarchy as a SceneTree object. Player = get_tree().root.get_node("Root/Player") We must perform these operations within the _ready() function: func _ready(): When the skeleton enters the scene tree, we need to do two things: This variable is the countdown used to restores the default behavior. bounce_countdown: when the skeleton hits an obstacle, it changes direction for a certain amount of time to try to go around it.It’s used to choose the correct idle animation. last_direction: it’s the last direction of movement before stopping.direction: it’s the current movement direction of the skeleton.The export keyword makes this variable visible in the Inspector. speed: it’s the movement speed of the skeleton.The new() method is used to create an object from a class. As the name says, it’s a class for generating pseudo-random numbers. rng: is an object of type RandomNumberGenerator.We will need it to get the player’s current position. player: it is a reference to the Player node.This is the list of variables and what they are used for: Call it Skelton.gd and save it in the Entitites/Skeleton folder, then open it.įirst, let’s add all the variables we’ll need: # Node references If the skeleton comes into contact with an obstacle, it will change direction casually in an attempt to get around it.Īttach a script to the Skeleton node. Otherwise, it will randomly decide whether to stay still, change movement direction or continue in the current direction. If the player is within a certain distance, the skeleton will move towards it. The Artificial Intelligence of the skeleton will be very simple.
