상속: MonoBehaviour
    public override void OnHitWeapon(BaseWeapon weapon, BaseCharacter attacker, DamageInfo dmg)
    {
        //Test to see if the person who just shot us is closer than our current target (usually the sandcastle)
        if (GameHandler.IsPlayer(attacker))
        {
            if (Vector3.Distance(transform.position, attacker.transform.position) < Vector3.Distance(transform.position, currentIntent.targetPosition))
            {
                //If the attacker is close, switch to him as the target and attack him/her
                currentIntent = new AIIntent() { owner = this, target = attacker, intent = Intent.Attack, intentAssignTime = Time.fixedTime };
            }
        }

        base.OnHitWeapon(weapon, attacker, dmg);

        if (this.CurrentHealth <= 0)
        {
            if (GameHandler.IsPlayer(attacker))
            {
                (attacker as PlayerController).RewardForKill(150, this);
                GameHandler.instance.spawnHandler.OnCrabDeath();

                //GameObject g = ItemDrop[Random.Range(0, ItemDrop.Length)];

                float r = Random.RandomRange(0.0f, 1.0f);

                if (r < dropProbabilty)
                {
                    GameObject g = (GameObject)GameObject.Instantiate(ItemDrop[Random.Range(0, ItemDrop.Length)], transform.position, transform.rotation);
                    g.rigidbody.AddForce(Vector3.up * 5, ForceMode.Impulse);
                }
            }
        }
    }
예제 #2
0
 public void AbsorbedDamage(DamageInfo dinfo)
 {
     Apparel_MedievalShield.SoundAbsorbDamage.PlayOneShot(this.wearer.Position);
     this.impactAngleVect = Vector3Utility.HorizontalVectorFromAngle(dinfo.Angle);
     Vector3 loc = this.wearer.TrueCenter() + this.impactAngleVect.RotatedBy(180f) * 0.5f;
     MoteThrower.ThrowStatic(loc, ThingDefOf.Mote_ShotHit_Spark, 1f);
 }
예제 #3
0
    public bool TakeDamage(DamageInfo damageInfo)
    {
        if (!alive)
            return false;

        SendMessage( "OnIncomingDamage", damageInfo, SendMessageOptions.DontRequireReceiver );	// Allow other components to modify the damage.

        if (damageInfo.rejected)
            return false;

        health -= (int)damageInfo.damage;

        SendMessage( "OnTakeDamage", damageInfo, SendMessageOptions.DontRequireReceiver );
        if ( damageInfo.attacker )
        {
            damageInfo.attacker.SendMessage( "OnDamageDealt", new DamageReport{ victim = gameObject, damageInfo = damageInfo }, SendMessageOptions.DontRequireReceiver );
        }

        if (!alive)
        {
            SendMessage( "OnKilled", damageInfo, SendMessageOptions.DontRequireReceiver );
            if ( damageInfo.attacker )
            {
                damageInfo.attacker.SendMessage( "OnKilledOther", new DamageReport{ victim = gameObject, damageInfo = damageInfo }, SendMessageOptions.DontRequireReceiver );
            }
        }

        return true;
    }
예제 #4
0
 void Update()
 {
     if (_countingDown)
     {
         warningText.text = string.Format("Entering Atmosphere. Destruction Imminent.");
         if (timer.currentTime > 0)
         {
             countdownText.text = string.Format("{0}", ((int)timer.currentTime + 1).ToString());
         }
         else
         {
             _countingDown = false;
             DamageInfo damageInfo = new DamageInfo(gameObject, int.MaxValue);
             HealthController health = GameObject.FindGameObjectWithTag("Player").GetComponent<HealthController>();
             if (health != null)
             {
                 health.Damage(damageInfo);
             }
         }
     }
     else if (_justFinished)
     {
         _justFinished = false;
         warningText.text = "";
         countdownText.text = "";
     }
 }
예제 #5
0
        public bool handleActorAttack(DamageInfo damageInfo)
        {
            for (int i = 0; i < actors.Count; i++)
            {
                victim = actors.ElementAt(i);
                if (victim.Equals(damageInfo.attacker))
                    continue;
                else if (victim.hitBox.Intersects(damageInfo.attackRect))
                {
                    victim.velocity += damageInfo.attacker.sightVector * 20;
                    victim.onHurt(damageInfo);
                    Recoil recoil = new Recoil(victim.animationList, victim);
                    if (!victim.animationList.has(recoil))
                        victim.animationList.pushFront(recoil);
                    if (victim.health <= 0)
                    {
                        victim.onKill(damageInfo);
                        actors.Remove(victim);
                    }
                    return true;
                }
            }

            return false;
            
        }
예제 #6
0
	private void Damage(float damage)
	{
		HitInfo hitInfo = new HitInfo(Entity, Entity, Vector3.zero, Vector3.zero, "Untagged");
		DamageInfo damageInfo = new DamageInfo(hitInfo, damage);

		GlobalEvents.Invoke(new WeaponDamageEvent(null, damageInfo));
	}
예제 #7
0
	private void Kill()
	{
		HitInfo hitInfo = new HitInfo(Entity, Entity, Vector3.zero, Vector3.zero, "Untagged");
		DamageInfo damageInfo = new DamageInfo(hitInfo, health.CurrentHealth);

		GlobalEvents.Invoke(new WeaponDamageEvent(null, damageInfo));
	}
 private static void InformPsychology(DamageInfo dinfo, Pawn pawn)
 {
     if (!pawn.Dead && pawn.needs.mood != null && pawn.thinker != null && dinfo.Def.battleWound)
     {
         pawn.needs.mood.thoughts.TryGainThought(ThoughtDefOf.BattleWounded);
     }
 }
예제 #9
0
        override public void update(float dt)
        {
            elapsed += dt;
            curFrame = (int)(elapsed * 12);

            switch (curFrame)
            {
                case(0):
                    owner.setAnimationFrame(0, 0);
                    break;
                case(3):
                    if(!hitActor){
                        Point offset = new Point(0, 40);
                        float s = (float)(Math.Sin(owner.bodyRotation));
                        float c = (float)(Math.Cos(owner.bodyRotation));
                        Point newOffset = new Point((int)(offset.X * c - offset.Y * s), (int)(offset.X * s + offset.Y * c));
                        this.attackBox.X = owner.hitBox.Center.X + newOffset.X;
                        this.attackBox.Y = owner.hitBox.Center.Y + newOffset.Y;
                        this.attackBox.Width = 30;
                        this.attackBox.Height = 30;
                        owner.attackBox = this.attackBox;
                        owner.velocity.X += (float)Math.Cos(owner.bodyRotation + MathHelper.Pi / 2) * 2;
                        owner.velocity.Y += (float)Math.Sin(owner.bodyRotation + MathHelper.Pi / 2) * 2;
                        DamageInfo damageInfo = new DamageInfo(owner, 20, this.attackBox);
                        owner.onAttack(damageInfo);
                        //hitActor = actorManager.handleActorAttack(damageInfo);
                    }
                    owner.setAnimationFrame(curFrame, 1);
                    break;
                default:
                    owner.setAnimationFrame(curFrame, 1);
                    owner.isAttacking = false;
                    break;
            }
        }
 private static BodyPartRecord GetExactPartFromDamageInfo(DamageInfo dinfo, Pawn pawn)
 {
     if (dinfo.Part.Value.Part == null)
     {
         BodyPartRecord randomNotMissingPart = pawn.health.hediffSet.GetRandomNotMissingPart(dinfo.Part.Value.Height, dinfo.Part.Value.Depth);
         if (randomNotMissingPart == null)
         {
             Log.Warning("GetRandomNotMissingPart returned null (any part).");
         }
         return randomNotMissingPart;
     }
     if (!dinfo.Part.Value.CanMissBodyPart)
     {
         return (
             from x in pawn.health.hediffSet.GetNotMissingParts(null, null)
             where x == dinfo.Part.Value.Part
             select x).FirstOrDefault<BodyPartRecord>();
     }
     BodyPartRecord randomNotMissingPart2 = pawn.health.hediffSet.GetRandomNotMissingPart(null, null);
     if (randomNotMissingPart2 == null)
     {
         Log.Warning("GetRandomNotMissingPart returned null (specified part).");
     }
     return randomNotMissingPart2;
 }
예제 #11
0
		public void mod_AdjustDamageDealt(GameObject enemy, DamageInfo damage, bool testing) {
			if (IEModOptions.DisableFriendlyFire && gameObject && enemy?.GetComponent<Faction>()?.IsFriendly(gameObject) == true && base.IsPartyMember) {
				damage.IsCriticalHit = damage.Interrupts = damage.IsGraze =damage.IsKillingBlow = false;
				damage.IsMiss = true;
				return;
			}
			orig_AdjustDamageDealt(enemy, damage, testing);
		}
 public virtual void Launch(Transform tower, Transform target, DamageInfo dmg)
 {
     isLaunched = true;
     Tower = tower;
     Target = target;
     TargetLocation = target.position;
     Damage = dmg;
 }
예제 #13
0
    public virtual void OnDamage(DamageInfo dmg)
    {
        CombatTextManager.Instance.Show(dmg.amount.ToString(), 40, Color.yellow, transform.position, Vector3.up, 1.5f);
        Hitpoint -= dmg.amount;

        if (Hitpoint <= 0)
            OnDeath();
    }
예제 #14
0
    void ReceiveDamage( DamageInfo damageInfo )
    {
        health -= damageInfo.amount;

        if(health <= 0) {
            setDying(true);
        }
    }
 public override float Apply(DamageInfo dinfo, Thing thing)
 {
     Pawn pawn = thing as Pawn;
     if (pawn == null)
     {
         return base.Apply(dinfo, thing);
     }
     return this.ApplyToPawn(dinfo, pawn);
 }
예제 #16
0
        // apply remaining damage and scatter things in slots, if holder is destroyed
        public override void PostPostApplyDamage(DamageInfo dinfo, float totalDamageDealt)
        {
            if (parent.HitPoints < 0)
            {
                foreach (var thing in slots)
                    thing.HitPoints -= (int)totalDamageDealt - parent.HitPoints;

                slots.TryDropAll(parent.Position, ThingPlaceMode.Near);
            }
        }
    public override void Action()
    {
        var dmg = new DamageInfo();
        dmg.amount = 5;

        foreach (Collider c in Physics.OverlapSphere(hitOrigin.position, hitLength, targetMask))
        {
            c.SendMessage("OnDamage", dmg);
        }
    }
예제 #18
0
        public DamageInfo Copy()
        {
            DamageInfo newInfo = new DamageInfo();
            newInfo.minPhysical = this.minPhysical;
            newInfo.maxPhysical = this.maxPhysical;
            newInfo.fire = this.fire;
            newInfo.lightning = this.lightning;
            newInfo.water = this.water;

            return newInfo;
        }
 public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt)
 {
     if (this.def.defName != "PlasteelBattery" || this.def.defName != "UraniumBattery")
     {
         if (!base.Destroyed && this.ticksToExplode == 0 && dinfo.Def == DamageDefOf.Flame && Rand.Value < 0.05f && base.GetComp<CompPowerBattery>().StoredEnergy > 500f)
         {
             this.ticksToExplode = Rand.Range(70, 150);
             this.StartWickSustainer();
         }
     }
 }
예제 #20
0
    public void Damage(DamageInfo damageInfo)
    {
        _charge -= damageInfo.Damage;

        if (healthBar != null)
        {
            healthBar.fillAmount = _charge / maxCharge;
        }

        _wait = Time.time + waitBeforeRecharge;
        StartCoroutine(ShowShieldRenderer(0.2f));
    }
