コード例 #1
0
 public void SetManager(FlockManager mgr)
 {
     manager       = mgr;
     neighbourDist = mgr.neighbourRadius;
     speed         = mgr.objSpeed;
     rotationSpeed = mgr.objRotSpeed;
 }
コード例 #2
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="manager"></param>
    void Flocking(FlockManager manager)
    {
        Vector3 centre = Vector3.zero;
        Vector3 avoid  = Vector3.zero;
        float   fSpeed = 0.01f;
        float   nDistance;
        int     groupSize = 0;

        foreach (var a in manager.GetAllFlock())
        {
            if (a == transform)
            {
                continue;
            }
            var agt = a.GetComponent <FlockAgent>();

            nDistance = Vector3.Distance(a.transform.position, transform.position);
            if (nDistance <= manager._neighborDistance)
            {
                if (agt.GetType() == _type)
                {
                    centre += a.transform.position;
                }
                else
                {
                    centre += (transform.position - a.position);
                }
                groupSize++;

                if (nDistance < manager._avoidDistance)
                {
                    avoid += (transform.position - a.position);
                }

                fSpeed += agt.GetSpeed();
            }
        }
        if (groupSize > 0)
        {
            centre = (centre) / groupSize + (manager.GetGoalPos(this));
            _speed = fSpeed / groupSize;

            Vector3 dir = (centre + avoid) - transform.position + (-toAvoid);

            if (dir != Vector3.zero)
            {
                transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(dir), manager._flockSpeed * Time.deltaTime);
                //if (fDirection != 0)
                //    direction = fDirection / Mathf.Abs(fDirection);

                flocking = true;
                Debug.DrawRay(transform.position, dir.normalized * manager._lookRange * 2f, Color.red);
            }
        }
        else
        {
            flocking           = false;
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(-toAvoid), manager._flockSpeed * Time.deltaTime);
        }
    }
コード例 #3
0
 // Use this for initialization
 void Start()
 {
     withtarget   = false;
     flockManager = FindObjectOfType <FlockManager>();
     initialPos   = transform.position;
     target       = initialPos - new Vector3(-70, 0, 0);
 }
コード例 #4
0
 /// <summary>
 /// change Speed by probability
 /// </summary>
 void ChangeSpeed(FlockManager manager)
 {
     if (Random.Range(0, 100) < 20)
     {
         _speed = Random.Range(manager._minSpeed, manager._maxSpeed);
     }
 }
コード例 #5
0
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        mAgentAi = animator.gameObject.GetComponent <AgentAi>();


        mAgentAi.mAgent.m_Target = FlockManager.getTarget(mAgentAi.mAgent.m_Agent).m_Target;
    }
コード例 #6
0
ファイル: BoidAgent.cs プロジェクト: mellofnd/wgj150
    private void ApplyRules()
    {
        Vector3 avoidPos    = Vector3.zero;
        Vector3 stirDir     = Vector3.zero;
        Vector3 cohesionPos = Vector3.zero;
        Vector3 allignPos   = Vector3.zero;

        float distance = 0;
        float avgSpeed = 0.1f;

        neighbourCount = 0;

        Vector3 goalPos = FlockManager.GetInstance().GoalPos;

        foreach (var neighbour in mBoids)
        {
            if (neighbour != gameObject)
            {
                distance = Vector3.Distance(neighbour.transform.position, transform.position);

                if (distance <= cohesionDist)
                {
                    neighbourCount++;
                    Debug.DrawLine(transform.position,
                                   neighbour.transform.position,
                                   new Color(1, 1, 1, 0.5f));
                    cohesionPos += neighbour.transform.position;
                    allignPos   += neighbour.transform.forward;
                    if (distance <= avoidanceDist)
                    {
                        avoidPos += neighbour.transform.position;
                    }

                    avgSpeed += neighbour.GetComponent <BoidAgent> ().speed;
                }
            }
        }

        if (neighbourCount > 0)
        {
            //Ajuste da direção de coesão e alinhamento
            cohesionPos = cohesionPos / neighbourCount;
            allignPos   = allignPos / neighbourCount;

            //Ajuste da velocidade média do agente
            speed = avgSpeed / neighbourCount;
            speed = Mathf.Clamp(speed, 0, maxSpeed);

            //Correção do vetor de movimento do agente
            stirDir = (cohesionPos + avoidPos + allignPos + goalPos) - transform.position;
        }
        else
        {
            stirDir = goalPos - transform.position;
        }

        transform.rotation = Quaternion.Slerp(transform.rotation,
                                              Quaternion.LookRotation(stirDir),
                                              Time.deltaTime * rotationSpeed);
    }
