Boids Flocking System problem with speed calculation interfering with boundaries

11 views Asked by At

My boundary method and speed method both work perfectly fine separately but when both are called, my boundary method stops working, im following this guide and my code as far as im aware is perfect in comparison to the sample.

    private void Update()
    {
        CheckEdges();

        LimitSpeed();
        MoveBoid();
    }

    // Private
    private void CheckEdges()
    {
        // Top Margin
        if(this.transform.position.y > this.screenMax.y - 1.0f)
        {
            this.velocity.y -= this.turnFactor;
        }

        // Bottom Margin
        if(this.transform.position.y < this.screenMin.y + 1.0f)
        {
            this.velocity.y += this.turnFactor;
        }

        // Left Margin
        if(this.transform.position.x < this.screenMin.x + 1.0f)
        {
            this.velocity.x += this.turnFactor;
        }

        // Right Margin
        if(this.transform.position.x > this.screenMax.x - 1.0f)
        {
            this.velocity.x -= this.turnFactor;
        }
    }

    private void LimitSpeed()
    {
        float speed = Mathf.Sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y);

        if(speed > minSpeed)
        {
            this.velocity.x = (this.velocity.x / speed) * this.minSpeed;
            this.velocity.y = (this.velocity.y / speed) * this.minSpeed;
        }

        if(speed < maxSpeed)
        {
            this.velocity.x = (this.velocity.x / speed) * this.maxSpeed;
            this.velocity.y = (this.velocity.y / speed) * this.maxSpeed;
        }
    }

    private void MoveBoid()
    {
        this.transform.position += (Vector3)this.velocity * Time.deltaTime;
    }

Ive refactored and rewrote this code many times but still cannot find a solution, I have triple checked the pseudo-code guide and i cant find what im missing.

0

There are 0 answers