Inheritance: MonoBehaviour
Beispiel #1
0
    public void getNewLeader(List <Predator> herd)
    {
        Predator newLeader = GetComponent <LeaderSelectorPredator>().getLeader(herd);

        foreach (Predator p in herd)
        {
            p.setLeader(newLeader.gameObject);
            p.leader = this.gameObject;
            if (p.gameObject.transform.Find("leaderLigth") != null)
            {
                Destroy(p.gameObject.transform.Find("leaderLigth").gameObject);
            }
            p.isLeader = false;
        }
        newLeader.isLeader = true;
        newLeader.setLeader(newLeader.gameObject);
        GameObject brigth = new GameObject("leaderLigth");

        brigth.AddComponent(typeof(Light));                                                             //se le agrega la luz

        brigth.transform.parent = newLeader.gameObject.transform;                                       //Se fija a la entidad


        brigth.light.type = LightType.Spot;                                                                     //Se elije el tipo de luz SPOT

        //Se pone la mira hacia abajo
        brigth.transform.position = brigth.transform.parent.position + new Vector3(0, 1, 0);
        brigth.transform.rotation = Quaternion.Euler(new Vector3(90, 0, 0));

        //Color, Alcance, Dispercion
        brigth.light.color     = Color.blue;
        brigth.light.intensity = 2;
        brigth.light.range     = 50F;
        brigth.light.spotAngle = 180f;
    }
Beispiel #2
0
 public void PredatorDied(Predator predator)
 {
     if (OnPredatorDied != null)
     {
         OnPredatorDied.Invoke(predator);
     }
 }
Beispiel #3
0
    public static SavedPredator savePredator(GameObject predatorObject)
    {
        Predator      PredScriptRef = predatorObject.GetComponent <Predator>();
        SavedPredator predatorSave  = new SavedPredator();

        predatorSave.xCoord = predatorObject.transform.position.x;
        predatorSave.yCoord = predatorObject.transform.position.y;
        predatorSave.zCoord = predatorObject.transform.position.z;

        predatorSave.waterLevel         = PredScriptRef.waterLevel;
        predatorSave.nutrientValue      = PredScriptRef.nutrientValue;
        predatorSave.reproductiveChance = PredScriptRef.reproductiveChance;
        predatorSave.reproductiveRate   = PredScriptRef.reproductiveRate;
        predatorSave.awareness          = PredScriptRef.awareness;
        predatorSave.lethality          = PredScriptRef.lethality;


        predatorSave.movementSpeed           = PredScriptRef.movementSpeed;
        predatorSave.controlSpeed            = PredScriptRef.controlSpeed;
        predatorSave.consumptionRate         = PredScriptRef.consumptionRate;
        predatorSave.movementConsumptionRate = PredScriptRef.movementConsumptionRate;
        predatorSave.nutrientLevel           = PredScriptRef.nutrientLevel;

        return(predatorSave);
    }
Beispiel #4
0
    public static GameObject loadPredator(SavedPredator predatorSave)
    {
        // We are essentially building the Predator object from scratch here.
        // GameObject loadedPredator = GameObject.CreatePrimitive(PrimitiveType.Cube);
        GameObject loadedPredator = Resources.Load("Prefabs/Predator") as GameObject;

        // Predator predScriptRef = loadedPredator.AddComponent<Predator>();
        Predator predScriptRef = loadedPredator.GetComponent <Predator>();

        // loadedPredator.GetComponent<MeshRenderer>().material = (Resources.Load("Materials/Red", typeof(Material)) as Material);

        // loadedPredator.transform.localScale = new Vector3(1f, 1f, 1f);
        Vector3 pos = new Vector3(predatorSave.xCoord, predatorSave.yCoord, predatorSave.zCoord);

        loadedPredator.transform.position = pos;
        loadedPredator.tag = "predator";

        predScriptRef.waterLevel         = predatorSave.waterLevel;
        predScriptRef.nutrientValue      = predatorSave.nutrientValue;
        predScriptRef.reproductiveChance = predatorSave.reproductiveChance;
        predScriptRef.reproductiveRate   = predatorSave.reproductiveRate;
        predScriptRef.awareness          = predatorSave.awareness;
        predScriptRef.lethality          = predatorSave.lethality;


        predScriptRef.movementSpeed           = predatorSave.movementSpeed;
        predScriptRef.controlSpeed            = predatorSave.controlSpeed;
        predScriptRef.consumptionRate         = predatorSave.consumptionRate;
        predScriptRef.movementConsumptionRate = predatorSave.movementConsumptionRate;
        predScriptRef.nutrientLevel           = predatorSave.nutrientLevel;

        return(loadedPredator);
    }