예제 #21
0
    protected override void Action(Transform target)
    {
        //base.Action(target);
        lastAction = Time.time;

        DamageInfo dmg = new DamageInfo();
        dmg.amount = 5;

        //target.SendMessage("OnDamage", dmg);

        var arrow = Instantiate(projectile, transform.position, Quaternion.identity) as GameObject;
        arrow.GetComponent<BaseProjectile>().Launch(transform, target, dmg);
    }
 private static void PlayWoundedVoiceSound(DamageInfo dinfo, Pawn pawn)
 {
     if (pawn.Dead)
     {
         return;
     }
     if (dinfo.InstantOldInjury)
     {
         return;
     }
     if (dinfo.Def.externalViolence)
     {
         LifeStageUtility.PlayNearestLifestageSound(pawn, (LifeStageAge ls) => ls.soundWounded);
     }
 }
예제 #23
0
    protected override void Action(Transform target)
    {
        Debug.DrawRay(transform.position, target.position - transform.position, Color.red, 1.5f);
     
        //base.Action(target);
        lastAction = Time.time;

        DamageInfo dmg = new DamageInfo();
        dmg.amount = 2;

        foreach (var c in Physics.OverlapSphere(transform.position, range, LayerMask.GetMask("Enemy")))
        {
            //c.GetComponent<AICombat>().OnDamage(dmg);
            c.SendMessage("OnDamage", dmg);
        }
    }
예제 #24
0
        //-----------------------------------------------------------------------------
        // Overridden Methods
        //-----------------------------------------------------------------------------
        public override void OnBegin(MonsterState previousState)
        {
            timer = 0;
            flameAnimationPlayer.Play(GameData.ANIM_EFFECT_BURN);

            monster.Physics.Velocity = Vector2F.Zero;
            monster.Graphics.PauseAnimation();
            monster.IsPassable = true;

            // Apply damage (make monster invincible for burn duration).
            DamageInfo damageInfo = new DamageInfo(burnDamage);
            damageInfo.ApplyKnockBack		= false;
            damageInfo.Flicker				= false;
            damageInfo.InvincibleDuration	= burnDuration;
            monster.Hurt(damageInfo);
        }
예제 #25
0
 public override bool CheckPreAbsorbDamage(DamageInfo dinfo)
 {
     if (dinfo.Instigator != null)
     {
         SkillRecord melee = this.wearer.skills.GetSkill(SkillDefOf.Melee);
         System.Random random = new System.Random();
         int chance = random.Next(0, 21);
         if (chance >= melee.level)
         {
             System.Random random1 = new System.Random();
             int chance1 = random1.Next(0, 5);
             if (chance1 >= 3)
             {
                 this.HitPoints -= dinfo.Amount / 2;
                 if (this.HitPoints <= 0)
                 {
                     this.Break();
                 }
                 else
                 {
                     this.AbsorbedDamage(dinfo);
                 }
                 return true;
             }
         }
         else
         {
             System.Random random2 = new System.Random();
             int chance2 = random2.Next(0, 5);
             if (chance2 >= 2)
             {
                 this.HitPoints -= dinfo.Amount / 4;
                 if (this.HitPoints <= 0)
                 {
                     this.Break();
                 }
                 else
                 {
                     this.AbsorbedDamage(dinfo);
                 }
                 return true;
             }
         }
     }
     return false;
 }
 public override void PreApplyDamage(DamageInfo dinfo, out bool absorbed)
 {
     base.PreApplyDamage(dinfo, out absorbed);
     if (absorbed)
     {
         return;
     }
     if (dinfo.Def.harmsHealth)
     {
         float num = (float)(this.HitPoints - dinfo.Amount);
         if ((num < (float)base.MaxHitPoints * 0.98f && dinfo.Instigator != null && dinfo.Instigator.Faction != null) || num < (float)base.MaxHitPoints * 0.9f)
         {
             this.TrySpawnMechanoids();
         }
     }
     absorbed = false;
 }
 protected override void Impact(Thing hitThing)
 {
     base.Impact(hitThing);
     if (hitThing != null)
     {
         int damageAmountBase = this.def.projectile.damageAmountBase;
         BodyPartDamageInfo value = new BodyPartDamageInfo(null, null);
         DamageInfo dinfo = new DamageInfo(this.def.projectile.damageDef, damageAmountBase, this.launcher, this.ExactRotation.eulerAngles.y, new BodyPartDamageInfo?(value), this.equipment);
         hitThing.TakeDamage(dinfo);
         ExplosionThing(hitThing.Position);//Explosion method luncher
     }
     else
     {
         SoundDefOf.BulletImpactGround.PlayOneShot(base.Position);
         MoteThrower.ThrowStatic(this.ExactPosition, ThingDefOf.Mote_ShotHit_Dirt, 1f);
         ExplosionThing(this.Position);//Explosion method luncher
     }
 }
예제 #28
0
 public override void TickRare()
 {
     //List all things in cell
     List<Thing> list = Find.ThingGrid.ThingsListAt(Position);
     if (list.Count > 0)
     {
         //Loop over things
         for (int i = 0; i < list.Count; i++)
         {
             if (list[i].def.category == ThingCategory.Item)
             {
                 if (list[i].def.defName != "FreshCompost")
                 {
                     DamageInfo dinfo = new DamageInfo(DamageDefOf.Rotting, 1, null, null, null);
                     Thing compost = ThingMaker.MakeThing(ThingDef.Named("FreshCompost"));
                     Thing thing = list[i];
                     int stacksize = thing.stackCount;
                     if (thing.def.defName.Contains("Corpse"))
                     {
                         Corpse corpse = thing as Corpse;
                         if (corpse.innerPawn.def.race.Animal || corpse.innerPawn.def.race.Humanlike)
                         {
                             thing.TakeDamage(dinfo);
                             compost.stackCount = 25;
                         }
                     }
                     else
                     {
                         thing.TakeDamage(dinfo);
                         compost.stackCount = stacksize;
                     }
                     if (thing.HitPoints < 10)
                     {
                         thing.Destroy();
                         GenSpawn.Spawn(compost, Position);
                     }
                 }
             }
         }
     }
 }
예제 #29
0
 protected override void Impact(Thing hitThing)
 {
     base.Impact(hitThing);
     if (hitThing != null)
     {
         float height = this.GetProjectileHeight(this.shotHeight, this.distanceFromOrigin, this.shotAngle, this.shotSpeed);
         int damageAmountBase = this.def.projectile.damageAmountBase;
         BodyPartHeight? bodyPartHeight = null;
         Pawn pawn = hitThing as Pawn;
         if (pawn != null && pawn.GetPosture() == PawnPosture.Standing)	//Downed pawns randomly get damaged wherever, I guess
         {
             float fullHeight = Utility.GetCollisionHeight(hitThing);
             float percentOfBodySize = height / fullHeight;
             if (percentOfBodySize >= 0.8)
             {
                 bodyPartHeight = BodyPartHeight.Top;
             }
             else
             {
                 if (percentOfBodySize < 0.45)
                 {
                     bodyPartHeight = BodyPartHeight.Bottom;
                 }
                 else
                 {
                     bodyPartHeight = BodyPartHeight.Middle;
                 }
             }
         }
             //All the rest is handled further on - Even the BodyPartHeight not existing doesn't matter.
         BodyPartDamageInfo value = new BodyPartDamageInfo(bodyPartHeight, null);
         DamageInfo dinfo = new DamageInfo(this.def.projectile.damageDef, damageAmountBase, this.launcher, this.ExactRotation.eulerAngles.y, new BodyPartDamageInfo?(value), this.equipmentDef);
         hitThing.TakeDamage(dinfo);
     }
     else
     {
         SoundDefOf.BulletImpactGround.PlayOneShot(base.Position);
         MoteThrower.ThrowStatic(this.ExactPosition, ThingDefOf.Mote_ShotHit_Dirt, 1f);
     }
 }
예제 #30
0
	protected virtual void FixedUpdate()
	{
		if(firing)
		{
			foreach(WeaponComponent component in components)
			{
				component.TryFire();
			}

			if(CanFire())
			{
				Vector3 direction = GetAimDirection();
				HitInfo hit = GetHitInfo(direction);

				foreach(WeaponComponent component in components)
				{
					component.OnFire(hit);
				}

				GlobalEvents.Invoke(new WeaponFireEvent(this, hit));

				if(hit.target != null)
				{
					if(hit.target.GetComponentInChildren<Damagable>() != null)
					{
						DamageInfo damage = new DamageInfo(hit, GetDamage(hit));
						WeaponDamageEvent damageEvent = new WeaponDamageEvent(this, damage);

						foreach(WeaponComponent component in components)
						{
							component.OnDamage(damage);
						}

						GlobalEvents.Invoke(damageEvent);
						hit.target.Events.Invoke(damageEvent);
					}
				}
			}
		}
	}
예제 #31
0
 public abstract void Damage(DamageInfo _damageInfo);
예제 #32
0
        private void LaunchMortar(CharacterBody attackerBody, ProcChainMask procChainMask, GameObject victim, DamageInfo damageInfo, int stack)
        {
            GameObject    gameObject = attackerBody.gameObject;
            InputBankTest component  = gameObject.GetComponent <InputBankTest>();
            Vector3       position   = component ? component.aimOrigin : gameObject.transform.position;

            float         dmgCoef        = dmgCoefficient + (dmgStack * stack);
            float         damage         = Util.OnHitProcDamage(damageInfo.damage, attackerBody.damage, dmgCoef);
            ProcChainMask procChainMask2 = procChainMask;

            procChainMask2.AddProc(ProcType.Missile);
            FireProjectileInfo fireProjectileInfo = new FireProjectileInfo
            {
                projectilePrefab   = mortarPrefab,
                position           = position,
                procChainMask      = procChainMask2,
                target             = victim,
                owner              = gameObject,
                damage             = damage,
                crit               = damageInfo.crit,
                force              = 500f,
                damageColorIndex   = DamageColorIndex.Item,
                speedOverride      = -1f,
                damageTypeOverride = DamageType.AOE
            };
            int times = (int)(1 + stackAmount * stack);

            for (int t = 0; t < times; t++)
            {
                Vector3 direction;
                if (fixedAim)
                {
                    direction = gameObject.transform.forward;
                }
                else
                {
                    direction = component ? component.aimDirection : gameObject.transform.forward;
                }
                direction  = direction.normalized + new Vector3(0f, launchAngle, 0f);
                direction += new Vector3(Random.Range(-inaccuracyRate, inaccuracyRate),
                                         Random.Range(-inaccuracyRate, inaccuracyRate),
                                         Random.Range(-inaccuracyRate, inaccuracyRate));
                fireProjectileInfo.rotation = Util.QuaternionSafeLookRotation(direction);
                ProjectileManager.instance.FireProjectile(fireProjectileInfo);
            }
        }
