Example #1
0
    private void OnCollisionEnter2D(Collision2D collision)     // collision refers to other object
    {
        if (collision.gameObject.CompareTag("Sheep"))
        {
            SheepController otherSheep = collision.gameObject.GetComponent <SheepController>();
            if (isPanicked) //if this sheep is spooked
            {
                if (otherSheep)
                {
                    otherSheep.PanicSheep();
                }                  // Panic the other sheep
            }
            GenerateMovementDir(); // change direction of this sheep
            if (otherSheep)
            {
                otherSheep.GenerateMovementDir();
            }                                                     // change direction of other sheep
        }

        else if (collision.gameObject.CompareTag("Wolf")) // this sheep runs into a wolf
        {
            sheepRb.velocity = new Vector2(0f, 0f);
            GenerateMovementDir();
        }

        else if (collision.gameObject.CompareTag("Boundary"))                                      //switch direction if we hit edge of map
        {
            if (Mathf.Abs(collision.relativeVelocity.x) > Mathf.Abs(collision.relativeVelocity.y)) // if hitting a side wall
            {
                sheepRb.velocity = new Vector2(-sheepRb.velocity.x, sheepRb.velocity.y);
                movementDir      = new Vector2(-movementDir.x, movementDir.y);
            }
            else // if hitting a top/bot wall
            {
                sheepRb.velocity = new Vector2(sheepRb.velocity.x, -sheepRb.velocity.y);
                movementDir      = new Vector2(movementDir.x, -movementDir.y);
            }
        }
    }