Example #1
0
    void Start()
    {
        _rigidbody  = GetComponent <Rigidbody> ();
        birdControl = GetComponent <BirdControl>();

        Reset();
    }
 private void Awake()
 {
     Instance                 = this;
     birdRigidbody2D          = GetComponent <Rigidbody2D>();
     birdRigidbody2D.bodyType = RigidbodyType2D.Static;
     state = State.WaitingToStart;
 }
Example #3
0
	public BirdBody(Transform temp, ControllerInput input, BirdControl birdControl)
	{
		this.input = input;
		this.birdControl = birdControl;

		body = BirdBone.CreateBirdBone(temp);
	}
Example #4
0
    private void setupDistCache()
    {
        for (int i = 0; i < birdControls.Length; i++)
        {
            for (int j = i + 1; j < birdControls.Length; j++)
            {
                BirdControl        b1    = birdControls [i];
                BirdControl        b2    = birdControls [j];
                ColliderDistance2D cd    = b1.GetComponent <Collider2D>().Distance(b2.GetComponent <Collider2D>());
                Vector2            delta = (cd.pointB - cd.pointA);
                b1.SetDistance(b2, delta);
                b2.SetDistance(b1, -1 * delta);
            }
        }

        for (int i = 0; i < birdControls.Length; i++)
        {
            for (int j = 0; j < walls.Length; j++)
            {
                BirdControl        b1    = birdControls [i];
                GameObject         wall  = walls [j];
                ColliderDistance2D cd    = b1.GetComponent <Collider2D>().Distance(wall.GetComponent <Collider2D>());
                Vector2            delta = (cd.pointB - cd.pointA);
                b1.SetWallDist(j, delta);
            }
        }
    }
Example #5
0
    public BirdBody(Transform temp, ControllerInput input, BirdControl birdControl)
    {
        this.input       = input;
        this.birdControl = birdControl;

        body = BirdBone.CreateBirdBone(temp);
    }
Example #6
0
    public void OnTriggerEnter2D(Collider2D collider)
    {
        if (!countCollision)
        {
            return;
        }

        if (collider.gameObject.tag == "Bird")
        {
            BirdControl other = collider.GetComponent <BirdControl>();
            if (other.number < number || number == -1)
            {
                return;
            }
            handleBirdCollision(other);
        }
        if (collider.gameObject.tag == "Goal")
        {
            moving = false;
            gameObject.GetComponent <Collider2D>().enabled = false;
            transform.position = new Vector3(collider.transform.position.x, collider.transform.position.y, 10);
            statsControl.Complete(number);
            flockControl.IncrementGoal();
        }
        if (collider.gameObject.tag == "Wall")
        {
            handleWallCollision(collider);
        }
    }
Example #7
0
    private float calcScore(FlockControl.UnityState us, BirdControl me)
    {
        float score = 0;

        float gd = (us.goal.transform.position - transform.position).magnitude;

        score += GOAL_CONST * Mathf.Min(ASYMPTOTE, 1 / Mathf.Sqrt(gd));

        if (!me.Moving)
        {
            return(score);
        }

        foreach (BirdControl b in us.birds)
        {
            if (b.Equals(me) || !b.Moving)
            {
                continue;
            }

            float d = me.GetDistance(b).dist;
            score += BIRD_CONST * Mathf.Min(ASYMPTOTE, 1 / Mathf.Sqrt(d));
        }

        for (int i = 0; i < us.walls.Length; i++)
        {
            float d = me.WallDistance(i).dist;
            score += WALL_CONST * Mathf.Min(ASYMPTOTE, 1 / Mathf.Sqrt(d));
        }

        return(score);
    }
    private bool inView(BirdControl other, BirdControl me)
    {
        float   dir     = Mathf.Rad2Deg * Mathf.Atan2(me.Velocity.y, me.Velocity.x);
        Vector3 delta   = other.transform.position - me.transform.position;
        float   angleTo = Mathf.Rad2Deg * Mathf.Atan2(delta.y, delta.x);

        return(withinAngle(dir, angleTo, genome.Pathfind.View));
    }
 private void Start()
 {
     ScoreText     = transform.Find("ScoreText").GetComponent <Text>();
     HighscoreText = transform.Find("HighscoreText").GetComponent <Text>();
     Hide();
     BirdControl.GetInstance().OnDied += Bird_OnDied;
     transform.GetComponent <RectTransform>().anchoredPosition = Vector2.zero;
 }
    private int giveToken(FlockControl.UnityState us, int bird, int tokens, bool[] nextGotToken)
    {
        nextGotToken [bird] = true;
        BirdControl me = us.birds [bird];

        Vector2[] path = pf.CalculatePath(me);
        rewardForces [bird] = rewardPathfind(path, me);
        return(tokens - 1);
    }
