Пример #1
0
    public void ActivateTriggerDetection(UnitAI _sender, bool _activate)
    {
        CurAi       = _sender;
        equip       = CurAi.GetComponent <UnitEquip>();
        unit        = CurAi.GetComponent <Unit>();
        senderTrans = _sender.transform;

        switch (triggerType)
        {
        case TriggerType.OnEnter:
            DoEnterDetection(_activate);
            break;

        case TriggerType.OnExit:
            DoExitDetection(_activate);
            break;

        case TriggerType.OnStay:
            DoStayDetection(_activate);
            break;

        case TriggerType.ValueAmount:
            DoValueAmountDetection(_activate);
            break;
        }
    }
Пример #2
0
    void HandleIntercept(Entity ent)
    {
        Intercept intercept = new Intercept(SelectionMgr.inst.selectedEntity, ent);
        UnitAI    uai       = SelectionMgr.inst.selectedEntity.GetComponent <UnitAI>();

        AddOrSet(uai, intercept);
    }
Пример #3
0
    void Update()
    {
        if (_hasCreatingUnit)
        {
            _timeBeforeSpawn -= Time.deltaTime;
            if (_timeBeforeSpawn <= 0)
            {
                Quaternion unitRotation = new Quaternion();
                unitRotation.eulerAngles = _spawnRotation;
                unitRotation             = transform.rotation * unitRotation;

                UnitAI newUnit = GameObjectManager.CreateObject(_currentTaskData.Prefab, PositionChecker.FindNearestFreePosition(transform.TransformPoint(_spawnPoint)), unitRotation).GetComponent <UnitAI>();
                GameObjectManager.AddToPlayerObjectsList(OwnerPlayer, newUnit.transform);

                ////отправка юнита в пункт сбора
                //var message = new TaskDataMessage {
                //    TaskData = new FollowToPoint_Task.FollowToPoint_TaskData(AssemblyPoint ),
                //    NewQueue = true
                //};
                //newUnit.AddTask(message);

                DequeueUnitData();
            }
        }
    }
Пример #4
0
    public void DoEvent(UnitAITrigger _trigger, int _index, Collider _col = null)
    {
        curAI = _trigger.CurAi;
        if (!equip)
        {
            equip = curAI.GetComponent <UnitEquip>();
        }
        index    = _index;
        finished = false;

        if (_col)
        {
            curTarget = _col;
        }

        if (startType == StartType.Instant)
        {
            StartEvent();
        }
        else if (startType == StartType.WaitForPreviousToFinish && index > 0)
        {
            if (waitRoutine != null)
            {
                curAI.StopCoroutine(waitRoutine);
            }

            waitRoutine = curAI.StartCoroutine(StartWaitForPrevious(_trigger));
        }
    }
Пример #5
0
 public virtual void OnEnable()
 {
     source    = (UnitAI)target;
     sourceRef = serializedObject;
     SetupGUIStyle();
     GetProperties();
 }
Пример #6
0
        public void EndCombat()
        {
            // sequencing matters here - AI might do nasty stuff, so make sure refs are in a consistent state before you hand off!

            // first, get rid of any threat that still exists...
            first.GetThreatManager().ClearThreat(second);
            second.GetThreatManager().ClearThreat(first);

            // ...then, remove the references from both managers...
            first.GetCombatManager().PurgeReference(second.GetGUID(), _isPvP);
            second.GetCombatManager().PurgeReference(first.GetGUID(), _isPvP);

            // ...update the combat state, which will potentially remove IN_COMBAT...
            bool needFirstAI  = first.GetCombatManager().UpdateOwnerCombatState();
            bool needSecondAI = second.GetCombatManager().UpdateOwnerCombatState();

            // ...and if that happened, also notify the AI of it...
            if (needFirstAI)
            {
                UnitAI firstAI = first.GetAI();
                if (firstAI != null)
                {
                    firstAI.JustExitedCombat();
                }
            }
            if (needSecondAI)
            {
                UnitAI secondAI = second.GetAI();
                if (secondAI != null)
                {
                    secondAI.JustExitedCombat();
                }
            }
        }
