GPierre
GPierre

Reputation: 100

Hide seek behavior with only the vectors towards the enemy and the hiding spot

For a pygame class, I am asked to implement various seek behaviors with limited information about the game world. Most behaviors have been easy to do, but I am blocked trying to implement the hide behavior with the information I have access to.

I am given two vectors and the position of an agent in the world. The first vector is the distance between the agent and the enemy it has to hide from. The second vector is the distance from the agent and the nearest column it can hide behind. Given this, I'd like to move the agent towards the column and make sure it stays hidden from the enemy.

In graphical term, I am trying to find the vector b in this image, I have access to the vector u and v and I am trying to calculate the vector w plus a scalar a for the intended distance of from the column + its radius.

Vector graphics

I currently have this code running, but it is obviously wrong as the vector I calculate is outside the bounds of the game world.

player_to_col_vector = (
    col_distance[0] - enemy_distance[0],
    col_distance[1] - enemy_distance[1],
)

normalized = 1 / sqrt(player_to_col_vector[0] ** 2 + player_to_col_vector[1] ** 2)
dx = normalized * acceptable_distance
dy = normalized * acceptable_distance

I think my issue is that I now have the vector wa, but I have no idea how to find the b vector from the information I have.

Upvotes: 2

Views: 114

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

I assume that acceptable_distance corresponds to the size of the vector a in the image. So acceptable_distance is the distance between C and D

The calculation of the normalized vector is wrong. normalized is the reciprocal length of the vector from B to C:

normalized = 1 / sqrt(player_to_col_vector[0] ** 2 + player_to_col_vector[1] ** 2)

In the following lenBC is the distance between B and C. dirBC is a Unit vector (this means its length is 1) and is the direction form B to C:

lenBC = sqrt(player_to_col_vector[0] ** 2 + player_to_col_vector[1] ** 2)
dirBC = (player_to_col_vector[0] / lenBC, player_to_col_vector[1] / lenBC)

(dx, dy) is the vector from C to D.

dx, dy = (dirBC[0] * acceptable_distance, dirBC[1] * acceptable_distance)

The vector b, which is equal the point D, is the sum of the vector v and the vector a:

bx, by = (col_distance[0] + dx, col_distance[1] + dy)   

The vector from the point B to D is the sum of w and a:

BDx, BDy = (player_to_col_vector[0] + dx, player_to_col_vector[1] + dy)

Deleted, since the tag "pygame" was removed.

The above code does all the calculations. But note, in PyGame there is an much easier way to do this, by using pygame.math.Vector2 for calculations:

u = pygame.math.Vector2(enemy_distance)
v = pygame.math.Vector2(col_distance)  

w = v - u
a = w.normalize() * acceptable_distance
b = v + a

Upvotes: 1

Related Questions