Beispiel #5
0
    // Use this for initialization
    void Start()
    {
        goal = Instantiate(goalPrefab) as Goal;
        goal.transform.position = new Vector3(10, 0, 10);
        goal.name = "goal";

        generateJungle();
        int count  = 0;
        int countp = 0;

        while (count < 10)
        {
            prey      = Instantiate(preyPrefab) as Prey;
            prey.goal = goal;
            prey.name = "prey" + count.ToString();
            //print (prey.name);
            count = count + 1;
        }

        while (countp < 2)
        {
            predator      = Instantiate(predatorPrefab) as Predator;
            predator.name = "predator" + countp.ToString();
            countp        = countp + 1;
        }
    }
        void Update()
        {
            if (Time.fixedTime < timeToGo)
            {
                return;
            }
            timeToGo = Time.fixedTime + 5.0F;
            //Debug.Log ("Iniciando actualizacion de herds - Predator");
            Dictionary <int, int> predatorVisited = new Dictionary <int, int> ();

            elements = GameObject.FindObjectsOfType <Predator>();
            int[] curCluster = new int[elements.Count()];
            int   nElements  = elements.Length;
            int   nHerd      = 0;

            for (int i = 0; i < nElements; i++)
            {
                Predator curPredator = elements[i];
                if (!predatorVisited.ContainsKey(curPredator.GetInstanceID()))
                {
                    fillHerd(curPredator, nHerd++, predatorVisited);
                }
            }
            //Debug.Log ("Flood Fill terminado");
            nHerd++;
            //Debug.Log ("Creando listas de herds");
            List <List <Predator> > herds = new List <List <Predator> > ();

            for (int i = 0; i < nHerd; i++)
            {
                herds.Add(new List <Predator>());
            }
            for (int i = 0; i < nElements; i++)
            {
                int herdId = predatorVisited[elements[i].GetInstanceID()];
                herds[herdId].Add(elements[i]);
                elements[i].herdid = herdId;
            }
            //Debug.Log ("Creadas listas de herds");
            //Debug.Log ("Iniciando seleccion de lideres y asignacion de manadas");
            for (int i = 0; i < nHerd; i++)
            {
                if (herds[i].Count == 0)
                {
                    continue;
                }
                Predator          element  = herds[i][0];
                List <GameObject> herdList = new List <GameObject>();
                for (int j = 0; j < herds[i].Count; j++)
                {
                    herdList.Add(herds[i][j].gameObject);
                }
                for (int j = 0; j < herds[i].Count; j++)
                {
                    herds[i][j].herd = herdList;
                }
                //element.getNewLeader(herds[i]);
            }
            //Debug.Log ("Herds creadas y todo listo");
        }