Пример #7
0
    public void AddUnit(UnitAI unit)
    {
        if (population.Count < MAX_POSSIBLE_POPULATION)
        {
            population.Add(unit);
            unit.unit.government = this;
            unit.unit.team       = this.team;

            unit.transform.parent = this.transform;
            unit.tag = this.tag;
            //TODO: Optimize this
            foreach (var renderer in unit.GetComponentsInChildren <MeshRenderer>())
            {
                renderer.sharedMaterial = unitMaterial;
            }
            foreach (var renderer in unit.GetComponentsInChildren <SkinnedMeshRenderer>())
            {
                renderer.sharedMaterial = unitMaterial;
            }
        }
        else
        {
            Debug.LogError("TOO MANY PEOPLE");
        }
    }
Пример #8
0
    void HandleFollow(Entity ent)
    {
        Follow f   = new Follow(SelectionMgr.inst.selectedEntity, ent, new Vector3(10, 0, 0));
        UnitAI uai = SelectionMgr.inst.selectedEntity.GetComponent <UnitAI>();

        AddOrSet(uai, f);
    }
Пример #9
0
        public void UpdateCharmAI()
        {
            if (IsCharmed())
            {
                UnitAI newAI = null;
                if (IsPlayer())
                {
                    Unit charmer = GetCharmer();
                    if (charmer != null)
                    {
                        // first, we check if the creature's own AI specifies an override playerai for its owned players
                        Creature creatureCharmer = charmer.ToCreature();
                        if (creatureCharmer != null)
                        {
                            CreatureAI charmerAI = creatureCharmer.GetAI();
                            if (charmerAI != null)
                            {
                                newAI = charmerAI.GetAIForCharmedPlayer(ToPlayer());
                            }
                        }
                        else
                        {
                            Log.outError(LogFilter.Misc, $"Attempt to assign charm AI to player {GetGUID()} who is charmed by non-creature {GetCharmerGUID()}.");
                        }
                    }
                    if (newAI == null) // otherwise, we default to the generic one
                    {
                        newAI = new SimpleCharmedPlayerAI(ToPlayer());
                    }
                }
                else
                {
                    Cypher.Assert(IsCreature());
                    if (IsPossessed() || IsVehicle())
                    {
                        newAI = new PossessedAI(ToCreature());
                    }
                    else
                    {
                        newAI = new PetAI(ToCreature());
                    }
                }

                Cypher.Assert(newAI != null);
                SetAI(newAI);
                newAI.OnCharmed(true);
            }
            else
            {
                RestoreDisabledAI();
                // Hack: this is required because we want to call OnCharmed(true) on the restored AI
                RefreshAI();
                UnitAI ai = GetAI();
                if (ai != null)
                {
                    ai.OnCharmed(true);
                }
            }
        }
 public UnitActionTransition(UnitAI ai, UnitAction from, UnitAction to, UnitFunction precondition, double propability = 1.0)
 {
     _ai = ai;
     _from = from;
     _to = to;
     _precondition = precondition;
     _propability = propability;
 }
Пример #11
0
    private static UnitAI MakeAI(ScriptableUnitConfig data, int group, GameObject base_unit, Unit m_unit)
    {
        UnitAI ai = m_unit.gameObject.AddComponent <UnitAI>();

        ai.group_id = group;

        return(ai);
    }
Пример #12
0
    private UnitAI CreateDefender(UnitAI archerPrefab, Transform parent)
    {
        UnitAI CurUnit = Instantiate(archerPrefab, parent.position, Quaternion.identity, parent) as UnitAI;

        DefenderList.Add(CurUnit);
        FindTargetForDefenders();
        return(CurUnit);
    }
Пример #13
0
 public AIAggroEvent(UnitAI _ai, Unit _target)
 {
     ai       = _ai;
     target   = _target;
     rotator  = ai.GetComponentInChildren <UnitRotationController>();
     animator = ai.GetComponentInChildren <UnitAnimationController>();
     MDebug.Log("Turnevent Queue start aggro");
     Execute(0);
 }
Пример #14
0
 void AddOrSet(UnitAI uai, Command c)
 {
     if (Input.GetKey(KeyCode.LeftShift))
     {
         uai.AddCommand(c);
     }
     else
     {
         uai.SetCommand(c);
     }
 }
