Beispiel #1
0
        public override void OnMapLoaded()
        {
            CeilingHeight = Rect.Height;

            Body lowerPickedBody = Submarine.PickBody(SimPosition, SimPosition - new Vector2(0.0f, ConvertUnits.ToSimUnits(rect.Height / 2.0f + 0.1f)), null, Physics.CollisionWall);

            if (lowerPickedBody != null)
            {
                Vector2 lowerPickedPos = Submarine.LastPickedPosition;

                if (Submarine.PickBody(SimPosition, SimPosition + new Vector2(0.0f, ConvertUnits.ToSimUnits(rect.Height / 2.0f + 0.1f)), null, Physics.CollisionWall) != null)
                {
                    Vector2 upperPickedPos = Submarine.LastPickedPosition;

                    CeilingHeight = ConvertUnits.ToDisplayUnits(upperPickedPos.Y - lowerPickedPos.Y);
                }
            }
        }
        public static void Update(float deltaTime)
        {
            if (GameMain.GameSession == null)
            {
                return;
            }
#if CLIENT
            if (GameMain.Client != null)
            {
                return;
            }
#endif

            updateTimer -= deltaTime;
            if (updateTimer > 0.0f)
            {
                return;
            }
            updateTimer = UpdateInterval;

            if (Level.Loaded != null)
            {
                if (GameMain.GameSession.EventManager.CurrentIntensity > 0.99f)
                {
                    UnlockAchievement("maxintensity", true, c => c != null && !c.IsDead && !c.IsUnconscious);
                }

                foreach (Character c in Character.CharacterList)
                {
                    if (c.IsDead)
                    {
                        continue;
                    }
                    //achievement for descending below crush depth and coming back
                    if (c.WorldPosition.Y < SubmarineBody.DamageDepth || (c.Submarine != null && c.Submarine.WorldPosition.Y < SubmarineBody.DamageDepth))
                    {
                        roundData.EnteredCrushDepth.Add(c);
                    }
                    else if (c.WorldPosition.Y > SubmarineBody.DamageDepth * 0.5f)
                    {
                        //all characters that have entered crush depth and are still alive get an achievement
                        if (roundData.EnteredCrushDepth.Contains(c))
                        {
                            UnlockAchievement(c, "survivecrushdepth");
                        }
                    }
                }

                foreach (Submarine sub in Submarine.Loaded)
                {
                    foreach (Reactor reactor in roundData.Reactors)
                    {
                        if (reactor.Item.Condition <= 0.0f && reactor.Item.Submarine == sub)
                        {
                            //characters that were inside the sub during a reactor meltdown
                            //get an achievement if they're still alive at the end of the round
                            foreach (Character c in Character.CharacterList)
                            {
                                if (!c.IsDead && c.Submarine == sub)
                                {
                                    roundData.ReactorMeltdown.Add(c);
                                }
                            }
                        }
                    }

                    //convert submarine velocity to km/h
                    Vector2 submarineVel = Physics.DisplayToRealWorldRatio * ConvertUnits.ToDisplayUnits(sub.Velocity) * 3.6f;
                    //achievement for going > 100 km/h
                    if (Math.Abs(submarineVel.X) > 100.0f)
                    {
                        //all conscious characters inside the sub get an achievement
                        UnlockAchievement("subhighvelocity", true, c => c != null && c.Submarine == sub && !c.IsDead && !c.IsUnconscious);
                    }

                    //achievement for descending ridiculously deep
                    float realWorldDepth = Math.Abs(sub.Position.Y - Level.Loaded.Size.Y) * Physics.DisplayToRealWorldRatio;
                    if (realWorldDepth > 5000.0f)
                    {
                        //all conscious characters inside the sub get an achievement
                        UnlockAchievement("subdeep", true, c => c != null && c.Submarine == sub && !c.IsDead && !c.IsUnconscious);
                    }
                }
            }
        }
Beispiel #3
0
        private void FixBody(Character user, float deltaTime, float degreeOfSuccess, Body targetBody)
        {
            if (targetBody?.UserData == null)
            {
                return;
            }

            pickedPosition = Submarine.LastPickedPosition;

            if (targetBody.UserData is Structure targetStructure)
            {
                if (!fixableEntities.Contains("structure") && !fixableEntities.Contains(targetStructure.Prefab.Identifier))
                {
                    return;
                }
                if (targetStructure.IsPlatform)
                {
                    return;
                }

                int sectionIndex = targetStructure.FindSectionIndex(ConvertUnits.ToDisplayUnits(pickedPosition));
                if (sectionIndex < 0)
                {
                    return;
                }

                FixStructureProjSpecific(user, deltaTime, targetStructure, sectionIndex);
                targetStructure.AddDamage(sectionIndex, -StructureFixAmount * degreeOfSuccess, user);

                //if the next section is small enough, apply the effect to it as well
                //(to make it easier to fix a small "left-over" section)
                for (int i = -1; i < 2; i += 2)
                {
                    int nextSectionLength = targetStructure.SectionLength(sectionIndex + i);
                    if ((sectionIndex == 1 && i == -1) ||
                        (sectionIndex == targetStructure.SectionCount - 2 && i == 1) ||
                        (nextSectionLength > 0 && nextSectionLength < Structure.WallSectionSize * 0.3f))
                    {
                        //targetStructure.HighLightSection(sectionIndex + i);
                        targetStructure.AddDamage(sectionIndex + i, -StructureFixAmount * degreeOfSuccess);
                    }
                }
            }
            else if (targetBody.UserData is Character targetCharacter)
            {
                targetCharacter.LastDamageSource = item;
                ApplyStatusEffectsOnTarget(user, deltaTime, ActionType.OnUse, new List <ISerializableEntity>()
                {
                    targetCharacter
                });
                FixCharacterProjSpecific(user, deltaTime, targetCharacter);
            }
            else if (targetBody.UserData is Limb targetLimb)
            {
                targetLimb.character.LastDamageSource = item;
                ApplyStatusEffectsOnTarget(user, deltaTime, ActionType.OnUse, new List <ISerializableEntity>()
                {
                    targetLimb.character, targetLimb
                });
                FixCharacterProjSpecific(user, deltaTime, targetLimb.character);
            }
            else if (targetBody.UserData is Item targetItem)
            {
                targetItem.IsHighlighted = true;

                float prevCondition = targetItem.Condition;

                ApplyStatusEffectsOnTarget(user, deltaTime, ActionType.OnUse, targetItem.AllPropertyObjects);

                var levelResource = targetItem.GetComponent <LevelResource>();
                if (levelResource != null && levelResource.IsActive &&
                    levelResource.requiredItems.Any() &&
                    levelResource.HasRequiredItems(user, addMessage: false))
                {
                    levelResource.DeattachTimer += deltaTime;
#if CLIENT
                    Character.Controlled?.UpdateHUDProgressBar(
                        this,
                        targetItem.WorldPosition,
                        levelResource.DeattachTimer / levelResource.DeattachDuration,
                        Color.Red, Color.Green);
#endif
                }
                FixItemProjSpecific(user, deltaTime, targetItem, prevCondition);
            }
        }
