Example #1
0
    void Start()
    {
        behaviour = GetComponent <AnimalBehaviour>();

        foodLayer   = LayerMask.GetMask("Food");
        animalLayer = LayerMask.GetMask("Animals");
    }
    void MutateChild(AnimalBehaviour child, AnimalBehaviour mate)
    {
        AnimalBehaviour chosenParent;

        chosenParent = (Random.value > 0.5) ? mate : this;
        child.speed  = chosenParent.speed + NormalDistribution(0, 0.3f) * mutationAmount;
        if (child.speed < 0.2)
        {
            child.speed = 0.2f;
        }

        chosenParent      = (Random.value > 0.5) ? mate : this;
        child.senseRadius = chosenParent.senseRadius + NormalDistribution(0, 0.5f) * mutationAmount;
        if (child.senseRadius < 1)
        {
            child.senseRadius = 1;
        }

        chosenParent = (Random.value > 0.5) ? mate : this;
        child.reproductionThreshold = chosenParent.reproductionThreshold + NormalDistribution(0, 1f) * mutationAmount;

        chosenParent       = (Random.value > 0.5) ? mate : this;
        child.passedEnergy = chosenParent.passedEnergy + NormalDistribution(0, 1f) * mutationAmount;
        if (child.passedEnergy < 0)
        {
            child.passedEnergy = 0;
        }
    }
Example #3
0
    IEnumerator DataLogger()
    {
        string filePath = Path.Combine(@"./Assets/SimulationLogs/", System.DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".csv");

        using (StreamWriter writer = new StreamWriter(filePath)) {
            writer.WriteLine("Time,Number of Animals,Average sense radius, Average speed,Average reproduction threshold,Average passed energy");
            while (transform.childCount > 0)
            {
                numberOfListEntries++;
                float timeStamp   = numberOfListEntries * (1 / logFrequency);
                float animalCount = transform.childCount;

                float senseRadius           = 0;
                float speed                 = 0;
                float reproductionThreshold = 0;
                float passedEnergy          = 0;
                foreach (Transform animal in transform)
                {
                    AnimalBehaviour behaviour = animal.GetComponent <AnimalBehaviour>();
                    senseRadius           += behaviour.senseRadius;
                    speed                 += behaviour.speed;
                    reproductionThreshold += behaviour.reproductionThreshold;
                    passedEnergy          += behaviour.passedEnergy;
                }
                senseRadius           = senseRadius / animalCount;
                speed                 = speed / animalCount;
                reproductionThreshold = reproductionThreshold / animalCount;
                passedEnergy          = passedEnergy / animalCount;

                writer.WriteLine(FormatOutput($"{timeStamp},{animalCount},{senseRadius*valueMultiplier},{speed*valueMultiplier},{reproductionThreshold*valueMultiplier},{passedEnergy*valueMultiplier}"));
                yield return(new WaitForSeconds(1 / (logFrequency * simulationSpeed)));
            }
        }
    }
Example #4
0
 private void Awake()
 {
     m_animalFOV       = this.gameObject.AddComponent <AnimalFOV>();
     m_animalMesh      = GetComponentInChildren <AnimalMesh>();
     m_animalAwareness = gameObject.AddComponent <AnimalAwareness>();
     m_animalBehaviour = gameObject.AddComponent <AnimalBehaviour>();
 }
Example #5
0
    private void Start()
    {
        rb = GetComponent <Rigidbody2D>();
        StartCoroutine(ChooseNewDirection(timeTilDirectionChange));

        state     = CharacterState.HEALTHY;
        behaviour = AnimalBehaviour.WANDERING;
    }
Example #6
0
    void Start()
    {
        canvas     = transform.parent.GetComponent <AnimalSimulation>().animalCanvas;
        mainCamera = transform.parent.GetComponent <AnimalSimulation>().mainCamera;

        behaviour = transform.GetComponent <AnimalBehaviour>();

        infoText = CreateInfoText();
    }
Example #7
0
    // Start is called before the first frame update
    void Start()
    {
        animal    = GetComponentInParent <AnimalBehaviour>();
        drink     = startDrink;
        food      = startFood;
        health    = startHealth;
        maxReprod = 100.0f;

        targetCamera = GameObject.FindGameObjectWithTag("MainCamera").transform;
    }
