OpenSteer icon indicating copy to clipboard operation
OpenSteer copied to clipboard

steerForSeparation has some problem

Open menghaikang opened this issue 5 months ago • 1 comments

in function distanceSquared().

If two Vehicles completely overlap in same position, distanceSquared will be 0, causing a division - by - zero error (NAN).

template<class Super>
OpenSteer::Vec3
OpenSteer::SteerLibraryMixin<Super>::
steerForSeparation (const float maxDistance,
                    const float cosMaxAngle,
                    const AVGroup& flock)
{
    // steering accumulator and count of neighbors, both initially zero
    Vec3 steering;
    int neighbors = 0;

    // for each of the other vehicles...
    AVIterator flockEndIter = flock.end();
    for (AVIterator otherVehicle = flock.begin(); otherVehicle != flockEndIter; ++otherVehicle )
    {
        if (inBoidNeighborhood (**otherVehicle, radius()*3, maxDistance, cosMaxAngle))
        {
            // add in steering contribution
            // (opposite of the offset direction, divided once by distance
            // to normalize, divided another time to get 1/d falloff)
            const Vec3 offset = (**otherVehicle).position() - position();
            const float distanceSquared = offset.dot(offset);
            steering += (offset / -distanceSquared);

            // count neighbors
            ++neighbors;
        }
    }

    // divide by neighbors, then normalize to pure direction
    // bk: Why dividing if you normalize afterwards?
    //     As long as normilization tests for @c 0 we can just call normalize
    //     and safe the branching if.
    /*
    if (neighbors > 0) {
        steering /= neighbors;
        steering = steering.normalize();
    }
    */
    steering = steering.normalize();
    
    return steering;
}

menghaikang avatar Aug 07 '25 11:08 menghaikang

Great observation. SteerForSeparation could benefit from another parameter, minDistance. Hopefully subsequent iteration would provide enough of a nudge to the boid position to get it out of superposition and let the regular dynamics take effect. That might be a robust overall fix.

meshula avatar Sep 24 '25 21:09 meshula