Example #1
0
 public void InterruptPath()
 {
     if (this.type != VehicleType.BUILDING)
     {
         if (currentState == UnitState.RequestingPath)
         {
             if (PathRequestManager.instance.CurrentPathID == CurrentRequestID)
             {
                 cancelCurrentPath = true;
             }
             else
             {
                 PathRequestManager.RemoveRequestFromQueue(transform.position, CurrentTarget, OnPathFound, CurrentRequestID);
                 cancelCurrentPath = false;
             }
         }
         pathQueue.Clear();
         StopCoroutine("FollowPath");
         currentState = UnitState.Stopped;
     }
     else
     {
         pathQueue.Clear();
     }
 }
	private float t2 = 0.0f; //момент перехода Stop->Idle

	
	public override void StartVis()
	{
		if (unitState == UnitState.Idle) //Idle => Starting
		{
			base.StartVis();
			unitState = UnitState.Starting;
			soundStart.Play ();
			t = Time.time + L1; //когда должен запуститься звук работы
		}
		else if (unitState == UnitState.Stopping)
		{
			base.StartVis();
			unitState = UnitState.Starting;

			//останавливаем стартование
			float pos = soundStop.time;
			float p = pos / L3;
			soundStop.Stop();

			//запускаем остановку
			soundStart.time = L1 * (1.0f - p);
			soundStart.Play ();
			//Debug.Log("Stop time: " + soundStop.time);

			t = Time.time + pos;

		}
	}
Example #3
0
        public UnitBase()
        {
            UnitType = UnitTypes.Default;

            drawPosition = new Vector2f();
            _moveXCompleted = false;
            _moveYCompleted = false;

            EntityToAttack = null;
            allowMovement = false;

            Speed = 0;
            State = UnitState.Agro;
            Range = 1000;
            AttackDelay = 2000;
            attackTimer = new Stopwatch();
            attackTimer.Restart();

            StandardAttackDamage = 1;
            StandardAttackElement = Entity.DamageElement.Normal;

            Sprites = new Dictionary<AnimationTypes, AnimatedSprite>();

            const byte AnimationTypeCount = 8;
            for (int i = 0; i < AnimationTypeCount; i++)
            {
                Sprites.Add((AnimationTypes)i, new AnimatedSprite(100));
            }

            CurrentAnimation = AnimationTypes.Idle;
            SpriteFolder = "";
        }
	public override void StopVis()
	{
		if (unitState == UnitState.Idle || unitState == UnitState.Stopping)
		{
			return;
		}
		else
		{
			if (unitState == UnitState.Starting) //если мы только стартуем
			{ 
				//останавливаем стартование
				float pos = soundStart.time;
				float p = pos / L1;
				soundStart.Stop();

				//запускаем остановку
				soundStop.time = L3 * (1.0f - p);
				//Debug.Log("Stop time: " + soundStop.time);

				t2 = Time.time + pos; 
			}
			if (unitState == UnitState.Working) //если работаем
			{
				t2 = Time.time + L3;
				soundWork.Stop();
			}
			soundStop.Play ();
			unitState = UnitState.Stopping;
		}
	}
	public override void StopVis()
	{
		base.StopVis();
		if (unitState == UnitState.Starting) //если мы только стартуем
		{ 
			//останавливаем стартование
			float pos = Time.time - q;
			dt = pos;
			//float p = pos / L1;
			//Debug.Log("Pos: " + pos);
			//soundStart.Stop();
			
			//запускаем остановку
			//soundStop.time = L3 * (1.0f - p);
			//Debug.Log("Stop time: " + soundStop.time);
			
			t2 = Time.time + pos; 
		}
		else if (unitState == UnitState.Working)
		{
			t2 = Time.time + L3;
			dt = L3;
			//soundWork.Stop();
		}
		unitState = UnitState.Stopping;
		q = Time.time;
		v_from = Rot.Speed; 
		v_to = V1;
	}
Example #6
0
        public UnitBase(GameServer _server, Player player)
            : base(_server, player)
        {
            EntityType = Entity.EntityType.Unit;
            UnitType = UnitTypes.Default;

            EntityToAttack = null;

            Speed = .01f;
            Range = 50;
            AttackDelay = 100;
            AttackRechargeTime = 1000;
            SupplyUsage = 1;
            RangedUnit = false;

            StandardAttackDamage = 1;
            StandardAttackElement = Entity.DamageElement.Normal;

            State = UnitState.Agro;
            allowMovement = false;
            _moveXCompleted = false;
            _moveYCompleted = false;

            attackTimer = new Stopwatch();
            attackTimer.Reset();
            attackTimer.Stop();

            rechargeTimer = new Stopwatch();
            rechargeTimer.Restart();

            updatedMovePositionTimer = new Stopwatch();
            updatedMovePositionTimer.Start();
        }
	public override void StopImmidiately()
	{
		unitState = UnitState.Idle;
		soundStart.Stop ();
		soundWork.Stop ();
		soundStop.Stop ();
		t = t2 = 0.0f;
	}
 public override void MakeTransition(UnitState state)
 {
     if(state is UnitStateNormal)
     {
         state.Apply();
         _unit.UnitState = state;
     }
 }
Example #9
0
 private static void SetStateForAllSelected(UnitState<GameEntity> setState)
 {
     IEnumerable<GameUnit> selectedUnits = GetSelectedUnits();
     foreach (GameUnit selectedUnit in selectedUnits)
     {
         selectedUnit.GetStateMachine().ChangeState(setState);
     }
 }
    // Update is called once per frame
    protected override void Update()
    {
        base.Update();

        if (_gameController.CurrentState == GameController.GameState.PLAYING) {
            if (currentState == UnitState.WAITING) {

                if (_btUnitRef != null && !_btUnitRef.IsDead) {
                    this.attackTarget = _btUnitRef as Entity;
                    this.currentState = UnitState.ATTACKING;
                    //Debug.Log(this.Name + " engages " + _btUnitRef.Name);
                }

            }
            else if (currentState == UnitState.ATTACKING) {
                if (attackTarget != null && !attackTarget.IsDead) {
                    if (GetShouldFlee()) {
                        this.currentState = UnitState.FLEEING;
                    }
                    else if (GetIsWithinAttackingRange(attackTarget)) {
                        Attack(attackTarget);
                    }
                    else if (GetIsWithinPerceptionRange(attackTarget)) {
                        this.MoveTo(attackTarget.transform);
                    }
                    else {
                        Debug.LogWarning(attackTarget.Name + " is not in range for " + this.Name);
                    }
                }
                else {
                    this.currentState = UnitState.WAITING;
                }
            }
            else if (currentState == UnitState.FLEEING) {
                if (attackTarget != null && !attackTarget.IsDead) {
                    if (GetShouldFlee() && GetIsWithinPerceptionRange(attackTarget)) {
                        Flee();
                    }
                    else {
                        currentState = UnitState.WAITING;
                    }
                }
                else {
                    this.currentState = UnitState.WAITING;
                }
            }
            else if (currentState == UnitState.DEAD) {
                if (!IsDead)
                    IsDead = true;
            }
        }
        else {
            StopMoving();
            StopAllAnimations();
        }
    }
