Godot Version
Godot 4.4.1
Question
I’m making a top-down 3d game and I have programmed an enemy to walk back and forth.
However, I don’t know how to make walk in two other spots.
Here is the code for the positions and the directions:
func _ready():
startPosition = global_position
endPosition = startPosition + Vector2(10, 3*16)
func changeDirection():
var tempEnd = endPosition
endPosition = startPosition
startPosition = tempEnd
Hi,
All depends on the result you’re trying to achieve but here are some thoughts:
GDScript comes with a bunch of functions for random number generation.
One thing you could do is, when you call changeDirection, compute a new end position using two random numbers, one for the x position, one for the y.
This could look something like this:
func changeDirection():
var tempEnd = endPosition
endPosition = Vector2(randf_range(-500, 500), randf_range(-500, 500))
startPosition = tempEnd
This code will make the enemy go to a new random position in a square every time he reaches its current end position.
You could also use the startPosition and calculate a random position around it. This way, you can make sure the enemy is wandering randomly while keeping a certain distance from its spawn position.
This could look something like this:
func changeDirection():
endPosition = startPosition + Vector2.RIGHT.rotated(deg_to_rad(randf_range(-180, 180)) * randf() * 500
This code basically creates a vector pointing right and rotates it randomly. Multiplying by randf() * 500 is here to make the position random inside a circle with a radius of 500.
Keep in mind that I’m not changing startPosition here as I need it to be the reference point every time, to ensure the enemy always stays in the same global position of the game and cannot go too far away.
Anyway, there are plenty of ways to do movement in different directions.
Was there anything specific you were looking for, or is my answer enough for now?