Inheritance: MonoBehaviour
 public void ShouldBeAbleToAddAnExplosion()
 {
     var explosion = new Explosion(20, 22);
     _battlefield.Add(explosion);
     Assert.That(_battlefield.NewExplosions.Count, Is.EqualTo(1));
     Assert.That(_battlefield.Explosions.Count, Is.EqualTo(1));
 }
Example #2
0
        public void AddWorldObjectTest()
        {
            Planet planet1 = new Planet();
            WorldObject[] worldObjects = {planet1};

            World target = new World(worldObjects);
            WorldObject spaceship1 = new Spaceship();
            WorldObject spaceship2 = new Spaceship();
            WorldObject projectile = new Projectile();
            WorldObject explosion = new Explosion();
            WorldObject planet2 = new Planet();

            target.AddWorldObject(spaceship1);
            target.AddWorldObject(spaceship2);
            target.AddWorldObject(projectile);
            target.AddWorldObject(explosion);
            target.AddWorldObject(planet2);

            Assert.IsTrue((new List<WorldObject>(target.WorldObjects)).Contains(planet1));
            Assert.IsTrue((new List<WorldObject>(target.WorldObjects)).Contains(spaceship1));
            Assert.IsTrue((new List<WorldObject>(target.WorldObjects)).Contains(spaceship2));
            Assert.IsTrue((new List<WorldObject>(target.WorldObjects)).Contains(projectile));
            Assert.IsTrue((new List<WorldObject>(target.WorldObjects)).Contains(explosion));
            Assert.IsTrue((new List<WorldObject>(target.WorldObjects)).Contains(planet2));
        }
Example #3
0
 public override void InstantAction( TimeSpan gameTime )
 {
     Random r = new Random();
     chosenTank = Tanks[ r.Next( Tanks.Count ) ];
     if ( chosenTank.IsAlive )
     {
         Explosion explod = new Explosion( gameTime );
         explod.Initialize( Game );
         explod.LoadContent( Game.Content, Game.ScreenWidth, Game.ScreenHeight );
         explod.Position = chosenTank.Position;
         Game.QueueEntity( explod );
         Game.explod.Play();
         chosenTank.Destroy( gameTime );
     }
     else
     {
         Explosion explod = new Explosion( gameTime, 2000, ( float )Game.Settings[ "BlastRadius" ].Item2, false );
         explod.Initialize( Game );
         explod.LoadContent( Game.Content, Game.ScreenWidth, Game.ScreenHeight );
         explod.Position = chosenTank.Position;
         Game.QueueEntity( explod );
         reverseExplod.Play();
         chosenTank.IsAlive = true;
     }
 }
Example #4
0
        private void Explode()
        {
            if (Alive)
            {
                Vector2 explosionPoint = body.Position;
                world.RemoveBody(body);
                world.ProcessChanges();
                body = null;

                CuttingTools.Cut(world, explosionPoint + new Vector2(2, 2), explosionPoint - new Vector2(2, 2), 0.01f);
                //world.ProcessChanges();
                CuttingTools.Cut(world, explosionPoint + new Vector2(-2, 2), explosionPoint - new Vector2(-2, 2), 0.01f);
                //world.ProcessChanges();

                Explosion e = new Explosion(world);
                e.Activate(explosionPoint, 2, 10);
                
                Alive = false;
                
                pivot = null;

                Vector2 screenLoc = ProjectionHelper.FarseerToPixel(explosionPoint);
                ParticleEffectManager.explosionEffect.Trigger(screenLoc);
            }
        }
 public void ShouldDeleteExplosionOn17ThTick()
 {
     var explosion = new Explosion(20, 22);
     _battlefield.Add(explosion);
     for (var i = 0; i < 17; i++)
         _battlefield.Tick();
     Assert.That(_battlefield.Explosions.Count, Is.EqualTo(0));
 }
Example #6
0
 public GameView(SpriteBatch spriteBatch, Texture2D texture, Camera camera)
 {
     this.spriteBatch = spriteBatch;
     this.texture = texture;
     this.cam = camera;
     //explosionSystem = new ExplosionSystem(modelStartPosition);
     explosion = new Explosion(modelStartPosition);
 }
Example #7
0
 public PlayerHealthWatcher(
     PlayerModel model,
     Explosion.Factory explosionFactory,
     PlayerKilledSignal.Trigger killedSignal)
 {
     _killedSignal = killedSignal;
     _explosionFactory = explosionFactory;
     _model = model;
 }
Example #8
0
        private void OnCollision(CollisionEventArgs args)
        {
            var explosion = new Explosion(this.Engine.World);

            explosion.MaxShapes = 10000;

            explosion.Activate(this.Position, 10f, 1000f);

            this.Dispose();
        }
Example #9
0
    // Use this for initialization
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.isKinematic = true;
        rb.velocity = Vector3.zero;

        explosionAnim = GetComponentInChildren<Animator>();
        explosionCheck = GetComponentInChildren<Explosion>();
        shell = transform.GetChild(0);
    }
Example #10
0
 void PossuunOsui(PhysicsObject osuja, PhysicsObject kohde)
 {
     if (kohde != Maa)
     {
         Explosion PUM = new Explosion(200);
         PUM.Position = osuja.Position;
         Add(PUM);
         osuja.Destroy();
     }
 }
Example #11
0
 public override void CollisionCheck(Sprite a)
 {
     if (a.typ == Type.monster && a.stan == State.alive && materialWybuchowy != Explosion.exploded && Obliczarka.KolizjaDlaOkregow(this, a))
     {
         wielkoscObiektu = new Vector2(0, 0);
         materialWybuchowy = Explosion.exploded;
         teksturaPodstawowa = eksplozja;
     }
     if (a.typ == Type.monster && a.stan == State.alive && materialWybuchowy == Explosion.exploded && Obliczarka.KolizjaDlaOkregow(this, a))
         a.PrzyjmijUderzenie(obrazenia * lastTime);
 }
Example #12
0
 public EnemyHealthWatcher(
     EnemyModel model,
     Context context,
     Explosion.Factory explosionFactory,
     EnemyKilledSignal.Trigger killedSignal)
 {
     _killedSignal = killedSignal;
     _explosionFactory = explosionFactory;
     _context = context;
     _model = model;
 }
Example #13
0
 public Grenade()
 {
     pozycja = Config.pozycjaGracza;
     materialWybuchowy = Explosion.flight;
     cel = Config.pozycjaCelownika;
     wielkoscObiektu = new Vector2(1, 1);
     stan = State.alive;
     nrWarstwy = 4;
     typ = Type.bullet;
     punktWPolowie = Obliczarka.PunktDocelowy(pozycja, cel, Obliczarka.Odleglosc(pozycja, cel) / 2);
 }
Example #14
0
 //called from outside only by KinematicEnemy script
 public override void hit(IDamageable objectHit)
 {
     enemiesInRange = Physics2D.OverlapCircleAll(transform.position, explosionRange);
     foreach(Collider2D e in enemiesInRange) {
         if (e.tag == "Enemy" && !e.isTrigger) {
             e.GetComponent<Enemy> ().takeDamage (weapon.Player.Stats.Damage);
             if(GlobalSettings.bloodSplash)
                 spawnBloodSplashEffect (e.gameObject);
         }
     }
     explosion = BulletsPool.pool.getExplosion ();
     explosion.transform.position = transform.position;
     explosion.gameObject.SetActive (true);
     deactivate ();
 }
Example #15
0
        public InvaderGrid(GameScene scene, Vector2 position,Vector2 screenSize,int fireSpeed)
        {
            m_Scene = scene;
              m_Position = position;
              m_InitialPosition = position;
              m_ScreenSize = screenSize;
              m_Count = 64;
              m_InvaderRows = new List<InvaderBase>();
              m_ExplosionSample = new Explosion(new Vector2());
              float height = m_Position.Y;
              for (int rowNumber = 0; rowNumber < 5; rowNumber++)
              {
            if (rowNumber == 0) //Invader 1 row
            {
              for (int i = 0; i < 16; i++)
              {
            Invader1 invader = new Invader1(new Vector2(m_Position.X + i * (Invader1.InvaderWidth + 2), height),fireSpeed);
            invader.Dead +=new InvaderDeadEventHandler(invader_Dead);
            m_InvaderRows.Add(invader);
              }
              height += Invader1.InvaderHeight + 8;
            }

            if (rowNumber == 1 || rowNumber == 2)
            {
              for (int i = 0; i < 12; i++)
              {
            Invader2 invader = new Invader2(new Vector2(m_Position.X + i * (Invader2.InvaderWidth + 2), height),fireSpeed);
            invader.Dead += new InvaderDeadEventHandler(invader_Dead);
            m_InvaderRows.Add(invader);
              }
              height += Invader2.InvaderHeight + 8;
            }

            if (rowNumber == 3 || rowNumber == 4)
            {
              for (int i = 0; i < 12; i++)
              {
            Invader3 invader = new Invader3(new Vector2(m_Position.X + i * (Invader3.InvaderWidth + 2), height),fireSpeed);
            invader.Dead +=new InvaderDeadEventHandler(invader_Dead);
            m_InvaderRows.Add(invader);
              }
              height += Invader3.InvaderHeight + 8;
            }

              }
        }
Example #16
0
        protected override void Initialize()
        {
            _screenWidth = GraphicsDevice.Viewport.Width;
            _screenHeight = GraphicsDevice.Viewport.Height;

            _background = new Background();
            _tank = new Tank();
            _cannon = new Cannon();
            _bullet = new Bullet();
            _alien = new Alien();
            _explosion = new Explosion();
            _particleList = new List<ParticleData>();

            _tankPositionX = _screenWidth/2;
            _tankPositionY = _screenHeight - 193;
            base.Initialize();
        }
Example #17
0
 public Rocket()
 {
     pozycja = Config.pozycjaGracza;
     materialWybuchowy = Explosion.flight;
     cel = Config.pozycjaCelownika;
     float a = (pozycja.Y - Config.pozycjaCelownika.Y) / (pozycja.X - Config.pozycjaCelownika.X);
     float b = pozycja.Y - a * pozycja.X;
     if (Config.pozycjaCelownika.X > pozycja.X)
         cel.X = Config.rozdzielczosc.X + Config.rozmiarPlanszy.X + 20;
     else
         cel.X = -Config.rozdzielczosc.X - 20;
     cel.Y = a * cel.X + b;
     wielkoscObiektu = new Vector2(1, 1);
     stan = State.alive;
     nrWarstwy = 4;
     typ = Type.bullet;
     punktWPolowie = Obliczarka.PunktDocelowy(pozycja, cel, Obliczarka.Odleglosc(pozycja, cel) / 2);
 }
Example #18
0
    public override void Destroy()
    {
        try
        {
            if (customDestroy != null)
            {
                customDestroy(this);
            }

            if (explosionUponDestruction)
            {
                Explosion expl = new Explosion(explosionRadius);
                expl.Position = this.Position;
                RampageRebellion.getGame().Add(expl);
            }
        }
        finally
        {
            base.Destroy();
        }
    }
        private ExplosionTest()
        {
            //Ground
            FixtureFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            float[] xs = new[] {-10.0f, -5.0f, 0.0f, 5.0f, 10.0f};

            for (int j = 0; j < ColumnCount; ++j)
            {
                PolygonShape shape = new PolygonShape(1);
                shape.SetAsBox(0.5f, 0.5f);

                for (int i = 0; i < RowCount; ++i)
                {
                    int n = j*RowCount + i;
                    Debug.Assert(n < RowCount*ColumnCount);
                    _indices[n] = n;

                    const float x = 0.0f;
                    Body body = BodyFactory.CreateBody(World);
                    body.BodyType = BodyType.Dynamic;
                    body.Position = new Vector2(xs[j] + x, 0.752f + 1.54f*i);
                    body.UserData = _indices[n];
                    _bodies[n] = body;

                    Fixture fixture = body.CreateFixture(shape);
                    fixture.Friction = 0.3f;

                    //First column is unaffected by the explosion
                    if (j == 0)
                    {
                        body.PhysicsLogicFilter.IgnorePhysicsLogic(PhysicsLogicType.Explosion);
                    }
                }
            }

            _radius = 5;
            _power = 3;
            _explosion = new Explosion(World);
        }
        public static void DoImpactExplosion(Thing instigator, float radius)
        {
            var explosion = new Explosion
            {
                position = instigator.Position,
                radius = radius,
                damType = DamageDefOf.Bomb,
                instigator = instigator,
                damAmount = Mathf.RoundToInt(DamageDefOf.Bomb.explosionDamage*radius),
                source = instigator.def,
                applyDamageToExplosionCellsNeighbors = true
            };

            // damage is proportional to the size o the object
            if (instigator.def.defName == "MeteoriteFlying")
            {
                explosion.postExplosionSpawnChance = 0.25f;
                explosion.postExplosionSpawnThingDef = ThingDef.Named("CobbleSlate");
            }

            Find.Map.GetComponent<ExplosionManager>().StartExplosion(explosion, null);
        }
Example #21
0
 public override void Update(GameTime time)
 {
     lastTime = (float)time.ElapsedGameTime.TotalSeconds;
     if (materialWybuchowy == Explosion.flight)
     {
         pozycja = Obliczarka.PunktDocelowy(pozycja, cel, predkosc * (float)time.ElapsedGameTime.TotalSeconds);
         if (pozycja == cel)
         {
             wielkoscObiektu = new Vector2(0, 0);
             materialWybuchowy = Explosion.exploded;
             teksturaPodstawowa = eksplozja;
         }
     }
     else
     {
         float powiekszenie = (float)time.ElapsedGameTime.TotalSeconds * (1f / timeOfExplosion);
         wielkoscObiektu += new Vector2(powiekszenie, powiekszenie);
         timeLeft -= (float)time.ElapsedGameTime.TotalSeconds;
         if (timeLeft < 0)
             stan = State.toDelete;
     }
 }
