I am currently trying to create boids. One of the rules is that boids have to separate. However, with the code I am using right now, they refuse to seperate, just kinda jitter around in place.
The code that determines direction:
function Boid.__index:CalculateDirection(): Vector3?
local AverageHeading = ZERO_VECTOR
local AveragePosition = ZERO_VECTOR
local SeperationHeading = ZERO_VECTOR
local NumBoids = 0
local AvoidBoids = 0
for Id, OtherBoid in ipairs(BoidArray) do
if OtherBoid.Id == self.Id then
continue
end
local Offset = self.Position - OtherBoid.Position
local Distance = Offset.Magnitude
if Distance > self.Range then
continue
end
if GetAngleBetweenVectors(self.Position, OtherBoid.Position) > self.ViewAngle then
continue
end
AverageHeading += OtherBoid.Direction
AveragePosition += OtherBoid.Position
if Distance <= AVOID_RADIUS then
SeperationHeading -= Offset / Distance
AvoidBoids += 1
end
NumBoids += 1
end
if NumBoids < 1 then
return
end
AverageHeading /= NumBoids
AverageHeading *= ALIGN_WEIGHT
AveragePosition = AveragePosition / NumBoids - self.Position
AveragePosition *= COHESIVE_WEIGHT
-- Dividing by 0 results in nan values, which caused me way too much headache :/
if AvoidBoids > 0 then
SeperationHeading /= AvoidBoids
SeperationHeading *= SEPERATION_WEIGHT
print(SeperationHeading)
else
return ClampVector((AverageHeading + AveragePosition) / 2, MAX_VELOCITY)
end
return ClampVector((AverageHeading + AveragePosition + SeperationHeading) / 3, MAX_VELOCITY)
end
Note: AVOID_WEIGHT = 9, every other weight is set to 1.
Edit: Video of the issue: