Pick a random angle to move to in the opposite direction of the current direction solution?

Godot Version

Godot 4.3.Stable

Question

Hello once again.

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?

Code:

func physics_update(_delta: float) -> void:
	
	if owner.avoidance_timer.time_left > 0:
		avoidance()
	else:
		pursue_target()
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

Here’s a visual example of what I want.

In general, the procedure should be something like this:

  1. Get a vector from the avoiding enemy to the enemy standing in its way.
  2. For comprehensibility, I would invert that vector. vector = -vector
    (This is optional though. You could just use a larger angle for rotation later instead.)
  3. Use an RNG to get either 1 or -1.
  4. Rotate the vector by a defined angle multiplied by the result of the RNG. vector = vector.rotated(angle * random_sign)

When an enemy collides with another enemy using move_and_collide() the avoidance timer starts btw

How do I define those angles?

I am lost.

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.)

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.