Example #22
0
        /// <summary>
        /// Räjähtävän blockin törmäys-event
        /// </summary>
        /// <param name="self">ExplodingBlock joka törmäsi</param>
        /// <param name="target">Block johon törmättiin</param>
        public void ExplodingDroppingBlockCollided(IPhysicsObject self, IPhysicsObject target)
        {
            Debug.Print("ExplodingBlock at " + self.Position + " collided with obj at " + target.Position);

            Explosion expl = new Explosion(80);
            //rajahdys.Sound = LoadSoundEffect("implosionSound"); // todo: fix sounds
            expl.Force = 0;
            expl.ShockwaveColor = Color.LightBlue;
            expl.Position = Vector.Average(new List<Vector> { self.Position, target.Position });

            List<GameObject> list = new List<GameObject>();
            if (target is PlayerBlock)
            {
                list = GetImmediateSurroundings(self as Block, target as Block);
            }
            else
            {
                list = GetImmediateSurroundings(self as Block);
            }
            list.ForEach(x => { Block y = x as Block; y.TryExplode(); });

            Peli.Instance.Add(expl);
        }
Example #23
0
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            SpotLight light = entity.Create <SpotLight>();

            light.Enabled.Value = !main.EditorEnabled;

            light.FieldOfView.Value = 1.0f;
            light.Attenuation.Value = 75.0f;

            Transform transform = entity.GetOrCreate <Transform>("Transform");

            light.Add(new Binding <Vector3>(light.Position, transform.Position));

            Turret turret = entity.GetOrCreate <Turret>("Turret");

            Command die = new Command
            {
                Action = delegate()
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.PLAY_TURRET_DEATH, entity);
                    ParticleSystem shatter = ParticleSystem.Get(main, "InfectedShatter");
                    Random         random  = new Random();
                    for (int i = 0; i < 50; i++)
                    {
                        Vector3 offset = new Vector3((float)random.NextDouble() - 0.5f, (float)random.NextDouble() - 0.5f, (float)random.NextDouble() - 0.5f);
                        shatter.AddParticle(transform.Position + offset, offset);
                    }
                    entity.Delete.Execute();
                }
            };
            VoxelAttachable attachable = VoxelAttachable.MakeAttachable(entity, main, true, true, die);

            attachable.Enabled.Value = true;
            attachable.Offset.Value  = 2;

            PointLight pointLight = entity.GetOrCreate <PointLight>();

            pointLight.Serialize = false;
            pointLight.Add(new Binding <Vector3>(pointLight.Position, transform.Position));

            LineDrawer laser = new LineDrawer {
                Serialize = false
            };

            entity.Add(laser);

            AI ai = entity.GetOrCreate <AI>("AI");

            ModelAlpha model = entity.Create <ModelAlpha>();

            model.Add(new Binding <Matrix>(model.Transform, transform.Matrix));
            model.Filename.Value = "AlphaModels\\pyramid";

            const float defaultModelScale = 0.75f;

            model.Scale.Value = new Vector3(defaultModelScale);

            const float sightDistance     = 80.0f;
            const float hearingDistance   = 20.0f;
            const float operationalRadius = 100.0f;

            model.Add(new Binding <Vector3, string>(model.Color, delegate(string state)
            {
                switch (state)
                {
                case "Alert":
                    return(new Vector3(1.0f, 1.0f, 0.25f));

                case "Aggressive":
                    return(new Vector3(1.0f, 0.5f, 0.25f));

                case "Firing":
                    return(new Vector3(1.0f, 0.0f, 0.0f));

                case "Disabled":
                    return(new Vector3(0.0f, 0.0f, 0.0f));

                default:
                    return(new Vector3(1.0f, 1.0f, 1.0f));
                }
            }, ai.CurrentState));
            laser.Add(new Binding <bool, string>(laser.Enabled, x => x != "Disabled" && x != "Suspended", ai.CurrentState));

            light.Add(new Binding <Vector3>(light.Color, model.Color));
            pointLight.Add(new Binding <Vector3>(pointLight.Color, model.Color));

            Voxel.GlobalRaycastResult rayHit = new Voxel.GlobalRaycastResult();
            Vector3 toReticle = Vector3.Zero;

            AI.Task checkOperationalRadius = new AI.Task
            {
                Interval = 2.0f,
                Action   = delegate()
                {
                    bool shouldBeActive = (transform.Position.Value - main.Camera.Position).Length() < operationalRadius && !Water.IsSubmerged(transform.Position);
                    if (shouldBeActive && ai.CurrentState == "Suspended")
                    {
                        ai.CurrentState.Value = "Idle";
                    }
                    else if (!shouldBeActive && ai.CurrentState != "Suspended")
                    {
                        ai.CurrentState.Value = "Suspended";
                    }
                },
            };

            turret.Add(new CommandBinding(turret.PowerOn, delegate()
            {
                if (ai.CurrentState == "Disabled")
                {
                    ai.CurrentState.Value = "Suspended";
                    checkOperationalRadius.Action();
                }
            }));

            turret.Add(new CommandBinding(turret.PowerOff, delegate()
            {
                ai.CurrentState.Value = "Disabled";
            }));

            light.Add(new Binding <Quaternion>(light.Orientation, delegate()
            {
                return(Quaternion.CreateFromYawPitchRoll(-(float)Math.Atan2(toReticle.Z, toReticle.X) - (float)Math.PI * 0.5f, (float)Math.Asin(toReticle.Y), 0));
            }, transform.Position, turret.Reticle));

            AI.Task updateRay = new AI.Task
            {
                Action = delegate()
                {
                    toReticle = Vector3.Normalize(turret.Reticle.Value - transform.Position.Value);
                    rayHit    = Voxel.GlobalRaycast(transform.Position, toReticle, operationalRadius);
                    laser.Lines.Clear();

                    Microsoft.Xna.Framework.Color color = new Microsoft.Xna.Framework.Color(model.Color);
                    laser.Lines.Add(new LineDrawer.Line
                    {
                        A = new Microsoft.Xna.Framework.Graphics.VertexPositionColor(transform.Position, color),
                        B = new Microsoft.Xna.Framework.Graphics.VertexPositionColor(rayHit.Position, color),
                    });
                }
            };

            ai.Add(new AI.AIState
            {
                Name  = "Disabled",
                Tasks = new AI.Task[] { },
            });

            ai.Add(new AI.AIState
            {
                Name  = "Suspended",
                Tasks = new[] { checkOperationalRadius, },
            });

            ai.Add(new AI.AIState
            {
                Name  = "Idle",
                Tasks = new[]
                {
                    checkOperationalRadius,
                    updateRay,
                    new AI.Task
                    {
                        Interval = 1.0f,
                        Action   = delegate()
                        {
                            Agent a = Agent.Query(transform.Position, sightDistance, hearingDistance, x => x.Entity.Type == "Player");
                            if (a != null)
                            {
                                ai.CurrentState.Value = "Alert";
                            }
                        },
                    },
                },
            });

            ai.Add(new AI.AIState
            {
                Name  = "Alert",
                Tasks = new[]
                {
                    checkOperationalRadius,
                    updateRay,
                    new AI.Task
                    {
                        Interval = 1.0f,
                        Action   = delegate()
                        {
                            if (ai.TimeInCurrentState > 3.0f)
                            {
                                ai.CurrentState.Value = "Idle";
                            }
                            else
                            {
                                Agent a = Agent.Query(transform.Position, sightDistance, hearingDistance, x => x.Entity.Type == "Player");
                                if (a != null)
                                {
                                    ai.TargetAgent.Value  = a.Entity;
                                    ai.CurrentState.Value = "Aggressive";
                                }
                            }
                        },
                    },
                },
            });

            AI.Task checkTargetAgent = new AI.Task
            {
                Action = delegate()
                {
                    Entity target = ai.TargetAgent.Value.Target;
                    if (target == null || !target.Active)
                    {
                        ai.TargetAgent.Value  = null;
                        ai.CurrentState.Value = "Idle";
                    }
                },
            };

            float lastSpotted = 0.0f;

            ai.Add(new AI.AIState
            {
                Name  = "Aggressive",
                Tasks = new[]
                {
                    checkTargetAgent,
                    updateRay,
                    new AI.Task
                    {
                        Action = delegate()
                        {
                            Entity target         = ai.TargetAgent.Value.Target;
                            turret.Reticle.Value += (target.Get <Transform>().Position - turret.Reticle.Value) * Math.Min(3.0f * main.ElapsedTime, 1.0f);
                        }
                    },
                    new AI.Task
                    {
                        Interval = 0.1f,
                        Action   = delegate()
                        {
                            if (Agent.Query(transform.Position, sightDistance, hearingDistance, ai.TargetAgent.Value.Target.Get <Agent>()))
                            {
                                lastSpotted = main.TotalTime;
                            }

                            if (ai.TimeInCurrentState.Value > 1.5f)
                            {
                                if (lastSpotted < main.TotalTime - 2.0f)
                                {
                                    ai.CurrentState.Value = "Alert";
                                }
                                else
                                {
                                    Vector3 targetPos = ai.TargetAgent.Value.Target.Get <Transform>().Position.Value;
                                    Vector3 toTarget  = Vector3.Normalize(targetPos - transform.Position.Value);
                                    if (Vector3.Dot(toReticle, toTarget) > 0.95f)
                                    {
                                        ai.CurrentState.Value = "Firing";
                                    }
                                }
                            }
                        }
                    },
                }
            });

            ai.Add(new AI.AIState
            {
                Name  = "Firing",
                Enter = delegate(AI.AIState last)
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.PLAY_TURRET_CHARGE, entity);
                },
                Exit = delegate(AI.AIState next)
                {
                    Voxel.State attachedState = attachable.AttachedVoxel.Value.Target.Get <Voxel>()[attachable.Coord];
                    if (!attachedState.Permanent && rayHit.Voxel != null && (rayHit.Position - transform.Position).Length() < 8.0f)
                    {
                        return;                         // Danger close, cease fire!
                    }
                    AkSoundEngine.PostEvent(AK.EVENTS.PLAY_TURRET_FIRE, entity);

                    bool hitVoxel = true;

                    Entity target = ai.TargetAgent.Value.Target;
                    if (target != null && target.Active)
                    {
                        Vector3 targetPos = target.Get <Transform>().Position;
                        Vector3 toTarget  = targetPos - transform.Position.Value;
                        if (Vector3.Dot(toReticle, Vector3.Normalize(toTarget)) > 0.2f)
                        {
                            float distance = toTarget.Length();
                            if (distance < rayHit.Distance)
                            {
                                AkSoundEngine.PostEvent(AK.EVENTS.PLAY_TURRET_MISS, transform.Position + toReticle * distance);
                            }
                        }

                        BEPUutilities.RayHit physicsHit;
                        if (target.Get <Player>().Character.Body.CollisionInformation.RayCast(new Ray(transform.Position, toReticle), rayHit.Voxel == null ? float.MaxValue : rayHit.Distance, out physicsHit))
                        {
                            Explosion.Explode(main, targetPos, 6, 8.0f);
                            hitVoxel = false;
                        }
                    }

                    if (hitVoxel && rayHit.Voxel != null)
                    {
                        Explosion.Explode(main, rayHit.Position + rayHit.Voxel.GetAbsoluteVector(rayHit.Normal.GetVector()) * 0.5f, 6, 8.0f);
                    }
                },
                Tasks = new[]
                {
                    checkTargetAgent,
                    updateRay,
                    new AI.Task
                    {
                        Action = delegate()
                        {
                            if (ai.TimeInCurrentState.Value > 0.75f)
                            {
                                ai.CurrentState.Value = "Aggressive";                                 // This actually fires (in the Exit function)
                            }
                        }
                    }
                }
            });

            this.SetMain(entity, main);

            entity.Add("On", turret.On);
            entity.Add("PowerOn", turret.PowerOn);
            entity.Add("PowerOff", turret.PowerOff);
        }
Example #24
0
 private static bool DrawHitEnemy( Explosion bang )
 {
     if (time.ElapsedMilliseconds - bang.time < timeShowHit)
     {
         ConsoleBuffer.PrintOnPositoin( bang.x, bang.y, 'X', ConsoleColor.Red);
         return true;
     }
     else
         return false;
 }