Beispiel #4
0
        public override void Update(float deltaTime, Camera cam)
        {
            this.cam = cam;

            if (IsToggle)
            {
                item.SendSignal(0, state ? "1" : "0", "signal_out", sender: null);
            }

            if (user == null ||
                user.Removed ||
                user.SelectedConstruction != item ||
                !user.CanInteractWith(item))
            {
                if (user != null)
                {
                    CancelUsing(user);
                    user = null;
                }
                if (!IsToggle)
                {
                    IsActive = false;
                }
                return;
            }

            user.AnimController.Anim = AnimController.Animation.UsingConstruction;

            if (userPos != Vector2.Zero)
            {
                Vector2 diff = (item.WorldPosition + userPos) - user.WorldPosition;

                if (user.AnimController.InWater)
                {
                    if (diff.Length() > 30.0f)
                    {
                        user.AnimController.TargetMovement = Vector2.Clamp(diff * 0.01f, -Vector2.One, Vector2.One);
                        user.AnimController.TargetDir      = diff.X > 0.0f ? Direction.Right : Direction.Left;
                    }
                    else
                    {
                        user.AnimController.TargetMovement = Vector2.Zero;
                    }
                }
                else
                {
                    diff.Y = 0.0f;
                    if (diff != Vector2.Zero && diff.LengthSquared() > 10.0f * 10.0f)
                    {
                        user.AnimController.TargetMovement = Vector2.Normalize(diff);
                        user.AnimController.TargetDir      = diff.X > 0.0f ? Direction.Right : Direction.Left;
                        return;
                    }
                    user.AnimController.TargetMovement = Vector2.Zero;
                }
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, user);

            if (limbPositions.Count == 0)
            {
                return;
            }

            user.AnimController.Anim = AnimController.Animation.UsingConstruction;

            user.AnimController.ResetPullJoints();

            if (dir != 0)
            {
                user.AnimController.TargetDir = dir;
            }

            foreach (LimbPos lb in limbPositions)
            {
                Limb limb = user.AnimController.GetLimb(lb.limbType);
                if (limb == null || !limb.body.Enabled)
                {
                    continue;
                }

                limb.Disabled = true;

                Vector2 worldPosition = new Vector2(item.WorldRect.X, item.WorldRect.Y) + lb.position * item.Scale;
                Vector2 diff          = worldPosition - limb.WorldPosition;

                limb.PullJointEnabled      = true;
                limb.PullJointWorldAnchorB = limb.SimPosition + ConvertUnits.ToSimUnits(diff);
            }
        }
Beispiel #5
0
        public override void UpdatePlacing(Camera cam)
        {
            Vector2 position = Submarine.MouseToWorldGrid(cam, Submarine.MainSub);

            if (PlayerInput.RightButtonClicked())
            {
                selected = null;
                return;
            }

            if (!ResizeHorizontal && !ResizeVertical)
            {
                if (PlayerInput.LeftButtonClicked())
                {
                    var item = new Item(new Rectangle((int)position.X, (int)position.Y, (int)sprite.size.X, (int)sprite.size.Y), this, Submarine.MainSub);
                    //constructor.Invoke(lobject);
                    item.Submarine = Submarine.MainSub;
                    item.SetTransform(ConvertUnits.ToSimUnits(Submarine.MainSub == null ? item.Position : item.Position - Submarine.MainSub.Position), 0.0f);
                    item.FindHull();

                    placePosition = Vector2.Zero;

                    // selected = null;
                    return;
                }
            }
            else
            {
                Vector2 placeSize = size;

                if (placePosition == Vector2.Zero)
                {
                    if (PlayerInput.LeftButtonHeld())
                    {
                        placePosition = position;
                    }
                }
                else
                {
                    if (ResizeHorizontal)
                    {
                        placeSize.X = Math.Max(position.X - placePosition.X, size.X);
                    }
                    if (ResizeVertical)
                    {
                        placeSize.Y = Math.Max(placePosition.Y - position.Y, size.Y);
                    }

                    if (PlayerInput.LeftButtonReleased())
                    {
                        var item = new Item(new Rectangle((int)placePosition.X, (int)placePosition.Y, (int)placeSize.X, (int)placeSize.Y), this, Submarine.MainSub);
                        placePosition = Vector2.Zero;

                        item.Submarine = Submarine.MainSub;
                        item.SetTransform(ConvertUnits.ToSimUnits(Submarine.MainSub == null ? item.Position : item.Position - Submarine.MainSub.Position), 0.0f);
                        item.FindHull();

                        //selected = null;
                        return;
                    }

                    position = placePosition;
                }
            }

            //if (PlayerInput.GetMouseState.RightButton == ButtonState.Pressed) selected = null;
        }
Beispiel #6
0
 public override void Draw(SpriteBatch spriteBatch)
 {
     spriteBatch.Draw(m_Texture, ConvertUnits.ToDisplayUnits(_circleBody.Position), null, Color.White, RotationAngle, m_Origin, 1.0f, SpriteEffects.None, 0f);
 }
Beispiel #7
0
        public void LoadContent(World world)
        {
            m_State       = MotionState.Locked;
            RotationAngle = (float)GameObject.RANDOM_GENERATOR.NextDouble();
            m_Direction.X = (float)Math.Cos(RotationAngle);
            m_Direction.Y = (float)Math.Sin(RotationAngle);

            Width  = m_Texture != null ? m_Texture.Width : 0;
            Height = m_Texture != null ? m_Texture.Height : 0;

            if (m_Texture != null)
            {
                m_Bounds.Width  = Width;
                m_Bounds.Height = Height;
                m_Bounds.X      = (int)Position.X - Width / 2;
                m_Bounds.Y      = (int)Position.Y - Height / 2;
                m_Origin.X      = Width / 2;
                m_Origin.Y      = Height / 2;
            }
            _circleBody               = BodyFactory.CreateCircle(world, ConvertUnits.ToSimUnits(35 / 2f), 1f, ConvertUnits.ToSimUnits(Position));
            _circleBody.BodyType      = BodyType.Dynamic;
            _circleBody.Mass          = 5f;
            _circleBody.LinearDamping = 3f;
            _circleBody.Restitution   = .7f;
            LoadExplodedParts();
        }
Beispiel #8
0
        public static Sprite CreateCat(
            Vector2 location,
            Texture2D texture,
            Vector2 velocity,
            float rotation)
        {
            Sprite sprite = new Sprite("sprite",
                                       location,
                                       texture,
                                       SpriteCreators.spriteSourceRectangles["cat00"],
                                       velocity,
                                       BodyType.Dynamic,
                                       false);

            SpriteCreators.AddFrames(sprite, "cat", 10);

            sprite.Frame = rand.Next(0, 10);

            /*
             * for (int i = 1; i <= 10; i++)
             * {
             *  string key = "cat" + i.ToString().PadLeft(2, '0');
             *  sprite.AddFrame(SpriteCreators.spriteSourceRectangles[key]);
             * }
             */

            sprite.Rotation = rotation;

            //rects
            //9, 19, 95, 111

            sprite.PhysicsBodyFixture              = FixtureFactory.AttachRectangle(ConvertUnits.ToSimUnits(95), ConvertUnits.ToSimUnits(100), 1, ConvertUnits.ToSimUnits(new Vector2(9, 10)), sprite.PhysicsBody);
            sprite.PhysicsBodyFixture.OnCollision += new OnCollisionEventHandler(sprite.HandleCollision);

            return(sprite);
        }