Пример #15
0
 public void SuppressFor(Unit who)
 {
     Suppress(who);
     if (who.GetCombatManager().UpdateOwnerCombatState())
     {
         UnitAI ai = who.GetAI();
         if (ai != null)
         {
             ai.JustExitedCombat();
         }
     }
 }
Пример #16
0
    public void ActivateAllEvents(UnitAI _sender, bool _activate)
    {
        if (unitAITriggers.Count < 1)
        {
            return;
        }

        curAI = _sender;

        for (int i = 0; i < unitAITriggers.Count; i++)
        {
            ActivateEvent(i, _activate);
        }
    }
Пример #17
0
    public void CreateIntercept(Entity source, Entity target, bool isAdd)
    {
        Intercept intercept = new Intercept(source, target);
        UnitAI    uai       = source.GetComponent <UnitAI>();

        if (isAdd)
        {
            uai.AddCommand(intercept);
        }
        else
        {
            uai.SetCommand(intercept);
        }
    }
    protected override void GetProperties(SerializedProperty _property)
    {
        base.GetProperties(_property);

        boldStyle = new GUIStyle
        {
            fontStyle = FontStyle.Bold,
        };

        //get property values
        unitAITriggers = _property.FindPropertyRelative("unitAITriggers");
        source         = fieldInfo.GetValue(_property.serializedObject.targetObject) as UnitAITriggerContainer;
        triggerSource  = source.unitAITriggers;
        aiSource       = _property.serializedObject.targetObject as UnitAI;
        equipSource    = aiSource.GetComponent <UnitEquip>();
    }
Пример #19
0
    void HandleMove(Vector3 point)
    {
        Move   m   = new Move(SelectionMgr.inst.selectedEntity, hit.point);
        UnitAI uai = SelectionMgr.inst.selectedEntity.GetComponent <UnitAI>();

        //AddOrSet(uai, m);

        if (Input.GetKey(KeyCode.LeftShift))
        {
            uai.AddCommand(m);
        }
        else
        {
            uai.SetCommand(m);
        }
    }
Пример #20
0
 // Update is called once per frame
 void Update()
 {
     foreach (Monster mon in monsters)
     {
         close = PlayerCloseEnough(mon);
         if (close)
         {
             //Debug.Log("ADDING INTERCEPT ");
             Intercept intercept = new Intercept(mon, Player.inst);
             UnitAI    uai       = mon.GetComponent <UnitAI>();
             uai.AddCommand(intercept);
             //Debug.Log(mon.velocity);
         }
         //Debug.Log("Player close false ");
     }
 }
Пример #21
0
    public static void TriggerUnitsForGroup(UnitAI unit, Unit triggerer)
    {
        int id = unit.group_id;

        Unit.AllUnits.ForEach(u =>
        {
            if (
                u.OwnerID == 1 &&
                u.gameObject.GetComponent <UnitAI>().group_id == id &&
                u != unit
                )
            {
                u.GetComponent <UnitAI>().Trigger(triggerer);
            }
        }
                              );
    }
Пример #22
0
    public TurnManager(PathFinder p, List<Unit> ally, List<Unit> enemy)
    {
        pathFinder = p;
        ai = new UnitAI(pathFinder);

        playerUnits = ally;
        aiUnits = enemy;

        NextTurn = UIManager.getUIManager().getNextTurnButton();
        Cancel = UIManager.getUIManager().getCancelButton();
        Wait = UIManager.getUIManager().getWaitButton();

        selectionState = State.OurTurnNoSelection;
        UIManager.getUIManager().ChangeButtonState(selectionState);

        toActAI = new Queue<Unit>();
    }
Пример #23
0
    public void DoEvent(UnitAITrigger _trigger, int _index, Collider2D _col = null)
    {
        curAI = _trigger.CurAi;
        index = _index;
        if (_col)
        {
            curTarget = _col;
        }

        if (startType == StartType.Instant)
        {
            curAI.StartCoroutine(StartTriggerEvent());
        }
        else if (startType == StartType.WaitForPreviousToFinish && index > 0)
        {
            curAI.StartCoroutine(StartWaitForPrevious(_trigger));
        }
    }