Beispiel #7
0
        private static void Reset(GameWindow window, ContentManager content)
        {
            GameElements.boss1Liv  = 3;
            GameElements.playerLiv = 1;
            GameElements.boss1.Liv = true;
            GameElements.player.Reset(0f, 200f, 2.5f, 4.5f);
            GameElements.Fiende.Clear();
            Random    random    = new Random();
            Texture2D tmpsprite = content.Load <Texture2D>("Images/Enemies/Predator");

            for (int i = 0; i < 5; i++)
            {
                int      rndX = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
                int      rndY = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
                Predator temp = new Predator(tmpsprite, (float)rndX, (float)rndY);
                GameElements.Fiende.Add(temp);
            }
            tmpsprite = content.Load <Texture2D>("Images/Enemies/mina");
            for (int i = 0; i < 5; i++)
            {
                int  rndX  = random.Next(window.get_ClientBounds().Width / 2, window.get_ClientBounds().Width - tmpsprite.get_Width());
                int  rndY  = random.Next(0, window.get_ClientBounds().Height - tmpsprite.get_Height());
                Mine temp2 = new Mine(tmpsprite, (float)rndX, (float)rndY);
                GameElements.Fiende.Add(temp2);
            }
        }
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.P))
            {
                IUnit prey;
                int   numberOfPrey = 5;
                m_Preys = new IUnit[numberOfPrey];

                for (int i = 0; i < numberOfPrey; i++)
                {
                    prey = new Prey();
                    m_Grid.AddToRandomnPosition(prey);
                    m_Preys[i] = prey;

                    Debug.Log("A prey was spawned @ square: " + m_Preys[i].GetGridPosition());
                }
            }

            if (Input.GetKeyDown(KeyCode.H))
            {
                IUnit predator;
                predator = new Predator();
                m_Grid.AddToRandomnPosition(predator);
                Debug.Log("A predator was spawned @ square: " + predator.GetGridPosition());

                int closest = m_Grid.FindClosest(predator, m_Preys);
                Debug.Log("The closest prey is @ square: " + closest);
            }
        }
Beispiel #9
0
    void StartRun()
    {
        map = GameObject.Instantiate(mapPrefab, new Vector3(0, 0, 0), Quaternion.identity).GetComponent <Map>();
        int startingPreys = Random.Range(5, 11);

        for (int i = 0; i < startingPreys; i++)
        {
            Vector2Int preyPos = new Vector2Int(0, 0);
            do
            {
                preyPos = new Vector2Int(Random.Range(0, 30), Random.Range(0, 30));
            } while (!map.IsEmpty(preyPos));

            AddPrey(preyPos);
        }

        Vector2Int pos = new Vector2Int();

        do
        {
            pos = new Vector2Int(Random.Range(0, 30), Random.Range(0, 30));
        } while (!map.IsEmpty(pos));
        predator = AddPredator(pos);

        currentTurn = 0;
        preysLeft   = startingPreys;

        StartCoroutine(TurnRepeat());
    }
Beispiel #10
0
 public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
 {
     base.OnStateEnter(animator, stateInfo, layerIndex);
     predatorAnimator        = animator;
     predator                = animator.gameObject.GetComponent <Predator>();
     predator.OnExecuteTurn += ExecuteTurn;
 }
Beispiel #11
0
        static void AnimalFeeder(Animal animal)
        {
            Console.WriteLine("Do you want to feed the animal? Enter [y]es or [n]o:");
            string input = Console.ReadLine();

            if (input == "y")
            {
                if (animal is Herbivore)
                {
                    Herbivore herbivore = animal as Herbivore;
                    herbivore.GrassQuantity++;
                    Console.WriteLine("Some grass given");
                }
                if (animal is Predator)
                {
                    Predator predator = animal as Predator;
                    predator.MeatQuantity++;
                    Console.WriteLine("Some meat given");
                }
                if (animal is IFishEatable)
                {
                    Console.WriteLine("Do you want to give it some fish? Enter [y]es or [n]o:");
                    string secondInput = Console.ReadLine();

                    if (secondInput == "y")
                    {
                        IFishEatable fishEater = animal as IFishEatable;
                        fishEater.FishQuantity++;
                        Console.WriteLine("Some fish given");
                    }
                }
            }
        }