Example #25
0
        protected override void OnFixedUpdate(float timeMult)
        {
            OnUpdateHitbox();
            HandleBlinking(timeMult);

            if (frozenTimeLeft > 0)
            {
                frozenTimeLeft -= timeMult;
                return;
            }

            MoveInstantly(new Vector2(speedX * timeMult, speedY * timeMult), MoveType.Relative, true);

            if (playerHit)
            {
                if (attackTime > 0f)
                {
                    attackTime -= timeMult;
                }
                else
                {
                    base.OnPerish(null);
                }
                return;
            }

            if (attackTime > 0f)
            {
                attackTime -= timeMult;
            }

            Vector3 pos = Transform.Pos;
            Vector3 targetPos;

            List <Player> players = api.Players;

            for (int i = 0; i < players.Count; i++)
            {
                targetPos = players[i].Transform.Pos;
                // Fly above the player
                targetPos.Y -= 100f;

                Vector3 direction = (pos - targetPos);
                float   length    = direction.Length;

                if (attackTime <= 0f && length < 260f)
                {
                    attackTime = 450f;

                    PlaySound("MagicFire");

                    SetTransition(AnimState.TransitionAttack, true, delegate {
                        Vector3 bulletPos = Transform.Pos + new Vector3(24f * (IsFacingLeft ? -1f : 1f), 0f, -2f);

                        MagicBullet bullet = new MagicBullet(this);
                        bullet.OnActivated(new ActorActivationDetails {
                            Api = api,
                            Pos = bulletPos
                        });
                        api.AddActor(bullet);

                        Explosion.Create(api, bulletPos, Explosion.TinyDark);
                    });
                }
                else if (length < 500f)
                {
                    direction.Normalize();
                    speedX = (direction.X * DefaultSpeed + speedX) * 0.5f;
                    speedY = (direction.Y * DefaultSpeed + speedY) * 0.5f;

                    IsFacingLeft = (speedX < 0f);
                    return;
                }
            }

            speedX = 0f;
            speedY = 0f;
        }
        public void Fire(bool charge)
        {
            if (barrel != null)
            {
                if (energyUI)
                {
                    float         energy = Mathf.Clamp(waitTilNextFire, 0, timeToFire).GetPercent(timeToFire) / 100;
                    RectTransform rt     = energyUI.GetComponent <RectTransform>();
                    if (rt)
                    {
                        Vector3 ls = rt.localScale;
                        ls.x          = energy;
                        rt.localScale = ls;
                    }
                }

                if (chargeUI)
                {
                    float         _power = Mathf.Clamp(power, 0, 10).GetPercent(10) / 100;
                    RectTransform rt     = chargeUI.GetComponent <RectTransform>();
                    if (rt)
                    {
                        Vector3 ls = rt.localScale;
                        ls.x          = _power;
                        rt.localScale = ls;
                    }
                }

                if (waitTilNextFire >= timeToFire)
                {
                    // cargando
                    if (charge)
                    {
                        // si el poder es menor que 10
                        if (power < 10f)
                        {
                            power += Time.deltaTime * speedCharge;
                            if (bullet == null && (power * 0.1f) > minPower)
                            {
                                bullet                 = MonoBehaviour.Instantiate(bulletsPrefab, tagBullets.position, tagBullets.rotation) as GameObject;
                                bulletComponent        = bullet.GetComponent <Bullet>();
                                bulletComponent.sender = tagBullets.root.gameObject;
                                bulletComponent.fire   = false;
                                particle               = bullet.GetComponentInChildren <ParticleSystem>();
                                light = bullet.GetComponentInChildren <Light>();
                                if (!lightIntensity.HasValue)
                                {
                                    lightIntensity = light.intensity;
                                    lightRange     = light.range;
                                }
                            }

                            if (fxAudio && fxAudio.AudioExistsStartWith("Power Charging"))
                            {
                                fxAudio.PlayStartWith("Power Charging");
                            }
                        }
                        else
                        {
                            if (fxAudio &&
                                fxAudio.AudioExistsStartWith("Power Stay") &&
                                fxAudio.IsPlayingStartWith("Power Charging"))
                            {
                                fxAudio.BlendClipsStartWith("Power Charging", "Power Stay", 3f, true);
                            }
                        }

                        if (bullet && bulletComponent)
                        {
                            Bullet bp = bulletsPrefab.GetComponent <Bullet>();
                            float  dr = bp.damageRate;

                            bullet.transform.position = tagBullets.position;
                            bullet.transform.rotation = tagBullets.rotation;
                            particle.startSize        = (power * 0.1f);
                            light.intensity           = power.GetPercent(10).ValueFromPercent(lightIntensity.Value);
                            light.range = power.GetPercent(10).ValueFromPercent(lightRange);
                            bulletComponent.damageRate = (dr / 10) * power;
                        }
                    }
                    else if ((power * 0.1f) < minPower && !charge) // si el poder es menor a minpower y no se esta cargando
                    {
                        power = 0f;
                        if (fxAudio && fxAudio.IsPlayingStartWith("Power Charging"))
                        {
                            fxAudio.StopFadeOutStartWith("Power Charging", 2f);
                        }
                    }
                }
                else
                {
                    power = 0f;
                }
                GameObject holdMuzzelFlash = null;
                // si el poder es mayor a minpower y no se esta cargando
                if ((power * 0.1f) > minPower && !charge)
                {
                    if (bulletsPrefab != null)
                    {
                        if (bullet && bulletComponent)
                        {
                            bullet.transform.position = tagBullets.position;
                            bulletComponent.fire      = true;
                            Bullet bp = bulletsPrefab.GetComponent <Bullet>();

                            if (bp)
                            {
                                Explosion expl = bp.explosion.GetComponent <Explosion>();
                                if (expl)
                                {
                                    float explSize  = expl.size;
                                    float explForce = expl.forcePower;
                                    bp.explosionSize  = (explSize / 10) * power;
                                    bp.explosionForce = (explForce / 10) * power;
                                }
                            }
                        }
                    }
                    if (muzzlePrefabs != null && muzzlePrefabs.Length > 0)
                    {
                        holdMuzzelFlash = MonoBehaviour.Instantiate(GetMuzzleRandom(), tagMuzzel.position, tagMuzzel.rotation) as GameObject;
                    }

                    waitTilNextFire = 0;

                    power = 0f;
                }

                if (fxAudio && bulletComponent && bulletComponent.fire)
                {
                    if (fxAudio.IsPlayingStartWith("Power Charging"))
                    {
                        fxAudio.StopStartWith("Power Charging");
                    }

                    if (fxAudio.IsPlayingStartWith("Power Stay"))
                    {
                        fxAudio.StopStartWith("Power Stay");
                    }

                    if (fxAudio.AudioExistsStartWith("Power Shoot"))
                    {
                        fxAudio.PlayStartWith("Power Shoot");
                    }
                }
                if (waitTilNextFire < timeToFire)
                {
                    waitTilNextFire += Time.deltaTime;
                }

                if (holdMuzzelFlash != null)
                {
                    holdMuzzelFlash.transform.parent = tagMuzzel;
                }
            }
        }
Example #27
0
        public Annoyer(EntityPreset preset, Player player)
            : base(preset.Position, "annoyer", 16, 16, DrawOrder.ENTITIES)
        {
            MapInteraction = false;
            _preset        = preset;
            _target        = player;
            Solid          = false;
            height         = 7;
            width          = 8;
            offset.X       = 3;
            offset.Y       = 2;

            explosion = new Explosion(Position)
            {
                exists = false
            };

            if (GlobalState.IsCell)
            {
                AddAnimation("flap", CreateAnimFrameArray(6, 7), 4, true);
            }
            else
            {
                int i = preset.Frame == T_SUPER ? 12 : 0;
                AddAnimation("flap", CreateAnimFrameArray(i, i + 1, i + 2, i + 3, i + 4, i + 5), 8, true);
            }
            Play("flap");

            if (preset.Frame == T_SUPER)
            {
                _health = 2;
            }

            fireballs = new EntityPool <Fireball>(preset.Frame == T_SUPER ? 4 : 0, () => new Fireball());

            _state = new StateMachineBuilder()
                     .State <ActiveState>("Active")
                     .Enter((state) => {
                velocity = Vector2.Zero;
                state.ChangeState(start_state);
                start_state = "Approach";         //TODO: Add way of entering nested states(see ChangeState in Hit, needs to go to Approach, not Wait)
            })
                     .Event <CollisionEvent <Player> >("Player", (state, p) => p.entity.ReceiveDamage(1))
                     .Event <CollisionEvent <Broom> >("Hit", (state, b) => {
                velocity = FacingDirection(b.entity.facing) * 150;
                if (velocity.Y < 0)
                {
                    velocity.X = GlobalState.RNG.Next(-30, 31);
                }
                _state.ChangeState("Hit");
            })

                     .Event("Fire", (state) => fireballs.Spawn((f) => f.Spawn(this, _target)))

                     .State <TimerState>("Wait")
                     .Enter((state) =>
            {
                state.Reset();
                state.AddTimer(0.25f, "ApproachCheck");
            })
                     .Event("ApproachCheck", (state) =>
            {
                if ((Position - _target.Position).Length() < 64)
                {
                    state.Parent.ChangeState("Approach");
                }
            })
                     .End()

                     .State("Approach")
                     .Update((state, time) => {
                MathUtilities.MoveTo(ref Position.X, ApproachTarget.X, 36);
                MathUtilities.MoveTo(ref Position.Y, ApproachTarget.Y, 36);
            })
                     .Condition(() => (Position - ApproachTarget).Length() < 2, (state) => state.Parent.ChangeState("Circle"))
                     .Exit((state) => velocity = Vector2.Zero)
                     .End()

                     .State <CirclingState>("Circle")
                     .Enter((state) => state.angle = 0)
                     .Update((state, time) =>
            {
                Position = _target.VisualCenter + new Vector2((float)Math.Cos(state.angle), (float)Math.Sin(state.angle)) * rotation_radius;
            })
                     .Event("Swoop", (state) => state.Parent.ChangeState("Swoop"))
                     .End()

                     .State <SwoopState>("Swoop")
                     .Enter((state) => state.target = Position + 3 * (_target.Position - Position))
                     .Update((state, time) => {   //TODO: make it possible for this to be a Condition
                if (MathUtilities.MoveTo(ref Position.X, state.target.X, 2.5f * 60) & MathUtilities.MoveTo(ref Position.Y, state.target.Y, 2.5f * 60))
                {
                    state.Parent.ChangeState("Approach");
                }
            })
                     .End()
                     .End()

                     .State <TimerState>("Hit")
                     .Enter((state) =>
            {
                SoundManager.PlaySoundEffect("player_hit_1");
                state.Reset();
                Flicker(0.2f);
                if (--_health <= 0)
                {
                    Solid = true;
                    state.AddTimer(0.25f, "Die");
                }
                else
                {
                    state.AddTimer(0.4f, "EndKnockback");
                }
            })
                     .Event("EndKnockback", (state) => _state.ChangeState("Active"))
                     .Event("Die", (state) => {
                exists             = _preset.Alive = false;
                explosion.exists   = true;
                explosion.Position = Position;
                SoundManager.PlaySoundEffect("hit_wall");
            })
                     .Exit((state) =>
            {
                Solid = false;
            })
                     .End()

                     .Build();
            _state.ChangeState("Active");
        }