コード例 #7
0
    public float height; //height off ground

    // Use this for initialization
    void Start()
    {
        //initialize
        fM = GameObject.Find("GameManager").GetComponent <FlockManager>(); //gain access to FlockManager
        GetNeighbors();                                                    //build the neighbors list for each unit
        position = transform.position;                                     //starting position is equal to placement in scene
        target   = GameObject.Find("Target");                              //test target
    }
コード例 #8
0
 // Use this for initialization
 void Start()
 {
     flockMan           = GameObject.FindGameObjectWithTag("FlockMan").GetComponent <FlockManager>();
     player             = GameObject.FindGameObjectWithTag("Player");
     transform.position = player.transform.position + player.transform.TransformDirection(offset) * 5;
     enter = true;
     //StartCoroutine(LeaveFlock(30));
 }
コード例 #9
0
    void Start()
    {
        //Get level and config data
        flockManager = FindObjectOfType <FlockManager>();
        conf         = FindObjectOfType <MemberConfig>();

        position = transform.position;
        velocity = new Vector3(Random.Range(-3, 3), Random.Range(-3, 3), 0);
    }
コード例 #10
0
ファイル: FlockChaseBehaviour.cs プロジェクト: Aleoris/DRUNK
        private void CheckNPCReachedTarget(NPCManager npc, FlockManager flock)
        {
            Vector3 targetWithoutY = new Vector3(flock.CurrentTargetLocation.x, 0, flock.CurrentTargetLocation.z);

            if (Vector3.Distance(targetWithoutY, npc.transform.position) <
                1.5f)
            {
                flock.AgentReachedTarget(npc);
            }
        }
コード例 #11
0
ファイル: Flock.cs プロジェクト: JipBoesenkool/GPT3
    // Use this for initialization
    void Start()
    {
        _original = this.GetComponentInChildren <Renderer> ().material.color;

        //random speed
        speed = Random.Range(minSpeed, maxSpeed);

        //get parent script
        parent  = transform.parent.gameObject;
        manager = parent.GetComponent <FlockManager> ();
    }
コード例 #12
0
 void Start()
 {
     myFlock = GetComponentInParent <FlockManager>();
     if (myFlock != null)
     {
         SetRandomSpeed();
         anim = GetComponent <Animator>();
         anim.SetFloat("cycleOffset", Random.Range(0f, 1f));
         anim.SetFloat("speedMultiplier", speed);
     }
 }
コード例 #13
0
ファイル: FoodScript.cs プロジェクト: sydneylin12/CSCI-5611
 /// <summary>
 /// Called on creation of food prefab.
 /// </summary>
 void Start()
 {
     // Start tracking food as soon as its spawned
     manager     = GameObject.Find("FishManager").GetComponent <FlockManager>();
     audioSource = gameObject.GetComponentInChildren <AudioSource>();
     ren         = gameObject.GetComponent <MeshRenderer>();
     collider    = gameObject.GetComponent <CapsuleCollider>();
     manager.foodQueue.Enqueue(gameObject);
     manager.foodList.Add(gameObject);
     audioSource.clip = plop;
     audioSource.Play();
 }
コード例 #14
0
        void Awake()
        {
            _npcManager   = GetComponent <NPCManager>();
            _flockManager = Indestructibles.FlockManagerInstance;

            Wander   = new WanderState(_npcManager, avoidObstacles, avoidNpCs);
            Chase    = new ChaseState(_npcManager, avoidObstacles);
            Idle     = new IdleState();
            Flocking = new FlockingState();

            CurrentState = Wander;
        }