예제 #33
0
        public static void HealthComponent_TakeDamage(On.RoR2.HealthComponent.orig_TakeDamage orig, HealthComponent self, DamageInfo damageInfo)
        {
            if (damageInfo == null)
            {
                orig(self, damageInfo); return;
            }
            else if (!self || !self.gameObject.GetComponent <CharacterBody>())
            {
                orig(self, damageInfo); return;
            }
            else if (!damageInfo.attacker || !damageInfo.attacker.GetComponent <CharacterBody>())
            {
                orig(self, damageInfo); return;
            }

            CharacterBody characterBody         = self.gameObject.GetComponent <CharacterBody>();
            CharacterBody attackerCharacterBody = damageInfo.attacker.GetComponent <CharacterBody>();

            Miscellaneous.FurySwipesController furySwipesController = attackerCharacterBody.GetComponent <Miscellaneous.FurySwipesController>();

            if (attackerCharacterBody.baseNameToken == "URSA_NAME" && characterBody.HasBuff(Survivor.Buffs.furySwipesDebuff) && damageInfo.procCoefficient >= 1 && furySwipesController)
            {
                int   count       = characterBody.GetBuffCount(Survivor.Buffs.furySwipesDebuff);
                float bonusDamage = count * (attackerCharacterBody.damage * furySwipesController.furySwipesMult);
                damageInfo.damage += bonusDamage;
            }

            orig(self, damageInfo);

            if (attackerCharacterBody.baseNameToken == "URSA_NAME" && damageInfo.procCoefficient >= 1)
            {
                characterBody.AddTimedBuff(Survivor.Buffs.furySwipesDebuff, Core.Config.passiveDebuffDuration.Value);
                foreach (CharacterBody.TimedBuff i in characterBody.timedBuffs)
                {
                    i.timer = Core.Config.passiveDebuffDuration.Value;
                }
            }
        }
예제 #34
0
        protected override void ApplySpecialEffectsToPart(Pawn pawn, float totalDamage, DamageInfo dinfo, ref DamageWorker.DamageResult result)
        {
            if (dinfo.HitPart.depth == BodyPartDepth.Inside)
            {
                List <BodyPartRecord> list = new List <BodyPartRecord>();
                for (BodyPartRecord bodyPartRecord = dinfo.HitPart; bodyPartRecord != null; bodyPartRecord = bodyPartRecord.parent)
                {
                    list.Add(bodyPartRecord);
                    if (bodyPartRecord.depth == BodyPartDepth.Outside)
                    {
                        break;
                    }
                }

                MaybeCauseHypothermia(pawn, dinfo);

                float num = (float)(list.Count - 1) + 0.5f;
                for (int i = 0; i < list.Count; i++)
                {
                    DamageInfo dinfo2 = dinfo;
                    dinfo2.SetHitPart(list[i]);
                    MaybeInfectWound(pawn, dinfo2);
                    base.FinalizeAndAddInjury(pawn, totalDamage / num * ((i != 0) ? 1f : 0.5f), dinfo2, ref result);
                }
            }
            else
            {
                int num2 = (this.def.cutExtraTargetsCurve == null) ? 0 : GenMath.RoundRandom(this.def.cutExtraTargetsCurve.Evaluate(Rand.Value));
                List <BodyPartRecord> list2;
                if (num2 != 0)
                {
                    IEnumerable <BodyPartRecord> enumerable = dinfo.HitPart.GetDirectChildParts();
                    if (dinfo.HitPart.parent != null)
                    {
                        enumerable = enumerable.Concat(dinfo.HitPart.parent);
                        enumerable = enumerable.Concat(dinfo.HitPart.parent.GetDirectChildParts());
                    }
                    list2 = enumerable.Except(dinfo.HitPart).InRandomOrder(null).Take(num2).ToList <BodyPartRecord>();
                }
                else
                {
                    list2 = new List <BodyPartRecord>();
                }
                list2.Add(dinfo.HitPart);
                float num3 = totalDamage * (1f + this.def.cutCleaveBonus) / ((float)list2.Count + this.def.cutCleaveBonus);
                if (num2 == 0)
                {
                    num3 = base.ReduceDamageToPreserveOutsideParts(num3, dinfo, pawn);
                }

                MaybeCauseHypothermia(pawn, dinfo);

                for (int j = 0; j < list2.Count; j++)
                {
                    DamageInfo dinfo3 = dinfo;
                    dinfo3.SetHitPart(list2[j]);
                    MaybeInfectWound(pawn, dinfo3);
                    base.FinalizeAndAddInjury(pawn, num3, dinfo3, ref result);
                }
            }
        }
예제 #35
0
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member

        private void On_GEMOnHitEnemy(On.RoR2.GlobalEventManager.orig_OnHitEnemy orig, GlobalEventManager self, DamageInfo damageInfo, GameObject victim)
        {
            orig(self, damageInfo, victim);

            if (!NetworkServer.active || !victim || !damageInfo.attacker || damageInfo.procCoefficient <= 0f || damageInfo.procChainMask.HasProc(ProcType.Missile))
            {
                return;
            }

            var vicb = victim.GetComponent <CharacterBody>();

            CharacterBody body = damageInfo.attacker.GetComponent <CharacterBody>();

            if (!body || !vicb || !vicb.healthComponent || !vicb.mainHurtBox)
            {
                return;
            }

            CharacterMaster chrm = body.master;

            if (!chrm)
            {
                return;
            }

            int icnt = GetCount(body);

            if (icnt == 0)
            {
                return;
            }

            icnt--;
            float m2Proc = procChance;

            if (icnt > 0)
            {
                m2Proc += stackChance * icnt;
            }
            if (m2Proc > capChance)
            {
                m2Proc = capChance;
            }
            if (!Util.CheckRoll(m2Proc * damageInfo.procCoefficient, chrm))
            {
                return;
            }

            for (int t = 0; t < missileAmount; t++)
            {
                ProcMissile(t, body, damageInfo.procChainMask, victim, damageInfo, icnt);
            }
        }
예제 #36
0
    protected override void ProcessDamage(Actor DamageSource, float DamageValue, Controller DamageInstigator, DamageInfo EventInfo)
    {
        _bullAudioController.PlayAudioClip(_bullAudioController.BullClips.DamageClip);

        PawnSprite.FlashSprite(true);

        _actorCurrentHealth -= DamageValue;

        if (_actorCurrentHealth <= 0)
        {
            TakesDamage = false;
            _bullStateMachine.ChangeConditionState <BullCState_Unconscious>();
        }

        base.ProcessDamage(DamageSource, DamageValue, DamageInstigator, EventInfo);
    }
