Ejemplo n.º 1
0
    void FixedUpdate()
    {
        if (!m_updatePosition)
        {
            return;
        }

        // Sort boids into cells
        SortBoidsIntoCells();

        // Find boids neighbours
        PerformNeighbourSearch();

        for (int i = 0; i < m_boids.Length; ++i)
        {
            Boid boid = m_boids[i];

            Vector3 newVelocity = Vector3.zero;

            // 1) SEPARATION
            Vector3 separation = Vector3.zero;
            if (m_enableSeparation)
            {
                separation = CalculateSeparation(i);
                if (m_drawSeparationDebugRays &&
                    separation.sqrMagnitude > 0.0f)
                {
                    DrawRedRay(boid, separation);
                }

                newVelocity += separation * m_separationFactor;
            }

            // 2) ALIGNMENT
            Vector3 alignment = Vector3.zero;
            if (m_enableAlignment)
            {
                alignment = CalculateAlignment(i);
                if (m_drawAlignmentDebugRays &&
                    alignment.sqrMagnitude > 0.0f)
                {
                    DrawRay(boid, alignment, Color.blue);
                }

                newVelocity += alignment * m_alignmentFactor;
            }

            // 3) COHESION
            Vector3 cohesion = Vector3.zero;
            if (m_enableCohesion)
            {
                cohesion = CalculateCohesion(i);
                if (m_drawCohesionDebugRays &&
                    cohesion.sqrMagnitude > 0.0f)
                {
                    DrawRay(boid, cohesion, Color.green);
                }

                newVelocity += cohesion * m_cohesionFactor;
            }

            // 4) AVOIDANCE
            if (m_obstacles.Length > 0)
            {
                Vector3 avoidance = Vector3.zero;
                if (m_enableAvoidance)
                {
                    avoidance = CalculateAvoidance(i);
                    if (m_drawAvoidanceDebugRays &&
                        avoidance.sqrMagnitude > 0.0f)
                    {
                        DrawRay(boid, avoidance, Color.yellow);
                    }

                    newVelocity += avoidance * m_avoidanceFactor;
                }
            }

            if (m_drawBoidAxis)
            {
                boid.DrawDebugAxis();
            }

            if (newVelocity.sqrMagnitude > 0)
            {
                boid.SetBoidVelocity(newVelocity);
            }

            boid.UpdatePosition();
            boid.ClearNeighbours();
        }
    }