Example #28
0
            private static float recursiveHandleDamage(ref ManDamage __instance, ref float __result, Damageable damageTarget, Damageable directHit, Component source, TankBlock targetBlock, Tank targetTank, string prefix, bool RecurseOverride = false)
            {
                if (RecurseOverride || PatchDamage.YetToHit.Contains(targetBlock))
                {
                    ExplosionNerf.IngressPoint.DebugPrint("\n" + prefix, "Resolving Block: " + targetBlock.name);
                    PatchDamage.YetToHit.Remove(targetBlock);

                    if (directHit != null)
                    {
                        ExplosionNerf.IngressPoint.DebugPrint(prefix, "direct hit detected");
                        TankBlock localHitBlock = directHit.Block;
                        if (localHitBlock != PatchDamage.hitBlock)
                        {
                            ExplosionNerf.IngressPoint.DebugPrint(prefix, "ONLY should happen when direct hit RESOLVED, block NOT destroyed");
                            ExplosionNerf.IngressPoint.DebugPrint(prefix, "RESOLUTION - ALWAYS BLOCK");
                            return(0.0f);
                        }

                        if (directHit == damageTarget)
                        {
                            // do actual dmg to targetBlock
                            ExplosionNerf.IngressPoint.DebugPrint(prefix, "Direct hit NEVER invincible - calculate dmg");

                            Explosion castSource = (Explosion)source;

                            // Console.WriteLine(directHit.MaxHealth <= 1.0f);
                            // Console.WriteLine(localHitBlock.GetComponent<ModuleShieldGenerator>() != null);
                            // Console.WriteLine(PatchDamage.rejectDamageEvent.GetValue());

                            ManDamage.DamageInfo damageInfo = PatchDamage.NewDamageInfo(directHit, damageTarget, targetBlock);
                            ExplosionNerf.IngressPoint.DebugPrint(prefix, "Damage: " + damageInfo.Damage.ToString());
                            float dmgDone = PatchDamage.DoDamage(ref __instance, directHit, damageTarget, damageInfo);
                            if (dmgDone == 0.0f)
                            {
                                ExplosionNerf.IngressPoint.DebugPrint(prefix, "Block NOT destroyed - mark invincible for now");
                                if (!PatchDamage.DeterminedInvincible.ContainsKey(targetTank))
                                {
                                    PatchDamage.DeterminedInvincible[targetTank] = new HashSet <TankBlock>();
                                }
                                PatchDamage.DeterminedInvincible[targetTank].Add(localHitBlock);
                            }
                            else
                            {
                                ExplosionNerf.IngressPoint.DebugPrint(prefix, "BLOCK DESTROYED - remove from consideration");
                                PatchDamage.DirectHit.SetValue(source, null);
                            }
                            PatchDamage.hitBlock = null;

                            // modify damageInfo for recursion purposes - no longer necessary
                            // damageInfo.ApplyDamageMultiplier(newDamageMult);

                            // modify dmg energy left in explosion
                            castSource.m_MaxDamageStrength *= (float)PatchDamage.m_AoEDamageBlockPercent.GetValue(directHit);
                            // PatchDamage.DirectHit.SetValue(source, null);
                            return(dmgDone);
                        }
                        else
                        {
                            ExplosionNerf.IngressPoint.DebugPrint(prefix, "Resolve Direct hit first");
                            float destroyed = PatchDamage.recursiveHandleDamage(ref __instance, ref __result, directHit, directHit, source, localHitBlock, targetTank, prefix + "|  ", true);

                            // if block was actually destroyed
                            if (destroyed != 0.0f)
                            {
                                // do actual dmg to targetBlock
                                PatchDamage.hitBlock = null;
                                ExplosionNerf.IngressPoint.DebugPrint(prefix, "Resolve NOT NECESSARILY invincible - calculate dmg (re-recurse)");
                                PatchDamage.YetToHit.Add(targetBlock);
                                directHit = (Damageable)PatchDamage.DirectHit.GetValue(source);
                                return(PatchDamage.recursiveHandleDamage(ref __instance, ref __result, damageTarget, directHit, source, targetBlock, targetTank, prefix + "|  "));
                            }
                            else
                            {
                                ExplosionNerf.IngressPoint.DebugPrint(prefix, "ONLY should happen when direct hit RESOLVED, block NOT destroyed");
                                ExplosionNerf.IngressPoint.DebugPrint(prefix, "RESOLUTION - ALWAYS BLOCK");
                                if (!PatchDamage.DeterminedInvincible.ContainsKey(targetTank))
                                {
                                    PatchDamage.DeterminedInvincible[targetTank] = new HashSet <TankBlock>();
                                }
                                PatchDamage.DeterminedInvincible[targetTank].Add(targetBlock);
                                return(0.0f);
                            }
                        }
                    }
                    else
                    {
                        ExplosionNerf.IngressPoint.DebugPrint(prefix, "no direct hit - Raycast time");
                        Vector3      actual  = source.transform.position - targetBlock.transform.position;
                        RaycastHit[] results = new RaycastHit[((int)actual.magnitude)];
                        int          hits    = Physics.RaycastNonAlloc(new Ray(targetBlock.transform.position, actual), results, actual.magnitude, Singleton.Manager <ManVisible> .inst.VisiblePickerMaskNoTechs, QueryTriggerInteraction.Ignore);

                        List <TankBlock> foundBlocks = new List <TankBlock>();
                        if (!PatchDamage.DeterminedInvincible.ContainsKey(targetTank))
                        {
                            PatchDamage.DeterminedInvincible[targetTank] = new HashSet <TankBlock>();
                        }
                        for (int i = 0; i < hits; i++)
                        {
                            // ExplosionNerf.IngressPoint.DebugPrint("Loop " + i.ToString());
                            RaycastHit test    = results[i];
                            Visible    visible = Visible.FindVisibleUpwards((Component)test.collider);
                            if ((UnityEngine.Object)visible != (UnityEngine.Object)null)
                            {
                                TankBlock block = visible.block;
                                if (block != null && block != targetBlock && block.tank != null)
                                {
                                    if (block.tank == targetTank)
                                    {
                                        // ExplosionNerf.IngressPoint.DebugPrint("Damage blocked");
                                        if (PatchDamage.YetToHit.Contains(block))
                                        {
                                            ExplosionNerf.IngressPoint.DebugPrint(prefix, "  Unresolved block found: " + block.name);
                                            foundBlocks.Add(block);
                                        }
                                        else if (PatchDamage.DeterminedInvincible[targetTank].Contains(block))
                                        {
                                            ExplosionNerf.IngressPoint.DebugPrint(prefix, "  Resolved INVINCIBLE found");
                                            PatchDamage.DeterminedInvincible[targetTank].Add(targetBlock);
                                            foundBlocks.Clear();
                                            return(0.0f);
                                        }
                                    }
                                }
                            }
                        }
                        ExplosionNerf.IngressPoint.DebugPrint(prefix, "Raycast initial pass done - no invincible found in path");
                        if (foundBlocks.Count > 0)
                        {
                            bool breakInvincible = false;
                            foreach (TankBlock block in foundBlocks)
                            {
                                if (PatchDamage.YetToHit.Contains(block))
                                {
                                    float destroyed = PatchDamage.recursiveHandleDamage(ref __instance, ref __result, block.GetComponent <Damageable>(), directHit, source, block, targetTank, prefix + "|  ");

                                    if (destroyed == 0.0f)
                                    {
                                        PatchDamage.DeterminedInvincible[targetTank].Add(targetBlock);

                                        breakInvincible = true;
                                        break;
                                    }
                                }
                                else if (PatchDamage.DeterminedInvincible[targetTank].Contains(block))
                                {
                                    PatchDamage.DeterminedInvincible[targetTank].Add(targetBlock);

                                    breakInvincible = true;
                                    ExplosionNerf.IngressPoint.DebugPrint(prefix, "Resolved INVINCIBLE found");
                                    break;
                                }
                            }

                            if (!breakInvincible)
                            {
                                ExplosionNerf.IngressPoint.DebugPrint(prefix, "(A) [Should be rare] Resolve NOT invincible - calculate dmg");
                                ManDamage.DamageInfo damageInfo = PatchDamage.NewDamageInfo(directHit, damageTarget, targetBlock);
                                ExplosionNerf.IngressPoint.DebugPrint(prefix, "Damage: " + damageInfo.Damage.ToString());
                                float dmgDone = PatchDamage.DoDamage(ref __instance, directHit, damageTarget, damageInfo);
                                if (dmgDone == 0.0f)
                                {
                                    ExplosionNerf.IngressPoint.DebugPrint(prefix, "Block NOT destroyed - mark invincible for now");
                                    if (!PatchDamage.DeterminedInvincible.ContainsKey(targetTank))
                                    {
                                        PatchDamage.DeterminedInvincible[targetTank] = new HashSet <TankBlock>();
                                    }
                                    PatchDamage.DeterminedInvincible[targetTank].Add(targetBlock);
                                }
                                else
                                {
                                    ExplosionNerf.IngressPoint.DebugPrint(prefix, "BLOCK DESTROYED - remove from consideration");
                                }
                                return(dmgDone);
                            }
                            else
                            {
                                ExplosionNerf.IngressPoint.DebugPrint(prefix, "Resolved INVINCIBLE found");
                                return(0.0f);
                            }
                        }
                        else
                        {
                            ExplosionNerf.IngressPoint.DebugPrint(prefix, "No blocks in way - Resolve NOT invincible - calculate dmg");
                            ManDamage.DamageInfo damageInfo = PatchDamage.NewDamageInfo(directHit, damageTarget, targetBlock);
                            ExplosionNerf.IngressPoint.DebugPrint(prefix, "Damage: " + damageInfo.Damage.ToString());
                            float dmgDone = PatchDamage.DoDamage(ref __instance, directHit, damageTarget, damageInfo);
                            if (dmgDone == 0.0f)
                            {
                                ExplosionNerf.IngressPoint.DebugPrint(prefix, "Block NOT destroyed - mark invincible for now");
                                if (!PatchDamage.DeterminedInvincible.ContainsKey(targetTank))
                                {
                                    PatchDamage.DeterminedInvincible[targetTank] = new HashSet <TankBlock>();
                                }
                                PatchDamage.DeterminedInvincible[targetTank].Add(targetBlock);
                            }
                            else
                            {
                                ExplosionNerf.IngressPoint.DebugPrint(prefix, "BLOCK DESTROYED - remove from consideration");
                            }
                            return(dmgDone);
                        }
                    }
                }
                ExplosionNerf.IngressPoint.DebugPrint(prefix, "END");
                return(0.0f);
            }
Example #29
0
 public Explosion(Explosion original, bool enableRendering)
 {
     setRenderable(enableRendering);
     initialize();
     copyFrom(original);
 }
Example #30
0
 // copy constructor
 public Explosion(Explosion original)
 {
     initialize();
     copyFrom(original);
 }
Example #31
0
 public void UpdateExplotion(Explosion explosion)
 {
     _bl.UpdateExplosion(explosion);
 }
Example #32
0
        public void AddExplosion(Vector2 position, int energy, IGameObject originator)
        {
            var e = new Explosion(position, energy, originator);

            this._gameObjectCollection.Add(e);
        }
Example #33
0
        public override void Update(double elapsedTime)
        {
            if (this.IsPaused)
            {
                return;
            }

            if (this.Position.Y <= 0)
            {
                this.State = StageState.Stop;
            }

            if (!this.IsStopedMove)
            {
                this.UpdateY(elapsedTime);
            }

            if (this.v2dNextUserPosition.Y >= this.Position.Y && this.v2dNextUserPosition.Y <= (this.Position.Y + 500))
            {
                ssUser.Position.Y = this.v2dNextUserPosition.Y;
            }
            else
            {
                ssUser.Position.Y += this.Velocity.Y * elapsedTime;
            }

            if (this.v2dNextUserPosition.X >= this.Position.X && this.v2dNextUserPosition.X <= (this.Position.X + 800))
            {
                ssUser.Position.X = this.v2dNextUserPosition.X;
            }


            #region createBullet
            ssUser.TimeAcummulator.Update(elapsedTime);
            if (createBullet)
            {
                if (ssUser.TimeAcummulator.IsOverflow)
                {
                    Vector2D posB;
                    posB.X = ssUser.Position.X + ssUser.AddPosBullet;
                    posB.Y = ssUser.Position.Y;
                    ssUser.BulletSettings.AddBullets(lstUserBullets, posB, this, true);
                    createBullet = false;
                }
            }
            #endregion

            #region enemy.Update
            for (int ie = 0; ie < lstEnemies.Count; ie++)
            {
                EnemySpaceShip enemy = lstEnemies[ie];
                switch (enemy.Update(ssUser, this, elapsedTime))
                {
                case CombatStatus.MeDie:
                case CombatStatus.BothDie:
                    lstEnemies.RemoveAt(ie);
                    ie--;
                    if (enemy.HasItem)
                    {
                        this.Items.Add(enemy.Item);
                    }
                    enemy.Dispose();
                    break;
                }
            }
            #endregion

            #region lstUserBullets
            for (int i = 0; i < lstUserBullets.Count; ++i)
            {
                Bullet bullet = lstUserBullets[i];
                bullet.Update(elapsedTime);
                if (bullet.Position.Y <= this.Position.Y)
                {
                    lstUserBullets.RemoveAt(i);
                    bullet.Dispose();
                    --i;
                    continue;
                }
                for (int j = 0; j < lstEnemies.Count; ++j)
                {
                    EnemySpaceShip enemy    = lstEnemies[j];
                    CombatStatus   cs       = bullet.VerifyCombat(enemy);
                    bool           breakFor = false;
                    switch (cs)
                    {
                    case CombatStatus.BothDie:
                        #region CombatStatus.BothDie
                        this.lstExplosions.Add(new Explosion(bullet.Position, ExplosionType.One));
                        lstUserBullets.RemoveAt(i);
                        bullet.Dispose();
                        --i;
                        lstEnemies.RemoveAt(j);
                        --j;
                        if (enemy.HasItem)
                        {
                            lstItem.Add(enemy.Item);
                        }
                        enemy.Dispose();
                        breakFor = true;
                        break;

                        #endregion
                    case CombatStatus.MeDie:
                        #region CombatStatus.MeDie
                        this.lstExplosions.Add(new Explosion(bullet.Position, ExplosionType.One));
                        lstUserBullets.RemoveAt(i);
                        bullet.Dispose();
                        --i;
                        breakFor = true;
                        break;

                        #endregion
                    case CombatStatus.CombatantDie:
                        #region CombatStatus.CombatantDie
                        this.lstExplosions.Add(new Explosion(bullet.Position, ExplosionType.One));
                        lstEnemies.RemoveAt(j);
                        --j;
                        if (enemy.HasItem)
                        {
                            lstItem.Add(enemy.Item);
                        }
                        enemy.Dispose();
                        break;
                        #endregion
                    }
                    if (breakFor)
                    {
                        break;
                    }
                }
            }
            #endregion

            #region lstEnemiesBullets
            for (int i = 0; i < lstEnemiesBullets.Count; ++i)
            {
                Bullet enBullet = lstEnemiesBullets[i];
                enBullet.Update(elapsedTime);
                if (enBullet.Position.Y >= (this.Position.Y + 816))
                {
                    lstEnemiesBullets.RemoveAt(i);
                    enBullet.Dispose();
                    --i;
                    continue;
                }
                if (enBullet.VerifyCombat(ssUser) != CombatStatus.None)
                {
                    this.lstExplosions.Add(new Explosion(enBullet.Position, ExplosionType.Two));
                    lstEnemiesBullets.RemoveAt(i);
                    enBullet.Dispose();
                    --i;
                    break;
                }
            }

            #endregion

            #region lstExplosions
            for (int i = 0; i < lstExplosions.Count; ++i)
            {
                Explosion exp = lstExplosions[i];
                exp.Update(elapsedTime);
                if (exp.Destroy())
                {
                    lstExplosions.RemoveAt(i);
                    exp.Dispose();
                    --i;
                }
            }
            #endregion

            #region lstItem
            for (int i = 0; i < lstItem.Count; ++i)
            {
                Item ib = lstItem[i];
                if (ib.Update(elapsedTime, ssUser))
                {
                    lstItem.RemoveAt(i);
                    ib.Dispose();
                    --i;
                }
            }
            #endregion
        }