Example #11
0
    public BirdTail(Transform firstTail, ControllerInput input, BirdControl birdControl)
    {
        this.input       = input;
        this.birdControl = birdControl;

        tail_1 = BirdBone.CreateBirdBone(firstTail);
        tail_2 = BirdBone.CreateBirdBone(firstTail.FindInChildren("Tail_2"));
        tail_3 = BirdBone.CreateBirdBone(firstTail.FindInChildren("Tail_3"));
    }
Example #12
0
	public BirdTail(Transform firstTail, ControllerInput input, BirdControl birdControl)
	{
		this.input = input;
		this.birdControl = birdControl;

		tail_1 = BirdBone.CreateBirdBone(firstTail);
		tail_2 = BirdBone.CreateBirdBone(firstTail.FindInChildren("Tail_2"));
		tail_3 = BirdBone.CreateBirdBone(firstTail.FindInChildren("Tail_3"));

	}
Example #13
0
    private void handleBirdCollision(BirdControl other)
    {
        velocity = getResultantVelocity(transform.position, other.transform.position, mass, other.mass, velocity, other.velocity);
        updateRotation();

        other.velocity = getResultantVelocity(other.transform.position, transform.position, other.mass, mass, other.velocity, velocity);
        other.updateRotation();
        statsControl.AddBirdCollision(number);
        statsControl.AddBirdCollision(other.number);
    }
    private Vector2 rewardSimple(Vector2 goalPos, BirdControl me)
    {
        Vector2 delta = goalPos - (Vector2)me.transform.position;

        if (delta.magnitude > genome.Reward.Distance)
        {
            return(Vector2.zero);
        }
        return(calcForce(delta, genome.Reward));
    }
Example #15
0
    public BirdHead(Transform neckTransfrom, ControllerInput input, BirdControl birdControl)
    {
        this.input       = input;
        this.birdControl = birdControl;

        neck = BirdBone.CreateBirdBone(neckTransfrom);

        head = BirdBone.CreateBirdBone(neckTransfrom.FindInChildren("Head"));

        beack = BirdBone.CreateBirdBone(neckTransfrom.FindInChildren("Head_Beak_Lower"));

        //headFeather = BirdBone.CreateBirdBone(neckTransfrom.FindInChildren("Head_Feather"));
    }
Example #16
0
    private void StartGame()
    {
        BirdControl control = bird.GetComponent <BirdControl>();

        control.inGame = true;
        control.JumpUp();

        readyPic.GetComponent <SpriteRenderer>().material.DOFade(0f, 0.2f);
        tipPic.GetComponent <SpriteRenderer>().material.DOFade(0f, 0.2f);

        scoreMgr.GetComponent <ScoreMgr>().SetScore(0);
        pipeSpawner.GetComponent <PipeSpawner>().StartSpawning();
    }
    private Vector2 getStaticForces(FlockControl.UnityState us, int birdNumber)
    {
        BirdControl me = us.birds [birdNumber];

        Vector2 cohes = cohesion(us.birds, me);

        Vector2 obstcl = obstacle(us.walls, me);

        Vector2 goal = rewardForces [me.Number];

        Vector2 bndry = boundary(us, me);

        return(cohes + obstcl + goal + bndry);
    }
Example #18
0
    private void randomizePositions(int m)
    {
        if (maps.ContainsKey(m))
        {
            loadFromMapState(maps[m]);
            return;
        }

        MapState ms = new MapState();

        ms.walls = new WallState[NUM_RANDOM_WALLS];
        for (int i = 0; i < NUM_RANDOM_WALLS; i++)
        {
            WallState ws = new WallState();

            float width = Random.Range(WALL_MIN_WIDTH, WALL_MAX_WIDTH);
            float area  = Random.Range(WALL_MIN_AREA, WALL_MAX_AREA);
            walls [i].transform.localScale = new Vector3(width, area / width, 1f);
            findPlacement(walls [i]);

            ws.postion   = walls [i].transform.position;
            ws.scale     = walls [i].transform.localScale;
            ws.rotation  = walls [i].transform.rotation;
            ms.walls [i] = ws;
        }

        findPlacement(goal);
        ms.goal = goal.transform.position;

        ms.birds = new BirdState[NUM_BIRDS];
        for (int i = 0; i < NUM_BIRDS; i++)
        {
            BirdControl bird = birdControls [i];
            findPlacement(bird.gameObject);

            BirdState bs = new BirdState();
            bs.size      = Random.Range(MIN_SIZE, MAX_SIZE);
            bs.speed     = Random.Range(MIN_SPEED, MAX_SPEED);
            bs.color     = new Color(Random.Range(.5f, 1f), Random.Range(.5f, 1f), Random.Range(.5f, 1f));
            bs.startPos  = bird.transform.position;
            bs.velocity  = new Vector2(Random.value - .5f, Random.value - .5f).normalized *bird.Speed;
            ms.birds [i] = bs;

            bird.Setup(bs, i, NUM_BIRDS, walls.Length);

            startPositions [i] = bird.transform.position;
        }

        maps[m] = ms;
    }