コード例 #15
0
 public override void OnInspectorGUI()
 {
     base.OnInspectorGUI();
     if (GUILayout.Button("Generate"))
     {
         flockManager = (FlockManager)target;
         flockManager.GenerateFlock();
     }
     if (GUILayout.Button("Reset"))
     {
         flockManager = (FlockManager)target;
         flockManager.RemoveFlock();
     }
 }
コード例 #16
0
ファイル: FlockBehaviour.cs プロジェクト: Sekaiichi4/Birdoid
 void Start()
 {
     minVel         = 1.5f;
     maxVel         = 6f;
     transVel       = Random.Range(minVel, maxVel);
     rotVel         = 1f;
     alignmentDist  = 4.0f;
     cohesionDist   = 6.0f;
     separationDist = 3.0f;
     outofBounds    = false;
     isFollowing    = false;
     isAvoiding     = false;
     fManager       = gameObject.GetComponentInParent <FlockManager>();
 }
コード例 #17
0
        //private Rigidbody2D dropsRigidbodies; //The rigidbodies on the drops


        override public void Start()
        {
            //call parent's start
            base.Start();

            fm        = GameObject.Find("FlockManagerGO").GetComponent <FlockManager>();
            baseColor = this.enemySprite.color;

            //for (int i = 0; i < drops.Count; i++) //For each drop in the list of drops
            //{
            //dropsRigidbodies = drops[0].GetComponent<Rigidbody2D>(); //Take the rigidbody from the drop
            //}
            this.enabled = false;
        }
コード例 #18
0
    // Spawned de betreffende objecten.
    public void Spawn(FlockManager fm)
    {
        // Positie van de speler binnen halen..
        Vector3 playerPos = player.transform.position;

        //check in welke layer de speler zwemt.
        if (playerPos.y > 430)                          //flying fish!!!
        {
            return;
        }
        else if (playerPos.y < 160)             //layer 3
        {
            spawnDataIndex = 3;
        }
        else if (playerPos.y < 250)             //layer 2
        {
            spawnDataIndex = 2;
        }
        else if (playerPos.y < 340)             //layer 1
        {
            spawnDataIndex = 1;
        }
        else if (playerPos.y < 430)             //layer 0
        {
            spawnDataIndex = 0;
        }

        // Get random position
        Vector3 randomPos = GetRandomPositionInRange(
            playerPos,
            spawnData[spawnDataIndex].minRange,
            spawnData[spawnDataIndex].maxRange
            );

        //get Y height
        RaycastHit hit;
        Ray        ray = new Ray(new Vector3(randomPos.x, 410f, randomPos.z), Vector3.down);

        if (Physics.Raycast(ray, out hit, 420f))
        {
            randomPos.y = hit.point.y + 20f;
        }

        // set fish tank.
        fm.Spawn(
            spawnData[spawnDataIndex],
            randomPos
            );
    }
コード例 #19
0
    void CheckForValidAddBirdCollision(Collider2D other)
    {
        FlockAgent agent = other.GetComponentInParent <FlockAgent>();

        // If a flock agent runs into this trigger, add all the birds in this flock to that flock
        if (agent != null && !flockManager.InFlock(agent))
        {
            FlockManager otherFlock = agent.transform.root.GetComponent <FlockManager>();
            if (otherFlock != null)
            {
                otherFlock.AddBirdsFromFlock(flockManager, flockManager.GetNumberOfAgents());
                Destroy(gameObject);
            }
        }
    }
コード例 #20
0
    void CheckTargetBird(Collider2D other)
    {
        FlockAgent agent = other.GetComponentInParent <FlockAgent>();

        // If this is a target bird and we don't already have a target
        if (agent != null && agent.Color == targetColor && !foundTarget)
        {
            FlockManager flockManager = agent.transform.root.GetComponent <FlockManager>();
            if (flockManager != null)
            {
                // We found a target!
                targetFlock = flockManager;
                foundTarget = true;
                targetFlock.birdsChangedEvent.AddListener(TargetChanged);
            }
        }
    }