Example #34
0
 /**
  *
  */
 public void OnExplosionEnter(Explosion explosion)
 {
     this.fuseLength = 0.15f;
 }
Example #35
0
        /// <summary>
        /// The method that will be used to draw everything in the frame
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {
            if (!Constants.tanks.ContainsKey(Constants.playerID))
            {
                return;
            }
            //Lock the world while everything is drawing
            lock (theWorld)
            {
                Tank theTank = Constants.tanks[Constants.playerID];

                double playerX = theTank.location.GetX();
                double playerY = theTank.location.GetY();

                // Before anything else draw the background
                e.Graphics.DrawImage(background, (int)(-playerX - 200), (int)(-playerY - 200), Constants.worldSize, Constants.worldSize);

                // calculate view/world size ratio
                double ratio          = (double)800 / (double)Constants.worldSize;
                int    halfSizeScaled = (int)(Constants.worldSize / 2.0 * ratio);

                double inverseTranslateX = -WorldSpaceToImageSpace(Constants.worldSize, playerX) + halfSizeScaled;
                double inverseTranslateY = -WorldSpaceToImageSpace(Constants.worldSize, playerY) + halfSizeScaled;

                e.Graphics.TranslateTransform((float)inverseTranslateX, (float)inverseTranslateY);

                //Draw every tank in the constants tanks dictionary
                foreach (int t in Constants.tanks.Keys)
                {
                    Tank currTank = Constants.tanks[t];

                    //If the tank is disconnected, draw an explosion
                    if (currTank.disconnected == true)
                    {
                        if (!Constants.explosions.ContainsKey(t))
                        {
                            Constants.explosions.Add(t, new Explosion(currTank.location, t));
                        }
                        continue;
                    }
                    // If the tank has zero hit points, draw an explosion
                    if (currTank.hitPoints == 0)
                    {
                        if (!Constants.explosions.ContainsKey(t))
                        {
                            Constants.explosions.Add(t, new Explosion(currTank.location, t));
                        }
                        continue;
                    }

                    //Draw the tank while ensuring the turret ispointing a valid direction
                    DrawObjectWithTransform(e, t, Constants.worldSize, currTank.location.GetX(), currTank.location.GetY(), currTank.orientation.ToAngle(), TankDrawer);
                    if (!float.IsNaN(currTank.aiming.ToAngle()) && !float.IsInfinity(currTank.aiming.ToAngle()))
                    {
                        DrawObjectWithTransform(e, t, Constants.worldSize, currTank.location.GetX(), currTank.location.GetY(), currTank.aiming.ToAngle(), TurretDrawer);
                    }
                    else
                    {
                        DrawObjectWithTransform(e, t, Constants.worldSize, currTank.location.GetX(), currTank.location.GetY(), 0, TurretDrawer);
                    }
                    DrawObjectWithTransform(e, t, Constants.worldSize, currTank.location.GetX(), currTank.location.GetY(), 0, GUIDrawer);
                }

                //A list to hold all repeated keys
                List <int> keys = new List <int>();

                //Draw all the explosions
                foreach (int t in Constants.explosions.Keys)
                {
                    Explosion currEx = Constants.explosions[t];
                    if (currEx.timeout < 4)
                    {
                        keys.Add(t);
                        continue;
                    }
                    DrawObjectWithTransform(e, t, Constants.worldSize, currEx.location.GetX(), currEx.location.GetY(), 0, ExplosionDrawer);
                }
                //Clear all the explosions
                foreach (int t in keys)
                {
                    if (Constants.tanks[t].hitPoints > 0)
                    {
                        Constants.explosions.Remove(t);
                    }
                }
                keys.Clear();

                //Draw all the projectiles
                foreach (int t in Constants.projectiles.Keys)
                {
                    Projectile currProjectile = Constants.projectiles[t];
                    if (currProjectile.died)
                    {
                        keys.Add(t);
                        continue;
                    }
                    DrawObjectWithTransform(e, t, Constants.worldSize, currProjectile.location.GetX(), currProjectile.location.GetY(), currProjectile.orientation.ToAngle(), ProjectileDrawer);
                }
                //Clear all the projectiles
                foreach (int t in keys)
                {
                    Constants.projectiles.Remove(t);
                }
                keys.Clear();

                // Draw all the powerups
                foreach (int t in Constants.powerups.Keys)
                {
                    Powerup currPowerup = Constants.powerups[t];
                    if (currPowerup.died)
                    {
                        keys.Add(t);
                        continue;
                    }
                    DrawObjectWithTransform(e, t, Constants.worldSize, currPowerup.location.GetX(), currPowerup.location.GetY(), 0, PowerupDrawer);
                }
                // Clear all the powerups
                foreach (int t in keys)
                {
                    Constants.powerups.Remove(t);
                }
                keys.Clear();

                //Draw all the beams
                foreach (int t in Constants.beams.Keys)
                {
                    Beam currbeam = Constants.beams[t];
                    DrawObjectWithTransform(e, t, Constants.worldSize, currbeam.origin.GetX(), currbeam.origin.GetY(), currbeam.direction.ToAngle(), BeamDrawer);
                }

                //Draw all the walls
                foreach (int t in Constants.walls.Keys)
                {
                    Wall currWall = Constants.walls[t];
                    if (currWall.endpointOne.GetX() == currWall.endpointTwo.GetX())
                    {
                        if (currWall.endpointOne.GetY() < currWall.endpointTwo.GetY())
                        {
                            for (double i = currWall.endpointOne.GetY(); i <= currWall.endpointTwo.GetY(); i += 50)
                            {
                                DrawObjectWithTransform(e, t, Constants.worldSize, currWall.endpointOne.GetX(), i, 0, WallDrawer);
                            }
                        }
                        else
                        {
                            for (double i = currWall.endpointOne.GetY(); i >= currWall.endpointTwo.GetY(); i -= 50)
                            {
                                DrawObjectWithTransform(e, t, Constants.worldSize, currWall.endpointOne.GetX(), i, 0, WallDrawer);
                            }
                        }
                    }
                    else
                    {
                        if (currWall.endpointOne.GetX() < currWall.endpointTwo.GetX())
                        {
                            for (double i = currWall.endpointOne.GetX(); i <= currWall.endpointTwo.GetX(); i += 50)
                            {
                                DrawObjectWithTransform(e, t, Constants.worldSize, i, currWall.endpointOne.GetY(), 0, WallDrawer);
                            }
                        }
                        else
                        {
                            for (double i = currWall.endpointOne.GetX(); i >= currWall.endpointTwo.GetX(); i -= 50)
                            {
                                DrawObjectWithTransform(e, t, Constants.worldSize, i, currWall.endpointOne.GetY(), 0, WallDrawer);
                            }
                        }
                    }
                }
            }
        }
Example #36
0
        public static Explosion GetExplosion()
        {
            Dictionary<AnimationKey, Animation> animations = new Dictionary<AnimationKey, Animation>();
            Animation animation = new Animation(16, 64, 64, 0, 0);
            animation.FramesPerSecond = 20;
            animations.Add(AnimationKey.Down, animation);

            Explosion explosion = new Explosion(ExplosionTexture, animations);

            return explosion;
        }
Example #37
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: load the teddy bear
            teddybear = Content.Load<Texture2D>("teddybear");
            teddybear2 = Content.Load<Texture2D>("teddybear2");

            //set the current teddy bear
            currentTeddyBear = teddybear;

            explosion = new Explosion(Content);

            //set rectangle
            drawRectangle = new Rectangle(windowWidth / 2 - teddybear.Width / 2,
                                          windowHeight / 2 - teddybear.Height / 2,
                                          teddybear.Width, teddybear.Height);
        }
Example #38
0
    // Update is called once per frame
    void Update()
    {
        UIManager.rocketjumpTimer = cooldownTimer;

        if (cooldownTimer < cooldown)
        {
            cooldownTimer += Time.deltaTime;
            cooldownTimer  = Mathf.Clamp(cooldownTimer, 0, cooldown);
            return;
        }

        if (Input.GetButtonDown("Hook") && !active)
        {
            //KostinKoodi
            jumpPackSound = FMODUnity.RuntimeManager.CreateInstance("event:/SX/Player/Big/PlayerBig_jetpack_Jump");

            FMODUnity.RuntimeManager.AttachInstanceToGameObject(jumpPackSound, GetComponent <Transform>(), GetComponent <Rigidbody>());
            jumpPackSound.start();

            playerMovement.grappling = true;
            playerMovement.specialAbilityDisables = true;
            playerMovement.dodging = false;
            playerRB.velocity      = new Vector3(playerRB.velocity.x, 0, playerRB.velocity.z);
            playerRB.AddForce(Vector3.up * initialThrust, ForceMode.Impulse);
            rocket = true;
            active = true;
        }

        if (rocket)
        {
            //Debug.Log("THRUST");
            playerRB.AddForce(Vector3.up * thrust, ForceMode.Acceleration);
            thrustTimer += Time.deltaTime;


            if (thrustTimer >= thrustDuration)
            {
                rocket      = false;
                decelerate  = true;
                thrustTimer = 0;
                //playerRB.velocity = new Vector3(playerRB.velocity.x, 0, playerRB.velocity.z);
            }
        }

        if (decelerate)
        {
            //Debug.Log("DECELERATE");
            playerRB.velocity = new Vector3(playerRB.velocity.x, Mathf.Lerp(playerRB.velocity.y, -0.5f, Time.deltaTime * 5), playerRB.velocity.z);
            if (playerRB.velocity.y <= 0)
            {
                //playerMovement.grappling = false;
                playerMovement.specialAbilityDisables = false;
                hover      = true;
                decelerate = false;
            }
        }

        if (hover)
        {
            //Debug.Log("HOVER");
            playerRB.velocity = new Vector3(playerRB.velocity.x, 0, playerRB.velocity.z);
            hoverTimer       += Time.deltaTime;
            if (hoverTimer >= hoverDuration)
            {
                hover         = false;
                hoverTimer    = 0;
                active        = false;
                cooldownTimer = 0;
                aoeIndicator.SetActive(false);
                playerMovement.grappling = false;

                //KostinKoodi
                jumpPackSound.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);
            }
        }

        if (hover)
        {
            //This creates a directional vector using angles which can be clamped. This makes it so that the raycast can be shot out using angles
            upDownAngle = transform.localRotation.eulerAngles.x;
            upDownAngle = CrashAngleClamp(upDownAngle, maxCrashAngle, 90);
            //Debug.Log(upDownAngle);
            crashLineOfSight = Quaternion.Euler(upDownAngle, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z) * Vector3.forward;
            //Debug.DrawRay(transform.position, crashLineOfSight * 10, Color.red);
            if (Physics.Raycast(transform.position, crashLineOfSight, out lineOfSight, 1000, mask) && !crashing)
            {
                aoeIndicator.SetActive(true);
                aoeIndicator.transform.position = lineOfSight.point;
                if (Input.GetButtonDown("Hook"))
                {
                    //Debug.Log("CRASH");
                    transform.parent.GetComponent <Collider>().enabled = false;
                    crashing        = true;
                    crashPoint      = aoeIndicator.transform.position;
                    crashDirection  = crashLineOfSight;
                    hoverTimer      = 0;
                    thrustTimer     = 0;
                    crashDelayTimer = crashDelay;
                    aoeIndicator.SetActive(false);
                }
            }
            else
            {
                aoeIndicator.SetActive(false);
            }
        }

        if (crashDelayTimer > 0)
        {
            crashDelayTimer -= Time.deltaTime;
        }

        if (crashing && crashDelayTimer <= 0)
        {
            hover = false;
            if (playerRB.velocity.magnitude < crashSpeed - 1 && !accelerated)
            {
                accelerated = false;
                //Debug.Log("ACC" + playerRB.velocity.magnitude);
                crashAcceleratingSpeed = Mathf.Lerp(crashAcceleratingSpeed, crashSpeed + crashAcceleratingSpeed * 2, Time.deltaTime * crashAcceleration);
            }
            else
            {
                accelerated = true;
                //Debug.Log("DONE");
                crashAcceleratingSpeed = crashSpeed;
            }
            playerRB.velocity = crashDirection.normalized * crashAcceleratingSpeed;
            GetComponent <MouseLook>().enabled = false;
            transform.parent.GetComponent <MouseLook>().enabled = false;
            if (turnWhenCrashing)
            {
                transform.forward = crashDirection;
                GetComponent <MouseLook>().originalRotation = transform.localRotation;
                GetComponent <MouseLook>().rotationY        = 0;
            }
            if ((transform.position - crashPoint).magnitude <= explosionProximity)
            {
                //Debug.Log("BOOOOOOOOOOOOOOM");
                Explosion.UnobstructedExplosionDamage(transform.parent.position, explosionRange, explosionDamage, explosionKnockback, explosionStunDuration, false);
                transform.parent.GetComponent <Collider>().enabled = true;
                playerRB.velocity /= 1.4f;
                crashing           = false;
                active             = false;
                GetComponent <MouseLook>().enabled = true;
                transform.parent.GetComponent <MouseLook>().enabled = true;
                cooldownTimer = 0;
                playerMovement.specialAbilityDisables = false;
                playerMovement.grappling = false;

                //KostinKoodi
                jumpPackSound.setParameterByName("JumpPack_Land", 1);
            }
        }
    }