Example #11
0
 public override void Activate()
 {
     base.Activate ();
     tracked_enemy = null;
     current_node = null;
     enemy_range_penalty_factor = 0;
     squad = null;
     id = global_id_counter ++;
     parameters.hp_current = parameters.hp_max;
 }
Example #12
0
    public void DealDamageToTrackedEnemy()
    {
        tracked_enemy.parameters.hp_current -= parameters.attack_damage;

        Debug.DrawLine (transform.position, tracked_enemy.transform.position, debug_attack_color);
        if (tracked_enemy.parameters.hp_current <= 0) {
            tracked_enemy.Deactivate();
            tracked_enemy = null;
        }
    }
Example #13
0
 void Start()
 {
     selectionManager = GameObject.Find("PlayerGameManager").GetComponent<SelectionManager>();
     //		selectionManager.RegisterUnit(new UnitObject());
     spawnQueueManager = GameObject.Find("PlayerGameManager").GetComponent<SpawnQueueManager>();
     selectionAgent = GetComponent<SelectionAgent>();
     state = UnitState.Defend;
     transform.GetChild(0).localScale = new Vector3(1, 1, 0) * throwRadius * 1.4f;
     // NOTE: I have no idea why 1.4 works.  It's 2 * 0.7, but I don't know why 70% is special.
 }
 protected virtual void Start()
 {
     m_state = UnitState.IDLING;
     m_onTheGround = true;
     m_curMoveSpeed = m_moveSpeed;
     m_health = Mathf.Max(0, m_health);
     m_curHealth = m_health;
     m_moveSpeed = Mathf.Max(0, m_moveSpeed);
     m_jumpSpeed = Mathf.Max(0, m_jumpSpeed);
     m_rigidbody = GetComponent<Rigidbody>();
 }
	//(стартование, остановка)

	public override void StartVis()
	{
		base.StartVis();
		unitState = UnitState.Starting;
		//soundStart.Play ();
		//foreach (VisRotation Rot in Rots)
		Rot.Speed = V1;

		t = Time.time + L1; //когда должен запуститься звук работы
		q = Time.time;
		dt = L1;

		v_from = V1;
		v_to = V2;
	}
Example #16
0
        float _walkAcceleration; //how much unit can accelerate when moving (px/sec^2)

        #endregion Fields

        #region Constructors

        public Unit(string key, Vector2 position, bool facingRight)
        {
            UnitData data = UnitDataDict[key];
            _position = position;
            _velocity = Vector2.Zero;
            _walkAcceleration = data.WalkAcceleration;
            _maxSpeed = data.MaxSpeed;
            _horizontalDeceleration = data.HorizontalDeceleration;
            _jumpSpeed = data.JumpSpeed;
            _gravity = data.Gravity;
            _health = data.Health;
            _hitRect = new Rectangle(
                (int)(position.X - data.HitRectWidth / 2.0f),
                (int)(position.Y - data.HitRectHeight / 2.0f),
                data.HitRectWidth, data.HitRectHeight);
            _sprite = new Sprite(key, facingRight);  //sprite key should match unit key
            _state = UnitState.Standing;
        }
Example #17
0
 void OnGUI()
 {
     if (selectionAgent.selected && state != UnitState.Spawn) {
         if (GUI.Button(new Rect(20, 20, 100, 20), "Spawn fast")) {
             state = UnitState.Spawn;
             spawnType = UnitClass.Fast;
         }
         if (GUI.Button(new Rect(20, 50, 100, 20), "Spawn slow")) {
             state = UnitState.Spawn;
             spawnType = UnitClass.Slow;
         }
     }
     if (state == UnitState.Spawn) {
         if (GUI.Button(new Rect(20, 20, 100, 20), "Exit spawning")) {
             state = UnitState.Defend;
         }
     }
 }
Example #18
0
 public void SwitchToState(UnitState state)
 {
     this.state = state;
     switch (state)
     {
         case UnitState.IDLE:
             this.SwitchToIdle();
             break;
         case UnitState.MOVING:
             this.SwitchToMoving();
             break;
         case UnitState.CUSTOM:
             this.SwitchToCustom();
             break;
         case UnitState.DESTROYING:
             this.SwitchToDestroying();
             break;
     }
 }
Example #19
0
    public void ChangeState(UnitState unitState)
    {
        state = unitState;
        GameManager.ins.AnyChanged();

        switch (unitState)
        {
            case UnitState.DEAD:
                Dead();
                break;
            case UnitState.RUN:
                SetActiveObject(true);
                break;
            case UnitState.NONE:
                SetActiveObject(false);
                break;

        }
    }
Example #20
0
        public UnitState GenerateInitiateUnit(CreateRoleOption option)
        {
            var unit = new UnitState
            {
                Race   = option.Race,
                Gender = option.Gender,
            };

            for (var i = 0; i < (int)BodyPartIndex.BodyPartCount; i++)
            {
                unit.BodyParts[i] = BodyPart.Create(1, 10);
            }
            for (var i = 0; i < (int)AbilityIndex.AbilityCount; i++)
            {
                unit.Abilities[i] = new UnitProperty();
            }
            for (var i = 0; i < (int)EffectIndex.EffectCount; i++)
            {
                unit.Effects[i] = new UnitProperty();
            }

            return(unit);
        }
Example #21
0
 public void MergeUnits(GameObject ownGO, GameObject other, bool isEnemy)
 {
     if (!isEnemy)
     {
         if (mergeTarget.transform.position.x > transform.position.x)
         {
             mergeTarget.GetComponent <UnitControl>().UpdateFlag(true, playerFlag, other, ownGO);
             mergingNow = true;
             State      = UnitState.Merging;
             GetComponent <Collider>().enabled = false;
         }
     }
     else if (isEnemy)
     {
         if (mergeTarget.transform.position.x < transform.position.x)
         {
             mergeTarget.GetComponent <UnitControl>().UpdateFlag(true, enemyFlag, other, ownGO);
             mergingNow = true;
             State      = UnitState.Merging;
             GetComponent <Collider>().enabled = false;
         }
     }
 }
            public void fillWithRawObj(JSONObject obj)
            {
                alyLandEndX     = int.Parse(obj.GetField("alyLandEndX").ToString());
                enemyLandStartX = int.Parse(obj.GetField("enemyLandStartX").ToString());
                currentPower    = int.Parse(obj.GetField("currentPower").ToString());
                alyPowerRegen   = int.Parse(obj.GetField("alyPowerRegen").ToString());
                enemyPower      = int.Parse(obj.GetField("enemyPower").ToString());
                enemyPowerRegen = int.Parse(obj.GetField("enemyPowerRegen").ToString());
                turnNumber      = int.Parse(obj.GetField("turnNumber").ToString());
                time            = int.Parse(obj.GetField("time").ToString());
                firstTurnIsMine = bool.Parse(obj.GetField("isFirst").ToString());
                unitList        = new List <UnitState>();
                //Logger.debug("Re game status before units");
                JSONObject rawUnits = obj.GetField("unitList");

                for (int i = 0; i < rawUnits.Count; i++)
                {
                    UnitState newUnit = new UnitState();
                    newUnit.fillWithRawObj(rawUnits[i]);
                    unitList.Add(newUnit);
                }
                //ogger.debug("Re game status parse complete");
            }
            public void fillWithRawObj(JsonData syncInfo)
            {
                alyLandEndX     = int.Parse(syncInfo["alyLandEndX"].ToString());
                enemyLandStartX = int.Parse(syncInfo["enemyLandStartX"].ToString());
                currentPower    = int.Parse(syncInfo["currentPower"].ToString());
                enemyPower      = int.Parse(syncInfo["enemyPower"].ToString());
                turnNumber      = int.Parse(syncInfo["turnNumber"].ToString());
                alyPowerRegen   = int.Parse(syncInfo["alyPowerRegen"].ToString());
                enemyPowerRegen = int.Parse(syncInfo["enemyPowerRegen"].ToString());
                time            = int.Parse(syncInfo["time"].ToString());
                firstTurnIsMine = bool.Parse(syncInfo["isFirst"].ToString());
                unitList        = new List <UnitState>();
                //Logger.debug("Re game status before units");
                JsonData rawUnits = syncInfo["unitList"];

                for (int i = 0; i < rawUnits.Count; i++)
                {
                    UnitState newUnit = new UnitState();
                    newUnit.fillWithRawObj(rawUnits[i]);
                    unitList.Add(newUnit);
                }
                //Logger.debug("Re game status parse complete");
            }
