void cleanupChecks() { // Frame cleanup checks here. if (cMemory != null) { onMission = true; } else { onMission = false; } if (_state == State.Move) { isMoving = true; } else { isMoving = false; _moveState = moveState.moveInit; } // if (_Logic_1 == State.Attack && target == null) { // _state = _Logic_1; // } }
public void Move(float _direction) { if (_moveState == moveState.idle || _moveState == moveState.move || _moveState == moveState.move_idle) { _moveState = moveState.move; DirectionSwitch(_direction); switch (_forceState) { case forceState.min: curSpeed = speed1; break; case forceState.normal: curSpeed = speed2; break; case forceState.max: curSpeed = speed3; break; } // Если сделать через AddForce(), тогда будет плавная смена направления движения, а не мгновенная. _rigidbody.velocity = Vector2.Lerp(_rigidbody.velocity, Vector2.right * direction * curSpeed * Time.deltaTime, Time.deltaTime * 5.0f); } else if (_moveState == moveState.fall || _moveState == moveState.jump || _moveState == moveState.jMove) { //Debug.Log("M -> JM, DS: " + _directionState + ", _dir: " + _direction + ", MS: " + _moveState + ", vel: " + _rigidbody.velocity); // Debug. JumpMove(_direction); } }
IEnumerator leapToCatnip(Vector3 dest, float time) { MeshRenderer mo = GameObject.Find("!").GetComponent <MeshRenderer>(); mo.enabled = true; GetComponent <Rigidbody>().transform.eulerAngles = new Vector3(0, Mathf.Atan2((dest.x - transform.position.x), (dest.z - transform.position.z)) * Mathf.Rad2Deg, 0); yield return(new WaitForSeconds(1)); if (hopping) { yield break; } hopping = true; var startPos = transform.position; var timer = 0.0f; AudioSource s = GameObject.Find("Jump").GetComponent <AudioSource> (); s.Play(); while (timer <= 1.0f) { var height = Mathf.Sin(Mathf.PI * timer) * hopHeight; transform.position = Vector3.Lerp(startPos, dest, timer) + Vector3.up * height; timer += Time.deltaTime / time; yield return(null); } hopping = false; ms = moveState.STOPPED; mo.enabled = false; }
private void Move() { transform.position = Vector2.MoveTowards(transform.position, nextWaypoint.position, moveSpeed * Time.deltaTime); transform.position = new Vector3(transform.position.x, transform.position.y, -1);// to ensure is always visible over the tiles direction = exit.transform.position - transform.position; directionIndicator.transform.position = transform.position + direction.normalized * 0.75f; followLocation = transform.position - direction.normalized * 0.75f; //to switch waypoints if (Vector2.Distance(transform.position, nextWaypoint.position) <= searchDistance) { if (nextWaypoint == currentTile.centre) { if (currentTile.name == goalTile.name) { currentState = moveState.win; } else { nextWaypoint = exit; } } else if (nextWaypoint == exit) { FindClosestTile(); } } }
// Update is called once per frame private void Update() { if (movementState == moveState.sliding) { //tick up slide timer timeSlid += Time.deltaTime; } RotateView(); // the jump state needs to read here to make sure it is not missed /*if (movementState != moveState.jumping) * { * m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); * }*/ if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); //PlayLandingSound(); m_MoveDir.y = 0f; if (movementState != moveState.sliding) { movementState = moveState.walking; } } if (!m_CharacterController.isGrounded && movementState != moveState.jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; }
private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } //if climbable set climb to true if (hit.gameObject.tag == "climbable" && m_CollisionFlags == CollisionFlags.Sides) { hitClimbable = true; //exit slide on hits if (movementState == moveState.sliding) { movementState = moveState.walking; } } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity * 0.1f, hit.point, ForceMode.Impulse); }
public EnemyShooter(Texture2D texture, int rows, int columns, Vector2 location, float angle) : base(texture, rows, columns, location, angle) { //Calls the base constructor first, then fills in these class specific fields. Type = EnemyManager.enemyType.shooter; Health = 100; idleTimeLimit = 7 * 1000; MoveState = EnemyShooter.moveState.enter; }
void moveInit() { GetComponent <AIPathfinder> ().target = navTarget; _moveState = moveState.moving; stuckCycles = 2; }
void Start() { target = transform.position; ms = moveState.STOPPED; catnipDown = false; yarnDown = false; canDropNip = false; nipCount = GameObject.Find("NipCount").GetComponent <Text> (); }
void onNav(GameObject actor, Vector3 position) { if (actor == this.gameObject) { navTarget = position; _moveState = moveState.moveInit; _state = State.Move; } }
private void OnTriggerStay2D(Collider2D collision) { if ((collision.transform.position.x * 10) % 10 != 0 && (collision.transform.position.y * 10) % 10 == 0) { objectScalar = 1; } else { objectScalar = 2; } //Directional Facing Cases if ((animator.GetInteger("Direction") == 1 && //Facing Left collision.gameObject.transform.position.x < this.gameObject.transform.position.x && Mathf.Abs(collision.gameObject.transform.position.y - this.gameObject.transform.position.y) < 2.25f * objectScalar) || (animator.GetInteger("Direction") == 3 && //Facing Right collision.gameObject.transform.position.x > this.gameObject.transform.position.x && Mathf.Abs(collision.gameObject.transform.position.y - this.gameObject.transform.position.y) < 2.25f * objectScalar) || (animator.GetInteger("Direction") == 0 && //Facing Down collision.gameObject.transform.position.y < this.gameObject.transform.position.y && Mathf.Abs(collision.gameObject.transform.position.x - this.gameObject.transform.position.x) < 2.25f * objectScalar) || (animator.GetInteger("Direction") == 2 && //Facing Up collision.gameObject.transform.position.y > this.gameObject.transform.position.y && Mathf.Abs(collision.gameObject.transform.position.x - this.gameObject.transform.position.x) < 2.25f * objectScalar)) { if (collision.gameObject.tag == "HideObject") { if (Input.GetButton("Jump")) { motion = moveState.hiding; collision.gameObject.GetComponent <HideHero>().Hero = this.gameObject; collision.gameObject.GetComponent <HideHero>().HideInObject(); //gameObject.SetActive(false); } proximity = nextTo.hide; } if (collision.gameObject.tag == "SearchObject") { if (Input.GetButton("Jump")) { searchItem(collision); proximity = nextTo.search; } } if (collision.gameObject.tag == "Door") { if (Input.GetButton("Jump")) { collision.gameObject.GetComponent <DoorScript>().updateDoor(); } } } }
public void forward() { //Find the distance to move. It's random, and is a percentage of the amount of screen space between the entity and the bottom. 50-80% seemed like an acceptable //range of space to make the enemy move Random rnd = new Random(); double dist = (rnd.NextDouble() * (0.80f - 0.5f) + 0.5f) * (Game1.graphics.PreferredBackBufferHeight - current_location.Y); //New location is offset by previously calculated distance, and enemy is commanded to move to the new location Vector2 nextLocation = new Vector2(current_location.X, current_location.Y + (float)dist); moveTo(nextLocation, 2); MoveState = EnemyShooter.moveState.forward; }
// Update is called once per frame void Update() { strafe = Input.GetAxis("Horizontal"); forward = Input.GetAxis("Vertical"); if (Input.GetButton("Crouch")) { currentMoveState = moveState.crouch; } else { currentMoveState = moveState.walk; } }
protected void Start() { startPos = transform.position; endPos = transform.position; endPos.x = transform.position.x + jumpDist; startRot = transform.rotation.eulerAngles; endRot = transform.rotation.eulerAngles; var aStar = GameObject.FindWithTag(AStarTag); pathFinding = aStar.GetComponent <PathFinding>(); rabbitState = moveState.ground; }
private void FixedUpdate() { if (_moveState == moveState.jump_idle && (_animator.GetCurrentAnimatorStateInfo(0).shortNameHash == _ahIdleR || _animator.GetCurrentAnimatorStateInfo(0).shortNameHash == _ahIdleL)) { _moveState = moveState.idle; } else if (_moveState == moveState.jMove_move && (_animator.GetCurrentAnimatorStateInfo(0).shortNameHash == _ahMoveR || _animator.GetCurrentAnimatorStateInfo(0).shortNameHash == _ahMoveL)) { _moveState = moveState.move; } if (GroundCheck()) { if (_moveState == moveState.jump || _moveState == moveState.fall) { _moveState = moveState.jump_idle; DamageFromFalling(); } else if (_moveState == moveState.jMove) { _moveState = moveState.jMove_move; DamageFromFalling(); } } else { if (_moveState == moveState.idle || _moveState == moveState.move || _moveState == moveState.move_idle) { _moveState = moveState.fall; } } if (_moveState == moveState.jMove && _rigidbody.velocity.x == 0) { _moveState = moveState.jump; } if (_moveState == moveState.preTriumph && (_animator.GetCurrentAnimatorStateInfo(0).shortNameHash == _ahTriumphR || _animator.GetCurrentAnimatorStateInfo(0).shortNameHash == _ahTriumphL)) { _moveState = moveState.triumph; } Animation(); }
public void MoveToIdle() { if (_moveState == moveState.move || _moveState == moveState.move_idle) { if (_rigidbody.velocity.x != 0) { _moveState = moveState.move_idle; _rigidbody.velocity = Vector2.Lerp(_rigidbody.velocity, Vector2.zero, Time.deltaTime); } else { _moveState = moveState.idle; } } }
private void OnLoad() { string playerToLoad = GManager.Instance.ReadNextObjectToLoad(); _thisTransform.name = GManager.FindStringParameterInObject(playerToLoad, "_thisTransform.name"); _thisTransform.position = GManager.FindVector3InObject(playerToLoad, "_thisTransform.position"); _rigidbody.velocity = GManager.FindVector2InObject(playerToLoad, "_rigidbody.velocity"); health = GManager.FindFloatParamInSObject(playerToLoad, "Player.health"); _directionState = (directionState)Enum.Parse(typeof(directionState), GManager.FindStringParameterInObject(playerToLoad, "Player._directionState", "", "")); _forceState = (forceState)Enum.Parse(typeof(forceState), GManager.FindStringParameterInObject(playerToLoad, "Player._forceState", "", "")); _moveState = (moveState)Enum.Parse(typeof(moveState), GManager.FindStringParameterInObject(playerToLoad, "Player._moveState", "", "")); _lowHealthWarning = false; UIPlayer.SetHealth(health); }
//private GameObject mainCamera; #endregion #region Initialization void Start() { animator = GetComponentInChildren <Animator>(); //coll = GetComponent<BoxCollider2D>(); //mainCamera = GameObject.FindGameObjectWithTag("MainCamera"); proximity = nextTo.open; motion = moveState.idle; childSprite = GetComponentInChildren <SpriteRenderer>(); storage = GameObject.FindGameObjectWithTag("GlobalStorage").GetComponent <GlobalVariables>(); if (storage == null) { Debug.Log("Error: Global Storage not found. Score will not display properly."); } }
public void Jump() { if (_moveState == moveState.idle) { _moveState = moveState.jump; ForceStateJump(); _rigidbody.AddForce(Vector2.up * curJumpForce * Time.deltaTime, ForceMode2D.Impulse); } else if (_moveState == moveState.move || _moveState == moveState.move_idle) { //Debug.Log("J -> JM, DS: " + _directionState + ", dir: " + direction + ", MS: " + _moveState + ", vel: " + _rigidbody.velocity); // Debug. JumpMove(0); } }
public void SetUpBeet() { coolDown = false; currentState = moveState.stopped; StartCoroutine(DelayedStart()); anim = GetComponentInChildren <Animator>(); //setup the beet on the board if (FindObjectOfType <GridManager>()) { grid = FindObjectOfType <GridManager>(); gridTiles = grid.GetBoard(); currentTile = grid.startTile.GetComponent <Tiles>(); /*gridTiles[0, 0].GetComponent<Tiles>(); *///sets it up on the 0 tile, we can change this if we want to start in other places goalTile = grid.GetGoal(); } else if (FindObjectOfType <PuzzleOneScript>()) { p1Grid = FindObjectOfType <PuzzleOneScript>(); gridTiles = p1Grid.GetBoard(); currentTile = gridTiles[0, 0].GetComponent <Tiles>(); goalTile = p1Grid.GetGoal(); } else if (FindObjectOfType <PuzzleTwoScript>()) { p2Grid = FindObjectOfType <PuzzleTwoScript>(); gridTiles = p2Grid.GetBoard(); currentTile = gridTiles[2, 2].GetComponent <Tiles>(); goalTile = p2Grid.GetGoal(); } else if (FindObjectOfType <PuzzleX>()) { pXGrid = FindObjectOfType <PuzzleX>(); gridTiles = pXGrid.GetBoard(); currentTile = gridTiles[4, 4].GetComponent <Tiles>(); goalTile = pXGrid.GetGoal(); } //when you add a new puzzle add it to the above. Only need to add here currentTile.SetBeetOn(true); nextWaypoint = currentTile.entryPoints[0]; exit = nextWaypoint; transform.position = currentTile.transform.position; anim.SetTrigger("Walk"); anim.SetBool("Lose", false); anim.SetBool("Win", false); }
void lifterSphere(float stickiness) { bool hitSomething; RaycastHit hitInfo; (hitSomething, hitInfo) = sphereCast(Vector3.down, stickiness); if (hitSomething) { groundNormal = hitInfo.normal; groundNormal = triangleNormal(Vector3.down, stickiness * 2, 0.5f); if (hitInfo.distance > 0) { } else { //Might be good to do do this in both? For smoothness? transform.position = Vector3.Lerp(transform.position, transform.position + Vector3.down * hitInfo.distance, controller.getPreservedTime() * 2); //rigidbody.MovePosition(Vector3.Lerp(transform.position, transform.position + Vector3.down * hitInfo.distance, controller.getPreservedTime() * 2) + transform.position); } if (shouldSlide()) { sliding = true; //currentVelocity = Vector3.ProjectOnPlane(currentVelocity, groundNormal); if (mainBodyCollision()) { Debug.LogWarning("Comming from lifterSphere, that main body collision was a bit wack, but dont worry"); } } else { sliding = false; } state = moveState.GROUNDED; resetAirStuff(currentVelocity); } else { state = moveState.IN_AIR; } }
private void DamageFromFalling() { //Debug.Log("Скорость падения: " + _rigidbody.velocity.y); // DEBUG float damage; if (Mathf.Abs(_rigidbody.velocity.y) <= _maxSafeSpeed) // Если упали с безопасной высоты (чуть больше 7 тайлов)... { return; } for (int i = 1; i < _fallingSpeeds.Length; i++) { if (Mathf.Abs(_rigidbody.velocity.y) <= _fallingSpeeds[i]) { damage = _damagesFalling[i - 1]; damage += (float)Math.Round((Mathf.Abs(_rigidbody.velocity.y) - _fallingSpeeds[i - 1]) * _damageFactors[i], 1, MidpointRounding.AwayFromZero); health = (float)Math.Round(health - damage, 1, MidpointRounding.AwayFromZero); UIPlayer.SetHealth(health); MessageManager.ShowMessageOnlyText("От падения с большой высоты персонаж получил урон: " + damage); if (health <= 0) { MessageManager.ShowMessageOnlyText("Ваш персонаж погиб от падения с большой высоты!"); _moveState = moveState.death; } else if (health < 20 && !_lowHealthWarning) { _lowHealthWarning = true; MessageManager.ShowMessageOnlyText("Персонаж имеет опасно низкий уровень здоровья. Будьте осторожнее!"); } return; } } // Если скорость падения больше чем при падении с 12 тайлов... damage = _damagesFalling[_fallingSpeeds.Length - 1]; health = (float)Math.Round(health - damage, 1, MidpointRounding.AwayFromZero); UIPlayer.SetHealth(health); MessageManager.ShowMessageOnlyText("Ваш персонаж погиб от падения с большой высоты!"); _moveState = moveState.death; }
/* * When reach next waypoint, set enemy * to move towards next target */ public void SwitchState(string nState) { Debug.Log("switch state called " + nState); moveState nextState; // find correct nextState to turn into if (nState == "forward") { nextState = moveState.forward; } else if (nState == "stop") { nextState = moveState.stop; } else if (nState == "backward") { nextState = moveState.backward; } else { Debug.Log("crash"); throw new System.Exception(" incorrect next state passed"); } // save previous velocity // and then set current body.velcoity to 0,0 if (nextState == moveState.stop && curMoveState == moveState.forward) { prevVelocity = body.velocity; body.velocity = new Vector2(0, 0); } /* * Switch velocity back to the forward state * //*/ else if (nextState == moveState.forward && curMoveState == moveState.stop) { body.velocity = prevVelocity; } curMoveState = nextState; }
public void straife() { //We want to pick a location that is between perpendicular and -30 degress, on the side with the least space //First, we determine which side to move to. True means we move right bool side = (current_location.X >= (Game1.graphics.PreferredBackBufferWidth / 2)); Random rnd = new Random(); //We can use pythagorean theorem to generate some random x and y offsets based on the restrictions we have double xDist, yDist; xDist = (side) ? (Game1.graphics.PreferredBackBufferWidth - current_location.X + 100) : (current_location.X * -1) - 100; yDist = (rnd.NextDouble() * (1.0f - 0.5f) + 0.5f) * (Math.Abs(xDist) / 1.73f); //sqrt(3) approximation. It's a magic number, but it's not a commonly used constant Vector2 newLocation = new Vector2(current_location.X + (float)xDist, current_location.Y + (float)yDist); moveTo(newLocation, 2.0f); MoveState = EnemyShooter.moveState.straife; }
// Use this for initialization void Start() { // fetch gameObject components body = gameObject.GetComponent <Rigidbody2D>(); hs = gameObject.GetComponent <HealthScript>(); // default moveState is forwards unless changed. curMoveState = moveState.forward; // fetch all waypoints WayPointList = WayParent.GetComponentsInChildren <WayPointScript>().ToList(); // order waypoint list then sort, cast into waypoint list, and assign WayPointList = WayPointList.OrderBy(wp => wp.wayIndex).ToList <WayPointScript>(); // if at least one waypoint exists, then set target to start if (WayPointList.Count() > 0) { currentTarget = spawnIndexWay; } }
IEnumerator lockOnToMouse(Vector3 dest, GameObject go) { MeshRenderer mo = GameObject.Find("!").GetComponent <MeshRenderer>(); mo.enabled = true; GetComponent <Rigidbody>().transform.eulerAngles = new Vector3(0, Mathf.Atan2((dest.x - transform.position.x), (dest.z - transform.position.z)) * Mathf.Rad2Deg, 0); yield return(new WaitForSeconds(1)); if (go.activeInHierarchy) { transform.position = Vector3.MoveTowards(transform.position, dest, Time.deltaTime * 5); } else { lockedMouse = null; mo.enabled = false; yield return(new WaitForSeconds(1)); ms = moveState.STOPPED; } }
public override void UpdateMovement(GameTime gameTime) { if (State == enemyState.idle) { //Idle means we finished a state, so we want to move to the next one. switch (MoveState) { //I need to think about what this means. What happens when we spawn it? We're probably checking this after it's moved to its location //So we need to make sure we are setting the state to enter and moving it before we get to this point case EnemyShooter.moveState.enter: //By this point it has been spawned and has moved to it's initial destination //Now we want to move down the screen towards the player forward(); break; case EnemyShooter.moveState.forward: //Now we want to move sideways off screen straife(); break; case EnemyShooter.moveState.straife: //This is a little redunandant. But it leaves room to make some changes later on MoveState = EnemyShooter.moveState.leaving; break; case EnemyShooter.moveState.leaving: //Kill it off, it should despawn now //Enemy manager will not update player score if it's health is > 0 State = Enemy.enemyState.dead; break; default: break; } } }
void applyIt() { RaycastHit hit; //DOUBLE CHECK if (Physics.CapsuleCast(transform.position + vars.bOffset1, transform.position + vars.bOffset2, vars.bodyRadius * 0.2f, currentVelocity, out hit, vars.bodyRadius * (1 - 0.2f), vars.mask)) { //YOU ARE INSIDE OF SOMETHING GET THE F**K OUT. transform.position -= currentVelocity.normalized * (vars.bodyRadius * (1 - 0.2f) - hit.distance + 0.001f); //rigidbody.MovePosition(transform.position - currentVelocity.normalized * (vars.bodyRadius * (1 - 0.2f) - hit.distance + 0.001f)); currentVelocity = Vector3.ProjectOnPlane(currentVelocity, hit.normal); resetAirStuff(currentVelocity); state = moveState.IN_AIR; } if ((currentVelocity.magnitude < 0.8f && direction.magnitude == 0)) { currentVelocity = Vector3.zero; } velocityMag = currentVelocity.magnitude; //division is never zero, as current > terminal if (currentVelocity.magnitude > vars.terminalVelocity) { currentVelocity = currentVelocity * vars.terminalVelocity / currentVelocity.magnitude; } transform.position += currentVelocity * controller.getDeltaTime(); //rigidbody.MovePosition(transform.position + currentVelocity * controller.getDeltaTime()); }
private void Update() { myPosition = gameObject.transform.position; getHookPosition = GameObject.FindGameObjectWithTag("Hook").transform.position; float distance = Vector2.Distance(gameObject.transform.position, hookPosition); checkRippleClick(); switch (state) { case moveState.Wander: if (wander == true) { /* Debug.Log("Wander State");*/ /* Flocking */ /* TODO */ /* Check hook position */ feelHook(); if (feelHook() == true) { wander = true; /* Debug.Log("State change to Flee");*/ /* if near hook, FLEE */ state = moveState.Flee; } } break; case moveState.Flee: if (flee == true) { /* Debug.Log("Flee State");*/ steeringForce += FleeForce(); /* Debug.Log("Count");*/ /* count second */ coounter(); /* Debug.Log("Back to Wander State");*/ /* After count, back to wander */ state = moveState.Wander; /* After Flee and back to wander, Check Ripple */ checkRippleClick(); if (checkRippleClick() == true) { /* Debug.Log("Change to Chase state");*/ /* Go to Chase state */ state = moveState.Chase; } } break; case moveState.Chase: if (chase == true) { Debug.Log("move state is: chase"); /* Choose a attract fish & change tag to destroy, at Hook script check collider to destroy*/ attractFish = manager.getAttractedFish(); attractFish.tag = "Destroy"; /* The Fish chase to Hook? */ /* TODO */ chase = false; } break; } }
void onOrder(Order order, GameObject unit, int statusCode, int ID) { if (order.playerID == playerID) { if (unit == this.gameObject) { if (debugActive) { Debug.Log("Order Recieved: " + name); } cMemory = order; if (order._type == Order.Type.Move || order._type == Order.Type.Recon) { navTarget = order.navTarget; _Logic_2 = _Logic_1; _state = State.Move; _Logic_1 = _state; _moveState = moveState.moveInit; return; } if (order._type == Order.Type.Attack) { if (_type == Type.mGun || _type == Type.missile) { if (order.unitTarget.tag == "Friendly") { if (order.unitTarget.GetComponent <unitAgent> ().playerID != playerID) { _Logic_2 = _Logic_1; _state = State.Attack; _Logic_1 = _state; navTarget = order.navTarget; target = order.unitTarget; _moveState = moveState.moveInit; return; } } if (order.unitTarget.tag == "Structure") { if (order.unitTarget.GetComponent <buildLogic> ().playerID != playerID) { _Logic_2 = _Logic_1; _state = State.Attack; _Logic_1 = _state; navTarget = order.navTarget; target = order.unitTarget; _moveState = moveState.moveInit; return; } } if (order.unitTarget.tag == "Resource") { if (isAggressive == true) { _Logic_2 = _Logic_1; _state = State.Attack; _Logic_1 = _state; navTarget = order.navTarget; target = order.unitTarget; _moveState = moveState.moveInit; return; } else { cMemory._type = Order.Type.Move; _Logic_2 = _Logic_1; _state = State.Move; _Logic_1 = _state; navTarget = order.navTarget; target = null; _moveState = moveState.moveInit; return; } } } if (_type == Type.miner) { if (order.unitTarget.tag == "Resource") { _Logic_2 = _Logic_1; _state = State.Mine; _Logic_1 = _state; _mineState = mineState.Mine; navTarget = order.navTarget; target = order.unitTarget; _moveState = moveState.moveInit; return; } if (order.unitTarget.tag == "Structure") { buildLogic bLogic = order.unitTarget.GetComponent <buildLogic> (); if (bLogic.playerID == playerID && bLogic._type == buildLogic.Type.Refinery) { _Logic_2 = _Logic_1; _state = State.Mine; _Logic_1 = _state; _mineState = mineState.Unload; navTarget = order.navTarget; target = order.unitTarget; _moveState = moveState.moveInit; return; } } } if (_type == Type.utility) { if (order.unitTarget.tag == "Friendly") { if (order.unitTarget.GetComponent <unitAgent> ().playerID == playerID) { _Logic_2 = _Logic_1; _state = State.Repair; _Logic_1 = _state; navTarget = order.navTarget; target = order.unitTarget; _moveState = moveState.moveInit; return; } } if (order.unitTarget.tag == "betaStructure") { buildLogic bLogic = order.unitTarget.GetComponent <buildLogic> (); if (bLogic.playerID == playerID) { _Logic_2 = _Logic_1; _state = State.Build; _Logic_1 = _state; navTarget = order.navTarget; target = order.unitTarget; _moveState = moveState.moveInit; return; } } } } if (order._type == Order.Type.Patrol) { patrolA = order.patrolA; patrolB = order.patrolB; _Logic_2 = _Logic_1; _state = State.Patrol; _Logic_1 = _state; _moveState = moveState.moveInit; return; } } } }
// Use this for initialization void Start() { // fetch gameObject components body = gameObject.GetComponent<Rigidbody2D>(); hs = gameObject.GetComponent<HealthScript>(); // default moveState is forwards unless changed. curMoveState = moveState.forward; // fetch all waypoints WayPointList = WayParent.GetComponentsInChildren<WayPointScript>().ToList(); // order waypoint list then sort, cast into waypoint list, and assign WayPointList = WayPointList.OrderBy(wp => wp.wayIndex).ToList<WayPointScript>(); // if at least one waypoint exists, then set target to start if(WayPointList.Count()>0) { currentTarget = spawnIndexWay; } }
/* When reach next waypoint, set enemy to move towards next target */ public void SwitchState(string nState ) { Debug.Log("switch state called "+nState); moveState nextState; // find correct nextState to turn into if (nState == "forward") nextState = moveState.forward; else if (nState == "stop") nextState = moveState.stop; else if (nState == "backward") nextState = moveState.backward; else { Debug.Log("crash"); throw new System.Exception(" incorrect next state passed"); } // save previous velocity // and then set current body.velcoity to 0,0 if (nextState == moveState.stop && curMoveState == moveState.forward) { prevVelocity = body.velocity; body.velocity = new Vector2(0, 0); } /* Switch velocity back to the forward state //*/ else if (nextState == moveState.forward && curMoveState == moveState.stop) { body.velocity = prevVelocity; } curMoveState = nextState; }