Beispiel #12
0
    void Run()
    {
        boids = Physics.OverlapSphere(tr.position, ќбласть¬идимости, -1)
                .Where(t => string.Compare(t.tag, "Predator") == 0)
                .ToArray();
        if (boids.Length > 0)
        {
            for (i = 0; i < boids.Length /*&& i < maxBoids*/; i++)
            {
                p = boids[i].GetComponent <Predator>();

                //cohesion += b.tr.position;
                //alignment += b.velocity;
                vector = tr.position - p.tr.position;
                if (vector.sqrMagnitude > 0 && vector.sqrMagnitude < ќбласть¬идимости * ќбласть¬идимости)
                {
                    runPredator += vector;                    // / vector.sqrMagnitude;
                    predatorCount++;
                }
            }

            /**/
            if (predatorCount > 0)
            {
                runPredator  = runPredator / predatorCount;
                runPredator  = Vector3.ClampMagnitude(runPredator, —корость);
                runPredator *= predatorCoefficient;
            }            /**/
        }
    }
    private GameObject seekTarget(GameObject go, Predator predator)
    {
        Transform tr = go.GetComponent <Transform>();
        Move      mv = go.GetComponent <Move>();

        float radius = 5f;

        if (mv.targetObject != null)
        {
            float dist = Vector3.Distance(tr.position, mv.targetObject.transform.position);

            radius = dist;
        }

        Collider2D[] colliders = Physics2D.OverlapCircleAll(tr.position, radius, LayerMask.GetMask("Ignore Raycast"));

        GameObject closestTarget = null;

        if (colliders.Length > 0)
        {
            float minDist = radius;

            foreach (Collider2D collider in colliders)
            {
                GameObject collidedGO = collider.gameObject;

                if (collidedGO == go)
                {
                    continue;
                }
                else
                {
                    if (_preysGO.contains(collidedGO.GetInstanceID()))
                    {
                        Prey prey = collidedGO.GetComponent <Prey>();

                        if (predator.myPreys.Contains(prey.myType))
                        {
                            float dist = Vector3.Distance(tr.position, collidedGO.transform.position);

                            if (dist < minDist)
                            {
                                if (!collidedGO.CompareTag("Targeted"))
                                {
                                    if (!_targetedPreysGO.contains(collidedGO.GetInstanceID()))
                                    {
                                        minDist       = dist;
                                        closestTarget = collidedGO;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return(closestTarget);
    }
Beispiel #14
0
    public Predator AddPredator(Vector2Int pos)
    {
        Predator predator = GameObject.Instantiate(predatorPrefab).GetComponent <Predator>();

        map.Set(pos, predator.gameObject);
        predator.Initialize(pos, map, this);
        return(predator);
    }
Beispiel #15
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < aquarium.aquariumSizeRow; i++)
            {
                for (int j = 0; j < aquarium.aquariumSizeColumn; j++)
                {
                    var obj = aquarium.cells[i, j];
                    if (obj != null)
                    {
                        var type = obj.GetType();
                        if (type == typeof(Predator))
                        {
                            Predator currentObj = (Predator)obj;
                            currentObj.isChecked = false;
                        }
                        else if (type == typeof(Herbivore))
                        {
                            Herbivore currentObj = (Herbivore)obj;
                            currentObj.isChecked = false;
                        }
                    }
                }
            }

            for (int i = 0; i < aquarium.aquariumSizeRow; i++)
            {
                for (int j = 0; j < aquarium.aquariumSizeColumn; j++)
                {
                    var obj = aquarium.cells[i, j];
                    if (obj != null)
                    {
                        var type = obj.GetType();
                        if (type == typeof(Predator))
                        {
                            Predator currentObj = (Predator)obj;
                            currentObj.checkFish(i, j, aquarium.cells, aquarium, DynamicGrid);
                        }
                        else if (type == typeof(Herbivore))
                        {
                            Herbivore currentObj = (Herbivore)obj;
                            currentObj.checkFish(i, j, aquarium.cells, aquarium, DynamicGrid);
                        }
                        else if (type == typeof(Seaweed))
                        {
                            Seaweed currentObj = (Seaweed)obj;
                            currentObj.checkStatus();
                        }
                        else if (type == typeof(Rock))
                        {
                            Console.WriteLine("Rock");
                        }
                    }
                }
            }

            mainWindow         = Application.Current.Windows.OfType <MainWindow>().FirstOrDefault();
            mainWindow.Content = DynamicGrid;
        }
Beispiel #16
0
        public Agent GenerateNewMigratingAgent(List <Agent> allAgents, Agent currentAgent)
        {
            Agent agent = null;

            AllPoints = new List <Point>();

            for (int i = 0; i < worldSize; i++)
            {
                for (int j = 0; j < worldSize; j++)
                {
                    AllPoints.Add(new Point(i, j));
                }
            }

            var plants = allAgents.Where(a => a.AgentType == AgentTypes.Plant).ToList();

            for (int i = 0; i < plants.Count; i++)
            {
                AllPoints.RemoveAll(p => plants[i].AgentLocation.X == p.X && plants[i].AgentLocation.Y == p.Y);
            }

            List <Point> pointsToRemove = new List <Point>();

            for (int i = 0; i < AllPoints.Count; i++)
            {
                var agents = allAgents.Where(a => a.AgentLocation.X == AllPoints[i].X && a.AgentLocation.Y == AllPoints[i].Y);

                if (agents.Count() >= 2)
                {
                    pointsToRemove.Add(new Point(AllPoints[i].X, AllPoints[i].Y));
                }
            }

            for (int i = 0; i < pointsToRemove.Count; i++)
            {
                AllPoints.RemoveAll(p => p.X == pointsToRemove[i].X && p.Y == pointsToRemove[i].Y);
            }

            int index = rand.Next(0, AllPoints.Count - 1);

            var newP    = new Point(AllPoints.ElementAt(index).X, AllPoints.ElementAt(index).Y);
            var network = currentAgent.GetNetwork();

            // якщо предок травоїдне, то створюємо нового травоїдного
            if (currentAgent.AgentType == AgentTypes.Herbivorous)
            {
                agent = new Herbivorous(newP, currentAgent.GetGeneration() + 1, new NeuralNetwork(network));
            }

            // якщо предок хижак - створюємо нового хижака
            else
            {
                agent = new Predator(newP, currentAgent.GetGeneration() + 1, new NeuralNetwork(network));
            }

            return(agent);
        }
Beispiel #17
0
        /// <summary>
        /// Muere el agente
        /// </summary>
        protected override void Die()
        {
            state = States.Die;
            GetComponent <DinasorsAnimationCorrector>().die();
            defense = 0;
            if (gameObject.transform.Find("leaderLigth") != null)
            {
                Destroy(gameObject.transform.Find("leaderLigth").gameObject);
            }

            if (herd.Contains(gameObject))
            {
                herd.Remove(gameObject);
            }
            foreach (GameObject go in herd)
            {
                go.GetComponent <DinoObject>().herd.Remove(gameObject);
            }
            if (isLeader == true)
            {
                Prey     p  = gameObject.GetComponent <Prey>();
                Predator pr = gameObject.GetComponent <Predator>();
                if (p != null)
                {
                    List <Prey> listHerd = new List <Prey>();
                    foreach (GameObject go in p.herd)
                    {
                        listHerd.Add(go.GetComponent <Prey>());
                    }
                    if (listHerd.Count > 0)
                    {
                        p.getNewLeader(listHerd);
                    }
                    else
                    {
                        p.isLeader = false;
                    }
                }
                if (pr != null)
                {
                    List <Predator> listHerd = new List <Predator>();
                    foreach (GameObject go in pr.herd)
                    {
                        listHerd.Add(go.GetComponent <Predator>());
                    }
                    if (listHerd.Count > 0)
                    {
                        pr.getNewLeader(listHerd);
                    }
                    else
                    {
                        pr.isLeader = false;
                    }
                }
            }
        }
 private void DrawPredator(Predator predator)
 {
     var color = new SolidColorBrush(System.Windows.Media.Color.FromRgb(predator.Color.Red, predator.Color.Green, predator.Color.Blue));
     Ellipse el = new Ellipse();
     el.Height = flock.Predator.size[1];
     el.Width = flock.Predator.size[0];
     el.Fill = color;
     Canvas.SetTop(el, flock.Predator.Position[1]);
     Canvas.SetLeft(el, flock.Predator.Position[0]);
     Canvas.Children.Add(el);
 }
Beispiel #19
0
 private void Starving()
 {
     for (int i = 0; i < PredatorList.Count; i++)
     {
         Predator predator = PredatorList[i];
         if (predator.food == 0)
         {
             PredatorList.RemoveAt(i);
         }
         predator.food--;
     }
 }
Beispiel #20
0
        static void Main(string[] args)
        {
            IAnimal bat   = new Bird(new Predator(new Mammal(new Animal())));
            IAnimal dog   = new Predator(new Mammal(new Animal()));
            IAnimal shark = new Predator(new Fish(new Animal()));

            System.Console.WriteLine(bat.Description());
            System.Console.WriteLine(dog.Description());
            System.Console.WriteLine(shark.Description());

            System.Console.ReadLine();
        }
Beispiel #21
0
    public IEnumerator EatPredator(Predator predator)
    {
        hasEaten = true;

        anim.SetTrigger("triggerEat");
        yield return(new WaitForSeconds(0.2f));

        if (predator)
        {
            gameController.RemovePredator(predator);
        }

        yield return(null);
    }
Beispiel #22
0
    void OnCollisionEnter(Collision col)
    {
        if (reproduce)
        {
            if (col.transform == closestPredator)
            {
                Predator parentTraits = closestPredator.GetComponent <Predator>();

                GameObject child = Instantiate(gameObject, transform.localPosition + Vector3.one * 5, Quaternion.identity, predatorContainer);
                energy -= 5000;
                parentTraits.energy   -= 5000;
                parentTraits.reproduce = reproduce = false;
                parentTraits.lastReproductionMoment = lastReproductionMoment = Time.time;

                Predator childTraits = child.GetComponent <Predator>();

                childTraits.speed              = (parentTraits.speed + speed) / Random.Range(1.5f, 2.5f) + Random.Range(-0.1f, 0.1f);
                childTraits.maxRadius          = (parentTraits.maxRadius + maxRadius) / Random.Range(1.5f, 2.5f) + Random.Range(-0.1f, 0.1f);
                childTraits.maxSize            = (parentTraits.maxSize + maxSize) / Random.Range(1.5f, 2.5f) + Random.Range(-0.1f, 0.1f);
                childTraits.reproductiveEnergy = (parentTraits.reproductiveEnergy + reproductiveEnergy) / Random.Range(1.5f, 2.5f) + Random.Range(-0.1f, 0.1f);
                childTraits.energy             = 10000 + Random.Range(-100f, 100f);
                childTraits.age = 0f;

                // Color Mutation
                Color parent1Color = closestPredator.GetChild(0).GetChild(1).GetComponent <Renderer>().material.color;
                Color parent2Color = transform.GetChild(0).GetChild(1).GetComponent <Renderer>().material.color;
                float r, g, b = 0f;
                r = (parent1Color.r + parent2Color.r) / Random.Range(1.5f, 2.5f) + Random.Range(-0.1f, 0.1f);
                g = (parent1Color.g + parent2Color.g) / Random.Range(1.5f, 2.5f) + Random.Range(-0.1f, 0.1f);
                b = (parent1Color.b + parent2Color.b) / Random.Range(1.5f, 2.5f) + Random.Range(-0.1f, 0.1f);
                child.transform.GetChild(0).GetChild(1).GetComponent <Renderer>().material.color = new Color(r, g, b);

                // Size mutation
                float x, y, z = 0f;
                x = (parentTraits.initialSize.x + initialSize.x) / Random.Range(1.5f, 2.5f) + Random.Range(-0.1f, 0.1f);
                y = (parentTraits.initialSize.y + initialSize.y) / Random.Range(1.5f, 2.5f) + Random.Range(-0.1f, 0.1f);
                z = (parentTraits.initialSize.z + initialSize.z) / Random.Range(1.5f, 2.5f) + Random.Range(-0.1f, 0.1f);
                child.transform.localScale = childTraits.initialSize = new Vector3(x, y, z);

                child.transform.localPosition = transform.localPosition;

                parentTraits.reproduce = false;
                closestPredator        = null;

                // Prevent getting stuck in one position after reproduction
                GetComponent <CapsuleCollider>().enabled = false;
                GetComponent <CapsuleCollider>().enabled = true;
            }
        }
    }
Beispiel #23
0
 private void tryEat()
 {
     for (int i = 0; i < PredatorList.Count; i++)
     {
         Predator predator = PredatorList[i];
         for (int j = 0; j < PreyList.Count; j++)
         {
             Prey   prey     = PreyList[j];
             double distance = Math.Sqrt(Math.Pow(prey.position.X - predator.position.X, 2) + Math.Pow(prey.position.Y - predator.position.Y, 2));
             if (distance <= 2 * radius)
             {
                 PreyList.RemoveAt(j);
                 predator.food = food;
             }
         }
     }
 }
Beispiel #24
0
        private List <Agent> GeneratePredators()
        {
            List <Agent> predators = new List <Agent>();

            for (int i = 0; i < amountOfPredators; i++)
            {
                int index = rand.Next(0, AllPoints.Count() - 1);

                int X = AllPoints.ElementAt(index).X;
                int Y = AllPoints.ElementAt(index).Y;

                Agent predator = new Predator(new Point(X, Y), 1, new NeuralNetwork());
                predators.Add(predator);
                AllPoints.RemoveAt(index);
            }
            return(predators);
        }
    // Use to process your families.
    protected override void onProcess(int familiesUpdateCount)
    {
        foreach (GameObject go in _triggeredGO)
        {
            Transform   tr       = go.GetComponent <Transform>();
            Triggered2D t2d      = go.GetComponent <Triggered2D>();
            Predator    predator = go.GetComponent <Predator>();
            Block       block    = go.GetComponent <Block>();

            block.timeSinceLastEffect += Time.deltaTime;
            bool effectApplied = false;

            //Debug.Log(go.name + " " + t2d.Targets.Length);

            foreach (GameObject target in t2d.Targets)
            {
                if (_preysGO.contains(target.GetInstanceID()))
                {
                    Prey prey = target.GetComponent <Prey>();

                    if (predator.myPreys.Contains(prey.myType))
                    {
                        //TODO slow the target
                        Move      mv         = target.GetComponent <Move>();
                        Transform collidedTr = target.GetComponent <Transform>();

                        float dist = Vector3.Distance(collidedTr.position, tr.position);

                        if (block.timeSinceLastEffect >= block.effectFreq)
                        {
                            //float f = (float) 0.5f * (1/dist);
                            float f = 0.5f;
                            mv.speedModifiers.Add(new SpeedModifier(f, false, 2f));
                            effectApplied = true;
                        }
                    }
                }
            }

            if (effectApplied)
            {
                block.timeSinceLastEffect = 0f;
            }
        }
    }
Beispiel #26
0
    //regresa la lista con 2 candidatos a reproducirse
    //valida que la lista de candidatos sea mayor que 1
    //valida que los candidatos tengan estamina mayor al 50%
    public void Procreate(List <GameObject> lstHerd)
    {
        // solo si la lista es mayor a uno realiza el procedimiento.
        if (lstHerd.Count > 1)
        {
            herdList = new List <Predator>();

            foreach (var p in lstHerd)
            {
                herdList.Add(p.GetComponent <Predator>());
            }

            int count = 0;

            //valida la cantidad de estamina y la edad necesarias para reproducirse.
            for (int index = 0; index < herdList.Count; index++)
            {
                var x       = herdList[index];
                var stamina = herdList[count].stamina;
                if (stamina < 50f || x.LifeState != DinoObject.LifeEnum.Adulto || (Time.time - x.LastMating <= 40 && x.LastMating > 0))
                {
                    //elimina los elementos que no cumplen condición.
                    herdList.Remove(herdList[count]);
                }
                count++;
            }
            if (herdList.Count > 2)
            {
                //elimina aleatoriamente elementos de la lista hasta que solo queden dos.
                while (herdList.Count > 2)
                {
                    int random = Random.Range(0, herdList.Count);
                    herdList.Remove(herdList[random]);
                }
                if (Hijo == null)
                {
                    Hijo = herdList[0];
                }
                ObtenerCarac();
                Instantiate(Hijo, herdList[0].transform.position, Quaternion.identity);
                herdList[0].LastMating = Time.time;
                herdList[1].LastMating = Time.time;
            }
        }
    }
        private void fillHerd(Predator p, int herd, Dictionary <int, int> predatorVisited)
        {
            if (predatorVisited.ContainsKey(p.GetInstanceID()))
            {
                return;
            }
            predatorVisited.Add(p.GetInstanceID(), herd);

            //Por cada objeto encontrado revisa si es un arbol y añada su cantidad de comida
            for (int i = 0; i < elements.Length; i++)
            {
                Predator vecino = elements[i];
                if (distance(p.transform.position, vecino.transform.position) <= p.comRange * p.comRange)
                {
                    fillHerd(vecino, herd, predatorVisited);
                }
            }
        }
Beispiel #28
0
    void CalculateVelocity()
    {
        velocity        = Vector3.zero;
        cohesion        = Vector3.zero;
        separation      = Vector3.zero;
        find            = Vector3.zero;
        separationCount = 0;

        cohesion  = cohesion - tr.position;
        cohesion  = Vector3.ClampMagnitude(cohesion, —корость);
        cohesion *= cohesionCoefficient;

        boids = Physics.OverlapSphere(tr.position, ќбласть¬идимости, -1)
                .Where(t => string.Compare(t.tag, "Predator") == 0)
                .ToArray();

        if (boids.Length >= 2)
        {
            for (i = 0; i < boids.Length /*&& i < maxBoids*/; i++)
            {
                p = boids[i].GetComponent <Predator>();

                //cohesion += b.tr.position;
                //alignment += b.velocity;
                vector = tr.position - p.tr.position;
                if (vector.sqrMagnitude > 0 && vector.sqrMagnitude < separationDistance * separationDistance)
                {
                    separation += vector / vector.sqrMagnitude;
                    separationCount++;
                }
            }

            /**/
            if (separationCount > 0)
            {
                separation  = separation / separationCount;
                separation  = Vector3.ClampMagnitude(separation, —корость);
                separation *= separationCoefficient;
            }            /**/
        }
        Find();

        velocity = Vector3.ClampMagnitude(cohesion + separation + find, —корость * 1.2f);
    }
    private void RecordFrame()
    {
        if (Predator1 != null)
        {
            RecordPredatorFrame(Predator1.gameObject);
        }
        else
        {
            Predator1 = GameObject.Find("/Canvas/Predator1").GetComponent <Predator>();
        }
        if (Predator2 != null)
        {
            RecordPredatorFrame(Predator2.gameObject);
        }
        else
        {
            Predator2 = GameObject.Find("/Canvas/Predator2").GetComponent <Predator>();
        }
        if (Predator3 != null)
        {
            RecordPredatorFrame(Predator3.gameObject);
        }
        else
        {
            Predator3 = GameObject.Find("/Canvas/Predator3").GetComponent <Predator>();
        }
        if (Predator4 != null)
        {
            RecordPredatorFrame(Predator4.gameObject);
        }
        else
        {
            Predator4 = GameObject.Find("/Canvas/Predator4").GetComponent <Predator>();
        }

        if (Prey != null)
        {
            RecordPreyFrame(Prey.gameObject);
        }
        else
        {
            Prey = GameObject.Find("/Canvas/Prey").GetComponent <Prey>();
        }
    }
Beispiel #30
0
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Graphics g      = Graphics.FromImage(DrawArea);
            Point    center = PointToClient(Cursor.Position);
            float    x      = center.X - radius;
            float    y      = center.Y - radius;

            if (radioButton1.Checked)
            {
                Prey prey;
                if (radioButton3.Checked)
                {
                    prey = new Prey(center, 'M');
                    g.DrawEllipse(new Pen(Brushes.Blue), x, y, width, height);
                }
                else
                {
                    prey = new Prey(center, 'F');
                    g.DrawEllipse(new Pen(Brushes.Yellow), x, y, width, height);
                }
                g.FillEllipse(Brushes.Green, x, y, width, height);
                PreyList.Add(prey);
            }
            else
            {
                Predator predator;
                if (radioButton3.Checked)
                {
                    predator = new Predator(center, 'M');
                    g.DrawEllipse(new Pen(Brushes.Blue), x, y, width, height);
                }
                else
                {
                    predator = new Predator(center, 'F');
                    g.DrawEllipse(new Pen(Brushes.Yellow), x, y, width, height);
                }
                g.FillEllipse(Brushes.Red, x, y, width, height);
                PredatorList.Add(predator);
            }
            pictureBox1.Image = DrawArea;
        }