Exemplo n.º 1
0
 public void Start()
 {
     // listen on damageable component
     // this needs to be in Start, because Damageable component event system is initialized in Awake
     DamageableComponent = GetComponent <DamageableComponent>();
     DamageableComponent.AddListener(this);
 }
Exemplo n.º 2
0
    void OnCollisionEnter(Collision other)
    {
        if (skipCollisionFrames <= 0)
        {
            if (other.gameObject.layer == DamagableLayer)
            {
                DamageableComponent damageable = other.gameObject.GetComponent <DamageableComponent>();

                if (damageable.damageableTeam != bulletTeam && damageable.health > 0)
                {
                    damageable.Damage(damage, armorBonus);

                    if (hitSplash)
                    {
                        Object.Instantiate(hitSplash, transform.position, new Quaternion());
                    }

                    Destroy(gameObject);
                }
            }
            else if (other.gameObject.layer == GroundLayer && groundSplash)
            {
                Object.Instantiate(groundSplash, other.contacts[0].point + new Vector3(0.0f, 6.0f, 0.0f), new Quaternion());
                Destroy(gameObject);
            }
            else if (other.gameObject.layer == WaterLayer && waterSplash)
            {
                Object.Instantiate(waterSplash, other.contacts[0].point + new Vector3(0.0f, 6.0f, 0.0f), new Quaternion());
                Destroy(gameObject);
            }
        }
    }
Exemplo n.º 3
0
    private void Killed(DamageableComponent damage)
    {
        // Roll random
        float roll = Random.value;

        // Iterate over chances to see if that's ours
        float totalChance = 0.0f;
        int   rolledIndex = 0;

        for (int i = 0, count = spawnables.Length; i < count; ++i)
        {
            totalChance += spawnables[i].chance;

            if (roll <= totalChance)
            {
                rolledIndex = i;
                break;
            }
        }

        // If prefab exists, spawn it. Null is valid, though, as 'spawn nothing'
        if (spawnables[rolledIndex].prefab != null)
        {
            GameObject newObject = Object.Instantiate(spawnables[rolledIndex].prefab);
            newObject.transform.position = transform.position + spawnOffset;
        }
    }
Exemplo n.º 4
0
 //##############################################################################################
 // When damaged, play a pseudo-random grunt or big oof
 //##############################################################################################
 public void OnDamaged(DamageableComponent damage)
 {
     if (playerHurtBarkComponent != null)
     {
         playerHurtBarkComponent.Bark();
     }
 }
Exemplo n.º 5
0
    //##############################################################################################
    // Setup the player, and collect the different components that will get used.
    //##############################################################################################
    void Start()
    {
        player       = this;
        respawnState = RespawnState.Alive;

        // Hide the cursor and lock it to screen
        Cursor.visible   = false;
        Cursor.lockState = CursorLockMode.Locked;

        // Try to target 60
        Application.targetFrameRate = 60;

        movementEnabled = true;
        lookingEnabled  = true;

        gun       = GetComponent <GunComponent>();
        character = GetComponent <CharacterController>();
        damage    = GetComponent <DamageableComponent>();

        damage.RegisterOnDamagedDelegate(OnDamaged);
        damage.RegisterOnKilledDelegate(OnKilled);

        respawnTimer          = new Timer(respawnTime);
        shakeDecayTimer       = new Timer(SHAKE_DECAY_TIME);
        safeTimer             = new Timer(SAFE_TIME);
        recoilDecayTimer      = new Timer();
        jumpTimer             = new Timer(jumpTime);
        sideJumpCooldownTimer = new Timer(SIDE_JUMP_COOLDOWN_TIME);
    }
Exemplo n.º 6
0
        public BoardCell <Entity> MoveBuildingWithinBoard(Entity building, int boardX, int boardZ)
        {
            BoardController    boardController    = Service.Get <BoardController>();
            BoardItemComponent boardItemComponent = building.Get <BoardItemComponent>();
            BoardItem <Entity> boardItem          = boardItemComponent.BoardItem;
            BuildingComponent  buildingComponent  = building.Get <BuildingComponent>();
            bool checkSkirt = buildingComponent.BuildingType.Type != BuildingType.Blocker;
            BoardCell <Entity> boardCell = boardController.Board.MoveChild(boardItem, boardX, boardZ, building.Get <HealthComponent>(), true, checkSkirt);

            if (boardCell != null)
            {
                TransformComponent transformComponent = building.Get <TransformComponent>();
                transformComponent.X = boardCell.X;
                transformComponent.Z = boardCell.Z;
                DamageableComponent damageableComponent = building.Get <DamageableComponent>();
                if (damageableComponent != null)
                {
                    damageableComponent.Init();
                }
                Building buildingTO = building.Get <BuildingComponent>().BuildingTO;
                buildingTO.SyncWithTransform(transformComponent);
                Service.Get <EventManager>().SendEvent(EventId.BuildingMovedOnBoard, building);
            }
            else
            {
                Service.Get <StaRTSLogger>().ErrorFormat("Failed to move building {0}:{1} to ({2},{3})", new object[]
                {
                    buildingComponent.BuildingTO.Key,
                    buildingComponent.BuildingTO.Uid,
                    boardX,
                    boardZ
                });
            }
            return(boardCell);
        }
 void PlayerKilled(DamageableComponent damaged)
 {
     if (currentlyModifying)
     {
         FirstPersonPlayerComponent.player.RemoveSpeedModifier(gameObject);
     }
 }
Exemplo n.º 8
0
    //##############################################################################################
    // If the bullet has a damageable and is killed, trigger the fx and mark it for destruction
    //##############################################################################################
    public void OnBulletKilled(DamageableComponent damageable)
    {
        shouldKill = true;

        // Spawn effects in place, because they will now no longer get spawned via collision
        if (optionalImpactEffects != null)
        {
            GameObject fx = GameObject.Instantiate(optionalImpactEffects);
            fx.transform.position = transform.position;
        }
    }
    //##############################################################################################
    // When damage, begin flashing, and update health text
    //##############################################################################################
    public void OnDamaged(DamageableComponent damaged)
    {
        damageFlashing           = true;
        damageFlashLayer.enabled = true;
        damageFlashTimer.Start();

        healthText.text = damaged.CurrentHealth().ToString();
        if (damaged.Dead())
        {
            healthText.enabled = false;
        }
    }