Beispiel #9
0
        public static Sprite CreateDog(
            Vector2 location,
            Texture2D texture,
            Vector2 velocity,
            float rotation)
        {
            Sprite sprite = new Sprite("sprite",
                                       location,
                                       texture,
                                       SpriteCreators.spriteSourceRectangles["rover00"],
                                       velocity,
                                       BodyType.Dynamic,
                                       false);


            //FarseerPhysics.Common.Vertices verts = new FarseerPhysics.Common.Vertices();

            SpriteCreators.AddFrames(sprite, "rover", 12);

            sprite.Rotation = rotation;

            //option 1 with two fixtures
            //rects
            //45, 16, 153, 114
            //0, 60, 45, 70
            //sprite.PhysicsBodyFixture = FixtureFactory.AttachRectangle(ConvertUnits.ToSimUnits(153), ConvertUnits.ToSimUnits(114), 1, ConvertUnits.ToSimUnits(new Vector2(45, 16)), sprite.PhysicsBody);
            //sprite.PhysicsBodyFixture = FixtureFactory.AttachRectangle(ConvertUnits.ToSimUnits(45), ConvertUnits.ToSimUnits(70), 1, ConvertUnits.ToSimUnits(new Vector2(0, 60)), sprite.PhysicsBody);
            //option 2 with one fixture
            //rects
            //16, 12, 175, 125
            sprite.PhysicsBodyFixture          = FixtureFactory.AttachRectangle(ConvertUnits.ToSimUnits(175), ConvertUnits.ToSimUnits(100), 10, ConvertUnits.ToSimUnits(new Vector2(16, 12)), sprite.PhysicsBody);
            sprite.PhysicsBodyFixture.Friction = 15f;

            sprite.PhysicsBodyFixture.OnCollision += new OnCollisionEventHandler(sprite.HandleCollision);

            sprite.PhysicsBody.Mass = 30f;

            return(sprite);
        }
Beispiel #10
0
        public static void Update(float deltaTime, Character character, Camera cam)
        {
            if (GUI.DisableHUD)
            {
                return;
            }

            if (!character.IsIncapacitated && character.Stun <= 0.0f)
            {
                if (character.Info != null && !character.ShouldLockHud() && character.SelectedCharacter == null)
                {
                    bool mouseOnPortrait = HUDLayoutSettings.BottomRightInfoArea.Contains(PlayerInput.MousePosition) && GUI.MouseOn == null;
                    if (mouseOnPortrait && PlayerInput.PrimaryMouseButtonClicked())
                    {
                        CharacterHealth.OpenHealthWindow = character.CharacterHealth;
                    }
                }

                if (character.Inventory != null)
                {
                    if (!LockInventory(character))
                    {
                        character.Inventory.Update(deltaTime, cam);
                    }
                    for (int i = 0; i < character.Inventory.Items.Length - 1; i++)
                    {
                        var item = character.Inventory.Items[i];
                        if (item == null || character.Inventory.SlotTypes[i] == InvSlotType.Any)
                        {
                            continue;
                        }

                        foreach (ItemComponent ic in item.Components)
                        {
                            if (ic.DrawHudWhenEquipped)
                            {
                                ic.UpdateHUD(character, deltaTime, cam);
                            }
                        }
                    }
                }

                if (character.IsHumanoid && character.SelectedCharacter != null && character.SelectedCharacter.Inventory != null)
                {
                    if (character.SelectedCharacter.CanInventoryBeAccessed)
                    {
                        character.SelectedCharacter.Inventory.Update(deltaTime, cam);
                    }
                    character.SelectedCharacter.CharacterHealth.UpdateHUD(deltaTime);
                }

                Inventory.UpdateDragging();
            }

            if (focusedItem != null)
            {
                if (character.FocusedItem != null)
                {
                    focusedItemOverlayTimer = Math.Min(focusedItemOverlayTimer + deltaTime, ItemOverlayDelay + 1.0f);
                }
                else
                {
                    focusedItemOverlayTimer = Math.Max(focusedItemOverlayTimer - deltaTime, 0.0f);
                    if (focusedItemOverlayTimer <= 0.0f)
                    {
                        focusedItem            = null;
                        shouldRecreateHudTexts = true;
                    }
                }
            }

            if (brokenItemsCheckTimer > 0.0f)
            {
                brokenItemsCheckTimer -= deltaTime;
            }
            else
            {
                brokenItems.Clear();
                brokenItemsCheckTimer = 1.0f;
                foreach (Item item in Item.ItemList)
                {
                    if (item.Submarine == null || item.Submarine.TeamID != character.TeamID || item.Submarine.Info.IsWreck)
                    {
                        continue;
                    }
                    if (!item.Repairables.Any(r => item.ConditionPercentage <= r.AIRepairThreshold))
                    {
                        continue;
                    }
                    if (Submarine.VisibleEntities != null && !Submarine.VisibleEntities.Contains(item))
                    {
                        continue;
                    }

                    Vector2 diff = item.WorldPosition - character.WorldPosition;
                    if (Submarine.CheckVisibility(character.SimPosition, character.SimPosition + ConvertUnits.ToSimUnits(diff)) == null)
                    {
                        brokenItems.Add(item);
                    }
                }
            }
        }
Beispiel #11
0
        private void CreateHull()
        {
            var hullRects = new Rectangle[] { item.WorldRect, dockingTarget.item.WorldRect };
            var subs      = new Submarine[] { item.Submarine, dockingTarget.item.Submarine };

            hulls  = new Hull[2];
            bodies = new Body[4];

            if (dockingTarget.door != null)
            {
                CreateDoorBody();
            }

            if (door != null)
            {
                dockingTarget.CreateDoorBody();
            }

            if (IsHorizontal)
            {
                if (hullRects[0].Center.X > hullRects[1].Center.X)
                {
                    hullRects = new Rectangle[] { dockingTarget.item.WorldRect, item.WorldRect };
                    subs      = new Submarine[] { dockingTarget.item.Submarine, item.Submarine };
                }

                hullRects[0] = new Rectangle(hullRects[0].Center.X, hullRects[0].Y, ((int)DockedDistance / 2), hullRects[0].Height);
                hullRects[1] = new Rectangle(hullRects[1].Center.X - ((int)DockedDistance / 2), hullRects[1].Y, ((int)DockedDistance / 2), hullRects[1].Height);

                for (int i = 0; i < 2; i++)
                {
                    hullRects[i].Location -= MathUtils.ToPoint((subs[i].WorldPosition - subs[i].HiddenSubPosition));
                    hulls[i] = new Hull(MapEntityPrefab.list.Find(m => m.Name == "Hull"), hullRects[i], subs[i]);
                    hulls[i].AddToGrid(subs[i]);

                    for (int j = 0; j < 2; j++)
                    {
                        bodies[i + j * 2] = BodyFactory.CreateEdge(GameMain.World,
                                                                   ConvertUnits.ToSimUnits(new Vector2(hullRects[i].X, hullRects[i].Y - hullRects[i].Height * j)),
                                                                   ConvertUnits.ToSimUnits(new Vector2(hullRects[i].Right, hullRects[i].Y - hullRects[i].Height * j)));
                    }
                }

                gap = new Gap(new Rectangle(hullRects[0].Right - 2, hullRects[0].Y, 4, hullRects[0].Height), true, subs[0]);
                if (gapId != null)
                {
                    gap.ID = (ushort)gapId;
                }

                LinkHullsToGap();
            }
            else
            {
                if (hullRects[0].Center.Y > hullRects[1].Center.Y)
                {
                    hullRects = new Rectangle[] { dockingTarget.item.WorldRect, item.WorldRect };
                    subs      = new Submarine[] { dockingTarget.item.Submarine, item.Submarine };
                }

                hullRects[0] = new Rectangle(hullRects[0].X, hullRects[0].Y + (int)(-hullRects[0].Height + DockedDistance) / 2, hullRects[0].Width, ((int)DockedDistance / 2));
                hullRects[1] = new Rectangle(hullRects[1].X, hullRects[1].Y - hullRects[1].Height / 2, hullRects[1].Width, ((int)DockedDistance / 2));

                for (int i = 0; i < 2; i++)
                {
                    hullRects[i].Location -= MathUtils.ToPoint((subs[i].WorldPosition - subs[i].HiddenSubPosition));
                    hulls[i] = new Hull(MapEntityPrefab.list.Find(m => m.Name == "Hull"), hullRects[i], subs[i]);
                    hulls[i].AddToGrid(subs[i]);

                    if (hullIds[i] != null)
                    {
                        hulls[i].ID = (ushort)hullIds[i];
                    }
                }

                gap = new Gap(new Rectangle(hullRects[0].X, hullRects[0].Y + 2, hullRects[0].Width, 4), false, subs[0]);
                if (gapId != null)
                {
                    gap.ID = (ushort)gapId;
                }

                LinkHullsToGap();
            }

            item.linkedTo.Add(hulls[0]);
            item.linkedTo.Add(hulls[1]);

            hullIds[0] = hulls[0].ID;
            hullIds[1] = hulls[1].ID;

            gap.DisableHullRechecks = true;
            gapId = gap.ID;

            item.linkedTo.Add(gap);

            foreach (Body body in bodies)
            {
                if (body == null)
                {
                    continue;
                }
                body.BodyType = BodyType.Static;
                body.Friction = 0.5f;

                body.CollisionCategories = Physics.CollisionWall;
            }
        }