Пример #24
0
 private void Update()
 {
     for (int i = 0; i < population.Count; ++i)
     {
         UnitAI unit = population[i];
         if (unit.unit.Alive)
         {
             if (updateTime[i] == 0 || updateTime[i] > thinkInterval)
             {
                 unit.Sense();
                 updateTime[i] = 0;
             }
             unit.Think();
             unit.Act();
             updateTime[i] += Time.deltaTime * Random.Range(0.9f, 1.1f);
         }
     }
 }
Пример #25
0
        public Unit(HexPoint point, AbstractPlayerData player, UnitData data)
        {
            _point = point;
            _player = player;
            _data = data;

            Strength = 10;

            _unitAI = _data.DefaultUnitAI;

            UpdateSpotting();

            InitTransitions();
            InitFormation();

            _entity = new UnitEntity(player, this, _data.ModelName);
            _entity.Point = point;
            _entity.Scale = new Vector3(_data.ModelScale);

            _unitActionBillboard = new BillboardSystem<UnitAction>(MainApplication.Instance.GraphicsDevice, MainApplication.Instance.Content);
            _unitActionBillboard.AddEntity(UnitAction.Idle, Provider.GetAtlas("UnitActionAtlas").GetTexture("Idle"), new Vector2(2, 2));
            _unitActionBillboard.AddEntity(UnitAction.Move, Provider.GetAtlas("UnitActionAtlas").GetTexture("Move"), new Vector2(2, 2));
            _unitActionBillboard.AddEntity(UnitAction.BuildFarm, Provider.GetAtlas("UnitActionAtlas").GetTexture("BuildFarm"), new Vector2(2, 2));
            _unitActionBillboard.AddEntity(UnitAction.BuildRoad, Provider.GetAtlas("UnitActionAtlas").GetTexture("BuildRoad"), new Vector2(2, 2));
            _unitActionBillboard.AddEntity(UnitAction.Found, Provider.GetAtlas("UnitActionAtlas").GetTexture("Found"), new Vector2(2, 2));

            UpdateUnitAction();

            // path mesh
            _pathMesh = new Mesh(MainApplication.Instance.GraphicsDevice, "paths");

            if( TextureManager.Instance.Device == null )
                TextureManager.Instance.Device = MainApplication.Instance.GraphicsDevice;

            TextureManager.Instance.Add("paths", MainApplication.Instance.Content.Load<Texture2D>("Content/Textures/Ground/paths"));
            _pathMesh.LoadContent(MainApplication.Instance.Content);
        }
Пример #26
0
 // Update is called once per frame
 void Update()
 {
     if (produceUnits)
     {
         if (unit != null)
         {
             if (unitSpawn != null)
             {
                 if (tSpawn >= unitProductionRate)
                 {
                     // First thing first, reset the clock
                     tSpawn = 0.0f;
                     // Instantiate the gameobject as a Transform to make the "unit" prefab and
                     // the new Unit variable types match
                     Transform newUnit = GameObject.Instantiate(unit, unitSpawn.position, Quaternion.identity) as Transform;
                     // Unity makes me write out an extra line delcaring the component as a new temp. variable
                     UnitAI tempAiComp = newUnit.GetComponent <UnitAI>();
                     tempAiComp.owner       = transform.gameObject;
                     tempAiComp.destination = new Vector3(0, 0, 20);
                 }
                 else
                 {
                     tSpawn += Time.deltaTime;
                 }
             }
             else
             {
                 Debug.LogError("No unit spawn found for : " + transform.name.ToString());
             }
         }
         else
         {
             Debug.LogError("No unit found for : " + transform.name.ToString());
         }
     }
 }
Пример #27
0
 public void Stop()
 {
     isActiv = false;
     reloadTimer = reloadCooldown;
     unit = null;
 }
Пример #28
0
 public void RemoveUnit(UnitAI unit)
 {
     population.Remove(unit);
 }
Пример #29
0
 public bool CanProduce(UnitAI unit)
 {
     return(population.Count < maxPopulation);
 }