コード例 #21
0
    /********************
     *     Methods
     *********************/
    // Use this for initialization
    void Start()
    {
        //Initialize attributes
        currentFixedNode = 0;
        pType            = PathType.Fixed;

        useDebug = true;

        //If a bad time was given, set the default to 10 seconds
        if (defaultRandomNodeTime <= 0)
        {
            defaultRandomNodeTime = 20.0f;
        }

        nodeCount = nodes.Length;

        //Add a default node if no nodes exist
        if (nodeCount == 0)
        {
            nodeCount = 1;
            nodes     = new Node[1];

            nodes[0] = new Node(defaultNodePosition, defaultNodeRadius);
        }

        //Get the terrain information
        terrain = Terrain.activeTerrain;
        tData   = terrain.terrainData;

        //Get an initial random node
        randomNode = GenerateRandomNode();

        //Set up the debug sphere
        //Create the sphere
        debugSphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        //Remove the collider to prevent collisions
        GameObject.Destroy(debugSphere.GetComponent <Collider>());
        //Set the position to the initial node
        debugSphere.transform.position = nodes[currentFixedNode].position;
        currentNode = nodes[currentFixedNode];

        target    = GameObject.Find("Target");
        fM        = GetComponent <FlockManager>();
        aStarChar = GameObject.Find("AStarUnit");
    }
コード例 #22
0
ファイル: RespawnBox.cs プロジェクト: Failender/CrowdRunner
    void Start()
    {
        sushis = transform.FindChild("Sushis");
        pManager = GameObject.Find("SushiManager").GetComponent<FlockManager>();
           // transform.Rotate(Vector3.up * Random.Range(0f, 360f));
        //+1 because random.range second argument is exlusive
        quantity = Random.Range(minQuantity, maxQuantity + 1);
        for (int i = 0; i < quantity; i++)
        {
            GameObject sushi = Instantiate(pManager.GetRandomSushi());
            sushi.transform.parent = sushis;

            sushi.GetComponent<Rigidbody>().isKinematic = true;
            sushi.GetComponent<Rigidbody>().detectCollisions = false;
            sushi.transform.localPosition = new Vector3(-1f+1*i%2 , 1 , -1.5f+2f*(i/2));
            sushi.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);

        }
    }
コード例 #23
0
    public void OnUpdate()
    {
        // optimzation problems so lets stop the agents from being able to update every frame and
        // do a lot of work every frame
        List <FlockingAgent> neighbors = FlockManager.Instance.GetAgentsInRadius(name, SearchRadius);

        List <Vector3> enemyPositions   = new List <Vector3>();
        List <Vector3> friendPositions  = new List <Vector3>();
        List <Vector2> friendVelocities = new List <Vector2>();

        FlockManager  flock = FlockManager.Instance;
        FlockingAgent neighbor;

        for (int i = 0; i < neighbors.Count; ++i)
        {
            neighbor = neighbors[i];

            if (neighbor.tag.Equals(Tag.Predator))
            {
                enemyPositions.Add(neighbor.transform.position);
            }
            else
            {
                friendPositions.Add(neighbor.transform.position);
                friendVelocities.Add(neighbor.Velocity);
            }
        }

        Vector2 temp = Acceleration + Combine(enemyPositions, friendPositions, friendVelocities);

        Acceleration = Vector2.ClampMagnitude(temp, maxAcceleration);
        Velocity     = Vector2.ClampMagnitude(Velocity + Acceleration * Time.deltaTime, maxVelocity);

        transform.position = transform.position + (Vector3)(Velocity * Time.deltaTime);
        KeepInBounds();

        // set agent alignment
        if (Velocity.magnitude > 0)
        {
            float angle = Mathf.Atan2(Velocity.y, Velocity.x) * Mathf.Rad2Deg - 90;
            transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        }
    }