Example #19
0
	public BirdHead(Transform neckTransfrom, ControllerInput input, BirdControl birdControl)
	{
		this.input = input;
		this.birdControl = birdControl;

		neck = BirdBone.CreateBirdBone(neckTransfrom);

		head = BirdBone.CreateBirdBone(neckTransfrom.FindInChildren("Head"));

		beack = BirdBone.CreateBirdBone(neckTransfrom.FindInChildren("Head_Beak_Lower"));

		//headFeather = BirdBone.CreateBirdBone(neckTransfrom.FindInChildren("Head_Feather"));

	}
    private Vector2 obstacle(GameObject[] walls, BirdControl me)
    {
        Vector2 force = Vector2.zero;

        for (int i = 0; i < walls.Length; i++)
        {
            BirdControl.CachedDelta cd = me.WallDistance(i);
            if (cd.dist > genome.Obstacle.Distance)
            {
                continue;
            }
            force += calcForce(-1 * cd.norm, cd.dist, genome.Cohesion);
        }
        return(force);
    }
    private Vector2 rewardPathfind(Vector2[] path, BirdControl me)
    {
        if (path.Length == 0)
        {
            return(Vector2.zero);
        }

        Vector2 force = Vector2.zero;

        for (int i = 0; i < genome.Pathfind.Steps && i < path.Length; i++)
        {
            Vector2 delta = (path [i] - (Vector2)me.transform.position);
            force += calcForce(delta.normalized, i + 1, genome.Pathfind.Chrom);
        }
        return(force);
    }
Example #22
0
    // Update is called once per frame
    void Update()
    {
        if (!gameStarted && Input.GetButtonDown("Fire1"))
        {
            gameStarted = true;
            StartGame();
        }
        BirdControl control = bird.GetComponent <BirdControl>();

        if (control.dead == true)
        {
            gameoverPic.SetActive(true);
            if (Input.GetButtonDown("Fire1"))
            {
                Application.LoadLevel(0);
            }
        }
    }
    private Vector2 cohesion(BirdControl[] birds, BirdControl me)
    {
        Vector2 force = Vector2.zero;

        foreach (BirdControl b in birds)
        {
            if (b.Equals(me) || !b.Moving)
            {
                continue;
            }
            BirdControl.CachedDelta cd = me.GetDistance(b);
            if (cd.dist > genome.Cohesion.Distance)
            {
                continue;
            }
            force += calcForce(cd.norm, cd.dist, genome.Cohesion);
        }
        return(force);
    }
    private Vector2 boundary(FlockControl.UnityState us, BirdControl me)
    {
        float xForce = 0;
        float yForce = 0;

        // Also, in this case, we are limiting the individual forces in the x and y dimensions to the force and distance of the genomes boundary
        // Whereas in other forces we limit the vector(x,y) to the corresponding parameters
        if (me.transform.position.x < us.roomWidth / 2)
        {
            float xDist = me.transform.position.x;
            if (xDist <= genome.Boundary.Distance)
            {
                xForce = genome.Boundary.Constant / Mathf.Pow(xDist, genome.Boundary.Exponent);
            }
        }
        else
        {
            float xDist = us.roomWidth - me.transform.position.x;
            if (xDist <= genome.Boundary.Distance)
            {
                xForce = -1 * genome.Boundary.Constant / Mathf.Pow(xDist, genome.Boundary.Exponent);
            }
        }

        if (me.transform.position.y < us.roomHeight / 2)
        {
            float yDist = me.transform.position.y;
            if (yDist <= genome.Boundary.Distance)
            {
                yForce = genome.Boundary.Constant / Mathf.Pow(yDist, genome.Boundary.Exponent);
            }
        }
        else
        {
            float yDist = us.roomHeight - me.transform.position.y;
            if (yDist <= genome.Boundary.Distance)
            {
                yForce = -1 * genome.Boundary.Constant / Mathf.Pow(yDist, genome.Boundary.Exponent);
            }
        }
        return(new Vector2(xForce, yForce));
    }
    private Vector2 repulsion(BirdControl[] birds, float[] forces, BirdControl me)
    {
        Vector2 force = Vector2.zero;

        foreach (BirdControl b in birds)
        {
            if (b.Equals(me) || !b.Moving)
            {
                continue;
            }

            BirdControl.CachedDelta cd = me.GetDistance(b);
            if (cd.dist > genome.Repulse.Distance)
            {
                continue;
            }
            force += calcForce(-1 * cd.norm, cd.dist, genome.Repulse);            // * forces[b.Number];
        }
        return(force);
    }