Beispiel #12
0
        /// <summary> Create Red Arrow Enemy with arrow Texture </summary>
        public Enemy(Vector2 setPosition, int setHitPoints)
            : base("AI/arrow", new Color(255, 0, 0))
        {
            // Create animation
            _animationCogwheel = new Animation("Enemies/DerGeraet", 7, 5, 0, 32, 1000, true);
            //_animationCogwheel = new Animation("Enemies/cogwheel", 4, 12, 0, 48, 2000, true);
            _animationCogwheel.IsAlive = true;
            _animationCogwheel.Scale   = 0.3f;


            // Assign hitpoints and create rectangle from Texture
            HitPoints     = setHitPoints;
            body          = BodyFactory.CreateRectangle(PhysicsGameScreen.World, ConvertUnits.ToSimUnits(Texture.Width), ConvertUnits.ToSimUnits(Texture.Height), density);
            body.UserData = "enemy";


            // Create Behavior
            enemyNav              = new BehaviorNav(0.2f);
            enemyNav.GoalReached += new EventHandler(enemyNav_GoalReached);
            enemyNav.NodeReached += new EventHandler(enemyNav_NodeReached);
            BehaviorList.Add(enemyNav);

            // set Position and start navigation
            Position = setPosition;
            NavigateToActor(Node.GetClosestNode(setPosition));
        } // Enemy(Vector2 setPosition, int setHitPoints)
Beispiel #13
0
        protected override void SetupPhysics(World world)
        {
            this.Body          = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(30), ConvertUnits.ToSimUnits(_texture.Height), _mass);
            this.Body.Position = ConvertUnits.ToSimUnits(this._position);
            this.Body.Rotation = _rotation;
            //  Give it it's own category but make it only collide with 10 (Player) and nothing else.
            this.Body.CollisionCategories = Category.Cat3;
            this.Body.CollidesWith        = Category.Cat10;

            this.Body.OnCollision  += Body_OnCollision;
            this.Body.OnSeparation += Body_OnSeparation;
            this.Body.Enabled       = _enabled;
            this.Body.IsSensor      = true;
        }
Beispiel #14
0
        public Player(Vector2 pos, VelcroPhysics.Dynamics.World world)
        {
            physicsBody = BodyFactory.CreateCircle(world, ConvertUnits.ToSimUnits(100f), 1f, ConvertUnits.ToSimUnits(pos), BodyType.Dynamic);
            physicsBody.LinearDamping = 10f;

            label                  = "player";
            textureDimensions      = new Vector2(100, 100);
            origin                 = textureDimensions / 2;
            damageBox              = FixtureFactory.AttachRectangle(ConvertUnits.ToSimUnits(30f), ConvertUnits.ToSimUnits(90f), 2f, new Vector2(0, ConvertUnits.ToSimUnits(100f)), physicsBody, null);
            damageBox.OnCollision += new VelcroPhysics.Collision.Handlers.OnCollisionHandler(this.Dealdamage);
        }
Beispiel #15
0
        public Wall(World world, Vector2 position, int width, int height)
        {
            this.width  = width;
            this.height = height;

            body             = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(width), ConvertUnits.ToSimUnits(height), 5f);
            body.Restitution = 0f;
            body.Friction    = 0f;
            body.BodyType    = BodyType.Static;
            body.Position    = new Vector2(ConvertUnits.ToSimUnits(position.X), ConvertUnits.ToSimUnits(position.Y));
            body.UserData    = this;
        }
        private void AddObject(LevelObject newObject, Level level)
        {
            if (newObject.Triggers != null)
            {
                foreach (LevelTrigger trigger in newObject.Triggers)
                {
                    trigger.OnTriggered += (levelTrigger, obj) =>
                    {
                        OnObjectTriggered(newObject, levelTrigger, obj);
                    };
                }
            }

            var spriteCorners = new List <Vector2>
            {
                Vector2.Zero, Vector2.Zero, Vector2.Zero, Vector2.Zero
            };

            Sprite sprite = newObject.Sprite ?? newObject.Prefab.DeformableSprite?.Sprite;

            //calculate the positions of the corners of the rotated sprite
            if (sprite != null)
            {
                Vector2 halfSize = sprite.size * newObject.Scale / 2;
                spriteCorners[0] = -halfSize;
                spriteCorners[1] = new Vector2(-halfSize.X, halfSize.Y);
                spriteCorners[2] = halfSize;
                spriteCorners[3] = new Vector2(halfSize.X, -halfSize.Y);

                Vector2 pivotOffset = sprite.Origin * newObject.Scale - halfSize;
                pivotOffset.X = -pivotOffset.X;
                pivotOffset   = new Vector2(
                    (float)(pivotOffset.X * Math.Cos(-newObject.Rotation) - pivotOffset.Y * Math.Sin(-newObject.Rotation)),
                    (float)(pivotOffset.X * Math.Sin(-newObject.Rotation) + pivotOffset.Y * Math.Cos(-newObject.Rotation)));

                for (int j = 0; j < 4; j++)
                {
                    spriteCorners[j] = new Vector2(
                        (float)(spriteCorners[j].X * Math.Cos(-newObject.Rotation) - spriteCorners[j].Y * Math.Sin(-newObject.Rotation)),
                        (float)(spriteCorners[j].X * Math.Sin(-newObject.Rotation) + spriteCorners[j].Y * Math.Cos(-newObject.Rotation)));

                    spriteCorners[j] += new Vector2(newObject.Position.X, newObject.Position.Y) + pivotOffset;
                }
            }

            float minX = spriteCorners.Min(c => c.X) - newObject.Position.Z;
            float maxX = spriteCorners.Max(c => c.X) + newObject.Position.Z;

            float minY = spriteCorners.Min(c => c.Y) - newObject.Position.Z - level.BottomPos;
            float maxY = spriteCorners.Max(c => c.Y) + newObject.Position.Z - level.BottomPos;

            if (newObject.Triggers != null)
            {
                foreach (LevelTrigger trigger in newObject.Triggers)
                {
                    if (trigger.PhysicsBody == null)
                    {
                        continue;
                    }
                    for (int i = 0; i < trigger.PhysicsBody.FarseerBody.FixtureList.Count; i++)
                    {
                        trigger.PhysicsBody.FarseerBody.GetTransform(out FarseerPhysics.Common.Transform transform);
                        trigger.PhysicsBody.FarseerBody.FixtureList[i].Shape.ComputeAABB(out FarseerPhysics.Collision.AABB aabb, ref transform, i);

                        minX = Math.Min(minX, ConvertUnits.ToDisplayUnits(aabb.LowerBound.X));
                        maxX = Math.Max(maxX, ConvertUnits.ToDisplayUnits(aabb.UpperBound.X));
                        minY = Math.Min(minY, ConvertUnits.ToDisplayUnits(aabb.LowerBound.Y) - level.BottomPos);
                        maxY = Math.Max(maxY, ConvertUnits.ToDisplayUnits(aabb.UpperBound.Y) - level.BottomPos);
                    }
                }
            }

#if CLIENT
            if (newObject.ParticleEmitters != null)
            {
                foreach (ParticleEmitter emitter in newObject.ParticleEmitters)
                {
                    Rectangle particleBounds = emitter.CalculateParticleBounds(new Vector2(newObject.Position.X, newObject.Position.Y));
                    minX = Math.Min(minX, particleBounds.X);
                    maxX = Math.Max(maxX, particleBounds.Right);
                    minY = Math.Min(minY, particleBounds.Y - level.BottomPos);
                    maxY = Math.Max(maxY, particleBounds.Bottom - level.BottomPos);
                }
            }
#endif
            objects.Add(newObject);
            if (newObject.NeedsUpdate)
            {
                updateableObjects.Add(newObject);
            }
            newObject.Position.Z += (minX + minY) % 100.0f * 0.00001f;

            int xStart = (int)Math.Floor(minX / GridSize);
            int xEnd   = (int)Math.Floor(maxX / GridSize);
            if (xEnd < 0 || xStart >= objectGrid.GetLength(0))
            {
                return;
            }

            int yStart = (int)Math.Floor(minY / GridSize);
            int yEnd   = (int)Math.Floor(maxY / GridSize);
            if (yEnd < 0 || yStart >= objectGrid.GetLength(1))
            {
                return;
            }

            xStart = Math.Max(xStart, 0);
            xEnd   = Math.Min(xEnd, objectGrid.GetLength(0) - 1);
            yStart = Math.Max(yStart, 0);
            yEnd   = Math.Min(yEnd, objectGrid.GetLength(1) - 1);

            for (int x = xStart; x <= xEnd; x++)
            {
                for (int y = yStart; y <= yEnd; y++)
                {
                    if (objectGrid[x, y] == null)
                    {
                        objectGrid[x, y] = new List <LevelObject>();
                    }
                    objectGrid[x, y].Add(newObject);
                }
            }
        }
