// Add separation or alignment forces if applicable. private void separationAndAlignment() { // position and distance of fish at index Vector3 pos = fish[fish_index].transform.position; Quaternion rot = fish[fish_index].transform.rotation; float dist = Vector3.Distance(transform.position, pos); fish_script fishScript = fish[fish_index].GetComponent <fish_script>(); // if not this fish if (dist > 0f && fishScript.isAlive == true) { // if within separation if (dist <= separation_distance) { // compute the scale of separationt float scale = separation_strength / dist; // add a separation force between this fish and its neighbour rigidbody.AddForce(scale * Vector3.Normalize(transform.position - pos)); } else if (dist < cohesion_distance && dist > separation_distance) // if within cohesive distance but not separation // compute the cohesive position { cohesion_pos = cohesion_pos + pos * (1f / (float)fish.Length); // alignment - small rotations are applied based on the alignments of the neighbours transform.rotation = Quaternion.RotateTowards(transform.rotation, rot, 10f); } // Wander forwards. rigidbody.AddForce(transform.forward * speed); } }
// Find the closest fish to me. private void findClosestFish() { GameObject fish = fishes[fish_index]; fish_script fishScript = fish.GetComponent <fish_script>(); if (fishScript.isAlive) { Vector3 fishPosition = fish.transform.position; float fishDistance = Vector3.Distance(transform.position, fishPosition); if (fishDistance < closestFishDistance) { closestFish = fish; closestFishDistance = fishDistance; } } fish_index++; if (fish_index >= fishes.Length) { fish_index = 0; finalClosestFish = closestFish; closestFishDistance = 50f; } }
// Chase the closest fish. private void chaseFish() { if (hunger >= hunger_threshold) { fish_script closestFishScript = finalClosestFish.GetComponent <fish_script>(); float step = 4.0f * Time.deltaTime; Vector3 fishPosition = closestFish.transform.position; float fishDistance = Vector3.Distance(transform.position, fishPosition); Vector3 targetDir = fishPosition - transform.position; Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F); rigidbody.AddForce(-speed * Vector3.Normalize(transform.position - fishPosition)); transform.rotation = Quaternion.LookRotation(newDir); // If the fish is quite close, eat the fish. if (fishDistance < 2.0f) { closestFishScript.eatenByShark(); foodLevel += closestFishScript.foodValue; } } }
public void set_fish_speed(float speed) { fish_script a_fish_script = (fish_script)fish.GetComponent(typeof(fish_script)); a_fish_script.fish_rotate_speed = speed; }