Example #39
0
 /*event handler for explosion animation*/
 private void ExplosionTimer_Tick(object sender, EventArgs e)
 {
     Explosion.ExplosionTime(this);
 }
 public ExplosionClearObserver(Explosion explosion, IBombExplosionStrategy strategy) : base(50)
 {
     _strategy  = strategy;
     _explosion = explosion;
 }
Example #41
0
 internal void RemoveExplosionObject(Explosion ex)
 {
     _explosionObjectsTBR.Add(ex);
 }
Example #42
0
 private void OnValidate()
 {
     ExplosionObject = GetComponentInChildren <Explosion>();
 }
Example #43
0
        public override IEnumerable <object> UpdateState()
        {
            while (GameMain.Instance.LoadingScreenOpen)
            {
                yield return(null);
            }

            // explosions and radio messages ------------------------------------------------------

            yield return(new WaitForSeconds(3.0f, false));

            //SoundPlayer.PlayDamageSound("StructureBlunt", 10, Character.Controlled.WorldPosition);
            //// Room 1
            //while (shakeTimer > 0.0f) // Wake up, shake
            //{
            //    shakeTimer -= 0.1f;
            //    GameMain.GameScreen.Cam.Shake = shakeAmount;
            //    yield return new WaitForSeconds(0.1f);
            //}
            //yield return new WaitForSeconds(2.5f);
            //GameMain.GameSession?.CrewManager.AddSinglePlayerChatMessage(radioSpeakerName, TextManager.Get("Mechanic.Radio.WakeUp"), ChatMessageType.Radio, null);

            //yield return new WaitForSeconds(2.5f);

            doctor.SetStun(1.5f);
            var explosion = new Explosion(range: 100, force: 10, damage: 0, structureDamage: 0);

            explosion.DisableParticles();
            GameMain.GameScreen.Cam.Shake = shakeAmount;
            explosion.Explode(Character.Controlled.WorldPosition - Vector2.UnitX * 25, null);
            SoundPlayer.PlayDamageSound("StructureBlunt", 10, Character.Controlled.WorldPosition - Vector2.UnitX * 25);

            yield return(new WaitForSeconds(0.5f, false));

            doctor.DamageLimb(
                Character.Controlled.WorldPosition,
                doctor.AnimController.GetLimb(LimbType.Torso),
                new List <Affliction> {
                new Affliction(AfflictionPrefab.InternalDamage, 10.0f)
            },
                stun: 3.0f, playSound: true, attackImpulse: 0.0f);

            shakeTimer = 0.5f;
            while (shakeTimer > 0.0f) // Wake up, shake
            {
                shakeTimer -= 0.1f;
                GameMain.GameScreen.Cam.Shake = shakeAmount;
                yield return(new WaitForSeconds(0.1f, false));
            }

            yield return(new WaitForSeconds(3.0f, false));

            GameMain.GameSession?.CrewManager.AddSinglePlayerChatMessage(radioSpeakerName, TextManager.Get("Doctor.Radio.KnockedDown"), ChatMessageType.Radio, null);

            // first tutorial segment, get medical supplies ------------------------------------------------------

            yield return(new WaitForSeconds(1.5f, false));

            SetHighlight(doctor_suppliesCabinet.Item, true);

            /*while (doctor.CurrentHull != doctor_suppliesCabinet.Item.CurrentHull)
             * {
             *  yield return new WaitForSeconds(2.0f);
             * }*/

            TriggerTutorialSegment(0, GameMain.Config.KeyBind(InputType.Select), GameMain.Config.KeyBind(InputType.Deselect)); // Medical supplies objective

            do
            {
                for (int i = 0; i < doctor_suppliesCabinet.Inventory.Items.Length; i++)
                {
                    if (doctor_suppliesCabinet.Inventory.Items[i] != null)
                    {
                        HighlightInventorySlot(doctor_suppliesCabinet.Inventory, i, highlightColor, .5f, .5f, 0f);
                    }
                }
                if (doctor.SelectedConstruction == doctor_suppliesCabinet.Item)
                {
                    for (int i = 0; i < doctor.Inventory.slots.Length; i++)
                    {
                        if (doctor.Inventory.Items[i] == null)
                        {
                            HighlightInventorySlot(doctor.Inventory, i, highlightColor, .5f, .5f, 0f);
                        }
                    }
                }
                yield return(null);
            } while (doctor.Inventory.FindItemByIdentifier("antidama1") == null); // Wait until looted
            yield return(new WaitForSeconds(1.0f, false));

            SetHighlight(doctor_suppliesCabinet.Item, false);
            RemoveCompletedObjective(segments[0]);

            yield return(new WaitForSeconds(1.0f, false));

            // 2nd tutorial segment, treat self -------------------------------------------------------------------------

            TriggerTutorialSegment(1, GameMain.Config.KeyBind(InputType.Health)); // Open health interface
            while (CharacterHealth.OpenHealthWindow == null)
            {
                doctor.CharacterHealth.HealthBarPulsateTimer = 1.0f;
                yield return(null);
            }
            yield return(null);

            RemoveCompletedObjective(segments[1]);
            yield return(new WaitForSeconds(1.0f, false));

            TriggerTutorialSegment(2); //Treat self
            while (doctor.CharacterHealth.GetAfflictionStrength("damage") > 0.01f)
            {
                if (CharacterHealth.OpenHealthWindow == null)
                {
                    doctor.CharacterHealth.HealthBarPulsateTimer = 1.0f;
                }
                else
                {
                    HighlightInventorySlot(doctor.Inventory, "antidama1", highlightColor, .5f, .5f, 0f);
                }

                yield return(null);
            }

            RemoveCompletedObjective(segments[2]);
            SetDoorAccess(doctor_firstDoor, doctor_firstDoorLight, true);

            while (CharacterHealth.OpenHealthWindow != null)
            {
                yield return(new WaitForSeconds(1.0f, false));
            }

            // treat patient --------------------------------------------------------------------------------------------

            //patient 1 requests first aid
            var newOrder = new Order(Order.GetPrefab("requestfirstaid"), patient1.CurrentHull, null, orderGiver: patient1);

            doctor.AddActiveObjectiveEntity(patient1, doctor_firstAidIcon, doctor_firstAidIconColor);
            //GameMain.GameSession.CrewManager.AddOrder(newOrder, newOrder.FadeOutTime);
            GameMain.GameSession.CrewManager.AddSinglePlayerChatMessage(patient1.Name, newOrder.GetChatMessage("", patient1.CurrentHull?.DisplayName, givingOrderToSelf: false), ChatMessageType.Order, null);

            while (doctor.CurrentHull != patient1.CurrentHull)
            {
                yield return(new WaitForSeconds(1.0f, false));
            }
            yield return(new WaitForSeconds(0.0f, false));

            GameMain.GameSession.CrewManager.AddSinglePlayerChatMessage(radioSpeakerName, TextManager.Get("Doctor.Radio.AssistantBurns"), ChatMessageType.Radio, null);
            GameMain.GameSession.CrewManager.AllowCharacterSwitch = false;
            GameMain.GameSession.CrewManager.AddCharacter(doctor);
            GameMain.GameSession.CrewManager.AddCharacter(patient1);
            GameMain.GameSession.CrewManager.ToggleCrewAreaOpen = true;
            patient1.CharacterHealth.UseHealthWindow            = false;

            yield return(new WaitForSeconds(3.0f, false));

            patient1.AIController.Enabled = true;
            doctor.RemoveActiveObjectiveEntity(patient1);
            TriggerTutorialSegment(3); // Get the patient to medbay

            while (patient1.CurrentOrder == null || patient1.CurrentOrder.Identifier != "follow")
            {
                GameMain.GameSession.CrewManager.HighlightOrderButton(patient1, "follow", highlightColor, new Vector2(5, 5));
                yield return(null);
            }

            SetDoorAccess(doctor_secondDoor, doctor_secondDoorLight, true);

            while (patient1.CurrentHull != medBay)
            {
                yield return(new WaitForSeconds(1.0f, false));
            }
            RemoveCompletedObjective(segments[3]);
            SetHighlight(doctor_medBayCabinet.Item, true);
            SetDoorAccess(doctor_thirdDoor, doctor_thirdDoorLight, true);
            patient1.CharacterHealth.UseHealthWindow = true;

            yield return(new WaitForSeconds(2.0f, false));

            TriggerTutorialSegment(4, GameMain.Config.KeyBind(InputType.Health)); // treat burns

            do
            {
                for (int i = 0; i < 3; i++)
                {
                    if (doctor_medBayCabinet.Inventory.Items[i] != null)
                    {
                        HighlightInventorySlot(doctor_medBayCabinet.Inventory, i, highlightColor, .5f, .5f, 0f);
                    }
                }
                if (doctor.SelectedConstruction == doctor_medBayCabinet.Item)
                {
                    for (int i = 0; i < doctor.Inventory.slots.Length; i++)
                    {
                        if (doctor.Inventory.Items[i] == null)
                        {
                            HighlightInventorySlot(doctor.Inventory, i, highlightColor, .5f, .5f, 0f);
                        }
                    }
                }
                yield return(null);
            } while (doctor.Inventory.FindItemByIdentifier("antibleeding1") == null); // Wait until looted
            SetHighlight(doctor_medBayCabinet.Item, false);
            SetHighlight(patient1, true);

            while (patient1.CharacterHealth.GetAfflictionStrength("burn") > 0.01f)
            {
                if (CharacterHealth.OpenHealthWindow == null)
                {
                    doctor.CharacterHealth.HealthBarPulsateTimer = 1.0f;
                }
                else
                {
                    HighlightInventorySlot(doctor.Inventory, "antibleeding1", highlightColor, .5f, .5f, 0f);
                }
                yield return(null);
            }
            RemoveCompletedObjective(segments[4]);
            SetHighlight(patient1, false);
            yield return(new WaitForSeconds(1.0f, false));

            GameMain.GameSession.CrewManager.AddSinglePlayerChatMessage(radioSpeakerName, TextManager.Get("Doctor.Radio.AssistantBurnsHealed"), ChatMessageType.Radio, null);

            // treat unconscious patient  ------------------------------------------------------

            //patient calls for help
            //patient2.CanSpeak = true;
            yield return(new WaitForSeconds(2.0f, false));

            newOrder = new Order(Order.GetPrefab("requestfirstaid"), patient2.CurrentHull, null, orderGiver: patient2);
            doctor.AddActiveObjectiveEntity(patient2, doctor_firstAidIcon, doctor_firstAidIconColor);
            //GameMain.GameSession.CrewManager.AddOrder(newOrder, newOrder.FadeOutTime);
            GameMain.GameSession.CrewManager.AddSinglePlayerChatMessage(patient2.Name, newOrder.GetChatMessage("", patient1.CurrentHull?.DisplayName, givingOrderToSelf: false), ChatMessageType.Order, null);
            patient2.AIController.Enabled = true;
            patient2.Oxygen = -50;
            CoroutineManager.StartCoroutine(KeepPatientAlive(patient2), "KeepPatient2Alive");

            /*while (doctor.CurrentHull != patient2.CurrentHull)
             * {
             *  yield return new WaitForSeconds(1.0f);
             * }*/
            do
            {
                yield return(null);
            } while (!tutorial_upperFinalDoor.IsOpen);
            yield return(new WaitForSeconds(2.0f, false));

            TriggerTutorialSegment(5, GameMain.Config.KeyBind(InputType.Health)); // perform CPR
            SetHighlight(patient2, true);
            while (patient2.IsUnconscious)
            {
                if (CharacterHealth.OpenHealthWindow != null && doctor.AnimController.Anim != AnimController.Animation.CPR)
                {
                    CharacterHealth.OpenHealthWindow.CPRButton.Pulsate(Vector2.One, Vector2.One * 1.5f, 1.0f);
                    CharacterHealth.OpenHealthWindow.CPRButton.Flash();
                }
                yield return(null);
            }
            RemoveCompletedObjective(segments[5]);
            SetHighlight(patient2, false);
            doctor.RemoveActiveObjectiveEntity(patient2);
            CoroutineManager.StopCoroutines("KeepPatient2Alive");

            SetDoorAccess(tutorial_submarineDoor, tutorial_submarineDoorLight, true);

            while (doctor.Submarine != Submarine.MainSub)
            {
                yield return(new WaitForSeconds(1.0f, false));
            }

            subPatients[2].Oxygen = -50;
            CoroutineManager.StartCoroutine(KeepPatientAlive(subPatients[2]), "KeepPatient3Alive");

            yield return(new WaitForSeconds(5.0f, false));

            GameMain.GameSession.CrewManager.AddSinglePlayerChatMessage(radioSpeakerName, TextManager.Get("Doctor.Radio.EnteredSub"), ChatMessageType.Radio, null);

            yield return(new WaitForSeconds(3.0f, false));

            TriggerTutorialSegment(6, GameMain.Config.KeyBind(InputType.Health)); // give treatment to anyone in need

            foreach (var patient in subPatients)
            {
                //patient.CanSpeak = true;
                patient.AIController.Enabled = true;
                SetHighlight(patient, true);
            }

            double subEnterTime = Timing.TotalTime;

            bool[] patientCalledHelp = new bool[] { false, false, false };

            while (subPatients.Any(p => p.Vitality < p.MaxVitality * 0.9f && !p.IsDead))
            {
                for (int i = 0; i < subPatients.Count; i++)
                {
                    //make patients call for help to make sure the player finds them
                    //(within 1 minute intervals of entering the sub)
                    if (!patientCalledHelp[i] && Timing.TotalTime > subEnterTime + 60 * (i + 1))
                    {
                        doctor.AddActiveObjectiveEntity(subPatients[i], doctor_firstAidIcon, doctor_firstAidIconColor);
                        newOrder = new Order(Order.GetPrefab("requestfirstaid"), subPatients[i].CurrentHull, null, orderGiver: subPatients[i]);
                        string message = newOrder.GetChatMessage("", subPatients[i].CurrentHull?.DisplayName, givingOrderToSelf: false);
                        GameMain.GameSession.CrewManager.AddSinglePlayerChatMessage(subPatients[i].Name, message, ChatMessageType.Order, null);
                        patientCalledHelp[i] = true;
                    }

                    if (subPatients[i].ExternalHighlight && subPatients[i].Vitality >= subPatients[i].MaxVitality * 0.9f)
                    {
                        doctor.RemoveActiveObjectiveEntity(subPatients[i]);
                        SetHighlight(subPatients[i], false);
                    }
                }
                yield return(new WaitForSeconds(1.0f, false));
            }
            RemoveCompletedObjective(segments[6]);
            foreach (var patient in subPatients)
            {
                SetHighlight(patient, false);
                doctor.RemoveActiveObjectiveEntity(patient);
            }

            // END TUTORIAL
            CoroutineManager.StartCoroutine(TutorialCompleted());
        }
        public override void ExplosionAffectCell(Explosion explosion, IntVec3 c, List <Thing> damagedThings, List <Thing> ignoredThings, bool canThrowMotes)
        {
            if (this.def.explosionCellMote != null && canThrowMotes)
            {
                Mote mote = c.GetFirstThing(explosion.Map, this.def.explosionCellMote) as Mote;
                if (mote != null)
                {
                    mote.spawnTick = Find.TickManager.TicksGame;
                }
                else
                {
                    float t     = Mathf.Clamp01((explosion.Position - c).LengthHorizontal / explosion.radius);
                    Color color = Color.Lerp(this.def.explosionColorCenter, this.def.explosionColorEdge, t);
                    PurpleIvyMoteMaker.ThrowExplosionCell(c, explosion.Map, this.def.explosionCellMote, color);
                }
            }
            DamageWorker_AddInjuryNoCamShaker.thingsToAffect.Clear();
            float        num  = float.MinValue;
            bool         flag = false;
            List <Thing> list = explosion.Map.thingGrid.ThingsListAt(c);

            for (int i = 0; i < list.Count; i++)
            {
                Thing thing = list[i];
                if (thing.def.category != ThingCategory.Mote && thing.def.category != ThingCategory.Ethereal)
                {
                    if (thing.Faction != PurpleIvyData.AlienFaction)
                    {
                        DamageWorker_AddInjuryNoCamShaker.thingsToAffect.Add(thing);
                        if (thing.def.Fillage == FillCategory.Full && thing.def.Altitude > num)
                        {
                            flag = true;
                            num  = thing.def.Altitude;
                        }
                    }
                }
            }
            for (int j = 0; j < DamageWorker_AddInjuryNoCamShaker.thingsToAffect.Count; j++)
            {
                if (DamageWorker_AddInjuryNoCamShaker.thingsToAffect[j].def.Altitude >= num)
                {
                    if (DamageWorker_AddInjuryNoCamShaker.thingsToAffect[j] is Pawn)
                    {
                        Pawn pawn = (Pawn)DamageWorker_AddInjuryNoCamShaker.thingsToAffect[j];
                        if (Rand.Chance(0.3f))
                        {
                            pawn.stances.stunner.StunFor(Rand.RangeInclusive(100, 200), explosion.instigator);
                        }
                    }
                    this.ExplosionDamageThing(explosion, DamageWorker_AddInjuryNoCamShaker.thingsToAffect[j], damagedThings, ignoredThings, c);
                }
            }
            if (!flag)
            {
                this.ExplosionDamageTerrain(explosion, c);
            }
            if (this.def.explosionSnowMeltAmount > 0.0001f)
            {
                float lengthHorizontal = (c - explosion.Position).LengthHorizontal;
                float num2             = 1f - lengthHorizontal / explosion.radius;
                if (num2 > 0f)
                {
                    explosion.Map.snowGrid.AddDepth(c, -num2 * this.def.explosionSnowMeltAmount);
                }
            }
            if (this.def == DamageDefOf.Bomb || this.def == DamageDefOf.Flame)
            {
                List <Thing> list2 = explosion.Map.listerThings.ThingsOfDef(ThingDefOf.RectTrigger);
                for (int k = 0; k < list2.Count; k++)
                {
                    RectTrigger rectTrigger = (RectTrigger)list2[k];
                    if (rectTrigger.activateOnExplosion && rectTrigger.Rect.Contains(c))
                    {
                        rectTrigger.ActivatedBy(null);
                    }
                }
            }
        }