Beispiel #17
0
 public void TransformOutToInside(Submarine submarine)
 {
     //transform outside coordinates to in-sub coordinates
     Position -= ConvertUnits.ToSimUnits(submarine.Position);
 }
Beispiel #18
0
        public override void Draw(SpriteBatch spriteBatch)
        {
            // spriteBatch.Draw(texture, Position, coinRect, Color.White);
            if (faceDir == FaceDir.left)
            {
                spriteBatch.Draw(texture, ConvertUnits.ToDisplayUnits(rigidbody.Position), rect, Color.White, rigidbody.Rotation, new Vector2(rect.Width / 2.0f, rect.Height / 2.0f), 1f, SpriteEffects.None, 1f);
            }
            else if (faceDir == FaceDir.right)
            {
                spriteBatch.Draw(texture, ConvertUnits.ToDisplayUnits(rigidbody.Position), rect, Color.White, rigidbody.Rotation, new Vector2(rect.Width / 2.0f, rect.Height / 2.0f), 1f, SpriteEffects.FlipHorizontally, 1f);
            }
            //base.Draw(spriteBatch);


#if DEBUG
            SpriteBatchEx.GraphicsDevice = Game1.graphics.GraphicsDevice;

            spriteBatch.DrawLine(ConvertUnits.ToDisplayUnits(rigidbody.Position), ConvertUnits.ToDisplayUnits(rigidbody.Position + new Vector2(distanceUp / 2, -distanceUp)), Color.Yellow);
            spriteBatch.DrawLine(ConvertUnits.ToDisplayUnits(rigidbody.Position), ConvertUnits.ToDisplayUnits(rigidbody.Position + new Vector2(0, -distanceUp)), Color.Yellow);
            spriteBatch.DrawLine(ConvertUnits.ToDisplayUnits(rigidbody.Position), ConvertUnits.ToDisplayUnits(rigidbody.Position + new Vector2(-distanceUp / 2, -distanceUp)), Color.Yellow);

            if (faceDir == FaceDir.right)
            {
                spriteBatch.DrawLine(ConvertUnits.ToDisplayUnits(rigidbody.Position), ConvertUnits.ToDisplayUnits(rigidbody.Position + new Vector2(distance, 0)), Color.BlueViolet);
            }
            else if (faceDir == FaceDir.left)
            {
                spriteBatch.DrawLine(ConvertUnits.ToDisplayUnits(rigidbody.Position), ConvertUnits.ToDisplayUnits(rigidbody.Position + new Vector2(-distance, 0)), Color.BlueViolet);
            }
#endif
        }
Beispiel #19
0
 public override void Load(World world)
 {
     if (m_Texture == null)
     {
         m_Texture = TextureBank.GetTexture("Face");
     }
     _circleBody               = BodyFactory.CreateCircle(world, ConvertUnits.ToSimUnits(35 / 2f), 1f, ConvertUnits.ToSimUnits(Position));
     _circleBody.BodyType      = BodyType.Dynamic;
     _circleBody.Mass          = 0.2f;
     _circleBody.LinearDamping = 2f;
     _circleBody.Position      = bodyPosition;
 }
Beispiel #20
0
        public Enemy(Vector2 p)
        {
            this.tile     = texture = Game1.content.Load <Texture2D>("Sprites/kenney_32x32");
            this.Position = p;

            sn_kill_enemy = Game1.content.Load <SoundEffect>("Sounds/Randomize3");

            killed  = false;
            bite    = false;
            faceDir = FaceDir.right;

            //Set rigidbody behaivior here
            // rigidbody = BodyFactory.CreateRectangle(Game1.world, ConvertUnits.ToSimUnits(rect.Width), ConvertUnits.ToSimUnits(rect.Height), 1.0f, ConvertUnits.ToSimUnits(this.Position));
            rigidbody                     = BodyFactory.CreateCircle(Game1.world, ConvertUnits.ToSimUnits(rect.Width / 2), 1.0f, ConvertUnits.ToSimUnits(this.Position));
            rigidbody.BodyType            = BodyType.Dynamic;
            rigidbody.FixedRotation       = true;
            rigidbody.Restitution         = 0f;            // No bounciness
            rigidbody.Friction            = 0f;
            rigidbody.CollisionCategories = Category.Cat3; // cat3 is coins

            rigidbody.OnCollision += Rigidbody_OnCollision;
        }
Beispiel #21
0
        public override void Update(float deltaTime, Camera cam)
        {
            base.Update(deltaTime, cam);

            if (equipper == null || equipper.Removed)
            {
                IsActive = false;
                return;
            }

            if (updateTimer > 0.0f)
            {
                updateTimer -= deltaTime;
                return;
            }

            visibleCharacters.Clear();
            foreach (Character c in Character.CharacterList)
            {
                if (c == equipper || !c.Enabled || c.Removed)
                {
                    continue;
                }

                float dist = Vector2.DistanceSquared(equipper.WorldPosition, c.WorldPosition);
                if (dist < Range * Range)
                {
                    Vector2 diff = c.WorldPosition - equipper.WorldPosition;
                    if (Submarine.CheckVisibility(equipper.SimPosition, equipper.SimPosition + ConvertUnits.ToSimUnits(diff)) == null)
                    {
                        visibleCharacters.Add(c);
                    }
                }
            }

            updateTimer = UpdateInterval;
        }