Example #24
0
    private void Start()
    {
        if (!animator)
        {
            animator = GetComponentInChildren <UnitAnimator>();
        }
        if (!rb)
        {
            rb = GetComponent <Rigidbody>();
        }
        if (!playerState)
        {
            playerState = GetComponent <UnitState>();
        }
        if (!capsule)
        {
            capsule = GetComponent <CapsuleCollider>();
        }

        if (!animator)
        {
            Debug.LogError("No animator found inside" + gameObject.name);
        }
        if (!rb)
        {
            Debug.LogError("No rigidbody component found on " + gameObject.name);
        }
        if (!playerState)
        {
            Debug.LogError("No UnitState component found on " + gameObject.name);
        }
        if (!capsule)
        {
            Debug.LogError("No Capsule Collider found on " + gameObject.name);
        }
        currentDirection = DIRECTION.Right;
    }
Example #25
0
    // select this unit
    public void selectUnit()
    {
        PlayerManager.Instance.getCurrentPlayer().selectedObject = gameObject;
        state     = UnitState.Selected;
        selectPos = pos;

        // mark tiles this unit can attack and reach
        TileMarker.Instance.Clear();
        TileMarker.Instance.markTravTiles(this);
        TileMarker.Instance.markAttackTiles(this);

        UIManager.Instance.ActivateFriendPanel(this);

        if (playerID == 1 || GameDirector.Instance.isMultiPlayer())
        {
            UIManager.Instance.setUnitUI(true);
        }

        createOverlay();

        //if unit has at least one AoE weapon, make the AoE button available
        bool AoE = false;

        foreach (Weapon w in weapons)
        {
            if (w.AoE)
            {
                AoE = true;
            }
        }
        if (AoE && (playerID == 1 || GameDirector.Instance.isMultiPlayer()))
        {
            UIManager.Instance.activateAoEButton();
        }

        Camera.main.GetComponent <AudioSource>().PlayOneShot(GameDirector.Instance.sfxSelect);
    }
Example #26
0
        public void SetState(UnitState state)
        {
            switch (state)
            {
            case UnitState.Moving:
            {
                if (_animation.GetBool("Stop"))
                {
                    _animation.SetBool("Stop", false);
                }
                break;
            }

            case UnitState.Stopped:
            {
                if (!_animation.GetBool("Stop"))
                {
                    _animation.SetBool("Stop", true);
                }

                break;
            }
            }
        }
Example #27
0
        public static CustomStateDetail GetCustomUnitState(UnitState state)
        {
            if (state.State <= 25)
            {
                var detail = new CustomStateDetail();

                detail.ButtonText  = state.ToStateDisplayText();
                detail.ButtonColor = state.ToStateCss();

                if (string.IsNullOrWhiteSpace(detail.ButtonColor))
                {
                    detail.ButtonColor = "label-default";
                }

                return(detail);
            }
            else
            {
                var customStateService = WebBootstrapper.GetKernel().Resolve <ICustomStateService>();
                var stateDetail        = customStateService.GetCustomDetailForDepartment(state.Unit.DepartmentId, state.State);

                return(stateDetail);
            }
        }
Example #28
0
 public bool ReciveDamage(int damage)
 {
     lives -= damage;
     //Debug.Log("Unit Recive damage");
     if (lives <= 0)
     {
         myAudioSource.Stop();
         myAudioSource.clip = deadClip;
         myAudioSource.Play();
         anim.SetTrigger("Die");
         //Anim die
         //Remove light
         lifeImage.fillAmount = 0;
         currentState         = UnitState.DIYING;
         UnitiesManager.instance.RemoveUnity(this);
         Destroy(this.gameObject, 2f);
         return(true);
     }
     else
     {
         lifeImage.fillAmount = (float)lives / (float)initialLives;
     }
     return(false);
 }
Example #29
0
        public static async Task <CustomStateDetail> GetCustomUnitState(UnitState state)
        {
            if (state.State <= 25)
            {
                var detail = new CustomStateDetail();

                detail.ButtonText  = state.ToStateDisplayText();
                detail.ButtonColor = state.ToStateCss();

                if (string.IsNullOrWhiteSpace(detail.ButtonColor))
                {
                    detail.ButtonColor = "label-default";
                }

                return(detail);
            }
            else
            {
                var customStateService = ServiceLocator.Current.GetInstance <ICustomStateService>();
                var stateDetail        = await customStateService.GetCustomDetailForDepartmentAsync(state.Unit.DepartmentId, state.State);

                return(stateDetail);
            }
        }
Example #30
0
    private void OnUpdate(object obj)
    {
        textHealth.text   = (int)unit.nowHp + "/" + (int)unit.maxHp;
        sliderHp.value    = unit.nowHp / unit.maxHp;
        textAttack.text   = ((int)unit.attackBig).ToString();
        textDefance.text  = ((int)unit.defance).ToString();
        textNowSpeed.text = ((int)unit.speed).ToString();
        UnitState state = (UnitState)obj;

        if (state == unit.state && BattleController.Instance.pauseRound <= 0)
        {
            now.SetActive(true);
        }
        else if (state != unit.state || BattleController.Instance.pauseRound > 0)
        {
            now.SetActive(false);
        }
        Tools.ClearChildFromParent(tsBuff);
        for (int i = 0; i < unit._buffs.Count; i++)
        {
            GameObject buffObj = Tools.CreateGameObject("UI/BattleScene/BuffCell", tsBuff);
            buffObj.GetComponent <BuffCell>().Create(unit._buffs[i]);
        }
    }