Пример #30
0
        public void UpdateCharmAI()
        {
            switch (GetTypeId())
            {
            case TypeId.Unit:
                if (i_disabledAI != null)     // disabled AI must be primary AI
                {
                    if (!IsCharmed())
                    {
                        i_AI         = i_disabledAI;
                        i_disabledAI = null;

                        if (IsTypeId(TypeId.Unit))
                        {
                            ToCreature().GetAI().OnCharmed(false);
                        }
                    }
                }
                else
                {
                    if (IsCharmed())
                    {
                        i_disabledAI = i_AI;
                        if (isPossessed() || IsVehicle())
                        {
                            i_AI = new PossessedAI(ToCreature());
                        }
                        else
                        {
                            i_AI = new PetAI(ToCreature());
                        }
                    }
                }
                break;

            case TypeId.Player:
            {
                if (IsCharmed())         // if we are currently being charmed, then we should apply charm AI
                {
                    i_disabledAI = i_AI;

                    UnitAI newAI = null;
                    // first, we check if the creature's own AI specifies an override playerai for its owned players
                    Unit charmer = GetCharmer();
                    if (charmer)
                    {
                        Creature creatureCharmer = charmer.ToCreature();
                        if (creatureCharmer)
                        {
                            PlayerAI charmAI = creatureCharmer.IsAIEnabled ? creatureCharmer.GetAI().GetAIForCharmedPlayer(ToPlayer()) : null;
                            if (charmAI != null)
                            {
                                newAI = charmAI;
                            }
                        }
                        else
                        {
                            Log.outError(LogFilter.Misc, "Attempt to assign charm AI to player {0} who is charmed by non-creature {1}.", GetGUID().ToString(), GetCharmerGUID().ToString());
                        }
                    }
                    if (newAI == null)         // otherwise, we default to the generic one
                    {
                        newAI = new SimpleCharmedPlayerAI(ToPlayer());
                    }
                    i_AI = newAI;
                    newAI.OnCharmed(true);
                }
                else
                {
                    if (i_AI != null)
                    {
                        // we allow the charmed PlayerAI to clean up
                        i_AI.OnCharmed(false);
                    }
                    else
                    {
                        Log.outError(LogFilter.Misc, "Attempt to remove charm AI from player {0} who doesn't currently have charm AI.", GetGUID().ToString());
                    }
                    // and restore our previous PlayerAI (if we had one)
                    i_AI         = i_disabledAI;
                    i_disabledAI = null;
                    // IsAIEnabled gets handled in the caller
                }
                break;
            }

            default:
                Log.outError(LogFilter.Misc, "Attempt to update charm AI for unit {0}, which is neither player nor creature.", GetGUID().ToString());
                break;
            }
        }
Пример #31
0
        public override void Process(Entity entity)
        {
            //todo:: причесать >_<
            IUnitAI ai;

            Unit unit = entity.GetComponent<Unit>();
            AIUtils.DropPrimaryStatsToBase(entity);
            switch (unit.unitClass)
            {
                case Unit.UnitClass.barbarian:
                {
                    ai = new BarbAI();
                }
                break;
                case Unit.UnitClass.mage:
                {
                    ai = new BarbAI();
                }
                break;
                default:

                    ai = new BarbAI();

                    break;
            }
            ai.unit = entity;
            var aiComp = new UnitAI();
            aiComp.unitAI = ai;

            ai.init();
            entity.AddComponent(aiComp);
            //DBManager.UpdateEntityFromTemplates(entity, "level_" + unit.currentLevel);
        }
Пример #32
0
	/// <summary>Spawns a given unit
	/// the units alliance must be 
	/// set before this is called
	/// .</summary>
	/// <param name="unit">Unit.</param>
	public void spawnUnit(UnitScript unit, bool spawnWithAI){
		if(spawnWithAI){
			UnitAI ai = new UnitAI(unit);
			unit.ai = ai;
		}
		unit.transform.position = new Vector3();
		unit.transform.SetParent(gridManager.unitObjectHolder);
		unitInstalled = unit;
		unit.spawnUnit(gridManager, this, teamSpawn);
		//Remove this spawn spot.
		removeSpawn();
	}
