private void displayInformationForUnit(IGameEntity entity) { //Remove previous values hideExtendedInformationPanel(); //Display window info windowInfo.GetComponent<Image>().enabled = true; currentPanel = Panel.UNIT; currentObject = (MonoBehaviour)entity; List<String> titles = new List<String>(); titles.Add("Attack rate"); titles.Add("Attack range"); titles.Add("Movement rate"); titles.Add("Resistance"); titles.Add("Sight range"); titles.Add("Strenght"); titles.Add("Weapon Ability"); List<String> values = new List<String>(); values.Add(entity.info.unitAttributes.attackRate.ToString()); values.Add(entity.info.unitAttributes.attackRange.ToString()); values.Add(entity.info.unitAttributes.movementRate.ToString()); values.Add(entity.info.unitAttributes.resistance.ToString()); values.Add(entity.info.unitAttributes.sightRange.ToString()); values.Add(entity.info.unitAttributes.strength.ToString()); values.Add(entity.info.unitAttributes.weaponAbility.ToString()); displayInformation(titles, values); }
public virtual bool CanBePerformed(IGameEntity source) { if (!(source.TargettedTile.GetTileEntity() is ICharacter)) return false; if (((Character)source).GetAlliance() == ((Character)source.TargettedTile.GetTileEntity()).GetAlliance()) return false; var distance = ArenaHelper.GetDistanceBetweenFloorPositions(source.ArenaLocation.GetTileLocation(), source.TargettedTile.GetTileLocation()); return InRange(distance); }
public virtual string Perform(IGameEntity source) { var character = source as Character; if (character == null) { throw new Exception("Source cannot be null..."); } source.ArenaLocation.RemoveEntityFromTile(source); source.TargettedTile.AddEntityToTile(source); return character.Name + " " + Verb + " to " + source.TargettedTile.GetTileLocation().XCoord + "," + source.TargettedTile.GetTileLocation().YCoord; }
void Start() { gameEntity = gameObject.GetComponent<IGameEntity>() as IGameEntity; inputController = gameObject.GetComponent<IGameEntityInput>() as IGameEntityInput; characterController = GetComponent<CharacterController>(); characterController.slopeLimit = slopeLimit; swimLevel = Settings.Instance().waterLevel - 1.5f; started = true; }
public Create(EntityAbility info, GameObject gameObject) : base(info, gameObject) { _entity = _gameObject.GetComponent<IGameEntity>(); switch (_info.targetType) { case EntityType.UNIT: _infoToBuild = Info.get.of(_info.targetRace, _info.targetUnit); break; case EntityType.BUILDING: _infoToBuild = Info.get.of(_info.targetRace, _info.targetBuilding); break; } }
public bool CheckWalls(IGameEntity entity) { bool collision = false; Vector2 wallSideToEntity = Vector2.Zero; foreach (Wall wall in WallManager.Instance.Walls) { if (wall.BoundingBox.Intersects(entity.BoundingBox)) { collision = true; Vector2 newVel = entity.Velocity; Point center = wall.BoundingBox.Center; wallSideToEntity = entity.Position - wall.LeftCenter; wallSideToEntity.Normalize(); float leftDot = Vector2.Dot(wallSideToEntity, wall.LeftNormal); wallSideToEntity = entity.Position - wall.RightCenter; wallSideToEntity.Normalize(); float rightDot = Vector2.Dot(wallSideToEntity, wall.RightNormal); wallSideToEntity = entity.Position - wall.TopCenter; wallSideToEntity.Normalize(); float topDot = Vector2.Dot(wallSideToEntity, wall.TopNormal); wallSideToEntity = entity.Position - wall.BottomCenter; wallSideToEntity.Normalize(); float bottomDot = Vector2.Dot(wallSideToEntity, wall.BottomNormal); if (leftDot > 0.0f && newVel.X > 0.0f) newVel.X = 0.0f; else if (rightDot > 0.0f && newVel.X < 0.0f) newVel.X = 0.0f; else if (topDot > 0.0f && newVel.Y > 0.0f) newVel.Y = 0.0f; else if (bottomDot > 0.0f && newVel.Y < 0.0f) newVel.Y = 0.0f; entity.Velocity = newVel; //break; } } return collision; }
/// <summary> /// Stops attacking the target and goes back to an IDLE state /// </summary> public void stopAttack() { if (_target != null) { // Hide target health Selectable selectable = _target.getGameObject().GetComponent <Selectable>(); selectable.NotAttackedEntity(); // Unregister all events _auto -= _target.unregisterFatalWounds(onTargetDied); _auto -= _target.getGameObject().GetComponent <FOWEntity>().unregister(FOWEntity.Actions.HIDDEN, onTargetHidden); _target = null; setStatus(EntityStatus.IDLE); } }
/// <summary> /// /// </summary> /// <param name="entity"></param> /// <returns></returns> public bool RecycleEntity(IGameEntity entity) { if (_recycledEntities.ContainsKey(entity.ID)) { return(false); } entity.Location = null; var returnVal = _recycledEntities.TryAdd(entity.ID, entity); if (_recycledEntities.Count > 0) { Timer.Start(); } return(returnVal); }
#pragma warning disable RefCounter002 public override int Diff(IGameEntity leftEntity, IGameEntity rightEntity, bool skipMissHandle) #pragma warning restore RefCounter002 { _componentComparator.LeftEntity = leftEntity; _componentComparator.RightEntity = rightEntity; _handler.OnDiffEntityStart(leftEntity, rightEntity); int count = SortedEnumeratableComparator <IGameComponent> .Diff( leftEntity.SortedComponentList, rightEntity.SortedComponentList, _componentComparator, _isIncludeDelegate); _handler.OnDiffEntityFinish(leftEntity, rightEntity); return(count); }
/// <summary> /// Dodaje encję. /// Nie można dodawać dwóch IDENTYCZNYCH(ten sam obiekt) encji - wiele encji o tym samym ID jest dozwolone. /// </summary> /// <param name="entity">Encja do dodania.</param> public void Add(IGameEntity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } else if (this.Entities.Contains(entity)) { throw new Exceptions.ArgumentAlreadyExistsException("entity"); } entity.OwnerManager = this; entity.GameInfo = this.GameInfo; this.Entities.Add(entity); entity.OnInit(); Logger.Trace("Entity {0} added to manager", entity.Id); }
public void onUnitDeselected(System.Object obj) { GameObject gameObject = (GameObject)obj; hideExtendedInformationPanel(); // Hide all info DestroyButtons(); HideInformation(); //Unregister unit events IGameEntity entity = gameObject.GetComponent <IGameEntity>(); entity.doIfUnit(unit => { unit.unregister(Unit.Actions.DAMAGED, onUnitDamaged); unit.unregister(Unit.Actions.DIED, onUnitDied); unit.unregister(Unit.Actions.HEALTH_UPDATED, onHealthUpdated); }); entity.doIfResource(resource => { resource.unregister(Resource.Actions.DAMAGED, onUnitDamaged); resource.unregister(Resource.Actions.DESTROYED, onUnitDied); resource.unregister(Resource.Actions.CREATE_UNIT, onBuildingUnitCreated); resource.unregister(Resource.Actions.ADDED_QUEUE, onBuildingLoadNewUnit); resource.unregister(Resource.Actions.HEALTH_UPDATED, onHealthUpdated); //resource.unregister(Resource.Actions.ADDED_QUEUE, onBuildingLoadNewUnit); currentResource = null; DestroyUnitCreationButtons(); }); entity.doIfBarrack(building => { building.unregister(Barrack.Actions.DAMAGED, onUnitDamaged); building.unregister(Barrack.Actions.DESTROYED, onUnitDied); building.unregister(Barrack.Actions.CREATE_UNIT, onBuildingUnitCreated); building.unregister(Barrack.Actions.ADDED_QUEUE, onBuildingLoadNewUnit); building.unregister(Barrack.Actions.HEALTH_UPDATED, onHealthUpdated); //building.unregister(Barrack.Actions.BUILDING_FINISHED, reloadActionsPanel); currentBarrack = null; DestroyUnitCreationButtons(); }); }
/// <summary> /// Constructs a damage contribution result /// </summary> /// <param name="damage">Contributed damage</param> /// <param name="issuer">Issuer</param> public DamageContributionResult(float damage, IGameEntity issuer) { if (damage < 0.0) { throw new ArgumentException("Damage contribution must be positive.", nameof(damage)); } if (issuer == null) { throw new ArgumentNullException(nameof(issuer)); } if (!issuer.IsValid) { throw new ArgumentException("Issuer is not valid.", nameof(issuer)); } Damage = damage; Issuer = issuer ?? throw new ArgumentNullException(nameof(issuer)); }
private void DoInsert(IGameEntity gameEntity) { var entityKey = gameEntity.EntityKey; bool hasAdd = false; if (preEntityKeys.Contains(entityKey)) { hasAdd = true; } else if (sendSnapshotFilter.IsIncludeEntity(gameEntity)) { if (sendSnapshotFilter.IsEntitySelf(gameEntity)) {//获取自己的备份 snapshot.AddEntity(gameEntity.GetSelfEntityCopy(seq)); hasAdd = true; } else if (!isAccountStage) { if (isPrepareStage && gameEntity.EntityType != (int)EEntityType.Player) { return; } //获取别人的备份 if (gameEntity.HasPositionFilter) { var positionFilter = gameEntity.GetComponent <PositionFilterComponent>(); var position = gameEntity.Position; if (!positionFilter.Filter(position.Value, sendSnapshotFilter.Position)) { snapshot.AddEntity(gameEntity.GetNonSelfEntityCopy(seq)); hasAdd = true; } } else { snapshot.AddEntity(gameEntity.GetNonSelfEntityCopy(seq)); hasAdd = true; } } } if (hasAdd && onInsert != null) { onInsert(gameEntity, forPre); } }
protected virtual void ExecuteMainTask() { if (this.CurrentMainTask != null) { if (this.CurrentMainTask.TargetGuid.IsValid && (this.MainAttackableTarget == null || this.MainAttackableTarget.GUID != this.CurrentMainTask.TargetGuid)) { IGameEntity gameEntity = null; this.gameEntityRepositoryService.TryGetValue(this.CurrentMainTask.TargetGuid, out gameEntity); this.MainAttackableTarget = (gameEntity as IGarrisonWithPosition); } int num = (int)this.CurrentMainTask.Behavior.Behave(this); if (this.DebugNode == null || !this.DebugNode.IsFoldout) { this.DebugNode = this.CurrentMainTask.Behavior.DumpDebug(); } if (num == 3) { this.State = TickableState.NeedTick; return; } this.CurrentMainTask.Behavior.Reset(); return; } else { if (this.defaultBehavior == null) { this.DebugNode = null; this.State = TickableState.NoTick; this.BehaviorState = ArmyWithTask.ArmyBehaviorState.Sleep; return; } int num2 = (int)this.defaultBehavior.Behave(this); if (this.DebugNode == null || !this.DebugNode.IsFoldout) { this.DebugNode = this.defaultBehavior.DumpDebug(); } if (num2 == 3) { this.State = TickableState.NeedTick; return; } this.defaultBehavior.Reset(); return; } }
public bool IsSyncSelfOrThird(IGameEntity entity, EntityKey self) { _isSelf = CalcIsSelf(entity, self); if (IsSyncNonSelf(entity, _isSelf)) { return(true); } if (IsSyncSelf(entity, _isSelf)) { return(true); } return(false); }
internal static void SetObjects(Dictionary <string, object> objects) { EngineApplicationInterface._objects = objects; EngineApplicationInterface.IPath = EngineApplicationInterface.GetObject <IPath>(); EngineApplicationInterface.IShader = EngineApplicationInterface.GetObject <IShader>(); EngineApplicationInterface.ITexture = EngineApplicationInterface.GetObject <ITexture>(); EngineApplicationInterface.IMaterial = EngineApplicationInterface.GetObject <IMaterial>(); EngineApplicationInterface.IMetaMesh = EngineApplicationInterface.GetObject <IMetaMesh>(); EngineApplicationInterface.IDecal = EngineApplicationInterface.GetObject <IDecal>(); EngineApplicationInterface.IClothSimulatorComponent = EngineApplicationInterface.GetObject <IClothSimulatorComponent>(); EngineApplicationInterface.ICompositeComponent = EngineApplicationInterface.GetObject <ICompositeComponent>(); EngineApplicationInterface.IPhysicsShape = EngineApplicationInterface.GetObject <IPhysicsShape>(); EngineApplicationInterface.IBodyPart = EngineApplicationInterface.GetObject <IBodyPart>(); EngineApplicationInterface.IMesh = EngineApplicationInterface.GetObject <IMesh>(); EngineApplicationInterface.IMeshBuilder = EngineApplicationInterface.GetObject <IMeshBuilder>(); EngineApplicationInterface.ICamera = EngineApplicationInterface.GetObject <ICamera>(); EngineApplicationInterface.ISkeleton = EngineApplicationInterface.GetObject <ISkeleton>(); EngineApplicationInterface.IGameEntity = EngineApplicationInterface.GetObject <IGameEntity>(); EngineApplicationInterface.IGameEntityComponent = EngineApplicationInterface.GetObject <IGameEntityComponent>(); EngineApplicationInterface.IScene = EngineApplicationInterface.GetObject <IScene>(); EngineApplicationInterface.IScriptComponent = EngineApplicationInterface.GetObject <IScriptComponent>(); EngineApplicationInterface.ILight = EngineApplicationInterface.GetObject <ILight>(); EngineApplicationInterface.IParticleSystem = EngineApplicationInterface.GetObject <IParticleSystem>(); EngineApplicationInterface.IPhysicsMaterial = EngineApplicationInterface.GetObject <IPhysicsMaterial>(); EngineApplicationInterface.ISceneView = EngineApplicationInterface.GetObject <ISceneView>(); EngineApplicationInterface.IView = EngineApplicationInterface.GetObject <IView>(); EngineApplicationInterface.ITableauView = EngineApplicationInterface.GetObject <ITableauView>(); EngineApplicationInterface.ITextureView = EngineApplicationInterface.GetObject <ITextureView>(); EngineApplicationInterface.IVideoPlayerView = EngineApplicationInterface.GetObject <IVideoPlayerView>(); EngineApplicationInterface.IThumbnailCreatorView = EngineApplicationInterface.GetObject <IThumbnailCreatorView>(); EngineApplicationInterface.IDebug = EngineApplicationInterface.GetObject <IDebug>(); EngineApplicationInterface.ITwoDimensionView = EngineApplicationInterface.GetObject <ITwoDimensionView>(); EngineApplicationInterface.IUtil = EngineApplicationInterface.GetObject <IUtil>(); EngineApplicationInterface.IEngineSizeChecker = EngineApplicationInterface.GetObject <IEngineSizeChecker>(); EngineApplicationInterface.IInput = EngineApplicationInterface.GetObject <IInput>(); EngineApplicationInterface.ITime = EngineApplicationInterface.GetObject <ITime>(); EngineApplicationInterface.IScreen = EngineApplicationInterface.GetObject <IScreen>(); EngineApplicationInterface.IMusic = EngineApplicationInterface.GetObject <IMusic>(); EngineApplicationInterface.IImgui = EngineApplicationInterface.GetObject <IImgui>(); EngineApplicationInterface.IMouseManager = EngineApplicationInterface.GetObject <IMouseManager>(); EngineApplicationInterface.IHighlights = EngineApplicationInterface.GetObject <IHighlights>(); EngineApplicationInterface.ISoundEvent = EngineApplicationInterface.GetObject <ISoundEvent>(); EngineApplicationInterface.ISoundManager = EngineApplicationInterface.GetObject <ISoundManager>(); EngineApplicationInterface.IConfig = EngineApplicationInterface.GetObject <IConfig>(); EngineApplicationInterface.IManagedMeshEditOperations = EngineApplicationInterface.GetObject <IManagedMeshEditOperations>(); }
public bool attackTarget(IGameEntity entity, bool selfDefense = false) { if (entity.info.isUnit) { return(attackTarget((Unit)entity, selfDefense)); } else if (entity.info.isBarrack) { return(attackTarget((Barrack)entity, selfDefense)); } else if (entity.info.isResource) { return(attackTarget((Resource)entity, selfDefense)); } throw new ArgumentException("Unkown entity type to attack"); }
public void unregisterBuildingToEvents(IGameEntity entity) { if (entity.info.isResource) { Resource resource = (Resource)entity; resource.unregister(Resource.Actions.NEW_HARVEST, OnNewHarvest); resource.unregister(Resource.Actions.NEW_EXPLORER, OnNewExplorer); resource.unregister(Resource.Actions.COLLECTION, OnCollection); resource.unregister(Resource.Actions.CREATED, OnCreated); resource.unregister(Resource.Actions.EXTERMINATED, OnDestroyed); } else if (entity.info.isBarrack) { Barrack barrack = (Barrack)entity; barrack.unregister(Barrack.Actions.CREATED, OnCreated); } }
public bool Validate(IGameEntity player, out string message) { message = string.Empty; if ((player.Position.X < 0) || (player.Position.X > board.Settings.BoardWidth)) { message = $"User Exeeded the board width limit of the map"; return(false); } if ((player.Position.Y < 0) || (player.Position.Y > board.Settings.BoardHeight)) { message = $"User Exeeded the board height limit of the map"; return(false); } return(true); }
/// <summary> /// We do not change the direction /// We just get to the next step /// </summary> /// <param name="CurrentPlayer"></param> /// <returns></returns> public override ActionResult ExecuteAction(IGameEntity CurrentPlayer) { currentPlayer = CurrentPlayer; var player = CurrentPlayer as Player; if (player != null) { player.Move(player.Position.Orientation); Console.WriteLine(ConvertDirection(player.Position.Orientation)); } return(new ActionResult() { Status = ActionStatus.COMPLETE }); }
/// <summary> /// Starts moving the unit towards a point on a terrain /// </summary> /// <param name="movePoint">Point to move to</param> public bool moveTo(Vector3 movePoint) { if (isImmobile) { return(false); } _detourAgent.MoveTo(movePoint); _followingTarget = false; _target = null; _movePoint = movePoint; setStatus(EntityStatus.MOVING); fire(Actions.MOVEMENT_START); return(true); }
#pragma warning disable RefCounter002 public bool TryGetEntity(EntityKey entityKey, out IGameEntity entity) #pragma warning restore RefCounter002 { entity = null; TEntity rc = GetEntityWithEntityKey(entityKey); if (rc == null) { // 就目前而言 GetEntityWithEntityKey 找不到 entityKey 对应的entity,则返回null return(false); } entity = GetWrapped(rc); return(entity != null); }
/// <summary> /// Returns all the gameObjects in some radius /// </summary> /// <param name="position"></param> /// <param name="radius"></param> /// <returns></returns> public static List <IGameEntity> getEntitiesNearPosition(Vector3 position, float radius) { GameObject[] foundGameObjects = getObjectsNearPosition(position, radius); List <IGameEntity> entities = new List <IGameEntity>(); for (int i = 0; i < foundGameObjects.Length; i++) { GameObject obj = foundGameObjects[i]; IGameEntity objEntity = obj.GetComponent <IGameEntity>(); if (objEntity != null && objEntity.status != EntityStatus.DEAD && objEntity.status != EntityStatus.DESTROYED) { entities.Add(objEntity); } } return(entities); }
private void AddToSelfNonSelf(IGameEntity entity) { if (_filter.IsSyncNonSelf(entity, Self)) { if (_nonSelfEntityMapCache != null) { _nonSelfEntityMapCache.Add(entity.EntityKey, entity); } } else if (_filter.IsSyncSelf(entity, Self)) { if (_selfEntityMapCache != null) { _selfEntityMapCache.Add(entity.EntityKey, entity); } } }
public virtual string Perform(IGameEntity source) { var sourceCharacter = source as Character; var targetCharacter = source.TargettedTile.GetTileEntity() as Character; if (sourceCharacter == null) { throw new Exception("Source cannot be null...."); } if (targetCharacter == null) { throw new Exception("Target cannot be null...."); } var healAmount = Helpers.SecureRandom.Next(HitsForFrom, HitsForTo); //TODO : Make more sophisticated. targetCharacter.ReceiveHeal(healAmount); sourceCharacter.LoseMana(ManaCost); return sourceCharacter.Name + " " + Verb + " " + Name + " on " + targetCharacter.Name + " for " + healAmount; }
public Game(IPlayers players, IGameCalculator gameCalculator, IGameRules gameRules, IGameEntity gamEntity) { Players = players; GameCalculator = gameCalculator; GameCalculator.GameId = Id; GameRules = gameRules; GamEntity = gamEntity; Id = Guid.NewGuid(); players.CurrentGameIdGuid = Id; gameCalculator.GameId = Id; }
public virtual string Perform(IGameEntity source) { var sourceCharacter = source as Character; var targetCharacter = source.TargettedTile.GetTileEntity() as Character; if (sourceCharacter == null) { throw new Exception("Source cannot be null...."); } if (targetCharacter == null) { throw new Exception("Target cannot be null...."); } var damage = SecureRandom.Next(HitsForFrom, HitsForTo); damage = DamageBlockHelper.GetSpellDamage(sourceCharacter, damage); targetCharacter.TakeSpellDamage(damage); sourceCharacter.LoseMana(ManaCost); return sourceCharacter.Name + " " + Verb + " " + Name + " on " + targetCharacter.Name + " for " + damage; }
public void onActorDeselected(System.Object obj) { //destroyButtons(); GameObject gameObject = (GameObject)obj; IGameEntity entity = gameObject.GetComponent <IGameEntity>(); entity.doIfResource(resource => { resource.unregister(Resource.Actions.BUILDING_FINISHED, showActionButtons); }); entity.doIfBarrack(barrack => { barrack.unregister(Barrack.Actions.BUILDING_FINISHED, showActionButtons); }); hideActionButtons(gameObject); }
public void OnSpawned(FieldCoords coords, IMemoryPool pool) { _pool = pool; Coords = coords; float tileSize = _gameSettings.TileSize; Entity = _tileFactory.Create(); Entity.Position = new Vector3(coords.X * tileSize, 0, coords.Y * tileSize); if (Random.value > _gameSettings.CrystalChance) { _crystal = _crystalFactory.Create(); _crystal.Position = new Vector3(coords.X * tileSize + Random.value * tileSize, 0, coords.Y * tileSize + Random.value * tileSize); //_crystal.Owner.transform.parent = Entity.Owner.transform; } _field.Elements.Add(this); }
public override void OnLeftEntityMissing(IGameEntity rightEntity) { // sync in SyncLatestManager //AssertUtility.Assert(false); EntityKey entityKey = rightEntity.EntityKey; _logger.DebugFormat("create entity {0}", entityKey); var localEntity = rewindProvider.CreateAndGetLocalEntity(entityKey); foreach (var rightComponent in rightEntity.ComponentList) { if (!IsExcludeComponent(rightComponent) && localEntity.GetComponent(rightComponent.GetComponentId()) == null) { OnLeftComponentMissing(localEntity, rightEntity, rightComponent); } } }
public void OnDiffComponent(IGameEntity leftEntity, IGameComponent leftComponent, IGameEntity rightEntity, IGameComponent rightComponent) { bool diff; var comp = leftComponent as IComparableComponent; // ReSharper disable once PossibleNullReferenceException diff = !comp.IsApproximatelyEqual(rightComponent); if (diff) { _logger.InfoFormat("cmd seq {0} component diff key[{1}], type[{2}],\n local {3}],\n remote[{4}]", _remoteCmdSeq, leftEntity.EntityKey, leftComponent.GetType(), leftComponent, rightComponent); } IsDiff = IsDiff || diff; }
public void OnLeftEntityMissing(IGameEntity rightEntity) { // sync in SyncLatestManager //AssertUtility.Assert(false); EntityKey entityKey = rightEntity.EntityKey; _logger.DebugFormat("create entity {0}", entityKey); var localEntity = _handler.CreateAndGetLocalEntity(entityKey); foreach (var rightComponent in rightEntity.ComponentList) { if (!IsExcludeComponent(rightComponent) && localEntity.GetComponent(rightComponent.GetComponentId()) == null) { _logger.DebugFormat("add component {0}:{1}", entityKey, rightComponent.GetType()); var localComponent = localEntity.AddComponent(rightComponent.GetComponentId(), rightComponent); } } }
// Hack to get key bindings working. void fixKeybinds(System.Object obj) { GameObject gameObject = (GameObject)obj; IGameEntity entity = gameObject.GetComponent <IGameEntity>(); var abilities = entity.info.abilities; var nabilities = abilities.Count; abilities_on_show.Clear(); for (int i = 0; i < nabilities; i++) { String ability = abilities[i].name; Ability abilityObj = entity.getAbility(ability); if (abilityObj.isUsable) { abilities_on_show.Add(abilityObj); } } }
public bool GetPositionAndRadius(IGameEntity gameEntity, out Vector3 position, out float radius) { var pos = gameEntity.Position.Value; var subManager = GetSubManager(gameEntity.EntityType); if (subManager != null) { position = subManager.GetPosition(gameEntity.EntityKey) + pos; radius = subManager.GetRadius(gameEntity.EntityKey); return(true); } { position = Vector3.zero; radius = 0; return(false); } }
public override void OnRightEntityMissing(IGameEntity leftEntity) { // sync in SyncLatestManager //AssertUtility.Assert(false); EntityKey entityKey = leftEntity.EntityKey; if (!rewindProvider.IsRemoteEntityExists(entityKey)) { _logger.DebugFormat("destroy entity {0}", leftEntity.EntityKey); rewindProvider.DestroyLocalEntity(leftEntity); } else { leftEntity.RemoveComponent <OwnerIdComponent>(); _logger.DebugFormat("ignore destroy entity {0}", leftEntity.EntityKey); } }
public bool GetPositionAndRadius(IGameEntity gameEntity, out Vector3 position, out float radius) { var comp = GetHitBoxComponent(gameEntity); var pos = gameEntity.Position.Value; if (comp != null) { position = comp.HitPreliminaryGeo.position + pos; radius = comp.HitPreliminaryGeo.radius; return(true); } else { position = Vector3.zero; radius = 0; return(false); } }
/// <summary> /// /// </summary> /// <param name="entity"></param> /// <param name="location"></param> /// <returns></returns> public bool SaveRecycledEntity(IGameEntity entity, IGameEntity location) { if (!_recycledEntities.ContainsKey(entity.ID)) { return(false); } var entityId = entity.ID; Task <bool> task = null; CancellationTokenSource tokenSource = null; try { tokenSource = new CancellationTokenSource(); task = Task.Factory.StartNew(() => SaveEntityFromRecycling(tokenSource.Token, entity), tokenSource.Token); task.Wait(tokenSource.Token); _log.InfoFormat(Resources.MSG_ENTITY_SAVED, entity.ID, task.Status); } catch (AggregateException ex) { _log.InfoFormat(Resources.MSG_TASK_CANCELLED, entity.ID); ex.InnerException.Handle(ExceptionHandlingOptions.RecordAndThrow, _log); } catch (Exception ex) { ex.Handle(ExceptionHandlingOptions.RecordAndThrow, _log); } finally { task.Cancel(tokenSource); } if (_recycledEntities.Count <= 0) { Timer.Stop(); } _eventManager.ThrowEvent <OnEntityDisposed>(this, new EventTable { { "EntityID", entityId } }); entity.Location = location; return(true); }
public override void Run(float deltaTime) { if (State == ExecutionState.NOT_STARTED) { var position = GameObject.Find("PlayerStronghold").transform.position; var rotation = Quaternion.Euler(0, 0, 0); GameObject gob = Storage.Info.get.createBuilding(testEnvironment.playerRace, Storage.BuildingTypes.STRONGHOLD, position, rotation); entity = gob.GetComponent<IGameEntity>(); State = ExecutionState.NOT_DONE; } else if (State == ExecutionState.NOT_DONE && elapsed > 1) { entity.Destroy(true); State = ExecutionState.DONE; } elapsed += deltaTime; }
void Start() { gameEntity = gameObject.GetComponent<IGameEntity>() as IGameEntity; inputController = gameObject.GetComponent<IGameEntityInput>() as IGameEntityInput; terrainCollisionHandler = gameObject.GetComponent<ITerrainCollision>() as ITerrainCollision; if (terrainCollisionHandler != null) { terrainCollisionHandler.Initialize(); } characterController = GetComponent<CharacterController>(); characterController.slopeLimit = slopeLimit; animationController = transform.GetComponentInChildren<DefaultAnimationController>(); swimLevel = Settings.Instance().waterLevel - 1.5f; initialized = true; }
private void UpdatePillageOnEndTurn(PointOfInterest pointOfInterest) { IGameEntity gameEntity = null; if (pointOfInterest.ArmyPillaging.IsValid) { if (this.GameEntityRepositoryService.TryGetValue(pointOfInterest.ArmyPillaging, out gameEntity)) { Army army = gameEntity as Army; if (army != null) { this.UpdatePillageProgress(army, pointOfInterest); return; } } DepartmentOfDefense.StopPillage(null, pointOfInterest); } this.UpdatePillageRecovery(pointOfInterest); }
/// <summary> /// Object initialization /// </summary> override public void Awake() { _nextUpdate = 0; _stored = 0; _collectionRate = 0; harvestUnits = 0; _xDisplacement = 0; _yDisplacement = 0; _info = Info.get.of(race, type); totalUnits = 0; _unitRotation = transform.rotation; hasDefaultUnit = false; civilInfo = Info.get.of(this.race, UnitTypes.CIVIL); _entity = this.GetComponent <IGameEntity>(); sounds = GameObject.Find("GameController").GetComponent <Managers.SoundsManager>(); // Call Building start base.Awake(); }
public EnemyManager(EnemiesDescription enemiesDescription) { player = EntityManager.Instance.GetPlayer(); if (enemiesDescription.EnemiesInfo != null) { foreach (EnemiesDescription.EnemyInfo curEnemyInfo in enemiesDescription.EnemiesInfo) { List<Vector2> curPatrolRoute = curEnemyInfo.PatrolTilePositions; for (int i = 0; i < curPatrolRoute.Count; i++) curPatrolRoute[i] = AStarGame.GameMap.TilePosToWorldPos(curPatrolRoute[i]); Vector2 curEnemyPosition = AStarGame.GameMap.TilePosToWorldPos(curEnemyInfo.StartingTilePosition); IGameEntity curEnemy = new SmartFarmer(TextureManager.FarmerSprite, curEnemyPosition, curPatrolRoute); curEnemy.MaxSpeed = curEnemyInfo.MaxSpeed; Enemies.Add(curEnemy); } } }
public virtual string Perform(IGameEntity source) { var character = source as Character; if (character == null) { throw new Exception("Source cannot be null...."); } var target = source.TargettedTile.GetTileEntity() as Character; if (target == null) { throw new Exception("Target cannot be null...."); } var weaponDamage = ((Equipment.Weapons.Weapon) PerformedWith).GetDamage(); var modifier = SecureRandom.Next(DamageFromModifier, DamageToModifier); var damage = modifier > 0 ? weaponDamage*(modifier/100) : weaponDamage; damage = DamageBlockHelper.GetPhysicalDamage(character, damage); var takenDamage = DamageBlockHelper.TakePhysicalDamage(target, damage); return character.Name + " " + Verb + " " + target.Name + " with " + Name + " for " + damage + ". " + target.Name + " blocks " + (damage - takenDamage) + " loses " + takenDamage + " health."; }
public StrategyAgent(AIController ai, AssistAgent assist, string name) : base(ai, name) { rnd = new System.Random(); //Until we have a better way to mix it we will just keep it random timings = new Stack<int>(); if (!ai.StoryMode) { timings.Push(rnd.Next(1300, 1700)); timings.Push(rnd.Next(400, 600)); if (rnd.Next(0, 9) < 3) //add a rush timings.Push(rnd.Next(60, 100)); } else { timings.Push(rnd.Next(10000, 13000)); } patrolPoints = ai.Macro.architect.baseCriticPoints; attacking = false; FIND_PLAYER_RATE = FIND_PLAYER_RATE - 60 * ai.DifficultyLvl; lastTarget = null; target = null; }
public Rangefinder(IGameEntity entity) { SensingEntity = entity; // Initialize feeler directions. Vector3 forwardDir = new Vector3(entity.Heading, 0.0f); forwardDir.Normalize(); Vector3 leftForwardDir = Vector3.Transform(forwardDir, Matrix.CreateRotationZ(MathHelper.ToRadians(-AngleBetweenFeelers))); leftForwardDir.Normalize(); Vector3 rightForwardDir = Vector3.Transform(forwardDir, Matrix.CreateRotationZ(MathHelper.ToRadians(AngleBetweenFeelers))); rightForwardDir.Normalize(); // Add 3 feelers. Vector3 position = new Vector3(entity.Position, 0.0f); Feelers.Add(new Ray(position, leftForwardDir)); Feelers.Add(new Ray(position, forwardDir)); Feelers.Add(new Ray(position, rightForwardDir)); rangefinderDebugger = new RangefinderDebugger(this); }
protected override void AddBuilding(IGameEntity entity) { Storage.BuildingInfo bi; addEntity(entity); bi = (Storage.BuildingInfo) entity.info; if (bi.type == Storage.BuildingTypes.STRONGHOLD) { cam.lookGameObject(entity.getGameObject()); } }
private void displayInformationForBarrack(IGameEntity entity) { displayInformationForStronghold(entity); }
private void displayInformationForStronghold(IGameEntity entity) { //Remove previous values hideExtendedInformationPanel(); //Display window info windowInfo.GetComponent<Image>().enabled = true; currentPanel = Panel.STRONGHOLD; currentObject = (MonoBehaviour)entity; List<String> titles = PopulationInfo.get.GetBuildingKeys().GetRange(0,10); List<String> values = PopulationInfo.get.GetBuildingValues().GetRange(0,10); displayInformation(titles, values); }
/// <summary> /// Returns <code>true</code> if the entity is under the camera. /// </summary> /// <returns><c>true</c>, if the entity is under the camera, <c>false</c> otherwise.</returns> /// <param name="entity">Entity.</param> private bool isEntityUnderCamera(IGameEntity entity) { Vector3 vp = mainCam.WorldToViewportPoint(entity.getTransform().position); return vp.x >= 0 && vp.y >= 0 && vp.x <= 1 && vp.y <= 1 && vp.z >= 0; }
/// <summary> /// Method to call when a unit or a resource is created or when a resource building /// adds or removes a worker. /// </summary> /// <param name="entity">Entity where their inner stats have changed.</param> /// <param name="packet">Package that represents an entity.</param> public void StatisticsChanged(IGameEntity entity, GrowthStatsPacket packet) { if (statistics[packet.type].ContainsKey(entity)) { statistics[packet.type][entity] = packet; } else { statistics[packet.type].Add(entity, packet); } updateStatistics(); }
public override void removeEntity(IGameEntity entity) { _activeEntities.Remove(entity); unregisterEntityEvents(entity); }
private void unregisterEntityEvents(IGameEntity entity) { if (entity.info.isBarrack) { Barrack barrack = (Barrack) entity; barrack.unregister(Barrack.Actions.DAMAGED, events.DisplayUnderAttack); barrack.unregister(Barrack.Actions.DESTROYED, events.DisplayBuildingDestroyed); barrack.unregister(Barrack.Actions.CREATE_UNIT, OnUnitCreated); barrack.unregister(Barrack.Actions.BUILDING_FINISHED, events.DisplayBuildingCreated); } else if (entity.info.isResource) { Resource resourcesBuilding = (Resource) entity; resourcesBuilding.unregister(Resource.Actions.DAMAGED, events.DisplayUnderAttack); resourcesBuilding.unregister(Resource.Actions.DESTROYED, events.DisplayBuildingDestroyed); resourcesBuilding.unregister(Resource.Actions.BUILDING_FINISHED, events.DisplayBuildingCreated); resourcesBuilding.unregister(Resource.Actions.CREATE_UNIT, OnUnitCreated); } else if (entity.info.isUnit) { Unit unit = (Unit) entity; unit.unregister(Unit.Actions.DIED, events.DisplayUnitDead); unit.unregister(Unit.Actions.DAMAGED, events.DisplayUnderAttack); unit.unregister(Unit.Actions.TARGET_TERMINATED, signalMissionUpdate); unit.unregister(Unit.Actions.EAT, onUnitEats); } }
public ChasingEnemyRenderer(Game game, IGameEntity owner) : base(game, owner) { isAutoRandom = false; }
void OnEntityLost(System.Object obj) { IGameEntity g = ((GameObject)obj).GetComponent<IGameEntity>(); if (g.info.isUnit) { g.unregisterFatalWounds(OnEntityLost); target = null; findTarget(); } }
private void findTarget() { int eBuild = ai.EnemyBuildings.Count; IGameEntity stronghold = null; IGameEntity nearestTower = null; float minDistance = Mathf.Infinity; if (eBuild > 0) { foreach(IGameEntity building in ai.EnemyBuildings) { if (building != null & building.status != EntityStatus.DESTROYED) { if (building.getType<Storage.BuildingTypes>() == Storage.BuildingTypes.WATCHTOWER) { nearestTower = building; foreach (Squad s in ai.Micro.squads) { try { float dist = Vector3.Distance(s.BoundingBox.Bounds.center, building.getGameObject().transform.position); if (dist < minDistance) { minDistance = dist; nearestTower = building; } } catch(Exception ex) { continue; } } } else if (building.getType<Storage.BuildingTypes>() == Storage.BuildingTypes.STRONGHOLD) { stronghold = building; } else { foreach (Squad s in ai.Micro.squads) { try { float dist = Vector3.Distance(s.BoundingBox.Bounds.center, building.getGameObject().transform.position); if (dist < minDistance) { minDistance = dist; nearestTower = building; } } catch (Exception ex) { continue; } } } } } if (nearestTower != null) { target = nearestTower; } else if (stronghold != null) { target = stronghold; } } else { //If we haven't found any enemy building we can't attack this time if(FIND_PLAYER_RATE > Time.time && lastSmell + FIND_PLAYER_RATE > Time.time) { Debug.Log(Time.time); RemovePush(); } else { lastSmell = Time.time; List<IBuilding> detected = ai.race == Storage.Races.ELVES ? Helpers.getBuildingsOfRaceNearPosition(ai.Micro.squads[0].BoundingBox.Bounds.center, 2000f, Storage.Races.MEN) : Helpers.getBuildingsOfRaceNearPosition(ai.Micro.squads[0].BoundingBox.Bounds.center, 800f, Storage.Races.ELVES); if(detected.Count > 0) { ai.EnemyBuildings.Add(detected[0]); } } } if(target != null && target != lastTarget) { target.registerFatalWounds(OnEntityLost); } lastTarget = target; }
/// <summary> /// Removes entity from the main dictionary. /// </summary> /// <param name="type">Type of resource this entity creates/destroys.</param> /// <param name="entity">Entity to Destroy.</param> public void RemoveEntity(WorldResources.Type type, IGameEntity entity) { statistics[type].Remove(entity); updateStatistics(); }
public virtual bool CanBePerformed(IGameEntity source) { return source.TargettedTile.GetTileEntity() == null && ArenaHelper.GetDistanceBetweenFloorPositions(source.ArenaLocation.GetTileLocation(), source.TargettedTile.GetTileLocation()) <= Distance; }
/// <summary> /// Add a IGameEntity to the list /// Player has a list with all the entities associated to him /// </summary> /// <param name="newEntity"></param> public override void addEntity(IGameEntity newEntity) { _activeEntities.Add(newEntity); registerEntityEvents(newEntity); if (newEntity.info.isBuilding) events.DisplayBuildingUnderConstruction((Storage.BuildingInfo) newEntity.info); Debug.Log(_activeEntities.Count + " entities"); }
public override void AddEntity(IGameEntity ent) { this.ForceRegistry.Add(ent, new WhenAwakeFG(Vector3.Down * 0.0000004f)); base.AddEntity(ent); }
protected override void AddUnit(IGameEntity entity) { addEntity(entity); }