Beispiel #22
0
        public override void Update(float deltaTime, Camera cam)
        {
            this.cam = cam;

            if (IsToggle)
            {
                item.SendSignal(State ? "1" : "0", "signal_out");
                item.SendSignal(State ? "1" : "0", "trigger_out");
            }

            if (user == null ||
                user.Removed ||
                user.SelectedConstruction != item ||
                item.ParentInventory != null ||
                !user.CanInteractWith(item) ||
                (UsableIn == UseEnvironment.Water && !user.AnimController.InWater) ||
                (UsableIn == UseEnvironment.Air && user.AnimController.InWater))
            {
                if (user != null)
                {
                    CancelUsing(user);
                    user = null;
                }
                if (!IsToggle)
                {
                    IsActive = false;
                }
                return;
            }

            user.AnimController.Anim = AnimController.Animation.UsingConstruction;

            if (userPos != Vector2.Zero)
            {
                Vector2 diff = (item.WorldPosition + userPos) - user.WorldPosition;

                if (user.AnimController.InWater)
                {
                    if (diff.LengthSquared() > 30.0f * 30.0f)
                    {
                        user.AnimController.TargetMovement = Vector2.Clamp(diff * 0.01f, -Vector2.One, Vector2.One);
                        user.AnimController.TargetDir      = diff.X > 0.0f ? Direction.Right : Direction.Left;
                    }
                    else
                    {
                        user.AnimController.TargetMovement = Vector2.Zero;
                    }
                }
                else
                {
                    diff.Y = 0.0f;
                    if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient && user != Character.Controlled)
                    {
                        if (Math.Abs(diff.X) > 20.0f)
                        {
                            //wait for the character to walk to the correct position
                            return;
                        }
                        else if (Math.Abs(diff.X) > 0.1f)
                        {
                            //aim to keep the collider at the correct position once close enough
                            user.AnimController.Collider.LinearVelocity = new Vector2(
                                diff.X * 0.1f,
                                user.AnimController.Collider.LinearVelocity.Y);
                        }
                    }
                    else
                    {
                        if (Math.Abs(diff.X) > 10.0f)
                        {
                            user.AnimController.TargetMovement = Vector2.Normalize(diff);
                            user.AnimController.TargetDir      = diff.X > 0.0f ? Direction.Right : Direction.Left;
                            return;
                        }
                    }
                    user.AnimController.TargetMovement = Vector2.Zero;
                }
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, user);

            if (limbPositions.Count == 0)
            {
                return;
            }

            user.AnimController.Anim = AnimController.Animation.UsingConstruction;

            user.AnimController.ResetPullJoints();

            if (dir != 0)
            {
                user.AnimController.TargetDir = dir;
            }

            foreach (LimbPos lb in limbPositions)
            {
                Limb limb = user.AnimController.GetLimb(lb.LimbType);
                if (limb == null || !limb.body.Enabled)
                {
                    continue;
                }

                if (lb.AllowUsingLimb)
                {
                    switch (lb.LimbType)
                    {
                    case LimbType.RightHand:
                    case LimbType.RightForearm:
                    case LimbType.RightArm:
                        if (user.Inventory.GetItemInLimbSlot(InvSlotType.RightHand) != null)
                        {
                            continue;
                        }
                        break;

                    case LimbType.LeftHand:
                    case LimbType.LeftForearm:
                    case LimbType.LeftArm:
                        if (user.Inventory.GetItemInLimbSlot(InvSlotType.LeftHand) != null)
                        {
                            continue;
                        }
                        break;
                    }
                }

                limb.Disabled = true;

                Vector2 worldPosition = new Vector2(item.WorldRect.X, item.WorldRect.Y) + lb.Position * item.Scale;
                Vector2 diff          = worldPosition - limb.WorldPosition;

                limb.PullJointEnabled      = true;
                limb.PullJointWorldAnchorB = limb.SimPosition + ConvertUnits.ToSimUnits(diff);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Control the Character according to player input
        /// </summary>
        public void ControlLocalPlayer(float deltaTime, Camera cam, bool moveCam = true)
        {
            if (!DisableControls)
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    keys[i].SetState();
                }
            }
            else
            {
                foreach (Key key in keys)
                {
                    if (key == null)
                    {
                        continue;
                    }
                    key.Reset();
                }
            }

            if (moveCam)
            {
                if (needsAir &&
                    pressureProtection < 80.0f &&
                    (AnimController.CurrentHull == null || AnimController.CurrentHull.LethalPressure > 50.0f))
                {
                    float pressure = AnimController.CurrentHull == null ? 100.0f : AnimController.CurrentHull.LethalPressure;

                    cam.Zoom = MathHelper.Lerp(cam.Zoom,
                                               (pressure / 50.0f) * Rand.Range(1.0f, 1.05f),
                                               (pressure - 50.0f) / 50.0f);
                }

                if (IsHumanoid)
                {
                    cam.OffsetAmount = MathHelper.Lerp(cam.OffsetAmount, 250.0f, deltaTime);
                }
                else
                {
                    //increased visibility range when controlling large a non-humanoid
                    cam.OffsetAmount = MathHelper.Lerp(cam.OffsetAmount, MathHelper.Clamp(Mass, 250.0f, 800.0f), deltaTime);
                }
            }

            cursorPosition = cam.ScreenToWorld(PlayerInput.MousePosition);
            if (AnimController.CurrentHull != null && AnimController.CurrentHull.Submarine != null)
            {
                cursorPosition -= AnimController.CurrentHull.Submarine.Position;
            }

            Vector2 mouseSimPos = ConvertUnits.ToSimUnits(cursorPosition);

            if (moveCam)
            {
                if (DebugConsole.IsOpen || GUI.PauseMenuOpen || IsUnconscious ||
                    (GameMain.GameSession?.CrewManager?.CrewCommander != null && GameMain.GameSession.CrewManager.CrewCommander.IsOpen))
                {
                    if (deltaTime > 0.0f)
                    {
                        cam.OffsetAmount = 0.0f;
                    }
                }
                else if (Lights.LightManager.ViewTarget == this && Vector2.DistanceSquared(AnimController.Limbs[0].SimPosition, mouseSimPos) > 1.0f)
                {
                    Body      body      = Submarine.CheckVisibility(AnimController.Limbs[0].SimPosition, mouseSimPos);
                    Structure structure = body == null ? null : body.UserData as Structure;

                    float sightDist = Submarine.LastPickedFraction;
                    if (body?.UserData is Structure && !((Structure)body.UserData).CastShadow)
                    {
                        sightDist = 1.0f;
                    }
                    cam.OffsetAmount = MathHelper.Lerp(cam.OffsetAmount, Math.Max(250.0f, sightDist * 500.0f), 0.05f);
                }
            }

            DoInteractionUpdate(deltaTime, mouseSimPos);

            DisableControls = false;
        }
