I am trying to make it so that if an enemy is bumping into another one, it should move away from the other enemy, either to the left or right in the opposite direction at a bit of an angle. I’ve already set up the movement logic itself, but it’s defining these 2 angles that I can’t quite wrap my head around. So how do I approach this?
func avoidance():
## Replace (owner.direction) with something that picks a random direction to move towards in the opposite direction
owner.direction = owner.global_position.direction_to(owner.direction)
owner.velocity = owner.direction * owner.run_speed
In general, the procedure should be something like this:
Get a vector from the avoiding enemy to the enemy standing in its way.
For comprehensibility, I would invert that vector. vector = -vector
(This is optional though. You could just use a larger angle for rotation later instead.)
Use an RNG to get either 1 or -1.
Rotate the vector by a defined angle multiplied by the result of the RNG. vector = vector.rotated(angle * random_sign)
The first thing you need is a vector from one enemy to the other. If you’re already using move_and_collide(), you can use the get_collider() function on the collision it returns to get the other enemy (to get its global_position).
So, if you already have a part like this in your code:
var collision := move_and_collide()
you can add something like that afterwards:
var avoiding_direction := (global_position - collision.get_collider().global_position).normalized()
var random_sign := (randi() % 2) * 2 - 1 ## random -1 or 1
var avoiding_angle := PI * 0.25
avoiding_direction = avoiding_direction.rotated(avoiding_angle * random_sign)
Then the avoiding_direction is the direction in which your enemy should move. (The direction is already relative to the enemy’s position and normalized.)