Example #45
0
        protected override bool OnPerish(ActorBase collider)
        {
            Explosion.Create(api, Transform.Pos + Speed, Explosion.Small);

            return(base.OnPerish(collider));
        }
Example #46
0
    private GameObject AddMissileToPool()
    {
        /* Instantiate a pool of missiles. This prevents new objects constantly
         * being created and allocating memory. This is used to increase
         * game performance.
         */

        if (missileProjectile)
        {
            // Instantiate a new bullet
            GameObject missile = Instantiate(missileProjectile) as GameObject;
            missile.hideFlags = HideFlags.HideInHierarchy;
            missile.SetActive(false);

            // Add despawn conditions
            DisableAfterSeconds disTime = missile.GetComponent <DisableAfterSeconds>();
            if (disTime)
            {
                disTime.Delay = despawnAfter;
            }

            // Apply settings to missile explosion
            Explosion expl = missile.GetComponent <Explosion> ();
            if (expl)
            {
                expl.Damage = damage;
                expl.mode   = dmgTagsMode;
                if (expl.mode == COLLISION_MODE.IgnoreSelected)
                {
                    expl.collisionTags.Add(transform.tag);
                }
                foreach (string str in dmgTags)
                {
                    expl.collisionTags.Add(str);
                }

                expl.ExplosiveForce = ExplosiveForce;
                expl.Radius         = ExplosionRange;
            }

            // Apply hit effect settings
            EmitParticle eP = missile.GetComponent <EmitParticle>();
            if (eP)
            {
                eP.amount    = hitParticles;
                eP.particles = AddHitEffectToPool();
            }

            // Gravity & rigidbody settings
            Rigidbody rb = missile.GetComponent <Rigidbody> ();
            rb.drag        = projectileDrag;
            rb.angularDrag = projectileAngularDrag;
            rb.useGravity  = false;
            if (projectileGravity > 0)
            {
                missile.AddComponent <ApplyGravity> ();
                missile.GetComponent <ApplyGravity> ().gravity = projectileGravity;
            }

            // Set collision-ignore-tags
            On_Collision oC = missile.GetComponent <On_Collision>();
            if (oC)
            {
                oC.collisionTags.Add(transform.tag);
            }

            // Add bullet to the pool
            missilePool.Add(missile);

            return(missile);
        }
        return(default(GameObject));
    }
Example #47
0
        public override void Apply(MonoBehaviour sender, float amount)
        {
            // Following function uses the code from the Explosions file.

            // Get data from container before despawning
            ObjectBehaviour objectBehaviour = sender.GetComponent <ObjectBehaviour>();
            RegisterObject  registerObject  = sender.GetComponent <RegisterObject>();
            BodyPart        bodyPart        = sender.GetComponent <BodyPart>();

            bool insideBody = false;

            if (bodyPart != null)
            {
                insideBody = bodyPart.Root != null;
            }

            // Based on radius calculation in Explosions\Explosion.cs, where an amount of 30u will have an
            // explosion radius of 1. Strength is determined using a logarthmic formula to cause diminishing returns.
            var strength = (float)(-463 + 205 * Mathf.Log(amount) + 75 * Math.PI) * potency;


            if (insideBody)
            {
                if (strength >= bodyPart.Health)
                {
                    float temp = bodyPart.Health;                     //temporary store to make sure we don't use an updated health when decrementing strength
                    bodyPart.TakeDamage(null, temp, AttackType.Internal, DamageType.Brute);
                    strength -= temp;
                }
                else
                {
                    bodyPart.TakeDamage(null, strength, AttackType.Internal, DamageType.Brute);
                    strength = 0;
                }

                foreach (BodyPart part in bodyPart.HealthMaster.ImplantList)
                {
                    if (part == bodyPart)
                    {
                        continue;                                       // we prioritised the origin organ first
                    }
                    if (part.ContainedIn == null)
                    {
                        continue;
                    }

                    if (strength >= part.Health)
                    {
                        float temp = part.Health;                         //temporary store to make sure we don't use an updated health when decrementing strength
                        part.TakeDamage(null, temp, AttackType.Internal, DamageType.Brute);
                        strength -= temp;
                    }
                    else
                    {
                        part.TakeDamage(null, strength, AttackType.Internal, DamageType.Brute);
                        strength = 0;
                    }
                }
            }

            // Explosion here
            var picked = sender.GetComponent <Pickupable>();

            if (picked != null)
            {
                //If sender is in an inventory use the position of the inventory.
                if (picked.ItemSlot != null)
                {
                    objectBehaviour = picked.ItemSlot.ItemStorage.gameObject.GetComponent <ObjectBehaviour>();
                    registerObject  = picked.ItemSlot.ItemStorage.gameObject.GetComponent <RegisterObject>();
                }
            }


            //Check if this is happening inside of an Object first (machines, closets?)
            if (registerObject == null)
            {
                //If not, we need to check if the item is a bodypart inside of a player
                if (insideBody)
                {
                    Explosion.StartExplosion(bodyPart.HealthMaster.RegisterTile.WorldPosition, strength,
                                             bodyPart.HealthMaster.RegisterTile.Matrix);
                }
                else
                {
                    //Otherwise, if it's not inside of a player, we consider it just an item
                    Explosion.StartExplosion(objectBehaviour.registerTile.LocalPosition, strength,
                                             objectBehaviour.registerTile.Matrix);
                }
            }
            else
            {
                Explosion.StartExplosion(registerObject.LocalPosition, strength,
                                         registerObject.Matrix);
            }


            // If sender is a pickupable item not inside the body, destroy it.
            if (picked != null && !insideBody)
            {
                Despawn.ServerSingle(sender.gameObject);
            }
        }
Example #48
0
        public void Explode(Vector3 p, float radius, float intensity)
        {
            var exp = new Explosion(p, radius, intensity);

            explosions.Add(exp);
        }
Example #49
0
            public override void Update()
            {
                if (Collision(_x, _y))
                {
                    Explosion _Explosion = new Explosion();
                    _Explosion._x = _x;//-_S.X;
                    _Explosion._y = _y;//-_S.Y;
                    _Explosion.Load();
                    RemoveFromPage(this);
                }
                _x += _right ? _S.X : -_S.X;
                _y += _S.Y;
                _S.Y++;

                base.Update();
            }
