Question

I am writing a simulation in Python, which includes agents that can travel in the environment, and have velocity vector v. the environment also includes another type of objects (food). I want the agents to "see" only food that is within distance r from the agent, and only when the angle between the food and the positive x axis, theta, is within some "field of view" that is defined as +-alpha degrees from the angle beta between the velocity vector and the positive X axis.

In the illustration I added here, the blue arrow is the velocity vector, it makes an angle of beta with the positive x axis, and I want the agent to see only the red dots. when I simply check if beta-alpha<=theta<=beta+alpha I don't get right results when the range (beta-alpha , beta+alpha) includes a transition from negative to positive angles or from 2pi to 0 and vice versa.

the code:

dx = food.x - agent.x
dy = food.y - agent.y
theta = atan2(dy,dx)
alpha = pi/6.
Vx,Vy = agent.velocity[0], agent.velocity[1]
beta = atan2(Vy,Vx)
if (beta-alpha<=theta and theta<=beta+alpha):
    food.color = (255,0,0)
else:
    food.color = (0,0,0)

enter image description here

Was it helpful?

Solution

Try fixing the boundary condition where alpha+beta and beta-alpha lies on either side of the positive x-axis. Assuming all your angles, beta and theta lie in the range (0, 2*Pi), this might work :

def checkMargingForTheta(alpha, beta, theta):
    low = beta - alpha
    high = beta + alpha

    if(high > 2*pi):
        high = high - 2*pi
    if(low < 0):
        low = 2*pi + low
    if(low > high):
        return (theta > low)
    else:
        return (low < theta and high > theta)

OTHER TIPS

Thanks, gaganbm! for future readers, the accurate answer is:

  def Atan2(y,x): #changing atan2() range to (0,2pi)
   a = atan2(y,x)
   if (a<0):
    a+=2*PI
   return a

  def checkMargingForTheta(alpha, beta, theta):
    low = beta - alpha
    high = beta + alpha

    if(high > 2*pi):
        high = high - 2*pi
    if(low < 0):
        low = 2*pi + low
    if(low > high):
        if (theta > high):
          return (theta>low)  
        else:
          return (True)
    else:
        return (low < theta and high > theta)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top