Example #31
0
    //============ Attack CoRoutine  ===============================//
    IEnumerator CoRoutine_Attack()
    {
        currentState         = UnitState.attacking;
        navMeshAgent.enabled = false;
        audioSrc.Stop();

        anim.SetTrigger("Attack - Standard");
        anim.SetFloat("Speed", 0);

        lerpData.originalPos    = this.transform.position;
        lerpData.originalLookAt = this.transform.position + this.transform.forward * 3;
        lerpData.targetPos      = enemyUnit.transform.position + (transform.position - enemyUnit.transform.position) * (3 / (enemyUnit.transform.position - transform.position).magnitude);
        lerpData.targetLookAt   = enemyUnit.transform.position + enemyUnit.transform.forward * -0.2f;
        lerpData.actionDuration = 0.15f;
        lerpData.actionTimer    = 0;

        enemyUnit.StartCoroutine(enemyUnit.CoRoutine_Die(this.transform.position));

        //------------  WaitForSeconds(0.1)  ---------------//
        yield return(new WaitForSeconds(0.1f));

        audioSrc.loop = false;
        audioSrc.clip = clip_Vocal_Attack;
        audioSrc.Play();

        enemyUnit = null;

        transform.position = lerpData.targetPos;
        transform.LookAt(lerpData.targetLookAt);

        //------------  WaitForSeconds(1.25)  ---------------//
        yield return(new WaitForSeconds(1.25f));

        navMeshAgent.enabled = true;
        currentState         = UnitState.notAttacking;
    }
    // Function to trigger enemy attack. Enemy attack scripts will be triggered here.
    IEnumerator AttackPC()
    {
        hasAttacked     = true;
        agent.isStopped = true;
        agent.ResetPath();
        agent.isStopped = false;
        animator.SetBool("running", false);

        // yield return here to wait for rotate to finish before continuing with the function.
        yield return(StartCoroutine(RotateTowardPlayer()));

        // ** Add attack trigger here.
        StartCoroutine(charTemplate.AttackTarget(nearestPC));

        // Adjust this wait time as needed for enemy attack animation to finish.
        yield return(new WaitForSecondsRealtime(2));

        Debug.Log("Attack over");
        currentState                 = UnitState.None;
        inAction                     = false;
        agent.stoppingDistance       = 0;
        unitTurnOver                 = true;
        turnManager.currentEnemyDone = true;
    }
Example #33
0
    public bool BuildUnit()
    {
        bool buildResult = false;
        if (allowedBuildLocation && GetIsPosWalkable(this.transform.position)) {
            if (playerOwner.PlayerGold >= this.GoldCost) {
                playerOwner.PlayerGold -= this.GoldCost;
                StatsCollector.TotalGoldSpent += this.GoldCost;
                playerOwner.unitsList.Add(this);
                currentUnitState = UnitState.PLACED;
                Invoke("activateTAIS", 0.25f);
                buildResult = true;
                playerOwner.ClearPlacingUnit();
                StatsCollector.AmountOfUnitsBought++;
            }
            else {
                playerOwner.DisplayFeedbackMessage("You do not have enough gold.");
            }
        }
        else {
            playerOwner.DisplayFeedbackMessage("You cannot build at that location.");
        }

        return buildResult;
    }
Example #34
0
    public void Move()
    {
        if (path.Count > 0)
        {
            Vector2Int t = path.Peek();
            //Debug.Log("t: " + t.x + "," + t.y);
            Vector3 target = new Vector3(t.x, transform.localPosition.y, t.y);

            //calculate the unit's position on top of the target tile
            ///MOVE
            if (Vector3.Distance(transform.localPosition, target) >= 0.15f)
            {
                CalculateHeading(target);
                SetHorizontalVelocity();

                //Locomotion
                transform.forward        = heading;
                transform.localPosition += velocity * Time.deltaTime;
            }
            else ///TILE DONE
            {
                //tile center reached
                transform.localPosition = target;
                //GridManager.UpdateUnitPosition(this, new Vector2(t.transform.localPosition.x, t.transform.parent.localPosition.z));
                path.Pop();

                //remainingMove--;
            }
        }
        else ///DONE MOVING
        {
            //Debug.Log("done moving");
            //state = UnitState.SelectingActionTarget;
            state = UnitState.AwaitingChoice;
        }
    }
Example #35
0
 public static bool IsUnitState(this Unit unit, UnitState state)
 {
     return(unit.UnitState.HasFlag(state));
 }
Example #36
0
 public void ReturnToPriorState()
 {
     state = priorState;
     UIManager.Instance.ListenForBattleUI(state == UnitState.ACTIVE);
     Debug.Log("Unit state is now: " + state);
 }
Example #37
0
    private void RunTAIS(Tactics tactic, Target target)
    {
        Entity tacTarget = GetTacticalTarget(target, playerOwner.unitsList);
        if (isHealer) {
            if (tacTarget == null || (tacTarget.CurrentHitPoints > tacTarget.MaxHitPoints * HealThreshold)) {
                tacTarget = GetMostDamagedUnit(playerOwner.unitsList);
            }

            if (tacTarget != null && (tacTarget.CurrentHitPoints <= tacTarget.MaxHitPoints * HealThreshold)) {
                if (GetIsWithinPerceptionRange(tacTarget)) {
                    healTarget = tacTarget;
                    this.currentUnitState = UnitController.UnitState.HEALING;
                }
            }
        }

        if (!isHealer || (isHealer && healTarget == null)) {
            if (tactic == Tactics.Guard) {
                attackTarget = GuardOther(tacTarget);
            }
            else if (tactic == Tactics.Follow) {
                attackTarget = FollowOther(tacTarget);
            }
            else if (tactic == Tactics.HoldTheLine) {
                attackTarget = StandGround(playerOwner.unitsList);
            }
            else {
                tacTarget = GetTacticalTarget(target, _gameController.enemies);
                if (GetIsWithinPerceptionRange(tacTarget)) {
                    attackTarget = tacTarget;
                }
            }

            // self defense fallback
            if ((attackTarget == null && lastAttacker != null) && GetIsWithinPerceptionRange(lastAttacker)) {
                attackTarget = lastAttacker;
            }
        }
    }
Example #38
0
 public void SetState(UnitState state)
 {
     UnitState.MakeTransition(state);
 }