コード例 #24
0
    public void UpdateFlock(FlockManager manager)
    {
        int flag = 0;

        transform.localPosition += transform.forward * _speed * direction * Time.deltaTime;
        //check obstacle in forward
        LookAt(transform.forward, transform.localScale.z + manager._lookRange);
        //check obstacle in back
        LookAt(-transform.forward, transform.localScale.z + manager._lookRange);
        //check obstacle in right
        LookAt(transform.right, transform.localScale.x + manager._lookRange);
        //check obstacle in left
        LookAt(-transform.right, transform.localScale.x + manager._lookRange);

        if (Random.Range(0, 100) < manager._updateRate)
        {
            Flocking(manager);
            ChangeSpeed(manager);
        }
    }
コード例 #25
0
    /*
     * Removes all of the birds from the given flock and adds them to this flock
     */
    public void AddBirdsFromFlock(FlockManager flockManager, int numberOfBirds)
    {
        // If there are enough birds in the given flock
        if (flockManager.flockAgents.Count >= numberOfBirds)
        {
            for (int i = 0; i < numberOfBirds; i++)
            {
                flockAgents.Add(flockManager.flockAgents[0]);
                flockManager.flockAgents[0].gameObject.transform.parent = transform;
                flockManager.flockAgents.Remove(flockManager.flockAgents[0]);
            }
        }
        else
        {
            Debug.LogError("Flock did not haven enough birds to add", flockManager);
        }

        flockManager.birdsChangedEvent.Invoke();
        birdsChangedEvent.Invoke();
    }
コード例 #26
0
    //Initialize population
    public void Start()
    {
        if (flockManager == null)
        {
            flockManager = GetComponent <FlockManager>();
        }

        generationSize = flockManager.flocksQuantityPerLayer;

        generation       = new Individual[generationSize];
        nextGeneration   = new Individual[generationSize];
        bestOfGeneration = new List <Individual>();
        scoreSum         = new float[generationSize];
        for (int i = 0; i < generationSize; i++)
        {
            scoreSum[i] = 0;
        }

        InitializeGeneration();
    }
コード例 #27
0
    void Start()
    {
        sensorMin       = float.MaxValue;
        sensorMax       = float.MinValue;
        spawnMultiplier = 1.0f;

        //init the fish tanks
        for (int i = 0; i < flockManagersAmount; i++)
        {
            FlockManager fm = Instantiate(
                flockManPrefab,
                Vector3.zero,
                Quaternion.identity
                ).GetComponent <FlockManager>();
            fm.transform.SetParent(this.transform);

            fm.fSpawner = this;

            Spawn(fm);
        }
    }
コード例 #28
0
ファイル: Boid.cs プロジェクト: Bnaga/ProjectVrij
    void Start()
    {
        // Components
        thisRigidbody  = GetComponent <Rigidbody>();
        neighborArea   = transform.Find("NeighborArea");
        separationArea = transform.Find("SeparationArea");

        // Flock
        flockManager = GetComponentInParent <FlockManager>();

        // Init
        transform.position = new Vector3(Random.value * 10f, Random.value * 10f, Random.value * 10f);
        //transform.position = new Vector3(Random.value * 10f, 0f, Random.value * 10f);
        thisRigidbody.velocity = new Vector3(Random.value * 2 - 1, Random.value * 2 - 1, Random.value * 2 - 1);
        //thisRigidbody.velocity = new Vector3(Random.value * 2 - 1, 0f, Random.value * 2 - 1);

        neighborArea.localScale   = new Vector3(neighborRadius * 2, neighborRadius * 2, neighborRadius * 2);
        separationArea.localScale = new Vector3(desiredSeparation * 2, desiredSeparation * 2, desiredSeparation * 2);
        neighborArea.gameObject.SetActive(false);
        separationArea.gameObject.SetActive(false);
    }