Example #8
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            scale += spread;
        }
        if (Input.GetKeyUp(KeyCode.Space))
        {
            dmgArea.SetActive(true);
            scream.SetActive(false);
            dmgArea.transform.localScale = new Vector3(scale, thin, scale);
            Vector2      pos       = new Vector2(transform.position.x, transform.position.y);
            Collider2D[] colliders = Physics2D.OverlapCircleAll(pos, 0.66f * scale, mask); // 0.5 is the radius of the collider
            for (int i = 0; i < colliders.Length; i++)
            {
                AnimalBehaviour animal = colliders[i].gameObject.GetComponent <AnimalBehaviour>();

                if (animal)
                {
                    animal.scared = true;
                    audioSource.PlayOneShot(audioClip);
                }
                Vector3 dist = animal.transform.position - transform.position;
                float   n    = dist.magnitude;
            }
            scale = initialRadius;
        }

        if (dmgArea.activeInHierarchy)
        {
            if (currentDmgDuration < dmgDuration)
            {
                currentDmgDuration += Time.deltaTime;
                if (currentDmgDuration < dmgDuration * j / 4)
                {
                    dmgArea.transform.Rotate(new Vector3(0, 50, 0));
                    dmgArea.transform.localScale = new Vector3(dmgArea.transform.localScale.x - 0.05f * ((-1) ^ j), thin, dmgArea.transform.localScale.z - 0.05f * ((-1) ^ j));
                    j++;
                }
            }
            else
            {
                dmgArea.SetActive(false);
                scream.SetActive(true);
                currentDmgDuration = 0;
                j = 1;
            }
        }

        scale = Mathf.Clamp(scale, 0, maxRadius);
        scream.transform.localScale = new Vector3(scale, thin, scale);
        scream.transform.position   = new Vector3(transform.position.x, transform.position.y, transform.position.z + 0.5f);
        dmgArea.transform.position  = new Vector3(transform.position.x, transform.position.y, transform.position.z + 0.5f);
    }
    public void MakeBaby(int numberOfBabies, int motherRef)
    {
        float mutate = Random.Range(1, 100);
        AnimalBehaviour animal;
        AnimalBehaviour mother = animalList [motherRef];
        Vector3 pos = mother.Getposition();
        float newPosX = Random.Range(-5.0f, 5.0f);
        float newPosZ = Random.Range(-5.0f, 5.0f);
        AnimalBehaviour.AnimalType type;
        int ID = mother.GetSpeciiesID();
        float energy, maxAge, maxSize;
        float speed, rot, foodSize, eatEff, willToLive;

           for (int i = 0; i < numberOfBabies; i++)
        {

            type = mother.GetType();
            energy = mother.GiveEnergyToYoung();
            maxAge = mother.GetMaxAge();
            maxSize = mother.GetMaxSize();
            speed = mother.GetSpeed();
            rot = mother.GetRot();
            foodSize = mother.GetFoodSize();
            eatEff = mother.GetEatEff();
            willToLive = mother.GetWillToLive();
            pos = new Vector3(pos.x + newPosX, pos.y, pos.z + newPosZ);

            if (mutate <= 20)
            { //make a new species
                //Randomise stuff here
                ID++;
            }

            if(type == AnimalBehaviour.AnimalType.herbivore)
            {
                animalObj = herbivoreObj;
            }
            else{
                animalObj =  carnivoreObj;
            }

            animal = Instantiate(animalObj, pos, Quaternion.identity)as AnimalBehaviour;
            animal.newAnimal(type, ID, pos, energy, maxAge, maxSize, speed, rot, foodSize, eatEff, willToLive);
            animalList.Add(animal);

            speciesList.Add(ID);
            speciesList[ID]++;
        }
    }
    // Use this for initialization
    void Awake()
    {
        // Make sure we have stack manager
        stackManager = Utility.GetComponentFromTag<StackManager>("StackManager");

        // Set up the box collider
        boxCollider = gameObject.GetComponent<BoxCollider>();
        boxCollider.transform.localScale = new Vector3(1.5f, 1.1f ,1.5f);
        boxCollider.transform.localPosition = new Vector3(0.0f, 0.5f, 0.0f);
        boxCollider.isTrigger = true;

        // Get parent object
        objParent = transform.parent.gameObject;
        animalBehaviour = objParent.GetComponent<AnimalBehaviour>();

        // Start disabled
        Disable();
    }
Example #11
0
    void Update()
    {
        // Dont process if we are frozen
        if (Time.timeScale == 0)
            return;

        if (controlledAnimal == null)
        {
            controlledAnimal = stackManager.currentAnimal.GetComponent<AnimalBehaviour>();
        }
        else
        {
            // Handle input based on input type
            if (usePS4Controller)
            {
                HandlePS4Input();
            }
            else
            {
                HandleKeyboardInput();
            }
        }
    }