Example #39
0
    IEnumerator OrderRoutine()
    {
        while (true)
        {
            if (BuildScript.m_IsBuild && m_IsSelect == true && transform.tag == "UnitLego")
            {
                m_Animator.SetBool("IsMineral", false);
                yield return(StartCoroutine("BuildRoutine"));

                StopCoroutine("OrderRoutine");
            }

            else if (m_IsPick)
            {
                if (IsInputRight() && TouchScript.m_Instance.IsOver)
                {
                    //m_IsStartToMove = true;
                    // SelectUnitScript.m_Instance.StopCoroutine("SelectRoutine");
                    // SelectUnitScript.m_Instance.StartCoroutine("SelectRoutine");
                    imgSelectbar.enabled = false;
                    imgHpbar.enabled     = false;
                    SelectUnitScript.m_Instance.SelectedUnit.Remove(transform.GetComponent <PlayerMove>());
                    Ray        ray = Camera.main.ScreenPointToRay(InputSpot());
                    RaycastHit hit;
                    if (Physics.Raycast(ray, out hit, Mathf.Infinity))
                    {
                        Debug.DrawRay(Camera.main.transform.position, hit.point - Camera.main.transform.position, Color.red);
                        HitOb = hit.collider.gameObject;
                        if (HitOb.layer == 30)   // Ground
                        {
                            SelectUnitScript.m_Instance.m_PickImage.transform.position = hit.point;
                            SelectUnitScript.m_Instance.m_PickImage.SetActive(true);
                            unitState = UnitState.walk;
                            m_Animator.SetBool("IsAttack", false);
                            m_Animator.SetBool("IsMineral", false);
                            m_Animator.SetBool("IsHeal", false);
                            m_Animator.SetBool("IsBuild", false);
                            StopCoroutine("AttackByBullet");
                            StopCoroutine("TraceRoutine");
                            StopCoroutine("MineralRoutine");
                            StopCoroutine("HealRoutine");
                            CancelInvoke("AttackByFlare");
                            yield return(StartCoroutine("Picking", hit.point));

                            SelectUnitScript.m_Instance.m_PickImage.SetActive(false);

                            m_IsSelect = false;
                        }
                    }
                }
            }

            else if (m_IsMineral)
            {
                if (IsInputRight())
                {
                    //m_IsStartToMove = true;
                    // SelectUnitScript.m_Instance.StopCoroutine("SelectRoutine");
                    //SelectUnitScript.m_Instance.StartCoroutine("SelectRoutine");
                    imgSelectbar.enabled = false;
                    imgHpbar.enabled     = false;
                    SelectUnitScript.m_Instance.SelectedUnit.Remove(transform.GetComponent <PlayerMove>());
                    Ray        ray = Camera.main.ScreenPointToRay(InputSpot());
                    RaycastHit hit;
                    if (Physics.Raycast(ray, out hit, Mathf.Infinity))
                    {
                        Debug.DrawRay(Camera.main.transform.position, hit.point - Camera.main.transform.position, Color.red);
                        HitOb = hit.collider.gameObject;
                        HitRS = HitOb.GetComponent <ResourceStatus>();
                        if (HitOb.layer == 26)   // Resource
                        {
                            if (transform.tag != "UnitLego")
                            {
                                StopCoroutine("OrderRoutine");
                            }
                            m_Animator.SetBool("IsMineral", false);

                            yield return(StartCoroutine("Picking", hit.point));

                            transform.rotation = Quaternion.LookRotation(hit.transform.position - transform.position);
                            unitState          = UnitState.mineral;
                            yield return(StartCoroutine("MineralRoutine"));
                        }
                    }
                }
            }

            else if (m_IsBoard)
            {
                if (IsInputRight() && TouchScript.m_Instance.IsOver)
                {
                    //m_IsStartToMove = true;
                    SelectUnitScript.m_Instance.StartCoroutine("SelectRoutine");
                    imgSelectbar.enabled = false;
                    imgHpbar.enabled     = false;
                    SelectUnitScript.m_Instance.SelectedUnit.Remove(transform.GetComponent <PlayerMove>());
                    Ray        ray = Camera.main.ScreenPointToRay(InputSpot());
                    RaycastHit hit;
                    if (Physics.Raycast(ray, out hit, Mathf.Infinity))
                    {
                        Debug.DrawRay(Camera.main.transform.position, hit.point - Camera.main.transform.position, Color.red);
                        HitOb = hit.collider.gameObject;
                        HitPM = HitOb.GetComponent <PlayerMove>();
                        if (HitOb.tag == "UnitAirballoon")   // AirUnit
                        {
                            unitState = UnitState.walk;
                            m_Animator.SetBool("IsAttack", false);
                            m_Animator.SetBool("IsMineral", false);
                            m_Animator.SetBool("IsBuild", false);
                            StopCoroutine("AttackByBullet");
                            StopCoroutine("TraceRoutine");
                            yield return(StartCoroutine("Picking", HitOb.transform.position));

                            m_IsSelect = false;
                            //yield return HitPM.StartCoroutine("Landing_TakeOff", false);
                            m_Nav.enabled = false;
                            transform.SetParent(HitPM.BalloonHeight, false);
                            Vector3 UPos  = Vector3.zero;
                            Vector3 URot  = Vector3.zero;
                            Vector3 UScal = Vector3.one;
                            UPos.x -= 5f;
                            URot.z -= 90f;
                            UScal  *= 0.6f;
                            transform.localPosition = UPos;
                            transform.localRotation = Quaternion.Euler(URot);
                            transform.localScale    = UScal;
                            //HitPM.m_IsFull = true;
                            UnitFuncScript.m_Instance.IsAirUnitfull = true;
                            //yield return HitPM.StartCoroutine("Landing_TakeOff", true);
                        }
                    }
                }
            }

            else if (m_IsAttack)
            {
                if (IsInputRight() || m_IsOffensive)
                {
                    TargetPointFalse();

                    //m_IsStartToMove = true;
                    //SelectUnitScript.m_Instance.StartCoroutine("SelectRoutine");
                    //if (transform.tag == "UnitLego" || transform.tag == "UnitClockMouse")
                    //{
                    //    m_IsSelect = false;
                    //    break;
                    //}

                    Ray        ray = Camera.main.ScreenPointToRay(InputSpot());
                    RaycastHit hit;

                    if (Physics.Raycast(ray, out hit, Mathf.Infinity) || m_IsOffensive)
                    {
                        Debug.DrawRay(Camera.main.transform.position, hit.point - Camera.main.transform.position, Color.red);
                        //SelectUnitScript.m_Instance.SelectedUnit.Remove(transform.GetComponent<PlayerMove>());
                        HitOb = hit.collider.gameObject;
                        UnitFuncScript.m_Instance.ClearFunc();
                        if ((HitOb.layer == 28 &&
                             !SelectUnitScript.m_Instance.IsUnitMyTeam(HitOb.GetComponent <PlayerMove>())) || m_IsOffensive)    // Unit
                        {
                            m_IsPM = true;
                            m_IsBS = false;
                            if (m_IsOffensive)
                            {
                                hit.point = HitPM.gameObject.transform.position;
                                goto offensive;
                            }
                            HitPM = HitOb.GetComponent <PlayerMove>();
                            offensive :;
                            HitPM.m_IsSelect           = false;
                            HitPM.imgSelectbar.enabled = false;
                            HitPM.m_Damage             = m_Power;
                            SelectUnitScript.m_Instance.SelectedUnit.Remove(HitPM);
                            SelectUnitScript.m_Instance.SelectedUnit.Remove(transform.GetComponent <PlayerMove>());

                            unitState = UnitState.attack;
                            yield return(StartCoroutine("Picking", hit.point));

                            switch (transform.tag)
                            {
                            case "UnitSoldier":
                            {
                                InvokeRepeating("AttackByBullet", 0f, 1.0f);
                                //HitPM.StartCoroutine("DamageRoutine");
                                //StartCoroutine("AttackByBullet");
                                yield return(StartCoroutine("ConditionForAttack", "no"));

                                CancelInvoke("AttackByBullet");
                                //StopCoroutine("AttackByBullet");
                                m_IsAttack = false;
                                break;
                            }

                            case "UnitBear":
                            {
                                StartCoroutine("BearAttackRoutine");
                                yield return(StartCoroutine("ConditionForAttack", "no"));

                                StopCoroutine("BearAttackRoutine");
                                m_IsAttack = false;
                                break;
                            }

                            case "UnitDinosaur":
                            {
                                InvokeRepeating("AttackByFlare", 1.8f, 1.5f);
                                yield return(StartCoroutine("ConditionForAttack", "no"));

                                CancelInvoke("AttackByFlare");
                                m_IsAttack = false;
                                break;
                            }

                            case "UnitRCcar":
                            {
                                CarAttakArea.gameObject.SetActive(true);
                                yield return(StartCoroutine("ConditionForAttack", "no"));

                                CarAttakArea.gameObject.SetActive(false);
                                m_IsAttack = false;
                                break;
                            }

                            default:
                                break;
                            }
                        }

                        else if (hit.transform.gameObject.layer == 27 &&
                                 !SelectUnitScript.m_Instance.IsBuildingMyTeam(hit.transform.GetComponent <BuildingStatus>())) // Building
                        {
                            //NoticeScript.m_Instance.Notice("빌딩 타겟 완료\n");
                            m_IsPM                     = false;
                            m_IsBS                     = true;
                            HitBS                      = HitOb.GetComponent <BuildingStatus>();
                            HitBS.m_IsSelect           = false;
                            HitBS.imgSelectbar.enabled = false;
                            HitBS.m_Damage             = m_Power;
                            unitState                  = UnitState.attack;
                            yield return(StartCoroutine("Picking", hit.point));

                            transform.rotation = Quaternion.LookRotation(hit.transform.position - transform.position);
                            m_Animator.SetBool("IsAttack", true);
                            switch (transform.tag)
                            {
                            case "UnitSoldier":
                            {
                                yield return(StartCoroutine("ConditionForAttack", "AttackByBullet"));

                                m_IsAttack = false;
                                break;
                            }

                            case "UnitBear":
                            {
                                yield return(StartCoroutine("ConditionForAttack", "BearAttackRoutine"));

                                m_IsAttack = false;
                                break;
                            }

                            case "UnitDinosaur":
                            {
                                yield return(StartCoroutine("ConditionForAttack", "AttackByFlare"));

                                break;
                            }

                            case "UnitRCcar":
                            {
                                CarAttakArea.gameObject.SetActive(true);
                                yield return(StartCoroutine("ConditionForAttack", "AttackByCar"));

                                CarAttakArea.gameObject.SetActive(false);
                                m_IsAttack = false;
                                break;
                            }

                            default:
                                break;
                            }
                        }
                    }
                }
            }

            else if (m_IsHeal)
            {
                imgSelectbar.enabled = false;
                imgHpbar.enabled     = false;
                //SelectUnitScript.m_Instance.SelectedUnit.Remove(transform.GetComponent<PlayerMove>());
                m_IsSelect = false;
                HealEffect.SetActive(true);
                yield return(StartCoroutine("HealRoutine"));

                HealEffect.SetActive(false);
                HealArea.gameObject.SetActive(false);
                m_IsSelect = false;
            }

            yield return(null);
        }
    }