コード例 #29
0
ファイル: Boid.cs プロジェクト: simonchauvin/Boids
    void Start()
    {
        // Components
        thisRigidbody = GetComponent<Rigidbody>();
        neighborArea = transform.FindChild("NeighborArea");
        separationArea = transform.FindChild("SeparationArea");

        // Flock
        flockManager = GetComponentInParent<FlockManager>();

        // Init
        transform.position = new Vector3(Random.value * 10f, Random.value * 10f, Random.value * 10f);
        //transform.position = new Vector3(Random.value * 10f, 0f, Random.value * 10f);
        thisRigidbody.velocity = new Vector3(Random.value * 2 - 1, Random.value * 2 - 1, Random.value * 2 - 1);
        //thisRigidbody.velocity = new Vector3(Random.value * 2 - 1, 0f, Random.value * 2 - 1);

        neighborArea.localScale = new Vector3(neighborRadius * 2, neighborRadius * 2, neighborRadius * 2);
        separationArea.localScale = new Vector3(desiredSeparation * 2, desiredSeparation * 2, desiredSeparation * 2);
        neighborArea.gameObject.SetActive(false);
        separationArea.gameObject.SetActive(false);
    }
コード例 #30
0
    /*
     * Shoots off the given number of birds out of the flock in the given direction
     */
    private void FireAgents(int numberOfBirds, Vector2 direction)
    {
        // Only fire the birds if there will be at least two birds remaining
        if (flockAgents.Count - numberOfBirds >= 2)
        {
            GameObject firedFlock = Instantiate(firedFlockPrefab,
                                                transform.position,
                                                Quaternion.LookRotation(direction, Vector3.up));

            FlockManager firedFlockManager = firedFlock.GetComponent <FlockManager>();

            if (firedFlockManager != null)
            {
                firedFlockManager.AddBirdsFromFlock(this, numberOfBirds);
            }
            else
            {
                Debug.LogError("Fired flock did not have a FlockManager component", firedFlockManager);
            }
        }
    }
コード例 #31
0
    // Use this for initialization
    void Start()
    {
        playerObject = GameObject.FindGameObjectWithTag("Player");

        flockManager = new FlockManager();
        foreach (GameObject go in Waypoints)
        {
            flockManager.AddWaypoint(go.GetComponent <FlockControllerWaypoint>());
        }

        flockMembers = new GameObject[numberOfMembers];
        for (int i = 0; i < numberOfMembers; i++)
        {
            Vector3 memberStartPosition = new Vector3(Random.Range(-range.x, range.x),
                                                      Random.Range(-range.y, range.y),
                                                      Random.Range(0, 0));
            flockMembers[i] = Instantiate(memberPrefab, this.transform.position + memberStartPosition,
                                          Quaternion.identity) as GameObject;
            flockMembers[i].GetComponent <FlockMember>().SetManager = this.gameObject;
        }

        currentWaypoint = flockManager.GetNextWaypoint();
    }
コード例 #32
0
ファイル: Indestructibles.cs プロジェクト: Aleoris/DRUNK
    public static void SetDefaultValues()
    {
        FlockManagerInstance = GameObject.Find("NPCMovementCoordinator").GetComponent <FlockManager>();

        UIManager = GameObject.Find("UI").GetComponent <UIManager>();
        Volume    = GameObject.Find("Camera").GetComponent <PostProcessVolume>();

        Player         = GameObject.Find("player");
        Renderers      = Player.GetComponentsInChildren <Renderer>();
        PlayerData     = Player.GetComponent <PlayerDataManager>().PlayerData;
        PlayerAnimator = Player.GetComponent <Animator>();

        MovementControls = new MovementControls(KeyCode.W, KeyCode.S, KeyCode.D, KeyCode.A);

        DebugControls = new DebugControls(
            KeyCode.V,
            KeyCode.B,
            KeyCode.N,
            KeyCode.M,
            KeyCode.I,
            KeyCode.O);
        DebugEnabled = true;
    }
コード例 #33
0
ファイル: Flocking.cs プロジェクト: ohappyfaced/Penguins
 public void setFlockManager(GameObject fManager)
 {
     flockMan = fManager.GetComponent<FlockManager> ();
 }