Beispiel #24
0
        public static void CreateItems(List <PurchasedItem> itemsToSpawn)
        {
            if (itemsToSpawn.Count == 0)
            {
                return;
            }

            WayPoint wp = WayPoint.GetRandom(SpawnType.Cargo, null, Submarine.MainSub);

            if (wp == null)
            {
                DebugConsole.ThrowError("The submarine must have a waypoint marked as Cargo for bought items to be placed correctly!");
                return;
            }

            Hull cargoRoom = Hull.FindHull(wp.WorldPosition);

            if (cargoRoom == null)
            {
                DebugConsole.ThrowError("A waypoint marked as Cargo must be placed inside a room!");
                return;
            }

#if CLIENT
            new GUIMessageBox("", TextManager.GetWithVariable("CargoSpawnNotification", "[roomname]", cargoRoom.DisplayName, true));
#endif

            Dictionary <ItemContainer, int> availableContainers = new Dictionary <ItemContainer, int>();
            ItemPrefab containerPrefab = null;
            foreach (PurchasedItem pi in itemsToSpawn)
            {
                float floorPos = cargoRoom.Rect.Y - cargoRoom.Rect.Height;

                Vector2 position = new Vector2(
                    Rand.Range(cargoRoom.Rect.X + 20, cargoRoom.Rect.Right - 20),
                    floorPos);

                //check where the actual floor structure is in case the bottom of the hull extends below it
                if (Submarine.PickBody(
                        ConvertUnits.ToSimUnits(new Vector2(position.X, cargoRoom.Rect.Y - cargoRoom.Rect.Height / 2)),
                        ConvertUnits.ToSimUnits(position),
                        collisionCategory: Physics.CollisionWall) != null)
                {
                    float floorStructurePos = ConvertUnits.ToDisplayUnits(Submarine.LastPickedPosition.Y);
                    if (floorStructurePos > floorPos)
                    {
                        floorPos = floorStructurePos;
                    }
                }
                position.Y = floorPos + pi.ItemPrefab.Size.Y / 2;

                ItemContainer itemContainer = null;
                if (!string.IsNullOrEmpty(pi.ItemPrefab.CargoContainerIdentifier))
                {
                    itemContainer = availableContainers.Keys.ToList().Find(ac =>
                                                                           ac.Item.Prefab.Identifier == pi.ItemPrefab.CargoContainerIdentifier ||
                                                                           ac.Item.Prefab.Tags.Contains(pi.ItemPrefab.CargoContainerIdentifier.ToLowerInvariant()));

                    if (itemContainer == null)
                    {
                        containerPrefab = ItemPrefab.Prefabs.Find(ep =>
                                                                  ep.Identifier == pi.ItemPrefab.CargoContainerIdentifier ||
                                                                  (ep.Tags != null && ep.Tags.Contains(pi.ItemPrefab.CargoContainerIdentifier.ToLowerInvariant())));

                        if (containerPrefab == null)
                        {
                            DebugConsole.ThrowError("Cargo spawning failed - could not find the item prefab for container \"" + containerPrefab.Name + "\"!");
                            continue;
                        }

                        Item containerItem = new Item(containerPrefab, position, wp.Submarine);
                        itemContainer = containerItem.GetComponent <ItemContainer>();
                        if (itemContainer == null)
                        {
                            DebugConsole.ThrowError("Cargo spawning failed - container \"" + containerItem.Name + "\" does not have an ItemContainer component!");
                            continue;
                        }
                        availableContainers.Add(itemContainer, itemContainer.Capacity);
#if SERVER
                        if (GameMain.Server != null)
                        {
                            Entity.Spawner.CreateNetworkEvent(itemContainer.Item, false);
                        }
#endif
                    }
                }
                for (int i = 0; i < pi.Quantity; i++)
                {
                    if (itemContainer == null)
                    {
                        //no container, place at the waypoint
                        if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsServer)
                        {
                            Entity.Spawner.AddToSpawnQueue(pi.ItemPrefab, position, wp.Submarine);
                        }
                        else
                        {
                            new Item(pi.ItemPrefab, position, wp.Submarine);
                        }
                        continue;
                    }
                    //if the intial container has been removed due to it running out of space, add a new container
                    //of the same type and begin filling it
                    if (!availableContainers.ContainsKey(itemContainer))
                    {
                        Item containerItemOverFlow = new Item(containerPrefab, position, wp.Submarine);
                        itemContainer = containerItemOverFlow.GetComponent <ItemContainer>();
                        availableContainers.Add(itemContainer, itemContainer.Capacity);
#if SERVER
                        if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsServer)
                        {
                            Entity.Spawner.CreateNetworkEvent(itemContainer.Item, false);
                        }
#endif
                    }

                    //place in the container
                    if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsServer)
                    {
                        Entity.Spawner.AddToSpawnQueue(pi.ItemPrefab, itemContainer.Inventory);
                    }
                    else
                    {
                        var item = new Item(pi.ItemPrefab, position, wp.Submarine);
                        itemContainer.Inventory.TryPutItem(item, null);
                    }

                    //reduce the number of available slots in the container
                    //if there is a container
                    if (availableContainers.ContainsKey(itemContainer))
                    {
                        availableContainers[itemContainer]--;
                    }
                    if (availableContainers.ContainsKey(itemContainer) && availableContainers[itemContainer] <= 0)
                    {
                        availableContainers.Remove(itemContainer);
                    }
                }
            }
            itemsToSpawn.Clear();
        }
Beispiel #25
0
        public override void Initialize()
        {
            colBodySize  = Size;
            CollisionBox = context.lvl.CollisionWorld.CreateRectangle((float)ConvertUnits.ToSimUnits(Size.X), (float)ConvertUnits.ToSimUnits(Size.Y), 1, ConvertUnits.ToSimUnits(Transform.Position), 0, BodyType.Kinematic);
            CollisionBox.SetCollisionCategories(collidesWith);
            CollisionBox.Tag = this;
            cntlr            = new PlatformController(CollisionBox, Category.Cat2)
            {
                speed           = 0.2f,
                easeAmount      = 1.7f,
                waitTime        = 0.5f,
                globalWaypoints = WayPoints.ToArray()
            };

            if (CustomProperties.ContainsKey("tex"))
            {
                var texture = CustomProperties["tex"].value.ToString();
                movingObj = context.lvl.getItemByName(texture);
                movingObj.Transform.Position = Transform.Position;
            }

            base.Initialize();
        }
Beispiel #26
0
        /// <summary>
        /// The constructor for the Camera2D class.
        /// </summary>
        /// <param name="graphics"></param>
        public Camera2D(GraphicsDevice graphics)
        {
            _graphics     = graphics;
            SimProjection = Matrix.CreateOrthographicOffCenter(0f, ConvertUnits.ToSimUnits(_graphics.Viewport.Width), ConvertUnits.ToSimUnits(_graphics.Viewport.Height), 0f, 0f, 1f);
            SimView       = Matrix.Identity;
            View          = Matrix.Identity;

            _translateCenter = new Vector2(ConvertUnits.ToSimUnits(_graphics.Viewport.Width / 2f), ConvertUnits.ToSimUnits(_graphics.Viewport.Height / 2f));

            ResetCamera();
        }