Example #40
0
 void TransitionToState(UnitState state, float delay)
 {
     countdownToNextState = delay;
     nextState            = state;
 }
Example #41
0
    protected override void RemoveSelf()
    {
        base.RemoveSelf();

        GameObject[] points = GameObject.FindGameObjectsWithTag("Waypoint");
        foreach (GameObject point in points) {
            if (point.transform.name.Contains("End")) {
                LastBuildLocation = point.transform.position;
                break;
            }
        }
        LastBuildLocation.x += Random.Range(-1f, 1f);
        LastBuildLocation.z += Random.Range(-1f, 1f);
        currentUnitState = UnitState.DEAD;
        Deselect(playerOwner.SelectedUnits);
    }
    private void MovementUpdate() {
        position = transform.position;

        // Find next waypoint
        Vector3 next = Vector3.zero;
        Vector3 nextSpot = Vector3.zero;
        if (wayPoints != null && wayPoints.Count > 0) {
            next = wayPoints.Peek();
            nextSpot = next + ((lastWayPoint == Vector3.zero || wayPoints.Count == 1) ? Vector3.zero : (next - lastWayPoint).normalized * wayPointRange);

            while (wayPoints.Count > 0 && (nextSpot - position).sqrMagnitude < wayPointRange * wayPointRange) {
                lastWayPoint = wayPoints.Dequeue();
                if (wayPoints.Count > 0) {
                    next = wayPoints.Peek();
                    nextSpot = next + ((lastWayPoint == Vector3.zero || wayPoints.Count == 1) ? Vector3.zero : (next - lastWayPoint).normalized * wayPointRange);
                } else if (state == UnitState.MOVING) {
                    state = UnitState.IDLE;
                    standPoint = lastWayPoint;
                }
            }
        }
        if (wayPoints == null || wayPoints.Count == 0) lastWayPoint = Vector3.zero;

        // Check line of sight to the next way point
        pathFindingRecheckTimer -= U.limitedDeltaTime;
        if (pathFindingRecheckTimer <= 0) {
            bool jumped = false;
            if (wayPoints != null && wayPoints.Count > 1) {
                Queue<Vector3>.Enumerator e = wayPoints.GetEnumerator();
                e.MoveNext(); e.MoveNext();
                Vector3 nextnext = e.Current;
                if (space.LineOfSight(position, nextnext, false, true)) {
                    lastWayPoint = wayPoints.Dequeue();
                    next = wayPoints.Peek();
                    nextSpot = next + (wayPoints.Count == 1 ? Vector3.zero : (next - lastWayPoint).normalized * wayPointRange);
                    jumped = true;
                }
            }
            if (!jumped && wayPoints != null && wayPoints.Count > 0 && !space.LineOfSight(position, next, false, true)) {
                List<Node> tempPath = spaceGraph.FindPath(spaceGraph.LazyThetaStar, position, next, space);
                if (tempPath != null) {
                    Queue<Vector3> newPath = new Queue<Vector3>();
                    foreach (Node node in tempPath) {
                        newPath.Enqueue(node.center);
                    }
                    wayPoints.Dequeue();
                    while (wayPoints.Count > 0) newPath.Enqueue(wayPoints.Dequeue());
                    wayPoints = newPath;
                }
            }
            pathFindingRecheckTimer += pathFindingRecheckInterval;
        }

        // Accelerate to target velocity
        Vector3 targetVelocity = Vector3.zero;
        if (wayPoints != null && wayPoints.Count > 0) {
            targetVelocity = (nextSpot - position).normalized * maxVelocity;
        }
        if ((targetVelocity - velocity).sqrMagnitude < U.Sq(acceleration * U.limitedDeltaTime)) {
            velocity = targetVelocity;
        } else {
            velocity += (targetVelocity - velocity).normalized * acceleration * U.limitedDeltaTime;
        }

        // Repulsive force from SpaceUnits
        Collider[] touch = Physics.OverlapSphere(position, radius + repulsiveRadius);
        foreach (Collider col in touch) {
            SpaceUnit ship = col.GetComponent<SpaceUnit>();
            if (ship != null) {
                float d = (ship.position - position).magnitude - radius - ship.radius;
                Vector3 acc = (position - ship.position).normalized * repulsiveCoeff * Mathf.Pow(1 - Mathf.Clamp01(d / repulsiveRadius), repulsivePow);
                //Vector3 acc = (position - ship.position).normalized * repulsiveCoeff / (d + radius) / (d + radius);
                velocity += acc * U.limitedDeltaTime;
            }
        }

        // Repulsive force from walls
        for (int i = 0; i < 16; i++) {
            Ray ray = new Ray(position, Random.onUnitSphere);
            RaycastHit res;
            if (Physics.Raycast(ray, out res, radius + repulsiveRadius) && res.collider.GetComponent<SpaceUnit>() == null) {
                float d = (res.point - position).magnitude - radius;
                Vector3 acc = (position - res.point).normalized * repulsiveCoeff * Mathf.Pow(1 - Mathf.Clamp01(d / repulsiveRadius), repulsivePow);
                velocity += acc * U.limitedDeltaTime / 16 * 8;
            }
        }
        position += velocity * U.limitedDeltaTime;

        // Update position
        transform.position = position;
        if (targetVelocity.sqrMagnitude > 0.0001f) {
            //transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(targetVelocity), Time.deltaTime * 5);
            transform.rotation = Quaternion.Lerp(Quaternion.identity, Quaternion.FromToRotation(transform.forward, targetVelocity), U.limitedDeltaTime * 5) * transform.rotation;
        }
        Rigidbody body = GetComponent<Rigidbody>();
        body.velocity = Vector3.zero;
        body.angularVelocity = Vector3.zero;
        if (Settings.showShipTrajectory) {
            DrawTrajectory();
        } else if (line != null) {
            ClearTrajectory();
        }
    }
 public void MoveOrder(List<Node> wp, float range) {
     if (wp == null || !movable) return;
     wayPoints = new Queue<Vector3>();
     foreach (Node node in wp) {
         wayPoints.Enqueue(node.center);
     }
     wayPointRange = range;
     state = UnitState.MOVING;
 }