Пример #33
0
 public BoneSpikeTargetSelector(UnitAI ai)
 {
     _ai = ai;
 }
Пример #34
0
 public void Attack(Transform target)
 {
     isActiv = true;
     unit = target.GetComponent<UnitAI>();
 }
Пример #35
0
        public void RemoveCharmedBy(Unit charmer)
        {
            if (!IsCharmed())
            {
                return;
            }

            if (charmer)
            {
                Cypher.Assert(charmer == GetCharmer());
            }
            else
            {
                charmer = GetCharmer();
            }

            Cypher.Assert(charmer);

            CharmType type;

            if (HasUnitState(UnitState.Possessed))
            {
                type = CharmType.Possess;
            }
            else if (charmer && charmer.IsOnVehicle(this))
            {
                type = CharmType.Vehicle;
            }
            else
            {
                type = CharmType.Charm;
            }

            CastStop();
            CombatStop(); // @todo CombatStop(true) may cause crash (interrupt spells)

            if (_oldFactionId != 0)
            {
                SetFaction(_oldFactionId);
                _oldFactionId = 0;
            }
            else
            {
                RestoreFaction();
            }

            ///@todo Handle SLOT_IDLE motion resume
            GetMotionMaster().InitializeDefault();

            // Vehicle should not attack its passenger after he exists the seat
            if (type != CharmType.Vehicle)
            {
                LastCharmerGUID = charmer.GetGUID();
            }

            Cypher.Assert(type != CharmType.Possess || charmer.IsTypeId(TypeId.Player));
            Cypher.Assert(type != CharmType.Vehicle || (IsTypeId(TypeId.Unit) && IsVehicle()));

            charmer.SetCharm(this, false);

            Player playerCharmer = charmer.ToPlayer();

            if (playerCharmer)
            {
                switch (type)
                {
                case CharmType.Vehicle:
                    playerCharmer.SetClientControl(this, false);
                    playerCharmer.SetClientControl(charmer, true);
                    RemoveUnitFlag(UnitFlags.Possessed);
                    break;

                case CharmType.Possess:
                    ClearUnitState(UnitState.Possessed);
                    playerCharmer.SetClientControl(this, false);
                    playerCharmer.SetClientControl(charmer, true);
                    charmer.RemoveUnitFlag(UnitFlags.RemoveClientControl);
                    RemoveUnitFlag(UnitFlags.Possessed);
                    break;

                case CharmType.Charm:
                    if (IsTypeId(TypeId.Unit) && charmer.GetClass() == Class.Warlock)
                    {
                        CreatureTemplate cinfo = ToCreature().GetCreatureTemplate();
                        if (cinfo != null && cinfo.CreatureType == CreatureType.Demon)
                        {
                            SetClass((Class)cinfo.UnitClass);
                            if (GetCharmInfo() != null)
                            {
                                GetCharmInfo().SetPetNumber(0, true);
                            }
                            else
                            {
                                Log.outError(LogFilter.Unit, "Aura:HandleModCharm: target={0} with typeid={1} has a charm aura but no charm info!", GetGUID(), GetTypeId());
                            }
                        }
                    }
                    break;

                case CharmType.Convert:
                    break;
                }
            }

            Player player = ToPlayer();

            if (player != null)
            {
                player.SetClientControl(this, true);
            }

            if (playerCharmer && this != charmer.GetFirstControlled())
            {
                playerCharmer.SendRemoveControlBar();
            }

            // a guardian should always have charminfo
            if (!IsGuardian())
            {
                DeleteCharmInfo();
            }

            // reset confused movement for example
            ApplyControlStatesIfNeeded();

            if (!IsPlayer() || charmer.IsCreature())
            {
                UnitAI charmedAI = GetAI();
                if (charmedAI != null)
                {
                    charmedAI.OnCharmed(false); // AI will potentially schedule a charm ai update
                }
                else
                {
                    ScheduleAIChange();
                }
            }
        }