Example #26
0
	public BirdWing(Transform shoulderTransform, string suffix, ControllerInput input, BirdControl birdControl)
	{
		this.input = input;
		this.birdControl = birdControl;

		if (suffix == "_L")
			sign = -1f;


		shoulder = BirdBone.CreateBirdBone(shoulderTransform);

		wing_1 = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_1" + suffix));

		//wing_1_f = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_F_1" + suffix));

		wing_2 = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_2" + suffix));
		wing_2_f = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_F_2" + suffix));

		wing_3 = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_3" + suffix));
		//wing_3_f = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_F_3" + suffix));
	}
    private Vector2 aligment(BirdControl[] birds, float[] forces, BirdControl me)
    {
        Vector2 force = Vector2.zero;

        foreach (BirdControl b in birds)
        {
            if (b.Equals(me) || !b.Moving)
            {
                continue;
            }

            BirdControl.CachedDelta cd = me.GetDistance(b);
            if (cd.dist > genome.Align.Distance)
            {
                continue;
            }
            float mag = calcForce(cd.norm, cd.dist, genome.Align).magnitude;            // * forces[b.Number];
            force += b.Velocity.normalized * mag;
        }
        return(force);
    }
Example #28
0
    // Resets the walls, goal and all birds.
    private void resetSimulation()
    {
        reachedGoal = 0;
        for (int i = 0; i < NUM_BIRDS; i++)
        {
            BirdControl bird = birdControls [i];
            bird.transform.position = startPositions [i];
            bird.Reset();
        }

        scoreControl.Setup(NUM_BIRDS);

        statsControl.Setup(NUM_BIRDS, MAX_TIME);

        uiControl.AwaitingText();

        decisionControl.StartGeneration(buildUnityState());

        startTime        = Time.time;
        hasReceivedStart = false;
        generation++;
    }
Example #29
0
    public BirdWing(Transform shoulderTransform, string suffix, ControllerInput input, BirdControl birdControl)
    {
        this.input       = input;
        this.birdControl = birdControl;

        if (suffix == "_L")
        {
            sign = -1f;
        }


        shoulder = BirdBone.CreateBirdBone(shoulderTransform);

        wing_1 = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_1" + suffix));

        //wing_1_f = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_F_1" + suffix));

        wing_2   = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_2" + suffix));
        wing_2_f = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_F_2" + suffix));

        wing_3 = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_3" + suffix));
        //wing_3_f = BirdBone.CreateBirdBone(shoulderTransform.FindInChildren("Wing_F_3" + suffix));
    }
    private Vector2 steer(BirdControl me, Vector2 force)
    {
        /* We want to steer our current velocity towards our aim velocity (the force on our bird), so take the average of the two
         * and reflect it over the goal/ That way we aim in a way that slows us down only in the desired dimension, and speeds
         * us up in the correct dimension.
         */
        Vector2 vel = me.Velocity.normalized;
        Vector2 aim = force.normalized;

        Vector2 ave        = ((vel + aim) / 2).normalized;
        Vector2 adjustment = Vector2.zero;

        // If our aim velocity is close to orthogonal to our genome velocity, just steer using our genome velocity
        if (Vector2.Dot(vel, aim) > -.5f && vel != Vector2.zero)
        {
            adjustment = Vector2.Reflect(-1 * ave, -1 * aim).normalized;
        }
        else
        {
            adjustment = aim;
        }
        return(adjustment.normalized * me.Speed);
    }
