Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flocking/ Boids Algorithm : Field Of view specified by angle in 3D

I am trying to make boids algorithm in Unity 3D.

I got into one problem: How to implement field of view in specific angle?

360 degrees is easy - U check only distance between two boids. But I dont want boids able to look behind themself. I also want to be able to change angle of view in Inspector, so it must be based on calculations.

I would be gratefull for any ideas:(

enter image description here enter image description here

I already tried with mesh collider which is cone but it didnt go well. - not working for 180 and higher. So I am looking best way to calculate this.

like image 502
scatterplot Avatar asked Oct 30 '25 22:10

scatterplot


1 Answers

Assume that the boid is at point p = (p.x, p.y, p.z) heading toward some point h = (h.x, h.y, h.z), and we want to know whether an object at point q = (q.x, q.y, q.z) is in the boid's field of vision.

The Law of Cosines gives us a formula for the cosine of the angle φ between the boid's heading and the boid's path to the object:

          (h−p) · (q−p)
cos(φ) = ---------------
         ||h−p|| ||q−p||

       = (dx1*dx2 + dy1*dy2 + dz1*dz2) /
         (sqrt(dx1*dx1 + dy1*dy1 + dz1*dz1) * sqrt(dx2*dx2 + dy2*dy2 + dz2*dz2))

where

dx1 = h.x - p.x
dy1 = h.y - p.y
dz1 = h.z - p.z
dx2 = q.x - p.x
dy2 = q.y - p.y
dz2 = q.z - p.z

Given some angle ρ (in whatever units your cosine function accepts, usually radians) past which the boid cannot see (putting the field of vision at ), we have

φ > ρ  if and only if  cos(φ) < cos(ρ),

so we can precompute cos(ρ) and then use the above formula for repeated tests.

To avoid division by zero and other numerical problems, you might want to check whether the denominator of the division is very small and if so declare that the boid can feel whatever the object is even outside its field of vision.

like image 77
David Eisenstat Avatar answered Nov 03 '25 04:11

David Eisenstat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!