Example #44
0
    // Update is called once per frame
    void Update()
    {
        switch(currentState)
        {
            case UnitState.CREATED:	// Creation stuff if applicable;
                SetState(2);
                matchController.inAction = false;
                break;
            case UnitState.IDLE:

                break;
            case UnitState.MOVING:
                //Debug.Log("Unit Moving");
                //Debug.Log(transform.position.x);
                //Debug.Log(targetDestination.x);
                //Debug.Log(transform.position.z);
                //Debug.Log(targetDestination.z);
                //HighlightAll();

              	//animate walk
                animation.Play("Walk");
                //targetDestination = movementArray[ movementArrayIndex ];
                // Smoothly rotates towards target

                setUnitRotation( targetDestination );

                if ( movementArray.Count > 0 ){
                    Vector3 NextPositionDestination = movementArray[ movementArray.Count - 1 ];
                    if(transform.position.x != NextPositionDestination.x || transform.position.z != NextPositionDestination.z)
                    {
                        transform.position = Vector3.MoveTowards(transform.position, new Vector3(NextPositionDestination.x, transform.position.y, NextPositionDestination.z), Time.deltaTime * moveSpeed);
                    }
                    else
                    {
                        movementArray.RemoveAt( movementArray.Count - 1  );
                    }

                }
                else
                if(transform.position.x != targetDestination.x || transform.position.z != targetDestination.z)
                {
                    transform.position = Vector3.MoveTowards(transform.position, new Vector3(targetDestination.x, transform.position.y, targetDestination.z), Time.deltaTime * moveSpeed);
                }
                else
                {
                    animation.CrossFade("Idle");
                    currentState = UnitState.IDLE;
                    matchController.inAction = false;
                    movementArray.Clear();

                    GameObject pObj_;
                    pObj_ = GameObject.FindWithTag("oAStar");
                    AStarTest AStar;
                    AStar = pObj_.GetComponent<AStarTest>();
                    AStar.movementArray.Clear();
                    AStar._ClearAStarGridMap();
                    matchController.UnHighlightTiles();
                }
                break;
            case UnitState.ATTACKING:

                //Debug.Log( "HI" );
                animation.CrossFade("Idle");
                currentState = UnitState.IDLE;
                matchController.inAction = false;
                break;
            case UnitState.TAKEHIT:
                break;
            case UnitState.DIEING:
                break;
            case UnitState.DEAD:
                Debug.Log( "dead" );
                Destroy( gameObject );
                break;
        }
    }
Example #45
0
    // Use this for initialization
    void Start()
    {
        if ( unitDiag == false )
        moveRangeDiag = moveRangeLR - ( moveRangeLR - 1 );
        else moveRangeDiag = moveRangeLR;

        rayHitPoint = new Vector3( 0.0f , 0.0f , 0.0f );
        onTileIndex = 0;//maybe scan tile array at start ?
        //renderer.material.color = new Color( 1 , 1 , 1 , 0.5f );
        gameObject.AddComponent("InputInterface");

        //matchController = GameObject.Find("MatchControllerObj").GetComponent<MatchController>();
        gameObject.tag = "Unit";

        movementArray = new List<Vector3>();

        GameObject pObj_;
        pObj_ = GameObject.FindWithTag("oScene0");
        scene0Script = pObj_.GetComponent<JTSScene0>();
        tilesArray = scene0Script.tileArray;
        enemyArray = scene0Script.enemyArray_debug;

        currentState = UnitState.CREATED;
    }
 public Unit(UnitIdentifier unitIdentifier, UnitData unitData)
 {
     UnitIdentifier = unitIdentifier;
     UnitData       = unitData;
     UnitState      = new UnitState(unitData.MaxHp);
 }
Example #47
0
 public virtual void SetMovement()
 {
     agent.isStopped = false;
     anim.SetBool("IsMoving", true);
     state = UnitState.Movement;
 }
Example #48
0
 public AIUnitController(UnitData data, UnitBehaviour behaviour, UnitState startingState) : base(data, behaviour, startingState)
 {
     targetLocations       = new List <Vector3>();
     currentTargetLocation = 0;
 }
Example #49
0
 public bool CheckForState(UnitState state) => (state & UnitState.Hexed) == 0;
Example #50
0
	public void OnThisDeath( UnitState.UnitStateEventArgs args ) {
		state.OnDeath -= OnThisDeath;
		motor.RagDoll (true);
		
	}
        /// <summary>
        ///     The is unit state.
        /// </summary>
        /// <param name="unit">
        ///     The unit.
        /// </param>
        /// <param name="state">
        ///     The state.
        /// </param>
        /// <returns>
        ///     The <see cref="bool" />.
        /// </returns>
        public static bool IsUnitState(this Unit unit, UnitState state)
        {
            if (unit == null || !unit.IsValid)
            {
                return false;
            }

            return unit.UnitState.HasFlag(state);
        }
