public override AIAction GFixedUpdate(UnitCommander unitCmd, Vector2 goalPos) { //Init Vector2 moveVec = Vector2.zero; Vector2 pos = unitCmd.transform.position; unitCmd.GetComponent<Rigidbody2D>().gravityScale = 1; state = AIState.MOVING; //Check for enemies float directionX = unitCmd.turnedRight ? 1f : -1f; Vector2 inFrontUpperLeft = new Vector2(pos.x + directionX * 0.5f, pos.y + 0.5f); Vector2 inFrontLowerRight = new Vector2(pos.x + directionX * 0.9f, pos.y - 0.5f); Collider2D[] inFrontColliders = Physics2D.OverlapAreaAll(inFrontUpperLeft, inFrontLowerRight); foreach (Collider2D coll in inFrontColliders) { if (coll.tag.Equals("Monster")){ state = AIState.ATTACKING; } } switch (state) { case AIState.MOVING: moveVec = Movement(unitCmd, goalPos); break; case AIState.ATTACKING: moveVec = AttackMove(unitCmd, inFrontColliders); break; default: break; } Debug.DrawLine(inFrontUpperLeft, inFrontLowerRight, Color.green); return new AIAction(moveVec, state == AIState.ATTACKING); }
protected Vector2 Movement(UnitCommander unitCmd, Vector2 goalPos) { Vector2 moveVec = Vector2.zero; Vector2 pos = unitCmd.transform.position; bool isOnStairs = false; Vector2 upperLeft = new Vector2(pos.x - 0.1f, pos.y + 0.5f); Vector2 lowerRight = new Vector2(pos.x + 0.1f, pos.y - 0.5f); Collider2D[] colliders = Physics2D.OverlapAreaAll(upperLeft, lowerRight); float totXForce = 0; foreach (Collider2D coll in colliders) { //Is on stairs? if (coll.tag.Equals("Stairs")) { isOnStairs = true; unitCmd.GetComponent<Rigidbody2D>().gravityScale = 0; unitCmd.GetComponent<Rigidbody2D>().velocity = Vector2.zero; break; }//Move away from other heroes // else if (coll.tag.Equals("Hero")) // { // float xDiff = coll.transform.position.x - pos.x; // float xForce = xDiff == 0 ? 0 : 0.1f/xDiff; // totXForce -= xForce; // } } //Move in x or y direction / Can move in y direction? if (isOnStairs && CanContinueOnStairs(pos, goalPos)){ // && transform.position.y - 0.5f < goalPos.y || transform.position.y - 0.6f > goalPos.y){ moveVec.y = Mathf.MoveTowards(pos.y, goalPos.y, 0.1f) - pos.y; }else{ moveVec.x = Mathf.MoveTowards(pos.x, goalPos.x, 0.1f) - pos.x; } //Apply hero-distancer force // if (totXForce > 0.1) totXForce = 0.1f; // if (totXForce < -0.1) totXForce = -0.1f; // if ((moveVec.x > 0 && totXForce < 0) || (moveVec.x < 0 && totXForce > 0)) moveVec.x += totXForce; return moveVec; }