예제 #37
0
        // RimWorld.Verb_MeleeAttack
        public static void DamageInfosToApply_PostFix(Verb_MeleeAttack __instance, ref IEnumerable <DamageInfo> __result, LocalTargetInfo target)
        {
            List <DamageInfo> newList = new List <DamageInfo>();
            //__result = null;
            ThingWithComps ownerEquipment = __instance.ownerEquipment;

            if (ownerEquipment != null)
            {
                //Log.Message("1");
                ThingComp comp = ownerEquipment.AllComps.FirstOrDefault((ThingComp x) => x is CompSlotLoadable);
                if (comp != null)
                {
                    //Log.Message("2");
                    CompSlotLoadable compSlotLoadable = comp as CompSlotLoadable;
                    if (compSlotLoadable.Slots != null && compSlotLoadable.Slots.Count > 0)
                    {
                        //Log.Message("3");
                        List <SlotLoadable> statSlots = compSlotLoadable.Slots.FindAll((SlotLoadable z) => !z.IsEmpty() && ((SlotLoadableDef)z.def).doesChangeStats == true);
                        if (statSlots != null && statSlots.Count > 0)
                        {
                            //Log.Message("4");
                            foreach (SlotLoadable slot in statSlots)
                            {
                                //Log.Message("5");
                                CompSlottedBonus slotBonus = slot.SlotOccupant.TryGetComp <CompSlottedBonus>();
                                if (slotBonus != null)
                                {
                                    //Log.Message("6");
                                    Type superClass = __instance.GetType().BaseType;
                                    if (slotBonus.Props.damageDef != null)
                                    {
                                        //Log.Message("7");
                                        float            num = __instance.verbProps.AdjustedMeleeDamageAmount(__instance, __instance.CasterPawn, __instance.ownerEquipment);
                                        DamageDef        def = __instance.verbProps.meleeDamageDef;
                                        BodyPartGroupDef weaponBodyPartGroup = null;
                                        HediffDef        weaponHediff        = null;
                                        if (__instance.CasterIsPawn)
                                        {
                                            //Log.Message("8");
                                            if (num >= 1f)
                                            {
                                                weaponBodyPartGroup = __instance.verbProps.linkedBodyPartsGroup;
                                                if (__instance.ownerHediffComp != null)
                                                {
                                                    weaponHediff = __instance.ownerHediffComp.Def;
                                                }
                                            }
                                            else
                                            {
                                                num = 1f;
                                                def = DamageDefOf.Blunt;
                                            }
                                        }

                                        //Log.Message("9");
                                        ThingDef def2;
                                        if (__instance.ownerEquipment != null)
                                        {
                                            def2 = __instance.ownerEquipment.def;
                                        }
                                        else
                                        {
                                            def2 = __instance.CasterPawn.def;
                                        }

                                        //Log.Message("10");
                                        Vector3 angle = (target.Thing.Position - __instance.CasterPawn.Position).ToVector3();

                                        //Log.Message("11");
                                        Thing caster = __instance.caster;

                                        //Log.Message("12");
                                        int newdamage = GenMath.RoundRandom(num);
//                                        Log.Message("applying damage "+newdamage+" out of "+num);
                                        DamageInfo damageInfo = new DamageInfo(slotBonus.Props.damageDef, newdamage, -1f, caster, null, def2);
                                        damageInfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside);
                                        damageInfo.SetWeaponBodyPartGroup(weaponBodyPartGroup);
                                        damageInfo.SetWeaponHediff(weaponHediff);
                                        damageInfo.SetAngle(angle);

                                        //Log.Message("13");
                                        newList.Add(damageInfo);

                                        __result = newList.AsEnumerable <DamageInfo>();
                                    }
                                    SlotBonusProps_VampiricEffect vampiricEffect = slotBonus.Props.vampiricHealChance;
                                    if (vampiricEffect != null)
                                    {
                                        //Log.Message("vampiricHealingCalled");
                                        float randValue = Rand.Value;
                                        //Log.Message("randValue = " + randValue.ToString());

                                        if (randValue <= vampiricEffect.chance)
                                        {
                                            MoteMaker.ThrowText(__instance.CasterPawn.DrawPos, __instance.CasterPawn.Map, "Vampiric Effect: Success", 6f);
                                            //MoteMaker.ThrowText(__instance.CasterPawn.DrawPos, __instance.CasterPawn.Map, "Success".Translate(), 6f);
                                            ApplyHealing(__instance.caster, vampiricEffect.woundLimit, target.Thing);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public static bool Prefix(ProjectileCE __instance, Thing ___launcher, IntVec3 ___originInt, Vector2 ___origin, Vector2 ___destinationInt, int ___startingTicksToImpactInt, int ___ticksToImpact, int ___intTicksToImpact, ThingDef ___equipmentDef, ref float ___suppressionAmount, Thing hitThing)
        {
            if (hitThing != null)
            {
                bool  Rending       = false;
                float RendingChance = 0.167f;
                Pawn  caster        = ___launcher as Pawn;
                Thing Launcher      = ___launcher;
                if (caster != null)
                {
                    if (caster.equipment != null)
                    {
                        //    Log.Warning(string.Format("___launcher: {0}", ___launcher));
                        if (caster.equipment.Primary != null)
                        {
                            //    Log.Warning(string.Format("caster.equipment != null"));
                            Launcher = caster.equipment.Primary;
                            //    Log.Warning(string.Format("Launcher = caster.equipment.Primary"));
                            CompWeapon_GunSpecialRules _GunSpecialRules = Launcher.TryGetCompFast <CompWeapon_GunSpecialRules>();
                            if (_GunSpecialRules != null)
                            {
                                //    Log.Warning(string.Format("_GunSpecialRules != null"));
                                Rending       = _GunSpecialRules.Rending;
                                RendingChance = _GunSpecialRules.RendingChance;
                            }
                        }
                        else
                        {
                            //    Log.Warning(string.Format("caster.equipment == null"));
                            if (caster.health.hediffSet.hediffs.Any(x => x.TryGetCompFast <HediffComp_VerbGiverExtra>() != null))
                            {
                                //    Log.Warning(string.Format("HediffComp_VerbGiverExtra: {0}", ___launcher));
                                HediffComp_VerbGiverExtra _VGE = caster.health.hediffSet.hediffs.Find(x => x.TryGetCompFast <HediffComp_VerbGiverExtra>() is HediffComp_VerbGiverExtra z && z.verbTracker.AllVerbs.Any(y => y.verbProps.defaultProjectile == __instance.def)).TryGetCompFast <HediffComp_VerbGiverExtra>();
                                if (_VGE != null)
                                {
                                    //    Log.Warning(string.Format("_VGE != null: {0}", _VGE.parent.LabelCap));
                                    GunVerbEntry entry = _VGE.Props.verbEntrys.Find(x => x.VerbProps.defaultProjectile == __instance.def);
                                    if (entry != null)
                                    {
                                        //    Log.Warning(string.Format("{0}, Rending: {1}, Chance: {2}", entry.VerbProps.label, entry.Rending, entry.RendingChance));
                                        Rending       = entry.Rending;
                                        RendingChance = entry.RendingChance;
                                    }
                                }
                            }
                        }
                    }
                }
                if (Rending)
                {
                    //    Log.Warning(string.Format("Rending: {0}", ___launcher));
                    Rand.PushState();
                    bool RendingEffect = Rand.Chance(RendingChance);
                    Rand.PopState();
                    if (RendingEffect)
                    {
                        DamageDef damageDef = __instance.def.projectile.damageDef;
                        DamageArmorCategoryDef armorCategory = damageDef.armorCategory != null ? damageDef.armorCategory: null;
                        StatDef armorcatdef = damageDef.armorCategory != null ? armorCategory.armorRatingStat : null;
                        float   num         = 0f;
                        float   num2        = Mathf.Clamp01((armorcatdef != null ? hitThing.GetStatValue(armorcatdef, true) : 0f) / 2f);
                        if (hitThing is Pawn hitPawn)
                        {
                            List <BodyPartRecord> allParts = hitPawn.RaceProps.body.AllParts;
                            List <Apparel>        list     = (hitPawn.apparel == null) ? null : hitPawn.apparel.WornApparel;
                            for (int i = 0; i < allParts.Count; i++)
                            {
                                float num3 = 1f - num2;
                                if (list != null)
                                {
                                    for (int j = 0; j < list.Count; j++)
                                    {
                                        if (list[j].def.apparel.CoversBodyPart(allParts[i]))
                                        {
                                            float num4 = Mathf.Clamp01((armorcatdef != null ? list[j].GetStatValue(armorcatdef, true) : 0f) / 2f);
                                            num3 *= 1f - num4;
                                        }
                                    }
                                }
                                num += allParts[i].coverageAbs * (1f - num3);
                            }
                        }
                        num = Mathf.Clamp(num * 2f, 0f, 2f);
                        float armorPenetration = num;

                        MoteMaker.ThrowText(hitThing.PositionHeld.ToVector3(), hitThing.MapHeld, "AdeptusMechanicus.Rending_Shot".Translate(__instance.LabelCap, hitThing.LabelShortCap), 3f);
                        //    Log.Warning(string.Format("ArmorPenetration: {0}", ArmorPenetration));

                        bool flag = ___launcher is AmmoThing;
                        Map  map  = __instance.Map;
                        LogEntry_DamageResult logEntry_DamageResult = null;
                        bool flag2 = __instance.logMisses || (!__instance.logMisses && hitThing != null && (hitThing is Pawn || hitThing is Building_Turret));
                        if (flag2)
                        {
                            bool flag3 = !flag;
                            if (flag3)
                            {
                                LogImpact(__instance, ___launcher, ___equipmentDef, hitThing, out logEntry_DamageResult);
                            }
                        }
                        bool flag4 = hitThing != null;
                        if (flag4)
                        {
                            int damageAmount = __instance.def.projectile.GetDamageAmount(1f, null);
                            DamageDefExtensionCE   damageDefExtensionCE   = __instance.def.projectile.damageDef.GetModExtension <DamageDefExtensionCE>() ?? new DamageDefExtensionCE();
                            ProjectilePropertiesCE projectilePropertiesCE = (ProjectilePropertiesCE)__instance.def.projectile;
                            //    float armorPenetration = (this.def.projectile.damageDef.armorCategory == DamageArmorCategoryDefOf.Sharp) ? projectilePropertiesCE.armorPenetrationSharp : projectilePropertiesCE.armorPenetrationBlunt;
                            DamageInfo     damageInfo          = new DamageInfo(__instance.def.projectile.damageDef, (float)damageAmount, armorPenetration, __instance.ExactRotation.eulerAngles.y, ___launcher, null, __instance.def, DamageInfo.SourceCategory.ThingOrUnknown, null);
                            BodyPartDepth  depth               = (damageDefExtensionCE != null && damageDefExtensionCE.harmOnlyOutsideLayers) ? BodyPartDepth.Outside : BodyPartDepth.Undefined;
                            BodyPartHeight collisionBodyHeight = new CollisionVertical(hitThing).GetCollisionBodyHeight(__instance.ExactPosition.y);
                            damageInfo.SetBodyRegion(collisionBodyHeight, depth);
                            bool flag5 = damageDefExtensionCE != null && damageDefExtensionCE.harmOnlyOutsideLayers;
                            if (flag5)
                            {
                                damageInfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside);
                            }
                            bool flag6 = flag && hitThing is Pawn;
                            if (flag6)
                            {
                                logEntry_DamageResult = new BattleLogEntry_DamageTaken((Pawn)hitThing, DefDatabase <RulePackDef> .GetNamed("DamageEvent_CookOff", true), null);
                                Find.BattleLog.Add(logEntry_DamageResult);
                            }
                            try
                            {
                                hitThing.TakeDamage(damageInfo).AssociateWithLog(logEntry_DamageResult);
                                bool flag7 = !(hitThing is Pawn) && projectilePropertiesCE != null && !projectilePropertiesCE.secondaryDamage.NullOrEmpty <SecondaryDamage>();
                                if (flag7)
                                {
                                    foreach (SecondaryDamage secondaryDamage in projectilePropertiesCE.secondaryDamage)
                                    {
                                        bool destroyed = hitThing.Destroyed;
                                        if (destroyed)
                                        {
                                            break;
                                        }
                                        DamageInfo dinfo = secondaryDamage.GetDinfo(damageInfo);
                                        hitThing.TakeDamage(dinfo).AssociateWithLog(logEntry_DamageResult);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Error("CombatExtended :: BulletCE impacting thing " + hitThing.LabelCap + " of def " + hitThing.def.LabelCap + " added by mod " + hitThing.def.modContentPack.Name + ". See following stacktrace for information.", false);
                                throw ex;
                            }
                            finally
                            {
                                Impact(__instance, ___launcher, ___equipmentDef, hitThing, ___originInt, ___origin, ___destinationInt, ___startingTicksToImpactInt, ___ticksToImpact, ___intTicksToImpact, ref ___suppressionAmount);
                            }
                        }
                        else
                        {
                            SoundDefOf.BulletImpact_Ground.PlayOneShot(new TargetInfo(__instance.Position, map, false));
                            bool castShadow = __instance.castShadow;
                            if (castShadow)
                            {
                                FleckMaker.Static(__instance.ExactPosition, map, FleckDefOf.ShotHit_Dirt, 1f);
                                bool takeSplashes = __instance.Position.GetTerrain(map).takeSplashes;
                                if (takeSplashes)
                                {
                                    FleckMaker.WaterSplash(__instance.ExactPosition, map, Mathf.Sqrt((float)__instance.def.projectile.GetDamageAmount(___launcher, null)) * 1f, 4f);
                                }
                            }
                            Impact(__instance, ___launcher, ___equipmentDef, hitThing, ___originInt, ___origin, ___destinationInt, ___startingTicksToImpactInt, ___ticksToImpact, ___intTicksToImpact, ref ___suppressionAmount);
                        }
                        NotifyImpact(__instance, ___launcher, hitThing, map, __instance.Position);
                    }
                    return(false);
                }
            }
            return(true);
        }
예제 #39
0
        public override IEnumerable <Gizmo> GetGizmos()
        {
            if (Find.WorldSelector.SingleSelectedObject == this)
            {
                yield return(new Gizmo_CaravanInfo(this));
            }
            foreach (Gizmo gizmo in base.GetGizmos())
            {
                yield return(gizmo);
            }
            if (IsPlayerControlled)
            {
                if (Find.WorldSelector.SingleSelectedObject == this)
                {
                    yield return(SettleInEmptyTileUtility.SettleCommand(this));
                }
                if (Find.WorldSelector.SingleSelectedObject == this && PawnsListForReading.Count((Pawn x) => x.IsColonist) >= 2)
                {
                    Command_Action command_Action = new Command_Action();
                    command_Action.defaultLabel = "CommandSplitCaravan".Translate();
                    command_Action.defaultDesc  = "CommandSplitCaravanDesc".Translate();
                    command_Action.icon         = SplitCommand;
                    command_Action.hotKey       = KeyBindingDefOf.Misc5;
                    command_Action.action       = delegate
                    {
                        Find.WindowStack.Add(new Dialog_SplitCaravan(this));
                    };
                    yield return(command_Action);
                }
                if (pather.Moving)
                {
                    Command_Toggle command_Toggle = new Command_Toggle();
                    command_Toggle.hotKey       = KeyBindingDefOf.Misc1;
                    command_Toggle.isActive     = (() => pather.Paused);
                    command_Toggle.toggleAction = delegate
                    {
                        if (pather.Moving)
                        {
                            pather.Paused = !pather.Paused;
                        }
                    };
                    command_Toggle.defaultDesc  = "CommandToggleCaravanPauseDesc".Translate(2f.ToString("0.#"), 0.3f.ToStringPercent());
                    command_Toggle.icon         = TexCommand.PauseCaravan;
                    command_Toggle.defaultLabel = "CommandPauseCaravan".Translate();
                    yield return(command_Toggle);
                }
                if (CaravanMergeUtility.ShouldShowMergeCommand)
                {
                    yield return(CaravanMergeUtility.MergeCommand(this));
                }
                foreach (Gizmo gizmo2 in forage.GetGizmos())
                {
                    yield return(gizmo2);
                }
                foreach (WorldObject item in Find.WorldObjects.ObjectsAt(base.Tile))
                {
                    foreach (Gizmo caravanGizmo in item.GetCaravanGizmos(this))
                    {
                        yield return(caravanGizmo);
                    }
                }
            }
            if (Prefs.DevMode)
            {
                Command_Action command_Action2 = new Command_Action();
                command_Action2.defaultLabel = "Dev: Mental break";
                command_Action2.action       = delegate
                {
                    if (PawnsListForReading.Where((Pawn x) => x.RaceProps.Humanlike && !x.InMentalState).TryRandomElement(out Pawn result6))
                    {
                        result6.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Wander_Sad);
                    }
                };
                yield return(command_Action2);

                Command_Action command_Action3 = new Command_Action();
                command_Action3.defaultLabel = "Dev: Make random pawn hungry";
                command_Action3.action       = delegate
                {
                    if (PawnsListForReading.Where((Pawn x) => x.needs.food != null).TryRandomElement(out Pawn result5))
                    {
                        result5.needs.food.CurLevelPercentage = 0f;
                    }
                };
                yield return(command_Action3);

                Command_Action command_Action4 = new Command_Action();
                command_Action4.defaultLabel = "Dev: Kill random pawn";
                command_Action4.action       = delegate
                {
                    if (PawnsListForReading.TryRandomElement(out Pawn result4))
                    {
                        result4.Kill(null, null);
                        Messages.Message("Dev: Killed " + result4.LabelShort, this, MessageTypeDefOf.TaskCompletion, historical: false);
                    }
                };
                yield return(command_Action4);

                Command_Action command_Action5 = new Command_Action();
                command_Action5.defaultLabel = "Dev: Harm random pawn";
                command_Action5.action       = delegate
                {
                    if (PawnsListForReading.TryRandomElement(out Pawn result3))
                    {
                        DamageInfo dinfo = new DamageInfo(DamageDefOf.Scratch, 10f, 999f);
                        result3.TakeDamage(dinfo);
                    }
                };
                yield return(command_Action5);

                Command_Action command_Action6 = new Command_Action();
                command_Action6.defaultLabel = "Dev: Down random pawn";
                command_Action6.action       = delegate
                {
                    if (PawnsListForReading.Where((Pawn x) => !x.Downed).TryRandomElement(out Pawn result2))
                    {
                        HealthUtility.DamageUntilDowned(result2);
                        Messages.Message("Dev: Downed " + result2.LabelShort, this, MessageTypeDefOf.TaskCompletion, historical: false);
                    }
                };
                yield return(command_Action6);

                Command_Action command_Action7 = new Command_Action();
                command_Action7.defaultLabel = "Dev: Plague on random pawn";
                command_Action7.action       = delegate
                {
                    if (PawnsListForReading.Where((Pawn x) => !x.Downed).TryRandomElement(out Pawn result))
                    {
                        Hediff hediff = HediffMaker.MakeHediff(HediffDefOf.Plague, result);
                        hediff.Severity = HediffDefOf.Plague.stages[1].minSeverity - 0.001f;
                        result.health.AddHediff(hediff);
                        Messages.Message("Dev: Gave advanced plague to " + result.LabelShort, this, MessageTypeDefOf.TaskCompletion, historical: false);
                    }
                };
                yield return(command_Action7);

                Command_Action command_Action8 = new Command_Action();
                command_Action8.defaultLabel = "Dev: Teleport to destination";
                command_Action8.action       = delegate
                {
                    base.Tile = pather.Destination;
                    pather.StopDead();
                };
                yield return(command_Action8);
            }
        }
예제 #40
0
        private void On_GEMOnHitEnemy(On.RoR2.GlobalEventManager.orig_OnHitEnemy orig, GlobalEventManager self, DamageInfo damageInfo, GameObject victim)
        {
            orig(self, damageInfo, victim);
            if (!NetworkServer.active || !damageInfo.attacker)
            {
                return;
            }

            CharacterBody body = damageInfo.attacker.GetComponent <CharacterBody>();

            if (!body || !body.HasBuff(pillageBuff))
            {
                return;
            }

            CharacterMaster chrm = body.master;

            if (!chrm)
            {
                return;
            }

            float mamt = (float)Run.instance.GetDifficultyScaledCost(body.GetBuffCount(pillageBuff)) * amount;

            if (!body.gameObject.TryGetComponent <PillageMoneyBuffer>(out var pmb))
            {
                pmb = body.gameObject.AddComponent <PillageMoneyBuffer>();
            }
            var bufferAmt = pmb.AddMoneyAndEmptyBuffer(Mathf.Max(mamt, 0f));

            if (Compat_ShareSuite.enabled && Compat_ShareSuite.MoneySharing())
            {
                Compat_ShareSuite.GiveMoney(bufferAmt);
            }
            else
            {
                chrm.GiveMoney(bufferAmt);
            }
        }
예제 #41
0
        // Token: 0x0600001E RID: 30 RVA: 0x00002BAC File Offset: 0x00000DAC
        public void addAcidDamage(Pawn p)
        {
            //    Log.Message(string.Format("addAcidDamage: {0}", p.LabelShort));
            List <BodyPartRecord> list = new List <BodyPartRecord>();
            //    Log.Message(string.Format("0 "));
            List <Apparel> wornApparel = new List <Apparel>();

            if (p.RaceProps.Humanlike)
            {
                wornApparel = p.apparel.WornApparel;
            }
            //    Log.Message(string.Format("1 "));
            int num = Mathf.RoundToInt((float)this.AcidDamage * Rand.Range(0.5f, 1.25f));
            //    Log.Message(string.Format("2 "));
            DamageInfo damageInfo = default(DamageInfo);

            //    Log.Message(string.Format("3 "));
            MoteMaker.ThrowDustPuff(p.Position, base.Map, 0.2f);
            //    Log.Message(string.Format("4 "));
            BodyPartHeight bodyPartHeight = p.Downed ? BodyPartHeight.Undefined : BodyPartHeight.Bottom;

            //    Log.Message(string.Format("{0}", bodyPartHeight));
            foreach (BodyPartRecord bodyPartRecord in p.health.hediffSet.GetNotMissingParts(bodyPartHeight, BodyPartDepth.Outside, null, null))
            {
                //    Log.Message(string.Format("{0}", bodyPartRecord.Label));
                bool flag = wornApparel.Count > 0;
                if (flag)
                {
                    bool flag2 = false;
                    for (int i = 0; i < wornApparel.Count; i++)
                    {
                        bool flag3 = wornApparel[i].def.apparel.CoversBodyPart(bodyPartRecord);
                        if (flag3)
                        {
                            flag2 = true;
                            //    Log.Message(string.Format("is protected"));
                            break;
                        }
                    }
                    bool flag4 = !flag2;
                    if (flag4)
                    {
                        //    Log.Message(string.Format("{0}", bodyPartRecord));
                        list.Add(bodyPartRecord);
                    }
                }
                else
                {
                    //    Log.Message(string.Format("{0}", bodyPartRecord));
                    list.Add(bodyPartRecord);
                }
            }
            for (int k = 0; k < list.Count; k++)
            {
                damageInfo = new DamageInfo(XenomorphDefOf.RRY_AcidBurn, (float)Mathf.RoundToInt(((float)num * list[k].coverage) * 10), 0f, -1f, this, list[k], null, 0, null);
                //    Log.Message(string.Format("addAcidDamage TakeDamage: {0}, list[k].coverage: {1}, damageInfo: {2}", list[k].customLabel, list[k].coverage, damageInfo));
                if (Rand.Chance(list[k].coverage))
                {
                    for (int j = 0; j < wornApparel.Count; j++)
                    {
                        bool flag3 = wornApparel[j].def.apparel.CoversBodyPart(list[k]);
                        if (flag3)
                        {
                            this.damageEntities(wornApparel[j], num);
                        }
                    }
                    p.TakeDamage(damageInfo);
                    break;
                }
            }
        }
예제 #42
0
 private void OnTakeDamage(DamageInfo damageInfo)
 {
     TakeDamage(damageInfo.damageDone);
 }
예제 #43
0
        private void CalculateDamageReduction(On.RoR2.HealthComponent.orig_TakeDamage orig, HealthComponent self, DamageInfo damageInfo)
        {
            if (damageInfo.attacker)
            {
                var inventoryCount = GetCount(self.body);
                if (inventoryCount > 0 && self.body.GetBuffCount(ShieldGateCooldown) <= 0)
                {
                    float currentShield = self.body.healthComponent.shield;
                    float dmgTaken      = damageInfo.damage * (100 / (100 + self.body.armor));

                    if (currentShield > 0 && dmgTaken > currentShield)
                    {
                        damageInfo.damage = currentShield * (100 / (100 + self.body.armor));

                        float timerReduction = Mathf.Min(((inventoryCount - 1) * shieldGateCooldownReduction), shieldGateCooldownAmount);
                        self.body.AddTimedBuffAuthority(ShieldGateCooldown.buffIndex, (shieldGateCooldownAmount - timerReduction));
                    }
                }
            }
            orig(self, damageInfo);
        }
예제 #44
0
 protected override void ApplySpecialEffectsToPart(Pawn pawn, float totalDamage, DamageInfo dinfo,
                                                   DamageResult result)
 {
     FinalizeAndAddInjury(pawn, totalDamage, dinfo, result);
 }
예제 #45
0
        // Token: 0x060039DE RID: 14814 RVA: 0x001B8078 File Offset: 0x001B6478
        private IEnumerable <DamageInfo> DamageInfosToApply(LocalTargetInfo target)
        {
            Pawn  hitPawn  = (Pawn)target;
            bool  flag     = XenomorphUtil.isInfectablePawn(hitPawn);
            float tgtmelee = 0f;
            float tgtdodge = 0f;

            if (hitPawn.RaceProps.Humanlike)
            {
                tgtmelee = hitPawn.skills.GetSkill(SkillDefOf.Melee).Level;
            }
            if (hitPawn.RaceProps.Humanlike)
            {
                tgtdodge = hitPawn.GetStatValue(StatDefOf.MeleeDodgeChance);
            }
            if (((Rand.Value * 100) * (1 - tgtdodge) > 50 + tgtmelee || hitPawn.Downed) && flag && hitPawn is Pawn)
            {
                infect = true;
            }
            float            damAmount        = this.verbProps.AdjustedMeleeDamageAmount(this, base.CasterPawn);
            float            armorPenetration = this.verbProps.AdjustedArmorPenetration(this, base.CasterPawn);
            DamageDef        damDef           = this.verbProps.meleeDamageDef;
            BodyPartGroupDef bodyPartGroupDef = null;
            HediffDef        hediffDef        = null;

            damAmount = Rand.Range(damAmount * 0.8f, damAmount * 1.2f);
            if (base.CasterIsPawn)
            {
                bodyPartGroupDef = this.verbProps.AdjustedLinkedBodyPartsGroup(this.tool);
                if (damAmount >= 1f)
                {
                    if (base.HediffCompSource != null)
                    {
                        hediffDef = base.HediffCompSource.Def;
                    }
                }
                else
                {
                    damAmount = 1f;
                    damDef    = DamageDefOf.Blunt;
                }
            }
            ThingDef source;

            if (base.EquipmentSource != null)
            {
                source = base.EquipmentSource.def;
            }
            else
            {
                source = base.CasterPawn.def;
            }
            Vector3    direction = (target.Thing.Position - base.CasterPawn.Position).ToVector3();
            DamageDef  def       = damDef;
            float      num       = damAmount;
            float      num2      = armorPenetration;
            Thing      caster    = this.caster;
            DamageInfo mainDinfo = new DamageInfo(def, num, num2, -1f, caster, null, source, DamageInfo.SourceCategory.ThingOrUnknown, null);

            mainDinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside);
            mainDinfo.SetWeaponBodyPartGroup(bodyPartGroupDef);
            mainDinfo.SetWeaponHediff(hediffDef);
            mainDinfo.SetAngle(direction);
            yield return(mainDinfo);

            if (this.surpriseAttack && ((this.verbProps.surpriseAttack != null && !this.verbProps.surpriseAttack.extraMeleeDamages.NullOrEmpty <ExtraMeleeDamage>()) || (this.tool != null && this.tool.surpriseAttack != null && !this.tool.surpriseAttack.extraMeleeDamages.NullOrEmpty <ExtraMeleeDamage>())))
            {
                IEnumerable <ExtraMeleeDamage> extraDamages = Enumerable.Empty <ExtraMeleeDamage>();
                if (this.verbProps.surpriseAttack != null && this.verbProps.surpriseAttack.extraMeleeDamages != null)
                {
                    extraDamages = extraDamages.Concat(this.verbProps.surpriseAttack.extraMeleeDamages);
                }
                if (this.tool != null && this.tool.surpriseAttack != null && !this.tool.surpriseAttack.extraMeleeDamages.NullOrEmpty <ExtraMeleeDamage>())
                {
                    extraDamages = extraDamages.Concat(this.tool.surpriseAttack.extraMeleeDamages);
                }
                foreach (ExtraMeleeDamage extraDamage in extraDamages)
                {
                    int   extraDamageAmount           = GenMath.RoundRandom(extraDamage.AdjustedDamageAmount(this, base.CasterPawn));
                    float extraDamageArmorPenetration = extraDamage.AdjustedArmorPenetration(this, base.CasterPawn);
                    def    = extraDamage.def;
                    num2   = (float)extraDamageAmount;
                    num    = extraDamageArmorPenetration;
                    caster = this.caster;
                    DamageInfo extraDinfo = new DamageInfo(def, num2, num, -1f, caster, null, source, DamageInfo.SourceCategory.ThingOrUnknown, null);
                    extraDinfo.SetBodyRegion(BodyPartHeight.Undefined, BodyPartDepth.Outside);
                    extraDinfo.SetWeaponBodyPartGroup(bodyPartGroupDef);
                    extraDinfo.SetWeaponHediff(hediffDef);
                    extraDinfo.SetAngle(direction);
                    yield return(extraDinfo);
                }
            }
            yield break;
        }
예제 #46
0
        public override void CompTick()
        {
            if (this.age > 0)
            {
                if (!this.initialized)
                {
                    this.initialized = true;
                }

                if (this.Pawn.Spawned)
                {
                    if (!this.Pawn.Downed)
                    {
                        if (Find.TickManager.TicksGame % 300 == 0)
                        {
                            if (this.sustainerPawn != null)
                            {
                                DetermineThreats();
                                DetermineSustainerPawn();

                                if (this.ShouldDespawn && this.Pawn.Position != this.sentinelLoc)
                                {
                                    if (sentinelLoc.Walkable(this.Pawn.Map))
                                    {
                                        this.Pawn.jobs.ClearQueuedJobs();
                                        this.Pawn.jobs.EndCurrentJob(JobCondition.InterruptForced, false);
                                        Job job = new Job(JobDefOf.Goto, this.sentinelLoc);
                                        this.Pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc);
                                    }
                                    else
                                    {
                                        Messages.Message("TM_SentinelCannotReturn".Translate(
                                                             this.sustainerPawn.LabelShort
                                                             ), MessageTypeDefOf.RejectInput, false);
                                        this.Pawn.Destroy(DestroyMode.Vanish);
                                    }
                                }

                                if (this.target.Thing is Pawn)
                                {
                                    Pawn prisonerPawn = this.target.Thing as Pawn;
                                    if (prisonerPawn.IsPrisoner)
                                    {
                                        Job job = new Job(JobDefOf.AttackMelee, prisonerPawn);
                                        this.Pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc);
                                    }
                                }
                            }
                            else
                            {
                                Log.Message("Sentinel has despawned due to lack of mana to sustain it.");
                                this.Pawn.Destroy(DestroyMode.Vanish);
                            }
                        }
                    }

                    if (this.Pawn.Downed)
                    {
                        if (this.killNow > 100)
                        {
                            DamageInfo dinfo = new DamageInfo(DamageDefOf.Blunt, 100, 0, (float)-1, this.sustainerPawn, null, null, DamageInfo.SourceCategory.ThingOrUnknown);
                            this.Pawn.TakeDamage(dinfo);
                        }
                        this.killNow++;
                    }

                    if (this.ShouldDespawn && this.Pawn.Position == this.sentinelLoc)
                    {
                        SingleSpawnLoop();
                        this.Pawn.Destroy(DestroyMode.Vanish);
                    }
                }
            }
            age++;
        }
예제 #47
0
        private void ProcMissile(int mNum, CharacterBody attackerBody, ProcChainMask procChainMask, GameObject victim, DamageInfo damageInfo, int stack)
        {
            GameObject    gameObject = attackerBody.gameObject;
            InputBankTest component  = gameObject.GetComponent <InputBankTest>();
            Vector3       position   = component ? component.aimOrigin : gameObject.transform.position;

            float         dmgCoef        = dmgCoefficient + (dmgStack * stack);
            float         damage         = Util.OnHitProcDamage(damageInfo.damage, attackerBody.damage, dmgCoef);
            ProcChainMask procChainMask2 = procChainMask;

            procChainMask2.AddProc(ProcType.Missile);
            FireProjectileInfo fireProjectileInfo = new FireProjectileInfo
            {
                projectilePrefab = GlobalEventManager.instance.missilePrefab,
                position         = position,
                rotation         = Util.QuaternionSafeLookRotation(DetermineFacing(mNum)),
                procChainMask    = procChainMask2,
                target           = victim,
                owner            = gameObject,
                damage           = damage,
                crit             = damageInfo.crit,
                force            = 200f,
                damageColorIndex = DamageColorIndex.Item
            };

            ProjectileManager.instance.FireProjectile(fireProjectileInfo);
        }
        /// <summary>
        /// Calculates primary DamageInfo from verb, as well as secondary DamageInfos to apply (i.e. surprise attack stun damage).
        /// Also calculates the maximum body height an attack can target, so we don't get rabbits biting out a colonist's eye or something.
        /// </summary>
        /// <param name="target">The target damage is to be applied to</param>
        /// <returns>Collection with primary DamageInfo, followed by secondary types</returns>
        private IEnumerable <DamageInfo> DamageInfosToApply(LocalTargetInfo target, bool isCrit = false)
        {
            float            damAmount        = (float)this.verbProps.AdjustedMeleeDamageAmount(this, base.CasterPawn, this.ownerEquipment);
            var              critDamDef       = CritDamageDef;
            DamageDef        damDef           = isCrit && critDamDef != DamageDefOf.Stun ? critDamDef : verbProps.meleeDamageDef;
            BodyPartGroupDef bodyPartGroupDef = null;
            HediffDef        hediffDef        = null;

            if (base.CasterIsPawn)
            {
                if (damAmount >= 1f)
                {
                    bodyPartGroupDef = this.verbProps.linkedBodyPartsGroup;
                    if (this.ownerHediffComp != null)
                    {
                        hediffDef = this.ownerHediffComp.Def;
                    }
                }
                else
                {
                    damAmount = 1f;
                    damDef    = DamageDefOf.Blunt;
                }
            }
            ThingDef source;

            if (this.ownerEquipment != null)
            {
                source = this.ownerEquipment.def;
            }
            else
            {
                source = base.CasterPawn.def;
            }
            Vector3        direction  = (target.Thing.Position - base.CasterPawn.Position).ToVector3();
            Thing          caster     = this.caster;
            BodyPartHeight bodyRegion = GetBodyPartHeightFor(target);   // Add check for body height
            DamageInfo     mainDinfo  = new DamageInfo(damDef, GenMath.RoundRandom(damAmount), -1f, caster, null, source);

            mainDinfo.SetBodyRegion(bodyRegion, BodyPartDepth.Outside);
            mainDinfo.SetWeaponBodyPartGroup(bodyPartGroupDef);
            mainDinfo.SetWeaponHediff(hediffDef);
            mainDinfo.SetAngle(direction);
            yield return(mainDinfo);

            // Apply secondary damage on surprise attack
            if (this.surpriseAttack && this.verbProps.surpriseAttack != null && this.verbProps.surpriseAttack.extraMeleeDamages != null)
            {
                List <ExtraMeleeDamage> extraDamages = this.verbProps.surpriseAttack.extraMeleeDamages;
                for (int i = 0; i < extraDamages.Count; i++)
                {
                    ExtraMeleeDamage extraDamage = extraDamages[i];
                    int amount = GenMath.RoundRandom((float)extraDamage.amount * base.GetDamageFactorFor(base.CasterPawn));
                    caster = this.caster;
                    DamageInfo extraDinfo = new DamageInfo(extraDamage.def, amount, -1f, caster, null, source);
                    extraDinfo.SetBodyRegion(bodyRegion, BodyPartDepth.Outside);
                    extraDinfo.SetWeaponBodyPartGroup(bodyPartGroupDef);
                    extraDinfo.SetWeaponHediff(hediffDef);
                    extraDinfo.SetAngle(direction);
                    yield return(extraDinfo);
                }
            }

            // Apply critical damage
            if (isCrit && critDamDef == DamageDefOf.Stun)
            {
                var critAmount = GenMath.RoundRandom(mainDinfo.Amount * 0.25f);
                var critDinfo  = new DamageInfo(critDamDef, critAmount, -1, caster, null, source);
                critDinfo.SetBodyRegion(bodyRegion, BodyPartDepth.Outside);
                critDinfo.SetWeaponBodyPartGroup(bodyPartGroupDef);
                critDinfo.SetWeaponHediff(hediffDef);
                critDinfo.SetAngle(direction);
                yield return(critDinfo);
            }
        }
예제 #49
0
    // MINION
    // Move towards a tower
    // Attack nearby enemies


    public void TakeDamage(DamageInfo info)
    {
        health -= info.damage;
    }
예제 #50
0
    public virtual void OnPostPhysicsStep(float dt)
    {
        //DebugOverlay.Box( 0.1f, WorldPos, -0.1f, 1.1f, Host.Color );

        if (!IsServer)
        {
            return;
        }

        if (Stuck)
        {
            if (TimeSinceStuck > 5)
            {
                Delete();
            }
            return;
        }

        float Speed    = 100.0f;
        var   velocity = Rot.Forward * Speed;

        var start = WorldPos;
        var end   = start + velocity;

        var tr = Trace.Ray(start, end)
                 .UseHitboxes()
                 //.HitLayer( CollisionLayer.Water, !InWater )
                 .Ignore(Owner)
                 .Ignore(this)
                 .Size(1.0f)
                 .Run();

        // DebugOverlay.Line( start, end, 10.0f );
        // DebugOverlay.Box( 10.0f, WorldPos, -1, 1, Color.Red );
        // DebugOverlay.Box( 10.0f, tr.EndPos, -1, 1, Color.Red );

        if (tr.Hit)
        {
            // TODO: CLINK NOISE (unless flesh)

            // TODO: SPARKY PARTICLES (unless flesh)

            Stuck          = true;
            TimeSinceStuck = 0;
            WorldPos       = tr.EndPos + Rot.Forward * -1;

            if (tr.Entity.IsValid())
            {
                var damageInfo = DamageInfo.FromBullet(tr.EndPos, tr.Direction * 200, 60.0f)
                                 .UsingTraceResult(tr)
                                 .WithAttacker(Owner)
                                 .WithWeapon(this);

                tr.Entity.TakeDamage(damageInfo);
            }

            // TODO: Parent to bone so this will stick in the meaty heads
            SetParent(tr.Entity, tr.Bone);
            Owner = null;

            //
            // Surface impact effect
            //
            tr.Normal = Rot.Forward * -1;
            tr.Surface.DoBulletImpact(tr);
            velocity = default;

            //
            // BUG: without this the bolt stops short of the wall on the client.
            //		need to make interp finish itself off even though it's not getting new positions?
            //
            ResetInterpolation();

            // DebugOverlay.Box( 10.0f, WorldPos, -1, 1, Color.Red );
            // DebugOverlay.Box( 10.0f, tr.EndPos, -1, 1, Color.Yellow );
        }
        else
        {
            WorldPos = end;
        }
    }
예제 #51
0
 protected override BodyPartRecord ChooseHitPart(DamageInfo dinfo, Pawn pawn)
 {
     return(pawn.health.hediffSet.GetRandomNotMissingPart(dinfo.Def, dinfo.Height, BodyPartDepth.Outside));
 }
예제 #52
0
 public override bool TakeDamage(DamageInfo info)
 {
     return(this.CanReceiveHit() && base.TakeDamage(info));
 }
예제 #53
0
 public override ActorDropListPair GetDropList(DamageInfo actor)
 {
     return(new ActorDropListPair(actor, dropList));
 }
예제 #54
0
        private Toil Collect()
        {
            return(new Toil()
            {
                initAction = delegate {
                    // Increment the record for how many cells this pawn has mined since this counts as mining
                    // TODO: B19 - change to quarry m3
                    pawn.records.Increment(RecordDefOf.CellsMined);

                    // Start with None to act as a fallback. Rubble will be returned with this parameter
                    ResourceRequest req = ResourceRequest.None;

                    // Use the mineModeToggle to determine the request
                    req = (Quarry.mineModeToggle ? ResourceRequest.Resources : ResourceRequest.Blocks);

                    MoteType mote = MoteType.None;
                    int stackCount = 1;

                    // Get the resource from the quarry
                    ThingDef def = Quarry.GiveResources(req, out mote, out bool singleSpawn, out bool eventTriggered);
                    // If something went wrong, bail out
                    if (def == null || def.thingClass == null)
                    {
                        Log.Warning("Quarry:: Tried to quarry mineable ore, but the ore given was null.");
                        mote = MoteType.None;
                        singleSpawn = true;
                        // This shouldn't happen at all, but if it does let's add a little reward instead of just giving rubble
                        def = ThingDefOf.ChunkSlagSteel;
                    }

                    Thing haulableResult = ThingMaker.MakeThing(def);
                    if (!singleSpawn && def != ThingDefOf.Component)
                    {
                        int sub = (int)(def.BaseMarketValue / 2f);
                        sub = Mathf.Clamp(sub, 0, 10);

                        stackCount += Mathf.Min(Rand.RangeInclusive(15 - sub, 40 - (sub * 2)), def.stackLimit - 1);
                    }

                    if (def == ThingDefOf.Component)
                    {
                        stackCount += Random.Range(0, 1);
                    }

                    haulableResult.stackCount = stackCount;

                    if (stackCount >= 30)
                    {
                        mote = MoteType.LargeVein;
                    }

                    bool usesQuality = false;
                    // Adjust quality for items that use it
                    if (haulableResult.TryGetComp <CompQuality>() != null)
                    {
                        usesQuality = true;
                        haulableResult.TryGetComp <CompQuality>().SetQuality(QualityUtility.RandomTraderItemQuality(), ArtGenerationContext.Outsider);
                    }
                    // Adjust hitpoints, this was just mined from under the ground after all
                    if (def.useHitPoints && !def.thingCategories.Contains(QuarryDefOf.StoneChunks) && def != ThingDefOf.Component)
                    {
                        float minHpThresh = 0.25f;
                        if (usesQuality)
                        {
                            minHpThresh = Mathf.Clamp((float)haulableResult.TryGetComp <CompQuality>().Quality / 10f, 0.1f, 0.7f);
                        }
                        int hp = Mathf.RoundToInt(Rand.Range(minHpThresh, 1f) * haulableResult.MaxHitPoints);
                        hp = Mathf.Max(1, hp);
                        haulableResult.HitPoints = hp;
                    }

                    // Place the resource near the pawn
                    GenPlace.TryPlaceThing(haulableResult, pawn.Position, Map, ThingPlaceMode.Near);

                    // If the resource had a mote, throw it
                    if (mote == MoteType.LargeVein)
                    {
                        MoteMaker.ThrowText(haulableResult.DrawPos, Map, Static.TextMote_LargeVein, Color.green, 3f);
                    }
                    else if (mote == MoteType.Failure)
                    {
                        MoteMaker.ThrowText(haulableResult.DrawPos, Map, Static.TextMote_MiningFailed, Color.red, 3f);
                    }

                    // If the sinkhole event was triggered, damage the pawn and end this job
                    // Even if the sinkhole doesn't incapacitate the pawn, they will probably want to seek medical attention
                    if (eventTriggered)
                    {
                        Messages.Message("QRY_MessageSinkhole".Translate(pawn.NameStringShort), pawn, MessageTypeDefOf.NegativeEvent);
                        DamageInfo dInfo = new DamageInfo(DamageDefOf.Crush, 9, category: DamageInfo.SourceCategory.Collapse);
                        dInfo.SetBodyRegion(BodyPartHeight.Bottom, BodyPartDepth.Inside);
                        pawn.TakeDamage(dInfo);

                        EndJobWith(JobCondition.Succeeded);
                    }
                    else
                    {
                        // Prevent the colonists from trying to haul rubble, which just makes them visit the platform
                        if (def == ThingDefOf.RockRubble)
                        {
                            EndJobWith(JobCondition.Succeeded);
                        }
                        else
                        {
                            // If this is a chunk or slag, mark it as haulable if allowed to
                            if (def.designateHaulable && Quarry.autoHaul)
                            {
                                Map.designationManager.AddDesignation(new Designation(haulableResult, DesignationDefOf.Haul));
                            }

                            // Try to find a suitable storage spot for the resource, removing it from the quarry
                            // If there are no platforms with free space, or if the resource is a chunk, try to haul it to a storage area
                            if (Quarry.autoHaul)
                            {
                                if (!def.thingCategories.Contains(QuarryDefOf.StoneChunks) && Quarry.HasConnectedPlatform && Quarry.TryFindBestPlatformCell(haulableResult, pawn, Map, pawn.Faction, out IntVec3 c))
                                {
                                    job.SetTarget(TargetIndex.B, haulableResult);
                                    job.count = haulableResult.stackCount;
                                    job.SetTarget(TargetIndex.C, c);
                                }
                                else
                                {
                                    StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(haulableResult.Position, haulableResult);
                                    if (StoreUtility.TryFindBestBetterStoreCellFor(haulableResult, pawn, Map, currentPriority, pawn.Faction, out c))
                                    {
                                        job.SetTarget(TargetIndex.B, haulableResult);
                                        job.count = haulableResult.stackCount;
                                        job.SetTarget(TargetIndex.C, c);
                                    }
                                }
                            }
                            // If there is no spot to store the resource, end this job
                            else
                            {
                                EndJobWith(JobCondition.Succeeded);
                            }
                        }
                    }
                },
예제 #55
0
        protected override void ApplySpecialEffectsToPart(Pawn pawn, float totalDamage, DamageInfo dinfo, DamageResult result)
        {
            if (Rand.Chance(BanProps.banChance))
            {
                Thing instigator = dinfo.Instigator;
                Pawn  pawnToBan  = null;

                bool haywire = false;

                if (Rand.Chance(BanProps.haywireBanChance))
                {
                    haywire = true;

                    IEnumerable <Pawn> bannablePawns = (Rand.Chance(BanProps.haywireBanPlayerPawnChance)) ?
                                                       instigator.Map.mapPawns.AllPawnsSpawned.Where(p => p.Faction == Faction.OfPlayer) : instigator.Map.mapPawns.AllPawnsSpawned;

                    pawnToBan = (Rand.Chance(BanProps.haywireBanMostValuablePawnChance)) ? GetMostValuablePawn(bannablePawns) : bannablePawns.RandomElement();
                }

                else
                {
                    pawnToBan = pawn;
                }

                BanPawn(pawnToBan, instigator, haywire);
            }

            else
            {
                base.ApplySpecialEffectsToPart(pawn, totalDamage, dinfo, result);
            }
        }
예제 #56
0
    private void Hit(CJObject cj_object, Collider coll, Vector3 hit_pos, Vector3 hit_dir)
    {
        Item currentItem = this.m_Player.GetCurrentItem(Hand.Right);

        if (cj_object)
        {
            HumanAI component = cj_object.GetComponent <HumanAI>();
            if (component)
            {
                if (component.m_Hallucination && component.m_HallucinationDisappearing)
                {
                    return;
                }
                this.HitHumanAI(component, hit_pos, hit_dir);
                this.MakeHitSound(coll.gameObject, currentItem.m_Info.m_ID);
                this.m_AlreadyHit = true;
                return;
            }
            else
            {
                this.HitObject(cj_object, hit_pos, hit_dir);
            }
        }
        else
        {
            RagdollBone component2 = coll.gameObject.GetComponent <RagdollBone>();
            if (component2 && component2.m_Parent)
            {
                DeadBody component3 = component2.m_Parent.GetComponent <DeadBody>();
                if (component3)
                {
                    component3.OnTakeDamage(new DamageInfo
                    {
                        m_DamageItem = currentItem,
                        m_Damager    = base.gameObject,
                        m_Position   = hit_pos,
                        m_HitDir     = hit_dir,
                        m_Normal     = -hit_dir
                    });
                    return;
                }
            }
        }
        DamageInfo     damageInfo = new DamageInfo();
        ObjectMaterial component4;

        if (cj_object != null)
        {
            component4 = cj_object.gameObject.GetComponent <ObjectMaterial>();
        }
        else
        {
            component4 = coll.gameObject.GetComponent <ObjectMaterial>();
        }
        EObjectMaterial mat = (!(component4 == null)) ? component4.m_ObjectMaterial : EObjectMaterial.Unknown;

        damageInfo.m_Damage     = currentItem.m_Info.m_DamageSelf * ObjectMaterial.GetDamageSelfMul(mat);
        damageInfo.m_DamageItem = currentItem;
        this.MakeHitSound(coll.gameObject, currentItem.m_Info.m_ID);
        currentItem.TakeDamage(damageInfo);
        this.OnHit();
    }
예제 #57
0
 void hook_HealthComponent_TakeDamage(On.RoR2.HealthComponent.orig_TakeDamage orig, HealthComponent self, DamageInfo damageInfo)
 {
     if (damageInfo.crit)
     {
         if (damageInfo.attacker && damageInfo.attacker.GetComponent <CharacterBody>() is CharacterBody attackerBody &&
             attackerBody.inventory && attackerBody.inventory.GetItemCount(this.ItemIndex) is int stacks && stacks > 0 &&
             attackerBody.GetComponent <CritStorage>() is CritStorage critStorage)
         {
             damageInfo.damage *= 1f + stacks * critStorage.crit * 0.1f * Mathf.Pow(2, stacks - 1);
         }
     }
     orig(self, damageInfo);
 }
예제 #58
0
    protected virtual void HitObject(CJObject obj, Vector3 hit_pos, Vector3 hit_dir)
    {
        this.m_AudioModule.PlayHitSound(1f, false);
        if (obj.GetParticleOnHit().Length > 3)
        {
            this.SpawnFX(obj.GetParticleOnHit(), hit_pos);
        }
        Item   currentItem = this.m_Player.GetCurrentItem(Hand.Right);
        Weapon weapon      = null;

        if (currentItem.m_Info.IsWeapon())
        {
            weapon = (Weapon)currentItem;
        }
        bool flag      = true;
        Item component = obj.GetComponent <Item>();

        if (component && component.m_IsPlant)
        {
            this.m_AlreadyHit = false;
        }
        else
        {
            this.m_AlreadyHit = true;
        }
        if (obj.CanReceiveDamageOfType(currentItem.m_Info.m_DamageType))
        {
            DamageInfo damageInfo = new DamageInfo();
            if (weapon != null)
            {
                WeaponInfo weaponInfo = (WeaponInfo)weapon.m_Info;
                if (obj.IsAI())
                {
                    damageInfo.m_Damage = weaponInfo.m_AnimalDamage;
                    if (((AI)obj).IsDead())
                    {
                        flag = false;
                    }
                }
                else if (component)
                {
                    if (component.m_IsPlant)
                    {
                        damageInfo.m_Damage = weaponInfo.m_PlantDamage;
                    }
                    else if (component.m_IsTree)
                    {
                        damageInfo.m_Damage = weaponInfo.m_TreeDamage;
                    }
                    else
                    {
                        damageInfo.m_Damage = weaponInfo.m_DefaultDamage;
                    }
                }
                else
                {
                    damageInfo.m_Damage = weaponInfo.m_DefaultDamage;
                }
            }
            else if (component && component.m_IsTree && weapon.m_Info.IsTorch())
            {
                damageInfo.m_Damage = 0f;
            }
            else
            {
                damageInfo.m_Damage = 1000f;
            }
            damageInfo.m_Damage    *= this.GetDamageMultiplier(currentItem);
            damageInfo.m_Damager    = this.m_Player.gameObject;
            damageInfo.m_Position   = hit_pos;
            damageInfo.m_HitDir     = hit_dir;
            damageInfo.m_Normal     = Vector3.up;
            damageInfo.m_DamageItem = currentItem;
            obj.TakeDamage(damageInfo);
            this.HitDestroyableChunkSource(obj.GetComponent <Collider>(), hit_pos, hit_dir, currentItem);
            if (flag)
            {
                this.ExecuteSkill(currentItem);
            }
        }
    }
예제 #59
0
        protected override bool TryCastShot()
        {
            bool castIsSuccesful = base.TryCastShot();

            if (castIsSuccesful)
            {
                Pawn targetPawn = this.currentTarget.Thing as Pawn;
                if ((targetPawn != null) &&
                    (!targetPawn.Dead) &&
                    (!targetPawn.Downed))
                {
                    ThingDef_PowerFist repelProperties = this.ownerEquipment.def as ThingDef_PowerFist;
                    if (repelProperties == null)
                    {
                        Log.Warning("MiningCo. PowerFist: cannot cast ownerEquipment into ThingWithCompsWithRepel.");
                        return(castIsSuccesful);
                    }
                    bool  casterWearsPowerArmor = IsCasterWearingPowerArmor();
                    int   repelDurationInTicks  = (int)repelProperties.repelDurationInTicks;
                    float maxRepelDistance      = 0;
                    float crushDamageFactor     = 0;
                    float electricDamageFactor  = 0;
                    float stunDurationInTicks   = 0;
                    float empDurationInTicks    = 0;

                    // Compute repel max distance and stun duration according to the target size. Flying squirrels!!! :-D
                    if (casterWearsPowerArmor)
                    {
                        crushDamageFactor    = repelProperties.crushDamageFactorWithPowerArmor;
                        electricDamageFactor = repelProperties.electricDamageFactorWithPowerArmor;
                        empDurationInTicks   = repelProperties.empDurationInTicks;
                        if (targetPawn.BodySize <= repelProperties.bodySizeSmall)
                        {
                            maxRepelDistance    = repelProperties.repelDistanceFactorWithPowerArmor * repelProperties.repelDistanceLong;
                            stunDurationInTicks = repelProperties.stunDurationInTicksLong;
                        }
                        else if (targetPawn.BodySize <= repelProperties.bodySizeMedium)
                        {
                            maxRepelDistance    = repelProperties.repelDistanceFactorWithPowerArmor * repelProperties.repelDistanceMedium;
                            stunDurationInTicks = repelProperties.stunDurationInTicksMedium;
                        }
                        else if (targetPawn.BodySize <= repelProperties.bodySizeBig)
                        {
                            maxRepelDistance    = repelProperties.repelDistanceFactorWithPowerArmor * repelProperties.repelDistanceShort;
                            stunDurationInTicks = repelProperties.stunDurationInTicksShort;
                        }
                    }
                    else
                    {
                        crushDamageFactor    = repelProperties.crushDamageFactor;
                        electricDamageFactor = repelProperties.electricDamageFactor;
                        if (targetPawn.BodySize <= repelProperties.bodySizeSmall)
                        {
                            maxRepelDistance    = repelProperties.repelDistanceLong;
                            stunDurationInTicks = repelProperties.stunDurationInTicksMedium;
                        }
                        else if (targetPawn.BodySize <= repelProperties.bodySizeMedium)
                        {
                            maxRepelDistance    = repelProperties.repelDistanceMedium;
                            stunDurationInTicks = repelProperties.stunDurationInTicksShort;
                        }
                    }
                    // Start repel if target is not too big.
                    IntVec3 vector = targetPawn.Position - this.CasterPawn.Position;
                    if (maxRepelDistance > 0)
                    {
                        float             repelDistance = 0f;
                        ThingDef          obstacleDef   = null;
                        PowerFistRepeller repeller      = GenSpawn.Spawn(Util_PowerFist.PowerFistRepellerDef, targetPawn.Position, targetPawn.Map) as PowerFistRepeller;
                        repeller.Notify_BeginRepel(targetPawn, vector, (int)maxRepelDistance, repelDurationInTicks, out repelDistance, out obstacleDef);
                        if (obstacleDef != null)
                        {
                            Vector3 motePosition = targetPawn.Position.ToVector3Shifted() + vector.ToVector3() * repelDistance;
                            MoteMaker.ThrowText(motePosition, targetPawn.Map, "Crushed", Color.red);
                            int        extraDamage = Mathf.RoundToInt(this.ownerEquipment.def.statBases.GetStatValueFromList(StatDefOf.MeleeWeapon_DamageAmount, 5) * crushDamageFactor);
                            DamageInfo infos       = new DamageInfo(DamageDefOf.Blunt, extraDamage, vector.AngleFlat, this.caster, null, obstacleDef);
                            targetPawn.TakeDamage(infos);
                        }
                    }
                    if ((targetPawn != null) &&
                        (targetPawn.Dead ||
                         targetPawn.Downed))
                    {
                        // Do not try to apply stun if pawn is dead/downed.
                        return(true);
                    }
                    // Apply stun or EMP.
                    if (targetPawn.RaceProps.IsMechanoid)
                    {
                        if (casterWearsPowerArmor)
                        {
                            DamageInfo infos = new DamageInfo(DamageDefOf.EMP, Mathf.RoundToInt(empDurationInTicks / StunDurationFactor_EMP), vector.AngleFlat, this.caster, null, this.ownerEquipment.def);
                            targetPawn.stances.stunner.Notify_DamageApplied(infos, true);
                            MoteMaker.ThrowExplosionInteriorMote(targetPawn.Position.ToVector3Shifted(), targetPawn.Map, ThingDef.Named("Mote_ElectricalSpark"));

                            int        extraDamage = Mathf.RoundToInt(this.ownerEquipment.def.statBases.GetStatValueFromList(StatDefOf.MeleeWeapon_DamageAmount, 5) * electricDamageFactor);
                            DamageInfo infos2      = new DamageInfo(Util_PowerFist.ElectricDamageDef, extraDamage, vector.AngleFlat, this.caster, null, this.ownerEquipment.def);
                            targetPawn.TakeDamage(infos2);
                        }
                    }
                    else if (stunDurationInTicks > 0)
                    {
                        DamageInfo infos = new DamageInfo(DamageDefOf.Stun, Mathf.RoundToInt(stunDurationInTicks / StunDurationFactor_Standard), vector.AngleFlat, this.caster, null, this.ownerEquipment.def);
                        targetPawn.stances.stunner.Notify_DamageApplied(infos, false);
                    }
                }
            }
            return(castIsSuccesful);
        }
예제 #60
0
    protected override void OnCreateCreatures()
    {
        base.OnCreateCreatures();
        EventManager.AddEventListener(CreatureEvents.DEAD, OnCreatureDead);

        //进入迷宫的时候要还原血量
        if (modulePVE.reopenPanelType == PVEReOpenPanel.Labyrinth)
        {
            int damage = (int)(player.maxHealth * (1.0f - moduleLabyrinth.labyrinthSelfInfo.healthRate / 100f));
            player.TakeDamage(null, DamageInfo.CreatePreCalculate(damage));
            player.rage = moduleLabyrinth.labyrinthSelfInfo.angerRate;

            //Logger.LogDetail("进入关卡赋值血量和怒气health = {0},anger = {1}", player.healthRate, player.rageRate);
        }

        moduleAI.StartAI();

        if (m_player.pet != null)
        {
            moduleAI.AddPetAI(m_player.pet);
        }

        //创建机器人
        int      enermyCreatureId = moduleLabyrinth.lastSneakPlayer.GetProto();
        PFashion enermyFashion    = moduleLabyrinth.sneakPlayerDetail.fashion;

        m_enermy = RobotCreature.CreateRobot(enermyCreatureId, Vector3.zero + Vector3.right * 5, new Vector3(0f, 90f, 0f), enermyFashion.weapon, enermyFashion.gun, "hero2", moduleLabyrinth.lastSneakPlayer.roleName);
        m_enermy.gameObject.name = "enermy_robot";
        m_enermy.direction       = CreatureDirection.BACK;
        m_enermy.avatar          = moduleLabyrinth.lastSneakPlayer.avatar;
        m_enermy.roleProto       = enermyCreatureId;

        CharacterEquip.ChangeCloth(m_enermy, moduleLabyrinth.sneakPlayerDetail.fashion);
        //重置属性
        ((RobotCreature)m_enermy).ResetRobotAttribute(moduleLabyrinth.sneakPlayerDetail.roleAttrs, enermyFashion);

        //创建宠物
        PItem pet = moduleLabyrinth.lastSneakPlayer.pet;

        if (pet != null && pet.itemTypeId != 0)
        {
            var show = ConfigManager.Get <ShowCreatureInfo>(pet.itemTypeId);
            if (show == null)
            {
                Logger.LogError("没有配置config_showCreatureInfo表。宠物ID = {0}, 没有出生位置信息。宠物模型创建失败", pet.itemTypeId);
            }

            var showData = show.GetDataByIndex(0);
            var data     = showData.data.GetValue <ShowCreatureInfo.SizeAndPos>(0);
            m_enermy.pet = PetCreature.Create(m_enermy, PetInfo.Create(pet), m_enermy.position_ + data.pos, m_enermy.eulerAngles, false, Module_Home.PET_OBJECT_NAME);

            moduleAI.AddPetAI(m_enermy.pet);
        }

        //设置被偷袭玩家BUFF
        if (moduleLabyrinth.sneakPlayerDetail.buffs != null)
        {
            ushort[] buffIds = moduleLabyrinth.sneakPlayerDetail.buffs;
            for (int i = 0, length = buffIds.Length; i < length; i++)
            {
                Buff.Create(buffIds[i], m_enermy);
            }
        }
        moduleAI.AddCreatureToCampDic(m_enermy);
        moduleAI.AddCreatureToCampDic(player);
        moduleAI.AddPlayerAI(m_enermy);

        combatCamera.enabled = false;
        combatCamera.LookTo(new Vector3((float)((CombatConfig.spvpStart.x + CombatConfig.spvpStart.y) * 0.5), 0, 0));

        //set initial health and rage
        modulePVE.SetPveGameData(EnumPVEDataType.Health, m_player.healthRate);
        modulePVE.SetPveGameData(EnumPVEDataType.Rage, m_player.rageRate);
    }