Example #31
0
    public void Start()
    {
        Application.targetFrameRate = (int)(FRAMES_PER_SECOND * SIMULATION_SPEED);
        Time.timeScale = SIMULATION_SPEED;
        Application.runInBackground = true;

        decisionControl.InitializeModel(NUM_BIRDS, randomizePositions);

        // Set the background based on room settings
        background.transform.position   = new Vector3(ROOM_WIDTH / 2, ROOM_HEIGHT / 2, 5);
        Camera.main.transform.position  = new Vector3(ROOM_WIDTH / 2, ROOM_HEIGHT / 2, -10);
        background.transform.localScale = new Vector3(ROOM_WIDTH + 5, ROOM_HEIGHT + 5, 1);
        background.GetComponent <Renderer>().material.color = Color.black;

        goal         = Instantiate <GameObject>(goalPrefab);
        statsControl = FindObjectOfType <StatsControl>();
        uiControl    = FindObjectOfType <UIControl>();

        // Generate birds
        birdControls = new BirdControl[NUM_BIRDS];
        for (int i = 0; i < NUM_BIRDS; i++)
        {
            BirdControl bird = Instantiate <GameObject>(birdPrefab).GetComponent <BirdControl>();
            birdControls [i] = bird;
        }

        walls = new GameObject[NUM_RANDOM_WALLS];
        for (int i = 0; i < walls.Length; i++)
        {
            walls [i] = Instantiate <GameObject>(wallPrefab);
        }

        startPositions = new Vector2[NUM_BIRDS];
        randomizePositions(0);
        resetSimulation();
    }
Example #32
0
	void Start ()
	{
		lastPose = new PoseData[birds.Length];
		mistress = GameObject.Find("BalconyBird").GetComponent<BirdControl>();
		mistress._initializeController();
	}
    private void generateRewards(FlockControl.UnityState us)
    {
        int pathfindTokens = PATHFIND_TOKENS;

        rewardForces = new Vector2[us.birds.Length];
        bool[] nextGotToken = new bool[us.birds.Length];

        /* In this function, we give away a number of tokens equal to PATHFIND_TOKENS to birds so that they use the more computational expensive pathfinding.
         * We prioritize the birds that previously received tokens, then birds with no leaders, but we want to make sure that as the number of active birds falls,
         * we still give away all of our tokens to birds that are active. If we have more tokens than active birds, every bird should use pathfinding.
         */

        // First we give priority to birds that are already holding tokens
        for (int bird = 0; bird < us.birds.Length; bird++)
        {
            BirdControl me = us.birds [bird];
            if (!gotRewardToken [bird] || !me.Moving)
            {
                continue;
            }
            if (Random.value > genome.Pathfind.Carryover)
            {
                continue;
            }
            // This bird had a token and carries it over in this frame
            pathfindTokens = giveToken(us, bird, pathfindTokens, nextGotToken);
        }

        // Then we prioritize birds with no leaders
        int[] birdIndex = range(us.birds.Length);
        shuffle(birdIndex);
        for (int i = 0; i < birdIndex.Length && pathfindTokens > 0; i++)
        {
            int         bird = birdIndex [i];
            BirdControl me   = us.birds [bird];
            if (!me.Moving || nextGotToken [bird])
            {
                continue;
            }

            bool hasLeader = false;
            foreach (BirdControl b in us.birds)
            {
                if (b.Equals(me) || !b.Moving)
                {
                    continue;
                }

                float dist = me.GetDistance(b).dist;
                // Distance here is used a bit differently than in other cases, but it is trained just the same and does not result in any issues.
                if (dist > genome.Pathfind.Distance)
                {
                    continue;
                }

                hasLeader = hasLeader || inView(b, me);
            }

            if (hasLeader)
            {
                continue;
            }
            // This bird has no leader so use a token
            pathfindTokens = giveToken(us, bird, pathfindTokens, nextGotToken);
        }

        // Now we give out the rest of the tokens randomly
        birdIndex = range(us.birds.Length);
        shuffle(birdIndex);
        for (int i = 0; i < birdIndex.Length && pathfindTokens > 0; i++)
        {
            int         bird = birdIndex [i];
            BirdControl me   = us.birds [bird];
            if (!me.Moving || nextGotToken [bird])
            {
                continue;
            }
            // This bird has received a token through random chance
            pathfindTokens = giveToken(us, bird, pathfindTokens, nextGotToken);
        }

        // The remainder of the birds do not receive tokens and so just do simple pathfinding towards the goal
        for (int bird = 0; bird < us.birds.Length; bird++)
        {
            BirdControl me = us.birds [bird];
            if (!me.Moving)
            {
                continue;
            }
            if (nextGotToken [bird])
            {
                // This bird already received a token
                continue;
            }
            rewardForces [bird] = rewardSimple(us.goal.transform.position, me);
        }

        gotRewardToken = nextGotToken;
    }
Example #34
0
 public void SetDistance(BirdControl other, Vector2 delta)
 {
     birdDeltas[other.number] = new CachedDelta(delta);
 }
Example #35
0
 public CachedDelta GetDistance(BirdControl other)
 {
     return(birdDeltas[other.number]);
 }