Exemplo n.º 10
0
        public BoardCell <Entity> AddBuildingToBoard(Entity building, int boardX, int boardZ, bool sendEvent)
        {
            BoardItemComponent boardItemComponent = building.Get <BoardItemComponent>();
            BoardItem <Entity> boardItem          = boardItemComponent.BoardItem;
            SizeComponent      size = boardItem.Size;
            BuildingComponent  buildingComponent = building.Get <BuildingComponent>();
            BuildingTypeVO     buildingType      = buildingComponent.BuildingType;
            bool      flag        = buildingType.Type == BuildingType.Clearable || buildingType.Type == BuildingType.Trap || buildingType.Type == BuildingType.ChampionPlatform;
            bool      flag2       = buildingType.Type == BuildingType.Blocker;
            int       walkableGap = flag2 ? 0 : this.CalculateWalkableGap(size);
            FlagStamp flagStamp   = this.CreateFlagStamp(building, buildingType, size, walkableGap);

            if (!flag)
            {
                this.AddUnWalkableUnDestructibleFlags(flagStamp, size, walkableGap, flag2);
            }
            boardItem.FlagStamp = flagStamp;
            BoardController    boardController = Service.Get <BoardController>();
            BoardCell <Entity> boardCell       = boardController.Board.AddChild(boardItem, boardX, boardZ, building.Get <HealthComponent>(), !flag2);

            if (boardCell == null)
            {
                Service.Get <StaRTSLogger>().ErrorFormat("Failed to add building {0}:{1} at ({2},{3})", new object[]
                {
                    buildingComponent.BuildingTO.Key,
                    buildingComponent.BuildingTO.Uid,
                    boardX,
                    boardZ
                });
                return(null);
            }
            TransformComponent transformComponent = building.Get <TransformComponent>();

            transformComponent.X = boardX;
            transformComponent.Z = boardZ;
            DamageableComponent damageableComponent = building.Get <DamageableComponent>();

            if (damageableComponent != null)
            {
                damageableComponent.Init();
            }
            buildingComponent.BuildingTO.SyncWithTransform(transformComponent);
            if (sendEvent)
            {
                Service.Get <EventManager>().SendEvent(EventId.BuildingPlacedOnBoard, building);
            }
            if (buildingType.Type == BuildingType.DroidHut)
            {
                this.DroidHut = building;
            }
            return(boardCell);
        }
    //##############################################################################################
    // Get the relevant component, and register for damageable delegates
    //##############################################################################################
    protected virtual void Start()
    {
        character         = GetComponent <CharacterController>();
        damage            = GetComponent <DamageableComponent>();
        rotation          = GetComponent <RotatableComponent>();
        materialAnimation = GetComponent <MaterialAnimationComponent>();

        if (damage != null)
        {
            damage.RegisterOnDamagedDelegate(Damaged);
            damage.RegisterOnKilledDelegate(Killed);
        }
    }