Example #12
0
    private void HandleModes()
    {
        if (!controlledAnimal.CanThrow())
        {
            return;
        }

        if (usePS4Controller)
        {
            if (Input.GetAxis("PS4_BUTTON_R2") > 0.0f)
            {
                // Setup throwing mode
                if (throwingMode == false)
                {
                    //if throwing mode is activated while the controlled animal has been moved a little on top of another stack without stepping off completely, remerge before activating throwing mode
                    for (int i =0; i<stackManager.levelStacks.Count; i++)
                    {
                        if (controlledAnimal.parentStack.Equals(stackManager.levelStacks [i]))
                            continue;

                        if (!controlledAnimal.beingThrown && (controlledAnimal.rigidBody.velocity.y >= (-0.001f)) && (Mathf.Abs(controlledAnimal.transform.position.x - stackManager.levelStacks [i].Get(0).transform.position.x) <= (controlledAnimal.animalHeight + 0.2f)) && (Mathf.Abs(controlledAnimal.transform.position.z - stackManager.levelStacks [i].Get(0).transform.position.z) <= (controlledAnimal.animalHeight + 0.2f)))
                        {
                            controlledAnimal.Stop();

                            stackManager.MergeStack(stackManager.levelStacks [i], controlledAnimal.parentStack, ExecutePosition.BOTTOM);

                            StartCoroutine(controlledAnimal.DisableMovement());
                            controlledAnimal.Stop();

                            // Tell the stack manager to update to the correct animal
                            stackManager.UpdateSelectedAnimal(stackManager.gameAnimals [animalIndex]);

                            // Update controlled animal
                            controlledAnimal = stackManager.currentAnimal.GetComponent<AnimalBehaviour>();


                        }
                    }

                    //Stop animal if moving
                    controlledAnimal.currentVelocity = Vector3.zero;
                    throwManager.ActivateThrowingMode(controlledAnimal);
                }
                throwManager.HandleCannonRotation();
                throwingMode = true;
            }
            else
            {
                // Trigger released - throw
                if (throwingMode == true)
                {
                    ControllerThrowCall();
                }
                throwingMode = false;
            }
        }
        else
        {
            if (Input.GetKeyDown(throwingWinKey))
            {
                throwingMode = !throwingMode;

                if (throwingMode)
                {
                    throwManager.ActivateThrowingMode(controlledAnimal);
                    controlledAnimal.currentVelocity = Vector3.zero;
                }
                else
                {
                    throwManager.DeactivateThrowingMode();
                }
            }
        }
    }
Example #13
0
 // Use this for initialization
 void Start()
 {
     view_cone_polygon = gameObject.GetComponent <PolygonCollider2D>();
     animal_behaviour  = gameObject.GetComponentInParent <AnimalBehaviour>();
     points            = new Vector2[6];
 }
Example #14
0
 public void HandleAnimalKeyboardThrowing()
 {
     if (Input.GetKey(KeyCode.RightArrow))
     {
         throwManager.RotateRight();
     }
     if (Input.GetKey(KeyCode.LeftArrow))
     {
         throwManager.RotateLeft();
     }
     if (Input.GetKey(KeyCode.UpArrow))
     {
         throwManager.RotateDown();
     }
     if (Input.GetKey(KeyCode.DownArrow))
     {
         throwManager.RotateUp();
     }
     
     if (Input.GetKeyDown(throwWinKey))
     {
         if (throwManager.trajectories.isThrowAllowed)
         {
             if (throwManager.CallThrow(controlledAnimal.gameObject, false))
             {
                 // If throw was successful - change controlled animal
                 controlledAnimal = controlledAnimal.GetAnimalAbove().GetComponent<AnimalBehaviour>();
             }
             throwingMode = false;
         }
     }
 }
Example #15
0
    //==============================================================================
    // Throwing Input
    //==============================================================================

    private void ControllerThrowCall()
    {
        if (throwManager.CallThrow(controlledAnimal.gameObject, true))
        {
            // If throw was successful - change controlled animal
            controlledAnimal = controlledAnimal.GetAnimalAbove().GetComponent<AnimalBehaviour>();
            animalIndex = stackManager.gameAnimals.IndexOf(controlledAnimal.gameObject);
        }
    }