Example #50
0
        public static Record CreateRecord(string Tag)
        {
            Record outRecord;

            switch (Tag)
            {
            case "TES4":
                outRecord = new Header();
                break;

            case "GMST":
                outRecord = new GameSetting();
                break;

            case "TXST":
                outRecord = new TextureSet();
                break;

            case "MICN":
                outRecord = new MenuIcon();
                break;

            case "GLOB":
                outRecord = new GlobalVariable();
                break;

            case "CLAS":
                outRecord = new Class();
                break;

            case "FACT":
                outRecord = new Faction();
                break;

            case "HDPT":
                outRecord = new HeadPart();
                break;

            case "HAIR":
                outRecord = new Hair();
                break;

            case "EYES":
                outRecord = new Eyes();
                break;

            case "RACE":
                outRecord = new Race();
                break;

            case "SOUN":
                outRecord = new Sound();
                break;

            case "ASPC":
                outRecord = new AcousticSpace();
                break;

            case "MGEF":
                outRecord = new MagicEffect();
                break;

            case "SCPT":
                outRecord = new Script();
                break;

            case "LTEX":
                outRecord = new LandscapeTexture();
                break;

            case "ENCH":
                outRecord = new ObjectEffect();
                break;

            case "SPEL":
                outRecord = new ActorEffect();
                break;

            case "ACTI":
                outRecord = new ESPSharp.Records.Activator();
                break;

            case "TACT":
                outRecord = new TalkingActivator();
                break;

            case "TERM":
                outRecord = new Terminal();
                break;

            case "ARMO":
                outRecord = new Armor();
                break;

            case "BOOK":
                outRecord = new Book();
                break;

            case "CONT":
                outRecord = new Container();
                break;

            case "DOOR":
                outRecord = new Door();
                break;

            case "INGR":
                outRecord = new Ingredient();
                break;

            case "LIGH":
                outRecord = new Light();
                break;

            case "MISC":
                outRecord = new MiscItem();
                break;

            case "STAT":
                outRecord = new Static();
                break;

            case "SCOL":
                outRecord = new StaticCollection();
                break;

            case "MSTT":
                outRecord = new MoveableStatic();
                break;

            case "PWAT":
                outRecord = new PlaceableWater();
                break;

            case "GRAS":
                outRecord = new Grass();
                break;

            case "TREE":
                outRecord = new Tree();
                break;

            case "FURN":
                outRecord = new Furniture();
                break;

            case "WEAP":
                outRecord = new Weapon();
                break;

            case "AMMO":
                outRecord = new Ammunition();
                break;

            case "NPC_":
                outRecord = new NonPlayerCharacter();
                break;

            case "CREA":
                outRecord = new Creature();
                break;

            case "LVLC":
                outRecord = new LeveledCreature();
                break;

            case "LVLN":
                outRecord = new LeveledNPC();
                break;

            case "KEYM":
                outRecord = new Key();
                break;

            case "ALCH":
                outRecord = new Ingestible();
                break;

            case "IDLM":
                outRecord = new IdleMarker();
                break;

            case "NOTE":
                outRecord = new Note();
                break;

            case "COBJ":
                outRecord = new ConstructibleObject();
                break;

            case "PROJ":
                outRecord = new Projectile();
                break;

            case "LVLI":
                outRecord = new LeveledItem();
                break;

            case "WTHR":
                outRecord = new Weather();
                break;

            case "CLMT":
                outRecord = new Climate();
                break;

            case "REGN":
                outRecord = new Region();
                break;

            case "NAVI":
                outRecord = new NavigationMeshInfoMap();
                break;

            case "DIAL":
                outRecord = new DialogTopic();
                break;

            case "QUST":
                outRecord = new Quest();
                break;

            case "IDLE":
                outRecord = new IdleAnimation();
                break;

            case "PACK":
                outRecord = new Package();
                break;

            case "CSTY":
                outRecord = new CombatStyle();
                break;

            case "LSCR":
                outRecord = new LoadScreen();
                break;

            case "ANIO":
                outRecord = new AnimatedObject();
                break;

            case "WATR":
                outRecord = new Water();
                break;

            case "EFSH":
                outRecord = new EffectShader();
                break;

            case "EXPL":
                outRecord = new Explosion();
                break;

            case "DEBR":
                outRecord = new Debris();
                break;

            case "IMGS":
                outRecord = new ImageSpace();
                break;

            case "IMAD":
                outRecord = new ImageSpaceAdapter();
                break;

            case "FLST":
                outRecord = new FormList();
                break;

            case "PERK":
                outRecord = new Perk();
                break;

            case "BPTD":
                outRecord = new BodyPartData();
                break;

            case "ADDN":
                outRecord = new AddonNode();
                break;

            case "AVIF":
                outRecord = new ActorValueInformation();
                break;

            case "RADS":
                outRecord = new RadiationStage();
                break;

            case "CAMS":
                outRecord = new CameraShot();
                break;

            case "CPTH":
                outRecord = new CameraPath();
                break;

            case "VTYP":
                outRecord = new VoiceType();
                break;

            case "IPCT":
                outRecord = new Impact();
                break;

            case "IPDS":
                outRecord = new ImpactDataSet();
                break;

            case "ARMA":
                outRecord = new ArmorAddon();
                break;

            case "ECZN":
                outRecord = new EncounterZone();
                break;

            case "MESG":
                outRecord = new Message();
                break;

            case "RGDL":
                outRecord = new Ragdoll();
                break;

            case "DOBJ":
                outRecord = new DefaultObjectManager();
                break;

            case "LGTM":
                outRecord = new LightingTemplate();
                break;

            case "MUSC":
                outRecord = new MusicType();
                break;

            case "IMOD":
                outRecord = new ItemMod();
                break;

            case "REPU":
                outRecord = new Reputation();
                break;

            case "RCPE":
                outRecord = new Recipe();
                break;

            case "RCCT":
                outRecord = new RecipeCategory();
                break;

            case "CHIP":
                outRecord = new CasinoChip();
                break;

            case "CSNO":
                outRecord = new Casino();
                break;

            case "LSCT":
                outRecord = new LoadScreenType();
                break;

            case "MSET":
                outRecord = new MediaSet();
                break;

            case "ALOC":
                outRecord = new MediaLocationController();
                break;

            case "CHAL":
                outRecord = new Challenge();
                break;

            case "AMEF":
                outRecord = new AmmoEffect();
                break;

            case "CCRD":
                outRecord = new CaravanCard();
                break;

            case "CMNY":
                outRecord = new CaravanMoney();
                break;

            case "CDCK":
                outRecord = new CaravanDeck();
                break;

            case "DEHY":
                outRecord = new DehydrationStage();
                break;

            case "HUNG":
                outRecord = new HungerStage();
                break;

            case "SLPD":
                outRecord = new SleepDeprivationStage();
                break;

            case "CELL":
                outRecord = new Cell();
                break;

            case "WRLD":
                outRecord = new Worldspace();
                break;

            case "LAND":
                outRecord = new GenericRecord();
                break;

            case "NAVM":
                outRecord = new NavigationMesh();
                break;

            case "INFO":
                outRecord = new DialogResponse();
                break;

            case "REFR":
                outRecord = new Reference();
                break;

            case "ACHR":
                outRecord = new PlacedNPC();
                break;

            case "ACRE":
                outRecord = new PlacedCreature();
                break;

            case "PGRE":
                outRecord = new PlacedGrenade();
                break;

            case "PMIS":
                outRecord = new PlacedMissile();
                break;

            default:
                Console.WriteLine("Encountered unknown record: " + Tag);
                outRecord = new GenericRecord();
                break;
            }

            outRecord.Tag = Tag;

            return(outRecord);
        }
Example #51
0
        public override void Hurt(Vector2 force, int damage, int killerIndex, Arrow arrow = null, Explosion explosion = null, ShockCircle shock = null)
        {
            if (shock && killerIndex == this.PlayerIndex)
            {
                // ShockCircle shouldn't kill friendly ghosts
                return;
            }

            if (this.HasShield)
            {
                this.HasShield = false;
                if (explosion && explosion.PlayerIndex != -1)
                {
                    base.Level.Session.MatchStats[explosion.PlayerIndex].ShieldsBroken += 1u;
                }
            }
            else
            {
                if (this.Alive && this.CanHurt)
                {
                    this.Health -= damage;
                    if (this.Health <= 0)
                    {
                        this.Die(killerIndex, arrow, explosion, shock);
                    }
                }
            }
            this.Speed = force;
        }
Example #52
0
 /// <summary>
 /// Makes the argument objectToMakeUnused marked as unused.  This method is generated to be used
 /// by generated code.  Use Destroy instead when writing custom code so that your code will behave
 /// the same whether your Entity is pooled or not.
 /// </summary>
 public static void MakeUnused(Explosion objectToMakeUnused)
 {
     MakeUnused(objectToMakeUnused, true);
 }
        void contactListener_BombExploded(object sender, EffectEventArgs e)
        {
            explosion = new Explosion(physicsWorld);
            Vector2 explosionLocation = e.spriteA.spriteBody.Position;
            float explosionRadius = 0f;
            float explosionForce = 0f;
            if (e.spriteA.TextureID == 48)
            {
                explosionRadius = ConvertUnits.ToSimUnits(GameSettings.ExplosiveForceRadiusMultiplier * 9f);
                explosionForce = GameSettings.ExplosivePower * 9f;  //large tnt
            }
            if (e.spriteA.TextureID == 49)
            {
                explosionRadius = ConvertUnits.ToSimUnits(GameSettings.ExplosiveForceRadiusMultiplier * 3f);
                explosionForce = GameSettings.ExplosivePower * 3f; //medium tnt
            }
            if (e.spriteA.TextureID == 50 || e.spriteA.SpriteType == Sprite.Type.Veggie)
            {
                explosionRadius = ConvertUnits.ToSimUnits(GameSettings.ExplosiveForceRadiusMultiplier);
                explosionForce = GameSettings.ExplosivePower; //small tnt
            }
            if (e.spriteA.TextureID == 20)
            {
                explosionRadius = ConvertUnits.ToSimUnits(GameSettings.ExplosiveForceRadiusMultiplier * e.spriteA.Scale);
                explosionForce = GameSettings.ExplosivePower * 0.5f * e.spriteA.Scale; //cherry
            }

            if (GameSettings.CheatFunsplosions)
            {
                explosionRadius *= 2f;
                explosionForce *= 2f;
            }

            explosion.Activate(explosionLocation, explosionRadius, explosionForce);

            contactListener.DoPoof(e.spriteA);
            Sprite smoke = new Sprite(13, 0, e.spriteA.Location + e.spriteA.SpriteOrigin - new Vector2(126,126) ,true);
            smoke.AnimationFPS = 12;
            smoke.Scale = (float)e.spriteA.SpriteRectWidth / 64f;
            smoke.TintColor *= 0.33f;
            EffectSprites.Add(smoke);
            smoke = new Sprite(14, 0, e.spriteA.Location + e.spriteA.SpriteOrigin - new Vector2(62, 62), true);
            smoke.AnimationFPS = LevelDataManager.rand.Next(6, 12);
            smoke.Scale = (float)e.spriteA.SpriteRectWidth / 64f;
            smoke.TotalRotation = (float)(LevelDataManager.rand.Next(0, 314)) / 100.0f;
            smoke.TintColor *= 0.33f;
            EffectSprites.Add(smoke);
            smoke = new Sprite(14, 0, e.spriteA.Location + e.spriteA.SpriteOrigin - new Vector2(62, 62), true);
            smoke.AnimationFPS = LevelDataManager.rand.Next(6, 12);
            smoke.Scale = (float)e.spriteA.SpriteRectWidth / 64f;
            smoke.TotalRotation = (float)(LevelDataManager.rand.Next(0, 314)) / 100.0f;
            smoke.TintColor *= 0.33f;
            EffectSprites.Add(smoke);
            smoke = new Sprite(15, 0, e.spriteA.Location + e.spriteA.SpriteOrigin - new Vector2(30, 30), true);
            smoke.AnimationFPS = LevelDataManager.rand.Next(6, 12);
            smoke.Scale = (float)e.spriteA.SpriteRectWidth / 64f;
            smoke.TotalRotation = (float)(LevelDataManager.rand.Next(0, 314)) / 100.0f;
            smoke.TintColor *= 0.33f;
            EffectSprites.Add(smoke);
            smoke = new Sprite(15, 0, e.spriteA.Location + e.spriteA.SpriteOrigin - new Vector2(30, 30), true);
            smoke.AnimationFPS = LevelDataManager.rand.Next(6, 12);
            smoke.Scale = (float)e.spriteA.SpriteRectWidth / 64f;
            smoke.TotalRotation = (float)(LevelDataManager.rand.Next(0, 314)) / 100.0f;
            smoke.TintColor *= 0.33f;
            EffectSprites.Add(smoke);
            Sprite bomb = new Sprite(0, 0, e.spriteA.Location + e.spriteA.SpriteOrigin - new Vector2(64, 64), true);
            bomb.HitPoints = 12;
            bomb.TotalRotation = 0.0001f;
            bomb.Scale = (float)e.spriteA.SpriteRectWidth / 64f;
            Vector2 position = ConvertUnits.ToSimUnits(bomb.SpriteCenterInWorld);
            float bombRadius = ConvertUnits.ToSimUnits(e.spriteA.SpriteRectWidth);
            if (e.spriteA.TextureID == 20)
            {
                bombRadius *= 0.5f *e.spriteA.Scale;
                bomb.Scale *= 0.5f *e.spriteA.Scale;
            }
            bomb.spriteBody = BodyFactory.CreateCircle(physicsWorld,bombRadius,1.0f,position, bomb);
            bomb.spriteBody.BodyType = BodyType.Dynamic;
            bomb.spriteBody.ResetDynamics();
            bomb.spriteBody.IsSensor = true;
            bomb.spriteBody.IgnoreGravity = true;
            bomb.SpriteType = Sprite.Type.Explosion;
            EffectSprites.Add(bomb);
            return;
        }
Example #54
0
 public void Explode()
 {
     Explosion.Destroy(gameObject, transform.position, explosionScale, vibrationDuration, vibrationIntensity);
 }
Example #55
0
 private void Start()
 {
     explosion = GetComponent <Explosion>();
     animator  = GetComponent <Animator>();
 }
Example #56
0
        private void Explode(BlockCoordinates location)
        {
            Explosion explosion = new Explosion(Level, location, 12, true);

            explosion.Explode();
        }
Example #57
0
            protected override bool OnPerish(ActorBase collider)
            {
                Explosion.Create(levelHandler, Transform.Pos, Explosion.Small);

                return(base.OnPerish(collider));
            }
Example #58
0
    // Opettajalle: Osuman käsittely on
    void LaserOsui(PhysicsObject ammus, PhysicsObject kohde)
    {
        ammus.Destroy();

        if (kohde.Tag == "isokivi" || kohde.Tag == "kivi")
        {
            kohde.Destroy();
            if (kohde.Tag == "isokivi")
            {
                for (int i = 0; i < 3; i++)
                {
                    PhysicsObject sirpale = new PhysicsObject(50, 50, Shape.Rectangle);
                    sirpale.Tag = "kivi";
                    sirpale.Position = kohde.Position + RandomGen.NextVector(30, 40);
                    Add(sirpale);
                }
            }

            Explosion boom = new Explosion(100);
            boom.Force = boom.Force / 1000;
            //boom.UseShockWave = false;
            boom.Position = kohde.Position;
            Add(boom);
        }
    }
Example #59
0
 private void NewExplosion()
 {
     Explosion explosion = new Explosion(this.Game, this.Screen, Vector2.Add(this.Position, new Vector2(this.random.Next(this.width*(int)scale), this.random.Next(this.height*(int)scale))));
     this.Screen.AddComponent(explosion);
 }
Example #60
0
        static void Main(string[] args)
        {
            var explosion = new Explosion();

            Console.WriteLine(explosion.MegaBoom());
        }