Exemplo n.º 12
0
        public bool FinalizeSafeBoardPosition(TroopTypeVO troopType, ref Entity spawnBuilding, ref IntPosition boardPosition, ref BoardCell <Entity> targetCell, TeamType teamType, TroopSpawnMode spawnMode, bool forceAllow)
        {
            targetCell    = this.boardController.Board.GetClampedDeployableCellAt(boardPosition.x, boardPosition.z, troopType.SizeX);
            boardPosition = new IntPosition(targetCell.X, targetCell.Z);
            BoardCell <Entity> boardCell = null;

            if (spawnMode == TroopSpawnMode.LeashedToBuilding)
            {
                if (targetCell.Children == null)
                {
                    return(false);
                }
                LinkedListNode <BoardItem <Entity> > linkedListNode = targetCell.Children.First;
                while (linkedListNode != null)
                {
                    spawnBuilding = linkedListNode.Value.Data;
                    BuildingComponent   buildingComponent   = spawnBuilding.Get <BuildingComponent>();
                    DamageableComponent damageableComponent = spawnBuilding.Get <DamageableComponent>();
                    if (buildingComponent != null && (forceAllow || buildingComponent.BuildingType.AllowDefensiveSpawn) && damageableComponent != null)
                    {
                        if (forceAllow && troopType.Type == TroopType.Champion)
                        {
                            boardPosition = new IntPosition(targetCell.X, targetCell.Z);
                            break;
                        }
                        targetCell = damageableComponent.FindASafeSpawnSpot(troopType.SizeX, out boardCell);
                        if (targetCell == null)
                        {
                            return(false);
                        }
                        boardPosition = new IntPosition(targetCell.X, targetCell.Z);
                        break;
                    }
                    else
                    {
                        linkedListNode = linkedListNode.Next;
                    }
                }
                if (linkedListNode == null)
                {
                    return(false);
                }
            }
            else if (!this.ValidateTroopPlacement(boardPosition, teamType, troopType.SizeX, true, out boardCell, forceAllow))
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 13
0
    //##############################################################################################
    // On killed, disable features and set state.
    //##############################################################################################
    public void OnKilled(DamageableComponent damage)
    {
        respawnState = RespawnState.Dying;
        respawnTimer.Start();

        // Stop movement
        velocity          = Vector3.zero;
        character.enabled = false;

        movementEnabled = false;
        lookingEnabled  = false;

        // Log this for debugging and data
        Logger.Info("=== PLAYER DEATH === at position " + transform.position + " from " + damage.GetDamager());
    }
Exemplo n.º 14
0
    private void OnHealingComplete(EntityUid uid, DamageableComponent component, HealingCompleteEvent args)
    {
        if (_mobStateSystem.IsDead(uid))
        {
            return;
        }

        if (TryComp <StackComponent>(args.Component.Owner, out var stack) && stack.Count < 1)
        {
            return;
        }

        if (component.DamageContainerID is not null &&
            !component.DamageContainerID.Equals(component.DamageContainerID))
        {
            return;
        }

        if (args.Component.BloodlossModifier != 0)
        {
            // Heal some bloodloss damage.
            _bloodstreamSystem.TryModifyBleedAmount(uid, args.Component.BloodlossModifier);
        }

        var healed = _damageable.TryChangeDamage(uid, args.Component.Damage, true);

        // Reverify that we can heal the damage.
        if (healed == null)
        {
            return;
        }

        _stacks.Use(args.Component.Owner, 1, stack);

        if (uid != args.User)
        {
            _adminLogger.Add(LogType.Healed, $"{EntityManager.ToPrettyString(args.User):user} healed {EntityManager.ToPrettyString(uid):target} for {healed.Total:damage} damage");
        }
        else
        {
            _adminLogger.Add(LogType.Healed, $"{EntityManager.ToPrettyString(args.User):user} healed themselves for {healed.Total:damage} damage");
        }

        if (args.Component.HealingEndSound != null)
        {
            SoundSystem.Play(args.Component.HealingEndSound.GetSound(), Filter.Pvs(uid, entityManager: EntityManager), uid, AudioHelpers.WithVariation(0.125f).WithVolume(-5f));
        }
    }
    //##############################################################################################
    // The gun components and the sprites must be 1-to-1 so that the sprite lookup finds a match.
    // Then, setup the timer and register for the damaged delegate.
    //##############################################################################################
    void Start()
    {
        if (gunComponents.Length != gunSprites.Length)
        {
            Logger.Error("FirstPersonHudComponent's gunComponents and gunSprites lengths don't match");
        }

        damageFlashTimer = new Timer(damageFlashTime);

        playerDamageable = GetComponent <DamageableComponent>();
        playerDamageable.RegisterOnDamagedDelegate(OnDamaged);
        playerDamageable.RegisterOnHealedDelegate(OnHealed);
        playerDamageable.RegisterOnRespawnedDelegate(OnRespawned);

        healthText.text = playerDamageable.CurrentHealth().ToString();
    }
Exemplo n.º 16
0
        public async Task TestDamageableComponents()
        {
            await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = Prototypes });

            var server = pairTracker.Pair.Server;

            var sEntityManager       = server.ResolveDependency <IEntityManager>();
            var sMapManager          = server.ResolveDependency <IMapManager>();
            var sPrototypeManager    = server.ResolveDependency <IPrototypeManager>();
            var sEntitySystemManager = server.ResolveDependency <IEntitySystemManager>();

            EntityUid           sDamageableEntity    = default;
            DamageableComponent sDamageableComponent = null;
            DamageableSystem    sDamageableSystem    = null;

            DamageGroupPrototype group1 = default !;