Example #16
0
    private void HandleAnimalSwitching(KeyCode key, int value)
    {
        // Check to make sure we do want to switch
        if (!Input.GetKeyDown(key))
            return;
        
        // Check animal is not being thrown or in mid-air
        if (!controlledAnimal.beingThrown && controlledAnimal.parentStack.Get(0).GetComponent<AnimalBehaviour>().isGrounded)
        {
            Debug.Log("Able to switch!");
            // Disable move velocity
            controlledAnimal.Stop();
        
            // Change index
            animalIndex = value;
        
            // Keep within the range
            Utility.Wrap(ref animalIndex, 0, stackManager.gameAnimals.Count - 1);
        
            // Tell the stack manager to update to the correct animal
            stackManager.UpdateSelectedAnimal(stackManager.gameAnimals [animalIndex]);
        
            // Update controlled animal
            controlledAnimal = stackManager.currentAnimal.GetComponent<AnimalBehaviour>();
        
            // Revert to movement mode upon animal change
            if (throwingMode)
            {
                throwingMode = false;
                throwManager.DeactivateThrowingMode();
            }
            return;
        }

        //look for the stack the controlled animals stack is currently on top of and remerge with it, before controlled animal is changed 
        for (int i =0; i<stackManager.levelStacks.Count; i++)
        {
            if (controlledAnimal.parentStack.Equals(stackManager.levelStacks [i]))
            {
                //Debug.Log("Index of Parentstack:"+i);
                continue;

            }

            //Debug.Log(controlledAnimal.rigidBody.velocity.y);
            //Debug.Log(Mathf.Abs(controlledAnimal.transform.position.x - stackManager.levelStacks[i].Get(0).transform.position.x));
            //Debug.Log(Mathf.Abs(controlledAnimal.transform.position.z - stackManager.levelStacks[i].Get(0).transform.position.z));

            //check if animal is not being thrown, falling and overlapping with another stack on the x- and z-plane
            if (!controlledAnimal.beingThrown && (controlledAnimal.rigidBody.velocity.y >= (-0.001f)) && (Mathf.Abs(controlledAnimal.transform.position.x - stackManager.levelStacks [i].Get(0).transform.position.x) <= (controlledAnimal.animalHeight + 0.2f)) && (Mathf.Abs(controlledAnimal.transform.position.z - stackManager.levelStacks [i].Get(0).transform.position.z) <= (controlledAnimal.animalHeight + 0.2f)))
            {
                //Debug.Log("Here");

                if (throwingMode)
                {
                    throwingMode = false;
                    throwManager.DeactivateThrowingMode();
                }

                controlledAnimal.Stop();


                stackManager.MergeStack(stackManager.levelStacks [i], controlledAnimal.parentStack, ExecutePosition.BOTTOM);

                StartCoroutine(controlledAnimal.DisableMovement());
                controlledAnimal.Stop();

                animalIndex = value;

                // Keep within the range
                Utility.Wrap(ref animalIndex, 0, stackManager.gameAnimals.Count - 1);

                // Tell the stack manager to update to the correct animal
                stackManager.UpdateSelectedAnimal(stackManager.gameAnimals [animalIndex]);

                // Update controlled animal
                controlledAnimal = stackManager.currentAnimal.GetComponent<AnimalBehaviour>();

                return;
            }
        }
    }