Пример #36
0
        public bool SetCharmedBy(Unit charmer, CharmType type, AuraApplication aurApp = null)
        {
            if (!charmer)
            {
                return(false);
            }

            // dismount players when charmed
            if (IsTypeId(TypeId.Player))
            {
                RemoveAurasByType(AuraType.Mounted);
            }

            if (charmer.IsTypeId(TypeId.Player))
            {
                charmer.RemoveAurasByType(AuraType.Mounted);
            }

            Cypher.Assert(type != CharmType.Possess || charmer.IsTypeId(TypeId.Player));
            Cypher.Assert((type == CharmType.Vehicle) == (GetVehicleKit() && GetVehicleKit().IsControllableVehicle()));

            Log.outDebug(LogFilter.Unit, "SetCharmedBy: charmer {0} (GUID {1}), charmed {2} (GUID {3}), type {4}.", charmer.GetEntry(), charmer.GetGUID().ToString(), GetEntry(), GetGUID().ToString(), type);

            if (this == charmer)
            {
                Log.outFatal(LogFilter.Unit, "Unit:SetCharmedBy: Unit {0} (GUID {1}) is trying to charm itself!", GetEntry(), GetGUID().ToString());
                return(false);
            }

            if (IsTypeId(TypeId.Player) && ToPlayer().GetTransport())
            {
                Log.outFatal(LogFilter.Unit, "Unit:SetCharmedBy: Player on transport is trying to charm {0} (GUID {1})", GetEntry(), GetGUID().ToString());
                return(false);
            }

            // Already charmed
            if (!GetCharmerGUID().IsEmpty())
            {
                Log.outFatal(LogFilter.Unit, "Unit:SetCharmedBy: {0} (GUID {1}) has already been charmed but {2} (GUID {3}) is trying to charm it!", GetEntry(), GetGUID().ToString(), charmer.GetEntry(), charmer.GetGUID().ToString());
                return(false);
            }

            CastStop();
            CombatStop(); // @todo CombatStop(true) may cause crash (interrupt spells)

            Player playerCharmer = charmer.ToPlayer();

            // Charmer stop charming
            if (playerCharmer)
            {
                playerCharmer.StopCastingCharm();
                playerCharmer.StopCastingBindSight();
            }

            // Charmed stop charming
            if (IsTypeId(TypeId.Player))
            {
                ToPlayer().StopCastingCharm();
                ToPlayer().StopCastingBindSight();
            }

            // StopCastingCharm may remove a possessed pet?
            if (!IsInWorld)
            {
                Log.outFatal(LogFilter.Unit, "Unit:SetCharmedBy: {0} (GUID {1}) is not in world but {2} (GUID {3}) is trying to charm it!", GetEntry(), GetGUID().ToString(), charmer.GetEntry(), charmer.GetGUID().ToString());
                return(false);
            }

            // charm is set by aura, and aura effect remove handler was called during apply handler execution
            // prevent undefined behaviour
            if (aurApp != null && aurApp.GetRemoveMode() != 0)
            {
                return(false);
            }

            _oldFactionId = GetFaction();
            SetFaction(charmer.GetFaction());

            // Pause any Idle movement
            PauseMovement(0, 0, false);

            // Remove any active voluntary movement
            GetMotionMaster().Clear(MovementGeneratorPriority.Normal);

            // Stop any remaining spline, if no involuntary movement is found
            Func <MovementGenerator, bool> criteria = movement => movement.Priority == MovementGeneratorPriority.Highest;

            if (!GetMotionMaster().HasMovementGenerator(criteria))
            {
                StopMoving();
            }

            // Set charmed
            charmer.SetCharm(this, true);

            Player player = ToPlayer();

            if (player)
            {
                if (player.IsAFK())
                {
                    player.ToggleAFK();
                }

                player.SetClientControl(this, false);
            }

            // charm is set by aura, and aura effect remove handler was called during apply handler execution
            // prevent undefined behaviour
            if (aurApp != null && aurApp.GetRemoveMode() != 0)
            {
                return(false);
            }

            // Pets already have a properly initialized CharmInfo, don't overwrite it.
            if (type != CharmType.Vehicle && GetCharmInfo() == null)
            {
                InitCharmInfo();
                if (type == CharmType.Possess)
                {
                    GetCharmInfo().InitPossessCreateSpells();
                }
                else
                {
                    GetCharmInfo().InitCharmCreateSpells();
                }
            }

            if (playerCharmer)
            {
                switch (type)
                {
                case CharmType.Vehicle:
                    AddUnitFlag(UnitFlags.Possessed);
                    playerCharmer.SetClientControl(this, true);
                    playerCharmer.VehicleSpellInitialize();
                    break;

                case CharmType.Possess:
                    AddUnitFlag(UnitFlags.Possessed);
                    charmer.AddUnitFlag(UnitFlags.RemoveClientControl);
                    playerCharmer.SetClientControl(this, true);
                    playerCharmer.PossessSpellInitialize();
                    AddUnitState(UnitState.Possessed);
                    break;

                case CharmType.Charm:
                    if (IsTypeId(TypeId.Unit) && charmer.GetClass() == Class.Warlock)
                    {
                        CreatureTemplate cinfo = ToCreature().GetCreatureTemplate();
                        if (cinfo != null && cinfo.CreatureType == CreatureType.Demon)
                        {
                            // to prevent client crash
                            SetClass(Class.Mage);

                            // just to enable stat window
                            if (GetCharmInfo() != null)
                            {
                                GetCharmInfo().SetPetNumber(Global.ObjectMgr.GeneratePetNumber(), true);
                            }

                            // if charmed two demons the same session, the 2nd gets the 1st one's name
                            SetPetNameTimestamp((uint)GameTime.GetGameTime());     // cast can't be helped
                        }
                    }
                    playerCharmer.CharmSpellInitialize();
                    break;

                default:
                case CharmType.Convert:
                    break;
                }
            }

            AddUnitState(UnitState.Charmed);

            if (!IsPlayer() || !charmer.IsPlayer())
            {
                // AI will schedule its own change if appropriate
                UnitAI ai = GetAI();
                if (ai != null)
                {
                    ai.OnCharmed(false);
                }
                else
                {
                    ScheduleAIChange();
                }
            }
            return(true);
        }