Exemplo n.º 17
0
        private void DealDamage(ISuicideAct suicide, IChatManager chat, DamageableComponent damageableComponent, IEntity source, IEntity target)
        {
            SuicideKind kind = suicide.Suicide(target, chat);

            if (kind != SuicideKind.Special)
            {
                damageableComponent.TakeDamage(kind switch
                {
                    SuicideKind.Brute => DamageType.Brute,
                    SuicideKind.Heat => DamageType.Heat,
                    SuicideKind.Cold => DamageType.Cold,
                    SuicideKind.Acid => DamageType.Acid,
                    SuicideKind.Toxic => DamageType.Toxic,
                    SuicideKind.Electric => DamageType.Electric,
                    _ => DamageType.Brute
                },
Exemplo n.º 18
0
    //##############################################################################################
    // Check for required data
    //##############################################################################################
    protected new void Start()
    {
        base.Start();

        if (gunModel == null)
        {
            Logger.Error("Gun Model on " + gameObject.name + "'s ModelAnimatedGunComponent cannot be null on start");
        }

        if (gunAnimator == null)
        {
            Logger.Error("Gun Animator on " + gameObject.name + "'s ModelAnimatedGunComponent cannot be null on start");
        }

        damage = GetComponent <DamageableComponent>();
    }
    private void Killed(DamageableComponent damage)
    {
        for (int i = 0, count = prefabsToSpawnOnDeath.Length; i < count; ++i)
        {
            DeathSpawnPrefab deathSpawn = prefabsToSpawnOnDeath[i];

            GameObject newEffects = Object.Instantiate(deathSpawn.effectsPrefab);
            newEffects.transform.position = transform.position + deathSpawn.effectsOffset;
            newEffects.transform.rotation = transform.rotation;
        }

        if (destroyOriginal)
        {
            Destroy(gameObject);
        }
    }
Exemplo n.º 20
0
    /// <summary>
    /// Awake
    /// </summary>
    protected void Awake()
    {
        gameObject.SetActive(false);
        Player      = gameObject.transform.parent.gameObject.GetComponent <PlayerController>();
        Damageable  = gameObject.transform.parent.gameObject.GetComponent <DamageableComponent>();
        AudioSource = GetComponent <AudioSource>();

        if (ProjectileSpawnLocation == null)
        {
            throw new UnassignedReferenceException("Did you forget to specify the spawn location?");
        }

        if (ProjectileType == null)
        {
            throw new UnassignedReferenceException("No projectile specified");
        }
    }
Exemplo n.º 21
0
        public async Task TestDamageableComponents()
        {
            var server = StartServerDummyTicker(new ServerContentIntegrationOption
            {
                ExtraPrototypes = Prototypes
            });

            await server.WaitIdleAsync();

            var sEntityManager       = server.ResolveDependency <IEntityManager>();
            var sMapManager          = server.ResolveDependency <IMapManager>();
            var sPrototypeManager    = server.ResolveDependency <IPrototypeManager>();
            var sEntitySystemManager = server.ResolveDependency <IEntitySystemManager>();

            sEntityManager.EventBus.SubscribeLocalEvent <DamageableComponent, DamageChangedEvent>(DamageChangedListener);

            EntityUid           sDamageableEntity    = default;
            DamageableComponent sDamageableComponent = null;
            DamageableSystem    sDamageableSystem    = null;

            DamageGroupPrototype group1 = default !;
        private IntPosition DetermineSpawnPosition()
        {
            IntPosition zero = IntPosition.Zero;

            switch (this.Type)
            {
            case CombatTriggerType.Area:
            case CombatTriggerType.Load:
                if (this.Leashed)
                {
                    TransformComponent transformComponent = ((Entity)this.Owner).Get <TransformComponent>();
                    if (transformComponent != null)
                    {
                        zero = new IntPosition(transformComponent.X, transformComponent.Z);
                    }
                }
                else
                {
                    DamageableComponent damageableComponent = ((Entity)this.Owner).Get <DamageableComponent>();
                    if (damageableComponent != null)
                    {
                        BoardCell <Entity> boardCell2;
                        BoardCell <Entity> boardCell = damageableComponent.FindASafeSpawnSpot(this.Troop.SizeX, out boardCell2);
                        zero = new IntPosition(boardCell.X, boardCell.Z);
                    }
                }
                break;

            case CombatTriggerType.Death:
            {
                TransformComponent transformComponent = ((Entity)this.Owner).Get <TransformComponent>();
                if (transformComponent != null)
                {
                    zero = new IntPosition(transformComponent.CenterGridX(), transformComponent.CenterGridZ());
                }
                break;
            }
            }
            return(zero);
        }
    //##############################################################################################
    // Setup the timers and check for required data
    //##############################################################################################
    protected new void Start()
    {
        base.Start();

        firingAnimationTimer    = new Timer(1.0f / firingFramerate);
        reloadingAnimationTimer = new Timer(1.0f / reloadingFramerate);

        if (gunSpriteImage == null)
        {
            Logger.Error("Gun Sprite Image on " + gameObject.name + "'s FlatAnimatedGunComponent cannot be null on start");
        }

        if (tintWithNearestLight)
        {
            lightListUpdateTimer = new Timer(LIGHT_UPDATE_TIME);
        }

        if (useGunBob)
        {
            gunImageRectTransform = gunSpriteImage.GetComponent <RectTransform>();
        }

        damage = GetComponent <DamageableComponent>();
    }
Exemplo n.º 24
0
        protected override Entity AddComponentAndDispatchAddEvent(ComponentBase comp, Type compCls)
        {
            bool flag = false;

            if (comp is AreaTriggerComponent)
            {
                this.AreaTriggerComp = (AreaTriggerComponent)comp;
                flag = true;
            }
            if (comp is ArmoryComponent)
            {
                this.ArmoryComp = (ArmoryComponent)comp;
                flag            = true;
            }
            if (comp is AssetComponent)
            {
                this.AssetComp = (AssetComponent)comp;
                flag           = true;
            }
            if (comp is AttackerComponent)
            {
                this.AttackerComp = (AttackerComponent)comp;
                flag = true;
            }
            if (comp is BarracksComponent)
            {
                this.BarracksComp = (BarracksComponent)comp;
                flag = true;
            }
            if (comp is BoardItemComponent)
            {
                this.BoardItemComp = (BoardItemComponent)comp;
                flag = true;
            }
            if (comp is BuildingAnimationComponent)
            {
                this.BuildingAnimationComp = (BuildingAnimationComponent)comp;
                flag = true;
            }
            if (comp is BuildingComponent)
            {
                this.BuildingComp = (BuildingComponent)comp;
                flag = true;
            }
            if (comp is ChampionComponent)
            {
                this.ChampionComp = (ChampionComponent)comp;
                flag = true;
            }
            if (comp is CivilianComponent)
            {
                this.CivilianComp = (CivilianComponent)comp;
                flag = true;
            }
            if (comp is ClearableComponent)
            {
                this.ClearableComp = (ClearableComponent)comp;
                flag = true;
            }
            if (comp is DamageableComponent)
            {
                this.DamageableComp = (DamageableComponent)comp;
                flag = true;
            }
            if (comp is DefenderComponent)
            {
                this.DefenderComp = (DefenderComponent)comp;
                flag = true;
            }
            if (comp is DefenseLabComponent)
            {
                this.DefenseLabComp = (DefenseLabComponent)comp;
                flag = true;
            }
            if (comp is DroidComponent)
            {
                this.DroidComp = (DroidComponent)comp;
                flag           = true;
            }
            if (comp is DroidHutComponent)
            {
                this.DroidHutComp = (DroidHutComponent)comp;
                flag = true;
            }
            if (comp is SquadBuildingComponent)
            {
                this.SquadBuildingComp = (SquadBuildingComponent)comp;
                flag = true;
            }
            if (comp is NavigationCenterComponent)
            {
                this.NavigationCenterComp = (NavigationCenterComponent)comp;
                flag = true;
            }
            if (comp is FactoryComponent)
            {
                this.FactoryComp = (FactoryComponent)comp;
                flag             = true;
            }
            if (comp is CantinaComponent)
            {
                this.CantinaComp = (CantinaComponent)comp;
                flag             = true;
            }
            if (comp is FleetCommandComponent)
            {
                this.FleetCommandComp = (FleetCommandComponent)comp;
                flag = true;
            }
            if (comp is FollowerComponent)
            {
                this.FollowerComp = (FollowerComponent)comp;
                flag = true;
            }
            if (comp is GameObjectViewComponent)
            {
                this.GameObjectViewComp = (GameObjectViewComponent)comp;
                flag = true;
            }
            if (comp is GeneratorComponent)
            {
                this.GeneratorComp = (GeneratorComponent)comp;
                flag = true;
            }
            if (comp is GeneratorViewComponent)
            {
                this.GeneratorViewComp = (GeneratorViewComponent)comp;
                flag = true;
            }
            if (comp is HealerComponent)
            {
                this.HealerComp = (HealerComponent)comp;
                flag            = true;
            }
            if (comp is TroopShieldComponent)
            {
                this.TroopShieldComp = (TroopShieldComponent)comp;
                flag = true;
            }
            if (comp is TroopShieldViewComponent)
            {
                this.TroopShieldViewComp = (TroopShieldViewComponent)comp;
                flag = true;
            }
            if (comp is TroopShieldHealthComponent)
            {
                this.TroopShieldHealthComp = (TroopShieldHealthComponent)comp;
                flag = true;
            }
            if (comp is HealthComponent)
            {
                this.HealthComp = (HealthComponent)comp;
                flag            = true;
            }
            if (comp is HealthViewComponent)
            {
                this.HealthViewComp = (HealthViewComponent)comp;
                flag = true;
            }
            if (comp is HQComponent)
            {
                this.HQComp = (HQComponent)comp;
                flag        = true;
            }
            if (comp is KillerComponent)
            {
                this.KillerComp = (KillerComponent)comp;
                flag            = true;
            }
            if (comp is LootComponent)
            {
                this.LootComp = (LootComponent)comp;
                flag          = true;
            }
            if (comp is MeterShaderComponent)
            {
                this.MeterShaderComp = (MeterShaderComponent)comp;
                flag = true;
            }
            if (comp is OffenseLabComponent)
            {
                this.OffenseLabComp = (OffenseLabComponent)comp;
                flag = true;
            }
            if (comp is PathingComponent)
            {
                this.PathingComp = (PathingComponent)comp;
                flag             = true;
            }
            if (comp is SecondaryTargetsComponent)
            {
                this.SecondaryTargetsComp = (SecondaryTargetsComponent)comp;
                flag = true;
            }
            if (comp is ShieldBorderComponent)
            {
                this.ShieldBorderComp = (ShieldBorderComponent)comp;
                flag = true;
            }
            if (comp is ShieldGeneratorComponent)
            {
                this.ShieldGeneratorComp = (ShieldGeneratorComponent)comp;
                flag = true;
            }
            if (comp is SizeComponent)
            {
                this.SizeComp = (SizeComponent)comp;
                flag          = true;
            }
            if (comp is ShooterComponent)
            {
                this.ShooterComp = (ShooterComponent)comp;
                flag             = true;
            }
            if (comp is StarportComponent)
            {
                this.StarportComp = (StarportComponent)comp;
                flag = true;
            }
            if (comp is StateComponent)
            {
                this.StateComp = (StateComponent)comp;
                flag           = true;
            }
            if (comp is StorageComponent)
            {
                this.StorageComp = (StorageComponent)comp;
                flag             = true;
            }
            if (comp is SupportComponent)
            {
                this.SupportComp = (SupportComponent)comp;
                flag             = true;
            }
            if (comp is SupportViewComponent)
            {
                this.SupportViewComp = (SupportViewComponent)comp;
                flag = true;
            }
            if (comp is TacticalCommandComponent)
            {
                this.TacticalCommandComp = (TacticalCommandComponent)comp;
                flag = true;
            }
            if (comp is ChampionPlatformComponent)
            {
                this.ChampionPlatformComp = (ChampionPlatformComponent)comp;
                flag = true;
            }
            if (comp is TeamComponent)
            {
                this.TeamComp = (TeamComponent)comp;
                flag          = true;
            }
            if (comp is TrackingComponent)
            {
                this.TrackingComp = (TrackingComponent)comp;
                flag = true;
            }
            if (comp is TrackingGameObjectViewComponent)
            {
                this.TrackingGameObjectViewComp = (TrackingGameObjectViewComponent)comp;
                flag = true;
            }
            if (comp is TransformComponent)
            {
                this.TransformComp = (TransformComponent)comp;
                flag = true;
            }
            if (comp is TransportComponent)
            {
                this.TransportComp = (TransportComponent)comp;
                flag = true;
            }
            if (comp is TroopComponent)
            {
                this.TroopComp = (TroopComponent)comp;
                flag           = true;
            }
            if (comp is TurretBuildingComponent)
            {
                this.TurretBuildingComp = (TurretBuildingComponent)comp;
                flag = true;
            }
            if (comp is TurretShooterComponent)
            {
                this.TurretShooterComp = (TurretShooterComponent)comp;
                flag = true;
            }
            if (comp is WalkerComponent)
            {
                this.WalkerComp = (WalkerComponent)comp;
                flag            = true;
            }
            if (comp is WallComponent)
            {
                this.WallComp = (WallComponent)comp;
                flag          = true;
            }
            if (comp is BuffComponent)
            {
                this.BuffComp = (BuffComponent)comp;
                flag          = true;
            }
            if (comp is TrapComponent)
            {
                this.TrapComp = (TrapComponent)comp;
                flag          = true;
            }
            if (comp is TrapViewComponent)
            {
                this.TrapViewComp = (TrapViewComponent)comp;
                flag = true;
            }
            if (comp is HousingComponent)
            {
                this.HousingComp = (HousingComponent)comp;
                flag             = true;
            }
            if (comp is ScoutTowerComponent)
            {
                this.ScoutTowerComp = (ScoutTowerComponent)comp;
                flag = true;
            }
            if (comp is SpawnComponent)
            {
                this.SpawnComp = (SpawnComponent)comp;
                flag           = true;
            }
            if (!flag && compCls != null)
            {
                Service.Logger.Error("Invalid component add: " + compCls.Name);
            }
            return(base.AddComponentAndDispatchAddEvent(comp, compCls));
        }
Exemplo n.º 25
0
    //##############################################################################################
    // Update the bullet, moving it along it's velocity, unless it collides with something.
    // If that something is a damageable, deal the damage to it. Either way, mark the bullet
    // for destruction next update.
    // This is done in Fixed Update so that the physics is properly synchronized for the bullet.
    //##############################################################################################
    void FixedUpdate()
    {
        // Prevents updating before firing information has been provided, since fixed update is
        // disjoint from regular unity update
        if (!fired)
        {
            return;
        }

        // The destruction is done 1 frame after being marked for kill so the bullet and effects
        // appear in the correct position visually for that last frame, before bullet is destroyed.
        if (shouldKill)
        {
            // Notify all delegates
            if (bulletDestroyedDelegates != null)
            {
                foreach (OnBulletDestroyed bulletDestroyedDelegate in bulletDestroyedDelegates)
                {
                    bulletDestroyedDelegate();
                }
            }

            // Destroy if not pooled, otherwise mark this bullet as freed
            if (poolIdentifier == null)
            {
                Destroy(gameObject);
            }
            else
            {
                PooledGameObjectManager.FreeInstanceToPool(poolIdentifier, gameObject);
            }

            return;
        }

        velocity += Physics.gravity * gravityModifier * Time.deltaTime * Time.deltaTime;
        Vector3 move     = velocity * Time.deltaTime;
        float   moveDist = move.magnitude;

        // Kill the bullet if it's gone too far
        if ((transform.position - startPosition).sqrMagnitude >= maxDistance * maxDistance)
        {
            shouldKill = true;
        }

        // See if move would hit anything, ignoring the 'no bullet collide' layer and triggers
        RaycastHit hit;

        if (Physics.Raycast(transform.position, move, out hit, moveDist, ~NO_BULLET_COLLIDE_LAYER, QueryTriggerInteraction.Ignore))
        {
            if (hit.collider.gameObject != firer)
            {
                transform.position = hit.point;

                DamageableComponent damageable = hit.collider.gameObject.GetComponent <DamageableComponent>();

                if (damageable == null)
                {
                    DamageablePieceComponent damageablePiece = hit.collider.gameObject.GetComponent <DamageablePieceComponent>();

                    if (damageablePiece != null)
                    {
                        damageable = damageablePiece.GetDamageableComponent();
                    }
                }

                if (damageable != null)
                {
                    // Never ricochet off a damageable
                    collisionsRemaining = 0;
                    damageable.DealDamage(damage, type, startPosition, firer);
                }
                else
                {
                    // Don't spawn decals when hitting damageable
                    if (optionalDecalObject != null && damageable == null)
                    {
                        GameObject decalInstance = GameObject.Instantiate(optionalDecalObject);

                        // Add random offset to prevent z-fighting
                        float randomOffset = (Random.value * BULLET_EFFECTS_OFFSET);

                        decalInstance.transform.position = hit.point + (hit.normal * (BULLET_DECAL_OFFSET + randomOffset));
                        decalInstance.transform.rotation = Quaternion.LookRotation(hit.normal);
                    }

                    // TODO add impact effects lookup system for hit object
                    if (optionalImpactEffects != null)
                    {
                        GameObject fx = GameObject.Instantiate(optionalImpactEffects);

                        // Scoot fx back away from collision a little
                        fx.transform.position = transform.position + (-move).normalized * BULLET_EFFECTS_OFFSET;
                    }
                }

                // Play impact sound if needed
                if (impactSound != null)
                {
                    SoundManagerComponent.PlaySound(impactSound, gameObject);
                }

                if (collisionsRemaining > 0)
                {
                    collisionsRemaining--;

                    if (Random.value <= collisionModeChance)
                    {
                        if (collisionMode == CollisionMode.Ricochet)
                        {
                            float velocityMagnitude = velocity.magnitude;
                            velocity           = Vector3.Reflect(velocity.normalized, hit.normal).normalized *velocityMagnitude;
                            transform.position = hit.point + (velocity * 0.01f);
                        }
                        else if (collisionMode == CollisionMode.Pierce)
                        {
                            transform.position += move;
                        }
                    }
                    else
                    {
                        collisionsRemaining = 0;
                    }
                }

                if (collisionsRemaining <= 0)
                {
                    shouldKill = true;
                }
            }
        }
        else
        {
            transform.position += move;
        }
    }
Exemplo n.º 26
0
 public void DamageChangedListener(EntityUid _, DamageableComponent comp, DamageChangedEvent args)
 {
     DamageChanged = true;
 }
 void Start()
 {
     parentDamageable = GetComponentInParent <DamageableComponent>();
 }
Exemplo n.º 28
0
 public override object Remove(Type compCls)
 {
     if (compCls == typeof(AreaTriggerComponent))
     {
         this.AreaTriggerComp = null;
     }
     else if (compCls == typeof(ArmoryComponent))
     {
         this.ArmoryComp = null;
     }
     else if (compCls == typeof(AssetComponent))
     {
         this.AssetComp = null;
     }
     else if (compCls == typeof(AttackerComponent))
     {
         this.AttackerComp = null;
     }
     else if (compCls == typeof(BarracksComponent))
     {
         this.BarracksComp = null;
     }
     else if (compCls == typeof(BoardItemComponent))
     {
         this.BoardItemComp = null;
     }
     else if (compCls == typeof(BuildingAnimationComponent))
     {
         this.BuildingAnimationComp = null;
     }
     else if (compCls == typeof(BuildingComponent))
     {
         this.BuildingComp = null;
     }
     else if (compCls == typeof(CantinaComponent))
     {
         this.CantinaComp = null;
     }
     else if (compCls == typeof(ChampionComponent))
     {
         this.ChampionComp = null;
     }
     else if (compCls == typeof(CivilianComponent))
     {
         this.CivilianComp = null;
     }
     else if (compCls == typeof(ClearableComponent))
     {
         this.ClearableComp = null;
     }
     else if (compCls == typeof(DamageableComponent))
     {
         this.DamageableComp = null;
     }
     else if (compCls == typeof(DefenderComponent))
     {
         this.DefenderComp = null;
     }
     else if (compCls == typeof(DefenseLabComponent))
     {
         this.DefenseLabComp = null;
     }
     else if (compCls == typeof(DroidComponent))
     {
         this.DroidComp = null;
     }
     else if (compCls == typeof(DroidHutComponent))
     {
         this.DroidHutComp = null;
     }
     else if (compCls == typeof(SquadBuildingComponent))
     {
         this.SquadBuildingComp = null;
     }
     else if (compCls == typeof(NavigationCenterComponent))
     {
         this.NavigationCenterComp = null;
     }
     else if (compCls == typeof(FactoryComponent))
     {
         this.FactoryComp = null;
     }
     else if (compCls == typeof(FleetCommandComponent))
     {
         this.FleetCommandComp = null;
     }
     else if (compCls == typeof(FollowerComponent))
     {
         this.FollowerComp = null;
     }
     else if (compCls == typeof(GameObjectViewComponent))
     {
         this.GameObjectViewComp = null;
     }
     else if (compCls == typeof(GeneratorComponent))
     {
         this.GeneratorComp = null;
     }
     else if (compCls == typeof(GeneratorViewComponent))
     {
         this.GeneratorViewComp = null;
     }
     else if (compCls == typeof(HealerComponent))
     {
         this.HealerComp = null;
     }
     else if (compCls == typeof(HealthComponent))
     {
         this.HealthComp = null;
     }
     else if (compCls == typeof(TroopShieldComponent))
     {
         this.TroopShieldComp = null;
     }
     else if (compCls == typeof(TroopShieldViewComponent))
     {
         this.TroopShieldViewComp = null;
     }
     else if (compCls == typeof(TroopShieldHealthComponent))
     {
         this.TroopShieldHealthComp = null;
     }
     else if (compCls == typeof(HealthViewComponent))
     {
         this.HealthViewComp = null;
     }
     else if (compCls == typeof(HQComponent))
     {
         this.HQComp = null;
     }
     else if (compCls == typeof(KillerComponent))
     {
         this.KillerComp = null;
     }
     else if (compCls == typeof(LootComponent))
     {
         this.LootComp = null;
     }
     else if (compCls == typeof(MeterShaderComponent))
     {
         this.MeterShaderComp = null;
     }
     else if (compCls == typeof(OffenseLabComponent))
     {
         this.OffenseLabComp = null;
     }
     else if (compCls == typeof(PathingComponent))
     {
         this.PathingComp = null;
     }
     else if (compCls == typeof(SecondaryTargetsComponent))
     {
         this.SecondaryTargetsComp = null;
     }
     else if (compCls == typeof(ShieldBorderComponent))
     {
         this.ShieldBorderComp = null;
     }
     else if (compCls == typeof(ShieldGeneratorComponent))
     {
         this.ShieldGeneratorComp = null;
     }
     else if (compCls == typeof(SizeComponent))
     {
         this.SizeComp = null;
     }
     else if (compCls == typeof(ShooterComponent))
     {
         this.ShooterComp = null;
     }
     else if (compCls == typeof(StarportComponent))
     {
         this.StarportComp = null;
     }
     else if (compCls == typeof(StateComponent))
     {
         this.StateComp = null;
     }
     else if (compCls == typeof(StorageComponent))
     {
         this.StorageComp = null;
     }
     else if (compCls == typeof(SupportComponent))
     {
         this.SupportComp = null;
     }
     else if (compCls == typeof(SupportViewComponent))
     {
         this.SupportViewComp = null;
     }
     else if (compCls == typeof(TacticalCommandComponent))
     {
         this.TacticalCommandComp = null;
     }
     else if (compCls == typeof(ChampionPlatformComponent))
     {
         this.ChampionPlatformComp = null;
     }
     else if (compCls == typeof(TeamComponent))
     {
         this.TeamComp = null;
     }
     else if (compCls == typeof(TrackingComponent))
     {
         this.TrackingComp = null;
     }
     else if (compCls == typeof(TrackingGameObjectViewComponent))
     {
         this.TrackingGameObjectViewComp = null;
     }
     else if (compCls == typeof(TransformComponent))
     {
         this.TransformComp = null;
     }
     else if (compCls == typeof(TransportComponent))
     {
         this.TransportComp = null;
     }
     else if (compCls == typeof(TroopComponent))
     {
         this.TroopComp = null;
     }
     else if (compCls == typeof(TurretBuildingComponent))
     {
         this.TurretBuildingComp = null;
     }
     else if (compCls == typeof(TurretShooterComponent))
     {
         this.TurretShooterComp = null;
     }
     else if (compCls == typeof(WalkerComponent))
     {
         this.WalkerComp = null;
     }
     else if (compCls == typeof(WallComponent))
     {
         this.WallComp = null;
     }
     else if (compCls == typeof(BuffComponent))
     {
         this.BuffComp = null;
     }
     else if (compCls == typeof(TrapComponent))
     {
         this.TrapComp = null;
     }
     else if (compCls == typeof(TrapViewComponent))
     {
         this.TrapViewComp = null;
     }
     else if (compCls == typeof(HousingComponent))
     {
         this.HousingComp = null;
     }
     else if (compCls == typeof(SpawnComponent))
     {
         this.SpawnComp = null;
     }
     return(base.Remove(compCls));
 }
        public async Task Test()
        {
            await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings { NoClient = true, ExtraPrototypes = Prototypes });

            var server = pairTracker.Pair.Server;

            var testMap = await PoolManager.CreateTestMap(pairTracker);

            var sEntityManager       = server.ResolveDependency <IEntityManager>();
            var sEntitySystemManager = server.ResolveDependency <IEntitySystemManager>();

            EntityUid                      sDestructibleEntity          = default;
            DamageableComponent            sDamageableComponent         = null;
            TestDestructibleListenerSystem sTestThresholdListenerSystem = null;
            DamageableSystem               sDamageableSystem            = null;

            await server.WaitPost(() =>
            {
                var coordinates = testMap.GridCoords;

                sDestructibleEntity          = sEntityManager.SpawnEntity(DestructibleDamageTypeEntityId, coordinates);
                sDamageableComponent         = IoCManager.Resolve <IEntityManager>().GetComponent <DamageableComponent>(sDestructibleEntity);
                sTestThresholdListenerSystem = sEntitySystemManager.GetEntitySystem <TestDestructibleListenerSystem>();
                sTestThresholdListenerSystem.ThresholdsReached.Clear();
                sDamageableSystem = sEntitySystemManager.GetEntitySystem <DamageableSystem>();
            });

            await server.WaitRunTicks(5);

            await server.WaitAssertion(() =>
            {
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);
            });

            await server.WaitAssertion(() =>
            {
                var bluntDamageType = IoCManager.Resolve <IPrototypeManager>().Index <DamageTypePrototype>("TestBlunt");
                var slashDamageType = IoCManager.Resolve <IPrototypeManager>().Index <DamageTypePrototype>("TestSlash");

                var bluntDamage = new DamageSpecifier(bluntDamageType, 5);
                var slashDamage = new DamageSpecifier(slashDamageType, 5);

                // Raise blunt damage to 5
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true);

                // No thresholds reached yet, the earliest one is at 10 damage
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);

                // Raise blunt damage to 10
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage, true);

                // No threshold reached, slash needs to be 10 as well
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);

                // Raise slash damage to 10
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true);

                // One threshold reached, blunt 10 + slash 10
                Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1));

                // Threshold blunt 10 + slash 10
                var msg       = sTestThresholdListenerSystem.ThresholdsReached[0];
                var threshold = msg.Threshold;

                // Check that it matches the YAML prototype
                Assert.That(threshold.Behaviors, Is.Empty);
                Assert.NotNull(threshold.Trigger);
                Assert.That(threshold.Triggered, Is.True);
                Assert.IsInstanceOf <AndTrigger>(threshold.Trigger);

                var trigger = (AndTrigger)threshold.Trigger;

                Assert.IsInstanceOf <DamageTypeTrigger>(trigger.Triggers[0]);
                Assert.IsInstanceOf <DamageTypeTrigger>(trigger.Triggers[1]);

                sTestThresholdListenerSystem.ThresholdsReached.Clear();

                // Raise blunt damage to 20
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true);

                // No new thresholds reached
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);

                // Raise slash damage to 20
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true);

                // No new thresholds reached
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);

                // Lower blunt damage to 0
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * -4, true);

                // No new thresholds reached, healing should not trigger it
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);

                // Raise blunt damage back up to 10
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true);

                // 10 blunt + 10 slash threshold reached, blunt was healed and brought back to its threshold amount and slash stayed the same
                Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1));

                sTestThresholdListenerSystem.ThresholdsReached.Clear();

                // Heal both types of damage to 0
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * -2, true);
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * -4, true);

                // No new thresholds reached, healing should not trigger it
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);

                // Raise blunt damage to 10
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true);

                // No new thresholds reached
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);

                // Raise slash damage to 10
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true);

                // Both types of damage were healed and then raised again, the threshold should have been reached as triggers once is default false
                Assert.That(sTestThresholdListenerSystem.ThresholdsReached.Count, Is.EqualTo(1));

                // Threshold blunt 10 + slash 10
                msg       = sTestThresholdListenerSystem.ThresholdsReached[0];
                threshold = msg.Threshold;

                // Check that it matches the YAML prototype
                Assert.That(threshold.Behaviors, Is.Empty);
                Assert.NotNull(threshold.Trigger);
                Assert.That(threshold.Triggered, Is.True);
                Assert.IsInstanceOf <AndTrigger>(threshold.Trigger);

                trigger = (AndTrigger)threshold.Trigger;

                Assert.IsInstanceOf <DamageTypeTrigger>(trigger.Triggers[0]);
                Assert.IsInstanceOf <DamageTypeTrigger>(trigger.Triggers[1]);

                sTestThresholdListenerSystem.ThresholdsReached.Clear();

                // Change triggers once to true
                threshold.TriggersOnce = true;

                // Heal blunt and slash back to 0
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * -2, true);
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * -2, true);

                // No new thresholds reached from healing
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);

                // Raise blunt damage to 10
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, bluntDamage * 2, true);

                // No new thresholds reached
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);

                // Raise slash damage to 10
                sDamageableSystem.TryChangeDamage(sDestructibleEntity, slashDamage * 2, true);

                // No new thresholds reached as triggers once is set to true and it already triggered before
                Assert.IsEmpty(sTestThresholdListenerSystem.ThresholdsReached);
            });

            await pairTracker.CleanReturnAsync();
        }
    private FormattedMessage CreateMarkup(EntityUid uid, HealthExaminableComponent component, DamageableComponent damage)
    {
        var msg = new FormattedMessage();

        var first = true;

        foreach (var type in component.ExaminableTypes)
        {
            if (!damage.Damage.DamageDict.TryGetValue(type, out var dmg))
            {
                continue;
            }

            if (dmg == FixedPoint2.Zero)
            {
                continue;
            }

            FixedPoint2 closest = FixedPoint2.Zero;

            string chosenLocStr = string.Empty;
            foreach (var threshold in component.Thresholds)
            {
                var str        = $"health-examinable-{component.LocPrefix}-{type}-{threshold}";
                var tempLocStr = Loc.GetString($"health-examinable-{component.LocPrefix}-{type}-{threshold}", ("target", Identity.Entity(uid, EntityManager)));

                // i.e., this string doesn't exist, because theres nothing for that threshold
                if (tempLocStr == str)
                {
                    continue;
                }

                if (dmg > threshold && threshold > closest)
                {
                    chosenLocStr = tempLocStr;
                    closest      = threshold;
                }
            }

            if (closest == FixedPoint2.Zero)
            {
                continue;
            }

            if (!first)
            {
                msg.PushNewline();
            }
            else
            {
                first = false;
            }
            msg.AddMarkup(chosenLocStr);
        }

        if (msg.IsEmpty)
        {
            msg.AddMarkup(Loc.GetString($"health-examinable-{component.LocPrefix}-none"));
        }

        // Anything else want to add on to this?
        RaiseLocalEvent(uid, new HealthBeingExaminedEvent(msg), true);

        return(msg);
    }