Example #17
0
 public void AssignTreatment(AnimalBehaviour.TREATMENTS treatment)
 {
     this.treatment = treatment;
 }
    // Update is called once per frame
    void Update()
    {
        gameTime += Time.deltaTime;

        //Start Simulation
        if (Input.GetKeyDown(KeyCode.Z))
        {
            AnimalBehaviour animal;
            animalObj = herbivoreObj;
            Vector3 pos = new Vector3(0, 0.5f, 0);
            animal = Instantiate(animalObj, pos, Quaternion.identity)as AnimalBehaviour;

            animal.newAnimal(AnimalBehaviour.AnimalType.herbivore,0, pos, 15, 20, 1,4, 0.075f, 4, 0.5f, 1.0f);

            animalList.Add(animal);
            speciesList [0]++;

            Invoke("MakeCarnivore",0.2f *(60.0f)); // make carnivores after a given amount of minutes.
        }

        for (int i = 0; i < animalList.Count; i++)
        {

            if (animalList [i] == null)
            {
                int specIndex = animalList [i].thisAnimalSpeciesID;
                animalList.Remove(animalList [i]);
                speciesList[specIndex]--;
            }else{

                if (animalList [i].GetIfReadyToPop() && animalList.Count <= MaxNumberOfAnimals)
                {
                    MakeBaby(2, i);
                    animalList [i].setReadyToPop(false);

                }
            }
        }
    }
    public void OnPathFinished()   //Will be called upon reaching the destination
    {
        pathfinder.ClearPath();
        switch (status)
        {
        case 0:
            GoSearchPath();
            break;

        case 1:
            if (pathTarget != null)
            {
                simulation.foodSpawner.allFoodPositions.Remove(GridHelper.WorldPosToGridPos(pathTarget.transform.position));
                Destroy(pathTarget);
                energy += foodEnergyGain;
            }
            pathTarget = null;
            if (energy > reproductionThreshold)
            {
                status = 2;
            }
            else
            {
                status = 0;
            }
            GoSearchPath();
            break;

        case 2:
            GoSearchPath();
            break;

        case 3:
            if (pathTarget != null)
            {
                AnimalBehaviour mateBehaviour = pathTarget.GetComponent <AnimalBehaviour>();
                if (mateBehaviour.status == 4)
                {
                    GameObject      childAnimal    = transform.parent.GetComponent <AnimalSimulation>().NewAnimal(transform.position);
                    AnimalBehaviour childBehaviour = childAnimal.GetComponent <AnimalBehaviour>();
                    energy -= passedEnergy;
                    mateBehaviour.energy -= mateBehaviour.passedEnergy;
                    childBehaviour.energy = passedEnergy + mateBehaviour.passedEnergy;
                    MutateChild(childBehaviour, mateBehaviour);
                    if (energy > reproductionThreshold)
                    {
                        status = 2;
                    }
                    else
                    {
                        status = 0;
                    }
                    if (mateBehaviour.energy > mateBehaviour.reproductionThreshold)
                    {
                        mateBehaviour.status = 2;
                    }
                    else
                    {
                        mateBehaviour.status = 0;
                    }
                    pathTarget = null;
                    mateBehaviour.pathTarget = null;
                    GoSearchPath();
                    mateBehaviour.GoSearchPath();
                }
                else
                {
                    status = 4;
                }
            }
            else
            {
                if (energy > reproductionThreshold)
                {
                    status = 2;
                }
                else
                {
                    status = 0;
                }
                GoSearchPath();
            }
            break;

        default:
            break;
        }
    }
    public void OnStep()                //Will be called each step
    {
        energy = EnergyFormula(energy); //Apply the energy formula
        sensing.Sense();
        switch (status)
        {
        case 0:
            if (sensing.closestFood != null)
            {
                pathfinder.ClearPath();
                status     = 1;
                pathTarget = sensing.closestFood.gameObject;
                pathfinder.GoPath(sensing.closestFood, speed);
            }
            else if (energy > reproductionThreshold)
            {
                status = 2;
            }
            break;

        case 1:
            if (pathTarget == null)
            {
                pathfinder.ClearPath();
                status = 0;
                GoSearchPath();
            }
            break;

        case 2:
            if (sensing.closestMate != null)
            {
                AnimalBehaviour mateBehaviour = sensing.closestMate.GetComponent <AnimalBehaviour>();
                if (mateBehaviour.status == 2)
                {
                    Vector2Int meetingPoint = mateBehaviour.PingMate(transform);
                    pathfinder.ClearPath();
                    status     = 3;
                    pathTarget = sensing.closestMate.gameObject;
                    pathfinder.GoPath(GridHelper.GridPosToWorldPos(meetingPoint, transform.position.y), speed);
                }
            }
            else if (energy < reproductionThreshold)
            {
                status = 0;
            }
            break;

        case 3:
            if (pathTarget == null)
            {
                pathfinder.ClearPath();
                if (energy > reproductionThreshold)
                {
                    status = 2;
                }
                else
                {
                    status = 0;
                }
                GoSearchPath();
            }
            break;

        default:
            break;
        }
    }
Example #21
0
    public void ActivateThrowingMode( AnimalBehaviour controlledAnimal )
    {
        // Place cannon at animal and orient it properly
        cannon.transform.position = controlledAnimal.transform.position;
        cannon.transform.rotation = controlledAnimal.transform.rotation;
        
        this.throwingAnimal = controlledAnimal.gameObject;
        this.throwAnimal = throwingAnimal.GetComponent<AnimalBehaviour>().GetAnimalAbove();
		
        trajectories.animalBeingThrown = throwAnimal.GetComponent<AnimalBehaviour>();
        trajectories.speciesBeingThrown = trajectories.animalBeingThrown.animalSpecies;
        trajectories.IgnoreAnimals();

        trajectories.SimulatePath();
        cannon.transform.parent.gameObject.SetActive(true);

        invisibleWalls.SetActive(false);
    }
    void EatAnimal(AnimalBehaviour animal)
    {
        float maxFood = animal.StealEnergy(eatSize);
        maxFood = (maxFood / eatEffeciency);

        energy += maxFood;
        hunger += maxFood;
    }