Beispiel #27
0
        public override bool Use(float deltaTime, Character character = null)
        {
            if (character == null || character.Removed)
            {
                return(false);
            }
            if (item.RequireAimToUse && !character.IsKeyDown(InputType.Aim))
            {
                return(false);
            }

            float degreeOfSuccess = DegreeOfSuccess(character);

            if (Rand.Range(0.0f, 0.5f) > degreeOfSuccess)
            {
                ApplyStatusEffects(ActionType.OnFailure, deltaTime, character);
                return(false);
            }

            Vector2 targetPosition = item.WorldPosition;

            targetPosition += new Vector2(
                (float)Math.Cos(item.body.Rotation),
                (float)Math.Sin(item.body.Rotation)) * Range * item.body.Dir;

            List <Body> ignoredBodies = new List <Body>();

            foreach (Limb limb in character.AnimController.Limbs)
            {
                if (Rand.Range(0.0f, 0.5f) > degreeOfSuccess)
                {
                    continue;
                }
                ignoredBodies.Add(limb.body.FarseerBody);
            }
            ignoredBodies.Add(character.AnimController.Collider.FarseerBody);

            IsActive    = true;
            activeTimer = 0.1f;

            Vector2 rayStart = ConvertUnits.ToSimUnits(item.WorldPosition);
            Vector2 rayEnd   = ConvertUnits.ToSimUnits(targetPosition);

            debugRayStartPos = item.WorldPosition;
            debugRayEndPos   = ConvertUnits.ToDisplayUnits(rayEnd);

            if (character.Submarine == null)
            {
                foreach (Submarine sub in Submarine.Loaded)
                {
                    Rectangle subBorders = sub.Borders;
                    subBorders.Location += new Point((int)sub.WorldPosition.X, (int)sub.WorldPosition.Y - sub.Borders.Height);
                    if (!MathUtils.CircleIntersectsRectangle(item.WorldPosition, Range * 5.0f, subBorders))
                    {
                        continue;
                    }
                    Repair(rayStart - sub.SimPosition, rayEnd - sub.SimPosition, deltaTime, character, degreeOfSuccess, ignoredBodies);
                }
                Repair(rayStart, rayEnd, deltaTime, character, degreeOfSuccess, ignoredBodies);
            }
            else
            {
                Repair(rayStart - character.Submarine.SimPosition, rayEnd - character.Submarine.SimPosition, deltaTime, character, degreeOfSuccess, ignoredBodies);
            }

            UseProjSpecific(deltaTime);

            return(true);
        }
Beispiel #28
0
        public static Body CreateRect(IPhysicsBody owner, PhysicsWorld world, float width, float height, BodyType type = BodyType.Static)
        {
            var body = BodyFactory.CreateRectangle(world.World, ConvertUnits.ToSimUnits(width), ConvertUnits.ToSimUnits(height), 1f);

            body.BodyType = type;
            body.UserData = owner;
            if (owner != null)
            {
                owner.Body = body;
            }

            return(body);
        }
Beispiel #29
0
        public override bool Use(float deltaTime, Character character = null)
        {
            if (character != null)
            {
                if (item.RequireAimToUse && !character.IsKeyDown(InputType.Aim))
                {
                    return(false);
                }
            }

            float degreeOfSuccess = character == null ? 0.5f : DegreeOfSuccess(character);

            if (Rand.Range(0.0f, 0.5f) > degreeOfSuccess)
            {
                ApplyStatusEffects(ActionType.OnFailure, deltaTime, character);
                return(false);
            }

            if (UsableIn == UseEnvironment.None)
            {
                ApplyStatusEffects(ActionType.OnFailure, deltaTime, character);
                return(false);
            }

            if (item.InWater)
            {
                if (UsableIn == UseEnvironment.Air)
                {
                    ApplyStatusEffects(ActionType.OnFailure, deltaTime, character);
                    return(false);
                }
            }
            else
            {
                if (UsableIn == UseEnvironment.Water)
                {
                    ApplyStatusEffects(ActionType.OnFailure, deltaTime, character);
                    return(false);
                }
            }

            Vector2 rayStart;
            Vector2 rayStartWorld;
            Vector2 sourcePos = character?.AnimController == null ? item.SimPosition : character.AnimController.AimSourceSimPos;
            Vector2 barrelPos = item.SimPosition + ConvertUnits.ToSimUnits(TransformedBarrelPos);

            //make sure there's no obstacles between the base of the item (or the shoulder of the character) and the end of the barrel
            if (Submarine.PickBody(sourcePos, barrelPos, collisionCategory: Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionItemBlocking) == null)
            {
                //no obstacles -> we start the raycast at the end of the barrel
                rayStart      = ConvertUnits.ToSimUnits(item.Position + TransformedBarrelPos);
                rayStartWorld = ConvertUnits.ToSimUnits(item.WorldPosition + TransformedBarrelPos);
            }
            else
            {
                rayStart = rayStartWorld = Submarine.LastPickedPosition + Submarine.LastPickedNormal * 0.1f;
                if (item.Submarine != null)
                {
                    rayStartWorld += item.Submarine.SimPosition;
                }
            }

            //if the calculated barrel pos is in another hull, use the origin of the item to make sure the particles don't end up in an incorrect hull
            if (item.CurrentHull != null)
            {
                var barrelHull = Hull.FindHull(ConvertUnits.ToDisplayUnits(rayStartWorld), item.CurrentHull, useWorldCoordinates: true);
                if (barrelHull != null && barrelHull != item.CurrentHull)
                {
                    if (MathUtils.GetLineRectangleIntersection(ConvertUnits.ToDisplayUnits(sourcePos), ConvertUnits.ToDisplayUnits(rayStart), item.CurrentHull.Rect, out Vector2 hullIntersection))
                    {
                        Vector2 rayDir = rayStart.NearlyEquals(sourcePos) ? Vector2.Zero : Vector2.Normalize(rayStart - sourcePos);
                        rayStartWorld = ConvertUnits.ToSimUnits(hullIntersection - rayDir * 5.0f);
                        if (item.Submarine != null)
                        {
                            rayStartWorld += item.Submarine.SimPosition;
                        }
                    }
                }
            }

            float spread = MathHelper.ToRadians(MathHelper.Lerp(UnskilledSpread, Spread, degreeOfSuccess));

            float angle = MathHelper.ToRadians(BarrelRotation) + spread * Rand.Range(-0.5f, 0.5f);
            float dir   = 1;

            if (item.body != null)
            {
                angle += item.body.Rotation;
                dir    = item.body.Dir;
            }
            Vector2 rayEnd = rayStartWorld + ConvertUnits.ToSimUnits(new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)) * Range * dir);

            ignoredBodies.Clear();
            if (character != null)
            {
                foreach (Limb limb in character.AnimController.Limbs)
                {
                    if (Rand.Range(0.0f, 0.5f) > degreeOfSuccess)
                    {
                        continue;
                    }
                    ignoredBodies.Add(limb.body.FarseerBody);
                }
                ignoredBodies.Add(character.AnimController.Collider.FarseerBody);
            }

            IsActive    = true;
            activeTimer = 0.1f;

            debugRayStartPos = ConvertUnits.ToDisplayUnits(rayStartWorld);
            debugRayEndPos   = ConvertUnits.ToDisplayUnits(rayEnd);

            Submarine parentSub = character?.Submarine ?? item.Submarine;

            if (parentSub == null)
            {
                foreach (Submarine sub in Submarine.Loaded)
                {
                    Rectangle subBorders = sub.Borders;
                    subBorders.Location += new Point((int)sub.WorldPosition.X, (int)sub.WorldPosition.Y - sub.Borders.Height);
                    if (!MathUtils.CircleIntersectsRectangle(item.WorldPosition, Range * 5.0f, subBorders))
                    {
                        continue;
                    }
                    Repair(rayStartWorld - sub.SimPosition, rayEnd - sub.SimPosition, deltaTime, character, degreeOfSuccess, ignoredBodies);
                }
                Repair(rayStartWorld, rayEnd, deltaTime, character, degreeOfSuccess, ignoredBodies);
            }
            else
            {
                Repair(rayStartWorld - parentSub.SimPosition, rayEnd - parentSub.SimPosition, deltaTime, character, degreeOfSuccess, ignoredBodies);
            }

            UseProjSpecific(deltaTime, rayStartWorld);

            return(true);
        }
Beispiel #30
0
 public void Draw()
 {
     _batch.Draw(sprite.Texture, ConvertUnits.ToDisplayUnits(_agentBody.Position), null, Color.White, _agentBody.Rotation, new Vector2(sprite.Texture.Width / 2f, sprite.Texture.Height / 2f), (float)ConvertUnits.ToDisplayUnits(1f) * radius * 2f / (float)sprite.Texture.Width, SpriteEffects.None, 0f);
 }