Example #52
0
 private void UpdateUnitState(UpdateUnitStateMessage msg)
 {
     _unitState = msg.State;
 }
Example #53
0
    IEnumerator BuildRoutine()
    {
        UnitFuncScript.m_Instance.ClearFunc();
        m_IsBuild            = true;
        imgSelectbar.enabled = false;
        Building             = BuildScript.BuildingTemp;
        Building.GetComponentInChildren <Renderer>().material.color = Color.red;
        unitState = UnitState.walk;
        m_Animator.SetBool("IsPick", true);
        BuildScript.m_IsBuild = false;
        float dis = 0.0f;

        switch (Building.tag)
        {
        case "B_ToyFactory": dis = 6f; break;

        default: dis = 4f; break;
        }
        NavMesh.CalculatePath(transform.position, BuildScript.BuildPos, NavMesh.AllAreas, m_Path);
        Vector3[] Corners = m_Path.corners;
        int       Index   = 1;

        while (Index < Corners.Length)
        {
            Debug.DrawRay(Camera.main.transform.position, BuildScript.BuildPos - Camera.main.transform.position, Color.red);
            m_Dir = (Corners[Index] - transform.position).normalized;
            transform.position += m_Dir * m_MoveSpeed * Time.deltaTime;
            transform.rotation  = Quaternion.LookRotation(m_Dir);
            if (Vector3.Distance(transform.position, Corners[Index]) < dis)
            {
                Index++;
            }
            yield return(null);
        }

        //Building.GetComponent<NavMeshObstacle>().enabled = true;
        transform.rotation    = Quaternion.LookRotation(BuildScript.BuildPos - transform.position);
        BuildScript.m_IsBuild = false;
        unitState             = UnitState.build;
        m_Animator.SetBool("IsPick", false);
        m_Animator.SetBool("IsBuild", true);

        yield return(new WaitForSeconds(5.0f));

        Building.GetComponentInChildren <Renderer>().material.color = Color.white;
        unitState = UnitState.idle;
        m_Animator.SetBool("IsBuild", false);
        m_IsSelect = false;
        SelectUnitScript.m_Instance.SelectedUnit.Remove(transform.GetComponent <PlayerMove>());
        m_IsBuild = false;

        switch (Building.tag)
        {
        case "B_Zenga":
            BuildScript.AttackArea.gameObject.SetActive(true);
            break;

        case "B_ToyFactory":
            FactoryScript FactoryFunc = Building.GetComponent <FactoryScript>();
            FactoryFunc.enabled = true;
            break;

        default:
            break;
        }

        StopCoroutine("BuildRoutine");
    }
Example #54
0
 private static void PropagateStateChange(Unit source, UnitState next_state)
 {
     UnitStateChange?.Invoke(source, next_state);
 }
Example #55
0
    IEnumerator TraceRoutine()
    {
        float tracedis = 0.0f;

        switch (transform.tag)
        {
        case "UnitSoldier":
            tracedis = 5f;
            break;

        case "UnitDinosaur":
            tracedis = 8f;
            break;

        case "UnitBear":
            tracedis = 2f;
            break;

        case "UnitRCcar":
            tracedis = 2f;
            break;

        default: tracedis = 2f;
            break;
        }

        while (HitPM != null)    //(HitPM.m_IsAlive)
        {
            if (HitPM.m_Hp <= 0) //(!HitPM.m_IsAlive)
            {
                HitPM.m_Hp                 = 0f;
                imgHpbar.enabled           = false;
                HitPM.imgHpbar.enabled     = false;
                HitPM.imgSelectbar.enabled = false;
                HitPM.unitState            = UnitState.die;
                // HitPM.m_Animator.SetBool("IsDie", true);
                // HitPM.Invoke("Death",3f);
                // HitPM.m_IsAlive = false;
                m_IsPM     = false;
                m_IsAttack = false;
                unitState  = UnitState.idle;
                m_Animator.SetBool("IsPick", false);
                m_Animator.SetBool("IsAttack", false);
                StopAllCoroutines();
            }

            Debug.Log("추적 루틴 실행중");


            if (Vector3.Distance(transform.position, HitPM.transform.position) >= (tracedis + 3f))//8.5f)
            {
                if (transform.tag == "UnitRCcar")
                {
                    CarAttakArea.gameObject.SetActive(false);
                }
                m_Animator.SetBool("IsPick", true);
                m_Animator.SetBool("IsAttack", false);
                m_Attackstop = true;
                //m_Nav.enabled = true;

                NavMesh.CalculatePath(transform.position, HitPM.transform.position, NavMesh.AllAreas, m_Path);
                Vector3[] TraceCorners = m_Path.corners;
                int       TraceIndex   = 1;
                while (TraceIndex < TraceCorners.Length)
                {
                    m_Dir = (TraceCorners[TraceIndex] - transform.position).normalized;
                    transform.position += m_Dir * m_MoveSpeed * Time.deltaTime;
                    transform.rotation  = Quaternion.LookRotation(m_Dir);
                    if (Vector3.Distance(transform.position, TraceCorners[TraceIndex]) < tracedis)
                    {
                        TraceIndex++;
                    }
                    yield return(null);
                }
            }

            else
            {
                m_Animator.SetBool("IsPick", false);
                m_Animator.SetBool("IsAttack", true);
                if (transform.tag == "UnitRCcar")
                {
                    CarAttakArea.gameObject.SetActive(true);
                }
                m_Attackstop = false;
            }


            transform.rotation = Quaternion.LookRotation(HitPM.transform.position - transform.position);
            yield return(null);
        }
    }
Example #56
0
 public virtual void UnitStateChange(UnitState newState)
 {
     state = newState;
 }
Example #57
0
 public void SelectTarget(Unit targetUnit)
 {
     targetEnemy = targetUnit;
     Look(targetEnemy.transform.position);
     unitState = UnitState.Attack;
 }
Example #58
0
    protected virtual void ReplacingBehaviour()
    {
        if (this.playerOwner != null) {
            if (_gameController.CurrentPlayState == GameController.PlayState.COMBAT) {
                currentUnitState = UnitState.PLACED;
            }

            Ray ray = playerOwner.GetComponentInChildren<Camera>().ScreenPointToRay(Input.mousePosition);
            foreach (RaycastHit hit in Physics.RaycastAll(ray)) {
                if (hit.collider.GetType() == typeof(TerrainCollider)) {
                    float height = Terrain.activeTerrain.SampleHeight(new Vector3(hit.point.x, 0f, hit.point.z));
                    height += this.transform.collider.bounds.size.y/2f + 0.1f;
                    Vector3 newPos = new Vector3(hit.point.x, height, hit.point.z);
                    if (this.GetIsPosWalkable(newPos)) {
                        this.transform.position = newPos;
                    }

                    break;
                }
            }

            checkForCollisions();

            DrawRangeCircles();
        }
    }
 private Unit(UnitIdentifier unitIdentifier, UnitData unitData, UnitState unitState)
 {
     UnitIdentifier = unitIdentifier;
     UnitData       = unitData;
     UnitState      = unitState;
 }
Example #60
0
 public void SetState( int newState )
 {
     previousState = currentState;
     currentState = (UnitState)newState;
 }