Пример #37
0
 void Start()
 {
     isActiv = true;
     unit = null;
 }
Пример #38
0
        // Choose next unit for orders. If all units ended turn, update cities.
        private void ChooseNextUnit()
        {
            // End turn if no units awaiting orders
            if (!_activeCiv.AnyUnitsAwaitingOrders)
            {
                ChoseNextCiv();

                // TODO: implement wait at end of turn
                //if (Options.AlwaysWaitAtEndOfTurn)
                //{
                //    OnWaitAtTurnEnd?.Invoke(null, new WaitAtTurnEndEventArgs());
                //}
                //else
                //{

                //}
            }
            // Choose next unit
            else
            {
                // Create an list of indexes of units awaiting orders
                var indexUAO = new List <int>();
                foreach (IUnit unit in _units.Where(u => u.Owner == _activeCiv && !u.Dead && u.AwaitingOrders && _activeUnit != u))
                {
                    indexUAO.Add(unit.Id);
                }

                //int indexActUnit = Game.GetUnits.FindIndex(unit => unit == Game.ActiveUnit);  //Determine index of unit that is currently still active but just ended turn

                if (_activeUnit.Id < indexUAO.First())
                {
                    _activeUnit = _units[indexUAO.First()];
                }
                else if (_activeUnit.Id == indexUAO.First())
                {
                    _activeUnit = _units[indexUAO.First() + 1];
                }
                else if (_activeUnit.Id >= indexUAO.Last())
                {
                    _activeUnit = _units[indexUAO.First()];
                }
                else
                {
                    for (int i = 0; i < indexUAO.Count; i++)
                    {
                        if ((_activeUnit.Id >= indexUAO[i]) && (_activeUnit.Id < indexUAO[i + 1]))
                        {
                            _activeUnit = _units[indexUAO[i + 1]];
                            break;
                        }
                    }
                }

                OnUnitEvent?.Invoke(null, new UnitEventArgs(UnitEventType.NewUnitActivated));

                // Set new unit command if player=AI
                if (_activeCiv != _playerCiv)
                {
                    Game.IssueUnitOrder(UnitAI.UnitOrder());
                }
            }
        }