public bool isAbove(CollisionBox target)
 {
     Rectangle rect = Rectangle.Intersect(cb.getBoundingBox(), target.getBoundingBox());
     if (this.Intersects(target) ? cb.getBoundingBox().Top == rect.Top : false)
         return rect.Height < rect.Width;
     return false;
 }
 public bool isRight(CollisionBox target)
 {
     Rectangle rect = Rectangle.Intersect(cb.getBoundingBox(), target.getBoundingBox());
     if (this.Intersects(target) ? cb.getBoundingBox().Right == rect.Right : false)
         return rect.Height > rect.Width;
     return false;
 }
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            targetRect = new AIDBC(new Vector2(400), 150f);
            mouseRect = new AIDBC(new Vector2(), 50f);

            base.Initialize();
        }
Esempio n. 4
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     TerrainObj terrainObj = otherBox.Parent as TerrainObj;
     if (terrainObj != null && !(terrainObj is DoorObj) && terrainObj.CollidesBottom && terrainObj.CollidesLeft && terrainObj.CollidesRight && terrainObj.CollidesTop)
     {
         Vector2 value = CollisionMath.RotatedRectIntersectsMTD(thisBox.AbsRect, (float)((int)thisBox.AbsRotation), Vector2.Zero, otherBox.AbsRect, (float)((int)otherBox.AbsRotation), Vector2.Zero);
         if (value != Vector2.Zero)
         {
             Vector2 heading = base.Heading;
             Vector2 vector = new Vector2(value.Y, value.X * -1f);
             Vector2 heading2 = 2f * (CDGMath.DotProduct(heading, vector) / CDGMath.DotProduct(vector, vector)) * vector - heading;
             base.X += value.X;
             base.Y += value.Y;
             base.Heading = heading2;
             SoundManager.Play3DSound(this, Game.ScreenManager.Player, new string[]
             {
                 "GiantSpike_Bounce_01",
                 "GiantSpike_Bounce_02",
                 "GiantSpike_Bounce_03"
             });
             this.m_selfDestructCounter++;
             this.m_selfDestructTimer = 1f;
         }
     }
 }
 public bool isBelow(CollisionBox target)
 {
     Rectangle rect = Rectangle.Intersect(cb.getBoundingBox(), target.getBoundingBox());
     if (this.Intersects(target) ? cb.getBoundingBox().Bottom == rect.Bottom : false)
         return rect.Height < rect.Width;
     return false;
 }
Esempio n. 6
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     if (this.State == 1)
     {
         base.CollisionResponse(thisBox, otherBox, collisionResponseType);
     }
 }
Esempio n. 7
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     PlayerObj playerObj = otherBox.AbsParent as PlayerObj;
     ProjectileObj projectileObj = otherBox.AbsParent as ProjectileObj;
     if (collisionResponseType == 2 && ((playerObj != null && this.m_invincibleCounter <= 0f) || (projectileObj != null && this.m_invincibleCounterProjectile <= 0f)) && ((this.Flip == SpriteEffects.None && otherBox.AbsParent.AbsPosition.X > base.X) || (this.Flip == SpriteEffects.FlipHorizontally && otherBox.AbsParent.AbsPosition.X < base.X)) && playerObj != null && playerObj.SpriteName != "PlayerAirAttack_Character")
     {
         if (base.CanBeKnockedBack)
         {
             base.CurrentSpeed = 0f;
             this.m_currentActiveLB.StopLogicBlock();
             bool arg_DD_1 = true;
             LogicBlock arg_DD_2 = this.m_generalBasicLB;
             int[] array = new int[3];
             array[0] = 100;
             base.RunLogicBlock(arg_DD_1, arg_DD_2, array);
         }
         if (this.m_target.IsAirAttacking)
         {
             this.m_target.IsAirAttacking = false;
             this.m_target.AccelerationY = -this.m_target.AirAttackKnockBack;
             this.m_target.NumAirBounces++;
         }
         else
         {
             if ((float)(this.m_target.Bounds.Left + this.m_target.Bounds.Width / 2) < base.X)
             {
                 this.m_target.AccelerationX = -this.ShieldKnockback.X;
             }
             else
             {
                 this.m_target.AccelerationX = this.ShieldKnockback.X;
             }
             this.m_target.AccelerationY = -this.ShieldKnockback.Y;
         }
         base.CollisionResponse(thisBox, otherBox, collisionResponseType);
         Point center = Rectangle.Intersect(thisBox.AbsRect, otherBox.AbsRect).Center;
         Vector2 position = new Vector2((float)center.X, (float)center.Y);
         this.m_levelScreen.ImpactEffectPool.DisplayBlockImpactEffect(position, new Vector2(2f, 2f));
         SoundManager.Play3DSound(this, Game.ScreenManager.Player, new string[]
         {
             "ShieldKnight_Block01",
             "ShieldKnight_Block02",
             "ShieldKnight_Block03"
         });
         this.m_invincibleCounter = base.InvincibilityTime;
         this.m_levelScreen.SetLastEnemyHit(this);
         base.Blink(Color.LightBlue, 0.1f);
         ProjectileObj projectileObj2 = otherBox.AbsParent as ProjectileObj;
         if (projectileObj2 != null)
         {
             this.m_invincibleCounterProjectile = base.InvincibilityTime;
             this.m_levelScreen.ProjectileManager.DestroyProjectile(projectileObj2);
             return;
         }
     }
     else
     {
         base.CollisionResponse(thisBox, otherBox, collisionResponseType);
     }
 }
Esempio n. 8
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     IPhysicsObj physicsObj = otherBox.AbsParent as IPhysicsObj;
     if (collisionResponseType == 2 && physicsObj.CollisionTypeTag == 2 && !this.m_wasHit)
     {
         SoundManager.Play3DSound(this, Game.ScreenManager.Player, new string[]
         {
             "EnemyHit1",
             "EnemyHit2",
             "EnemyHit3",
             "EnemyHit4",
             "EnemyHit5",
             "EnemyHit6"
         });
         SoundManager.PlaySound("Boss_Title_Exit");
         SoundManager.PlaySound("Player_Death_Grunt");
         Point center = Rectangle.Intersect(thisBox.AbsRect, otherBox.AbsRect).Center;
         if (thisBox.AbsRotation != 0f || otherBox.AbsRotation != 0f)
         {
             center = Rectangle.Intersect(thisBox.AbsParent.Bounds, otherBox.AbsParent.Bounds).Center;
         }
         Vector2 position = new Vector2((float)center.X, (float)center.Y);
         (otherBox.AbsParent as PlayerObj).AttachedLevel.ImpactEffectPool.DisplayEnemyImpactEffect(position);
         this.m_wasHit = true;
     }
     base.CollisionResponse(thisBox, otherBox, collisionResponseType);
 }
Esempio n. 9
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     if (otherBox.AbsParent is PlayerObj)
     {
         this.ChasePlayer();
     }
     base.CollisionResponse(thisBox, otherBox, collisionResponseType);
 }
Esempio n. 10
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     TerrainObj terrainObj = otherBox.AbsParent as TerrainObj;
     if (otherBox.AbsParent.Bounds.Top < this.TerrainBounds.Bottom - 20 && terrainObj != null && terrainObj.CollidesLeft && terrainObj.CollidesRight && terrainObj.CollidesBottom && collisionResponseType == 1 && otherBox.AbsRotation == 0f && this.m_collisionCheckTimer <= 0f && CollisionMath.CalculateMTD(thisBox.AbsRect, otherBox.AbsRect).X != 0f)
     {
         this.TurnHorse();
     }
     base.CollisionResponse(thisBox, otherBox, collisionResponseType);
 }
Esempio n. 11
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     PlayerObj playerObj = otherBox.AbsParent as PlayerObj;
     if (!Game.ScreenManager.Player.ControlsLocked && playerObj != null && playerObj.IsTouchingGround)
     {
         this.m_arrowIcon.Visible = true;
     }
     base.CollisionResponse(thisBox, otherBox, collisionResponseType);
 }
Esempio n. 12
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     if (otherBox.AbsParent is PlayerObj && !this.m_isAttacking)
     {
         this.m_currentActiveLB.StopLogicBlock();
         this.m_isAttacking = true;
         base.LockFlip = false;
     }
     base.CollisionResponse(thisBox, otherBox, collisionResponseType);
 }
Esempio n. 13
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     if (collisionResponseType == 1 && (otherBox.AbsParent is TerrainObj || otherBox.AbsParent is HazardObj) && !(otherBox.AbsParent is DoorObj))
     {
         base.CollisionResponse(thisBox, otherBox, collisionResponseType);
         base.AccelerationX = 0f;
         base.Y = (float)((int)base.Y);
         if (this.DropType == 10 && base.CurrentFrame == 1 && CollisionMath.CalculateMTD(thisBox.AbsRect, otherBox.AbsRect).Y < 0f)
         {
             base.PlayAnimation(2, base.TotalFrames, false);
         }
     }
 }
        public void CollisionBox_TooFarLeft_NoCollision()
        {
            var box = new CollisionBox(0, 0, 10, 10);
            box.SetParent(_collision);

            var square = GetMapSquare(new RectangleF(-15, 0, 10, 10));

            PointF collisionPoint = PointF.Empty;

            var didCollide = box.EnvironmentCollisions(PointF.Empty, square, ref collisionPoint);

            Assert.IsFalse(didCollide);
            Assert.AreEqual(PointF.Empty, collisionPoint);
        }
        public void CollisionBox_Overapping_DefaultVerticalApproach()
        {
            var box = new CollisionBox(0, 0, 10, 10);
            box.SetParent(_collision);

            var square = GetMapSquare(new RectangleF(8.6f, 4.1f, 10, 10));

            PointF collisionPoint = PointF.Empty;

            var didCollide = box.EnvironmentCollisions(PointF.Empty, square, ref collisionPoint);

            Assert.IsTrue(didCollide);
            // pushes the block out vertically
            Assert.AreEqual(new PointF(0, -5.9f), collisionPoint);
        }
Esempio n. 16
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     if (collisionResponseType == 2 && this.m_invincibleCounter <= 0f && otherBox.AbsParent is PlayerObj)
     {
         if ((float)(this.m_target.Bounds.Left + this.m_target.Bounds.Width / 2) < base.X)
         {
             this.m_target.AccelerationX = -this.m_target.EnemyKnockBack.X;
         }
         else
         {
             this.m_target.AccelerationX = this.m_target.EnemyKnockBack.X;
         }
         this.m_target.AccelerationY = -this.m_target.EnemyKnockBack.Y;
         Point center = Rectangle.Intersect(thisBox.AbsRect, otherBox.AbsRect).Center;
         Vector2 position = new Vector2((float)center.X, (float)center.Y);
         this.m_levelScreen.ImpactEffectPool.DisplayBlockImpactEffect(position, Vector2.One);
         this.m_levelScreen.SetLastEnemyHit(this);
         this.m_invincibleCounter = base.InvincibilityTime;
         base.Blink(Color.LightBlue, 0.1f);
         ProjectileObj projectileObj = otherBox.AbsParent as ProjectileObj;
         if (projectileObj != null)
         {
             this.m_levelScreen.ProjectileManager.DestroyProjectile(projectileObj);
             return;
         }
     }
     else if (otherBox.AbsParent is EnergonProjectileObj)
     {
         EnergonProjectileObj energonProjectileObj = otherBox.AbsParent as EnergonProjectileObj;
         if (energonProjectileObj != null)
         {
             Point center2 = Rectangle.Intersect(thisBox.AbsRect, otherBox.AbsRect).Center;
             Vector2 vector = new Vector2((float)center2.X, (float)center2.Y);
             this.DestroyProjectile(energonProjectileObj);
             if (energonProjectileObj.AttackType == this.m_currentAttackType)
             {
                 this.HitEnemy(energonProjectileObj.Damage, vector, true);
                 return;
             }
             this.m_levelScreen.ImpactEffectPool.DisplayBlockImpactEffect(vector, Vector2.One);
             return;
         }
     }
     else
     {
         base.CollisionResponse(thisBox, otherBox, collisionResponseType);
     }
 }
Esempio n. 17
0
 public Bat(int x, int y, TileMap tileMap)
 {
     base(x, y, WIDTH, HEIGHT, tileMap, GameObjectType.ENEMY, GameObject.Team.ENEMY);
     SetSpeed(MOVEMENT_SPEED);
     SetHealth(HEALTH);
     face     = Direction.RIGHT;
     radarBox = new CollisionBox(posX - RADAR_BOX_POSITION_MODIFIER, posY - RADAR_BOX_POSITION_MODIFIER,
                                 RADAR_BOX_SIZE, RADAR_BOX_SIZE);
     weapon = new Weapon(this, tileMap, this.GetHitBox().GetPosX(), this.GetHitBox().GetPosY(),
                         BASE_DAMAGE, BASE_PROJECTILE_SPEED, BASE_FIRE_RATE, this.GetTeam())
     {
     };
     shootingDirection = new Tuple <int, int>(0, 0);
     this.delayCounter = 0;
     this.pauseCounter = 0;
     this.isMoving     = true;
 }
 public bool Intersects(CollisionBox target)
 {
     if (cb.getBoundingBox().Intersects(target.getBoundingBox()))
         if (cb.getBoundinType() == target.getBoundinType())
         {
             if (cb.getBoundinType() == boundingType.AABB)
                 return true;
             else if (cb.getBoundinType() == boundingType.AIDBC)
             {
                 return Math.Abs(Vector2.Distance(cb.getCenter(), target.getCenter())) <= (cb.getSize().X + target.getSize().X)/2;
             }
         }
         else
         {
         }
     return false;
 }
Esempio n. 19
0
        public override void Draw(GameTime gameTime)
        {
            if (!IsInvincible)
            {
                Game.SpriteBatch.Draw(Sprite, Position, null, Color.White, Rotation, Center, 1f, SpriteEffects.None, 0f);

                // Draw Hitbox
                if (SlowMode)
                {
                    Game.SpriteBatch.Draw(_hitboxSprite, new Rectangle(
                                              (int)(CollisionBox.GetCenter().X - _hitboxRadius / 2f),
                                              (int)(CollisionBox.GetCenter().Y - _hitboxRadius / 2f),
                                              (int)_hitboxRadius,
                                              (int)_hitboxRadius),
                                          Color.White);
                }
            }

            base.Draw(gameTime);
        }
Esempio n. 20
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     if (otherBox.AbsParent is PlayerObj)
     {
         base.CurrentSpeed = 0f;
     }
     if (collisionResponseType != 1)
     {
         base.CollisionResponse(thisBox, otherBox, collisionResponseType);
         return;
     }
     if (!(otherBox.AbsParent is PlayerObj))
     {
         IPhysicsObj physicsObj = otherBox.AbsParent as IPhysicsObj;
         if (physicsObj.CollidesBottom && physicsObj.CollidesTop && physicsObj.CollidesLeft && physicsObj.CollidesRight)
         {
             base.Position += CollisionMath.RotatedRectIntersectsMTD(thisBox.AbsRect, thisBox.AbsRotation, Vector2.Zero, otherBox.AbsRect, otherBox.AbsRotation, Vector2.Zero);
         }
     }
 }
Esempio n. 21
0
 private void UpdateSelected()
 {
     SelectedBox = null;
     foreach (CollisionBox box in Boxes)
     {
         if ((box.ToRectangle() + Pivot).Contains(CursorSystem.CursorPos))
         {
             SelectedBox = box;
             break;
         }
     }
     foreach (IOutline outline in Outlines)
     {
         if (outline is CollisionBoxOutline boxOutline)
         {
             boxOutline.Color     = boxOutline.Box == SelectedBox ? Color.Magenta : Color.DarkMagenta;
             boxOutline.Thickness = boxOutline.Box == SelectedBox ? 3 : 2;
         }
     }
 }
Esempio n. 22
0
        /// <summary>
        /// Create and return a random shape object.
        /// </summary>
        private GameObject CreateRandomShape()
        {
            // tilemap actual size
            float tilemapActualSize = tilemapSize * tileSize;

            // collision shape and type
            ICollisionShape collisionShape = null;
            ShapeMeshes     shapeType      = ShapeMeshes.Cylinder;

            // random collision shape and type
            int randType = rand.Next(0, 2);

            switch (randType)
            {
            case 0:
                shapeType      = ShapeMeshes.SphereSmooth;
                collisionShape = new CollisionSphere();
                break;

            case 1:
                shapeType      = ShapeMeshes.Cube;
                collisionShape = new CollisionBox(2f, 2f, 2f);
                break;
            }

            // create shape
            float      sizeFactor    = 1.0f + (float)rand.NextDouble() * 1.25f;
            GameObject shape         = new GameObject();
            var        shapeRenderer = shape.AddComponent(new ShapeRenderer(shapeType)) as ShapeRenderer;

            shapeRenderer.MaterialOverride.DiffuseColor = new Color((rand.Next(0, 255)), (rand.Next(0, 255)), (rand.Next(0, 255)));
            var body = shape.AddComponent(new RigidBody(collisionShape, sizeFactor, 1f, 1f)) as RigidBody;

            body.Scale       = Vector3.One * tileSize * 0.25f * sizeFactor;
            body.Restitution = 0.5f;
            body.Position    = new Vector3(
                (float)rand.NextDouble() * tilemapActualSize,
                10f + (float)rand.NextDouble() * 45f,
                (float)rand.NextDouble() * tilemapActualSize);
            return(shape);
        }
Esempio n. 23
0
        public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
        {
            var physicsObj = otherBox.AbsParent as IPhysicsObj;

            if (collisionResponseType == 2 && physicsObj.CollisionTypeTag == 2 && !WasHit)
            {
                SoundManager.Play3DSound(this, Game.ScreenManager.Player, "EnemyHit1", "EnemyHit2", "EnemyHit3",
                                         "EnemyHit4", "EnemyHit5", "EnemyHit6");
                SoundManager.PlaySound("Boss_Title_Exit");
                SoundManager.PlaySound("Player_Death_Grunt");
                var center = Rectangle.Intersect(thisBox.AbsRect, otherBox.AbsRect).Center;
                if (thisBox.AbsRotation != 0f || otherBox.AbsRotation != 0f)
                {
                    center = Rectangle.Intersect(thisBox.AbsParent.Bounds, otherBox.AbsParent.Bounds).Center;
                }
                var position = new Vector2(center.X, center.Y);
                (otherBox.AbsParent as PlayerObj).AttachedLevel.ImpactEffectPool.DisplayEnemyImpactEffect(position);
                WasHit = true;
            }
            base.CollisionResponse(thisBox, otherBox, collisionResponseType);
        }
Esempio n. 24
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     if (otherBox.AbsParent is PlayerObj)
     {
         CurrentSpeed = 0f;
     }
     if (collisionResponseType != 1)
     {
         base.CollisionResponse(thisBox, otherBox, collisionResponseType);
         return;
     }
     if (!(otherBox.AbsParent is PlayerObj))
     {
         var physicsObj = otherBox.AbsParent as IPhysicsObj;
         if (physicsObj.CollidesBottom && physicsObj.CollidesTop && physicsObj.CollidesLeft &&
             physicsObj.CollidesRight)
         {
             Position += CollisionMath.RotatedRectIntersectsMTD(thisBox.AbsRect, thisBox.AbsRotation,
                                                                Vector2.Zero, otherBox.AbsRect, otherBox.AbsRotation, Vector2.Zero);
         }
     }
 }
Esempio n. 25
0
    private void OnTriggerEnter2D(Collider2D collision)
    {
        try{
            CollisionBox cb = collision.GetComponent <CollisionBox>();
            if (cb.owner != owner && collision.GetComponentInParent <BaseCharacter>() != null)
            {
                if (collision.gameObject.layer == LayerMask.NameToLayer("Hurt") && collided == false)
                {
                    collided = true;
                    if (del == null)
                    {
                        del = () =>
                        {
                            Debug.Log(this.name + " collided with: " + collision.name);
                            BaseCharacter player_hit = collision.gameObject.GetComponentInParent <BaseCharacter>();
                            player_hit._sm.currentState.FireCustomEvent(new EventList.HitEvent(player_hit, properties, launch_direction));
                            owner._stamina.Siphon(player_hit, CalculateDamage());

                            player_hit.sfxPlayer.Play(Services.SFXLibrary.GetSFX(SFXLibrary.SFXTags.Impact));
                            Camera.main.GetComponent <Cam>().ShakeCamera(.65f, 15);
                            if (player_hit.staminaSystem.GetCurrentMaxStamina() > 2)
                            {
                                owner.staminaSystem.Add();
                                player_hit.staminaSystem.Remove();
                            }
                            else
                            {
                                player_hit.staminaSystem.SpendOrbs(1);
                            }
                        };
                    }
                    del();
                }
            }
        }
        catch
        {
        }
    }
Esempio n. 26
0
        /// <summary>
        /// Helper method to read all collision boxes from a Puppet file and return a list of them
        /// </summary>
        /// <param name="sectionReader">BinaryReader instance containing the Collision Box section data</param>
        /// <param name="version">Version of the Puppet file</param>
        /// <returns>List of collision boxes from the Puppet file</returns>
        public static List <CollisionBox> ReadAllCollisionBoxes(BinaryReader sectionReader, Version version)
        {
            List <CollisionBox> collisionBoxes = new List <CollisionBox>();

            uint collisionBoxCount = sectionReader.ReadUInt32();

            for (int i = 0; i < collisionBoxCount; i++)
            {
                CollisionBox collisionBox = new CollisionBox();

                collisionBox.Unknown1 = sectionReader.ReadUInt32();
                collisionBox.Unknown2 = sectionReader.ReadUInt32();

                uint nameLength = sectionReader.ReadUInt32();

                collisionBox.Name = Encoding.UTF8.GetString(sectionReader.ReadBytes((int)nameLength));

                uint boneNameLength = sectionReader.ReadUInt32();

                collisionBox.BoneName = Encoding.UTF8.GetString(sectionReader.ReadBytes((int)boneNameLength));

                uint scriptLength = sectionReader.ReadUInt32();

                collisionBox.Script = Encoding.UTF8.GetString(sectionReader.ReadBytes((int)scriptLength));

                collisionBox.Unknown3 = sectionReader.ReadUInt32();

                collisionBox.MinX = sectionReader.ReadSingle();
                collisionBox.MinY = sectionReader.ReadSingle();
                collisionBox.MinZ = sectionReader.ReadSingle();
                collisionBox.MaxX = sectionReader.ReadSingle();
                collisionBox.MaxY = sectionReader.ReadSingle();
                collisionBox.MaxZ = sectionReader.ReadSingle();

                collisionBoxes.Add(collisionBox);
            }

            return(collisionBoxes);
        }
Esempio n. 27
0
        void Start()
        {
            var pos   = transform.position.ToVector3d();
            var scale = transform.localScale.ToVector3d() * 0.5;
            var rot   = transform.rotation.ToQuaternion();

            m_body                = new RigidBody();
            m_body.Position       = pos;
            m_body.Orientation    = rot;
            m_body.LinearDamping  = damping;
            m_body.AngularDamping = damping;
            m_body.SetMass(mass);
            m_body.SetAwake(true);
            m_body.SetCanSleep(true);

            var shape = new CollisionBox(scale);

            shape.Body = m_body;

            RigidPhysicsEngine.Instance.Bodies.Add(m_body);
            RigidPhysicsEngine.Instance.Collisions.Primatives.Add(shape);
        }
Esempio n. 28
0
        public override void Update(GameTime gameTime, Rectangle clientBounds)
        {
            //  TODO: add friction if collide with terrain

            // update old collisionBox position
            oldBoxPos.UpdateCollisionBox(
                new Vector2(position.X, position.Y),                              // player top left vertex (AABB max)
                new Vector2(position.X + frameSize.X, position.Y + frameSize.Y)); // player bottom right vertex (AABB min)

            // update position and velocity
            position += new Vector2(velocity.X * (float)gameTime.ElapsedGameTime.TotalSeconds,  // x = Vx * time
                                    velocity.Y * (float)gameTime.ElapsedGameTime.TotalSeconds + // y = Vy*time + (gravity * time^2) / 2
                                    ((Physics.World.Gravity.Y * (float)gameTime.ElapsedGameTime.TotalSeconds * (float)gameTime.ElapsedGameTime.TotalSeconds) / 2));
            velocity = new Vector2(velocity.X, velocity.Y + (Physics.World.Gravity.Y * (float)gameTime.ElapsedGameTime.TotalSeconds));

            // update collisionBox
            CollisionBox.UpdateCollisionBox(
                new Vector2(position.X, position.Y),                              // player top left vertex (AABB max)
                new Vector2(position.X + frameSize.X, position.Y + frameSize.Y)); // player bottom right vertex (AABB min)

            base.Update(gameTime, clientBounds);
        }
        public void Collision_FloatingPointError_StillWorks()
        {
            var hitbox = new CollisionBox(-7.5f, -9f, 15, 21);
            hitbox.Name = "Test";
            hitbox.Environment = true;
            hitbox.PushAway = true;
            _position.SetPosition(5f, 115.999992f);
            _collision.AddBox(hitbox);
            _collision.Message(new HitBoxMessage(EntityMock.Object, new List<CollisionBox>(), new HashSet<string>() { "Test" }, false));

            var layer = new Mock<IScreenLayer>();
            layer.SetupGet(l => l.Stage).Returns(Container);

            var tileset = new Common.Tileset() { TileSize = 16 };
            var backTile = new Common.Tile(1, new Common.TileSprite(tileset));
            var blankSquare = new MapSquare(layer.Object, backTile, 0, 0, 16);

            Screen.Setup(s => s.SquareAt(It.IsAny<float>(), It.IsAny<float>())).Returns(blankSquare);

            var blockTile = new Common.Tile(2, new Common.TileSprite(tileset));
            blockTile.Properties = new Common.TileProperties() { Blocking = true };
            var blockSquare = new MapSquare(layer.Object, blockTile, 0, 8, 16);

            Screen.Setup(s => s.SquareAt(It.IsInRange<float>(0, 16, Range.Inclusive), It.IsInRange<float>(128, 144, Range.Inclusive))).Returns(blockSquare);

            Assert.IsFalse(_collision.BlockBottom);

            Container.Tick();

            Assert.IsTrue(_collision.BlockBottom);

            Container.Tick();

            Assert.IsTrue(_collision.BlockBottom);

            Container.Tick();

            Assert.IsTrue(_collision.BlockBottom);
        }
Esempio n. 30
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();
        }
Esempio n. 31
0
        private void Move()
        {
            if (IsMoving == false)
            {
                return;
            }

            var entity = Screen.MainConsole.Entities.FirstOrDefault(e => e.Transform.Position ==
                                                                    Transform.Position +
                                                                    Transform.Direction.AsPoint());

            Point lastPosition = Transform.Position;

            switch (Transform.Direction)
            {
            case Direction.Right:
                Transform.Position = new Point(Transform.Position.X + Velocity, Transform.Position.Y);
                break;

            case Direction.Left:
                Transform.Position = new Point(Transform.Position.X - Velocity, Transform.Position.Y);
                break;

            case Direction.Up:
                Transform.Position = new Point(Transform.Position.X, Transform.Position.Y - Velocity);
                break;

            case Direction.Down:
                Transform.Position = new Point(Transform.Position.X, Transform.Position.Y + Velocity);
                break;
            }

            if (entity != null && CollisionBox.CheckCollision(Transform, entity.Transform))
            {
                Transform.Position = lastPosition;
            }
        }
Esempio n. 32
0
        public override void EventFired(object sender, Event e)
        {
            if (e is CollisionFaceSelectEvent s)
            {
                SelectedPropertyIndex = 0;
                Members.Clear();
                Box       = s.Box;
                FaceIndex = s.FaceIndex;
                Face      = Box.GetFaceProperties().ElementAt(FaceIndex);
                //object face = (object)(FaceIndex == 0 ? Box.TopFaceProperties : FaceIndex == 1 ? Box.RightFaceProperties : FaceIndex == 2 ? Box.BottomFaceProperties : Box.LeftFaceProperties);
                foreach (FieldInfo field in typeof(CollisionFaceProperties).GetFields())
                {
                    Members.Add(new FieldSummary(Owner, field, (object)Face));
                }
            }
            else if (e is ModalChangeEvent)
            {
                ModalActive  = true;
                ModalVisible = true;
            }
            else if (e is BeginModalChangeEvent bmce)
            {
                bmce.SystemName = "collision_cursor_mode";
                ModalActive     = false;
                ModalVisible    = false;
                switch (FaceIndex)
                {
                case 0: Box.TopFaceProperties = (CollisionFaceProperties)Face; break;

                case 1: Box.RightFaceProperties = (CollisionFaceProperties)Face; break;

                case 2: Box.BottomFaceProperties = (CollisionFaceProperties)Face; break;

                case 3: Box.LeftFaceProperties = (CollisionFaceProperties)Face; break;
                }
            }
        }
Esempio n. 33
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     PlayerObj playerObj = otherBox.AbsParent as PlayerObj;
     if (playerObj != null && !this.m_canHitEnemy)
     {
         if ((this.AttackType == 0 && otherBox.Type == 1 && !playerObj.IsAirAttacking) || (this.AttackType == 1 && otherBox.Type == 2 && playerObj.State == 6) || (this.AttackType == 2 && otherBox.Type == 1 && playerObj.IsAirAttacking))
         {
             base.Target = this.m_parent;
             base.CollisionTypeTag = 2;
             base.CurrentSpeed *= 2f;
             playerObj.AttachedLevel.ImpactEffectPool.DisplayEnemyImpactEffect(base.Position);
             return;
         }
         if (otherBox.Type == 2)
         {
             this.m_parent.DestroyProjectile(this);
             return;
         }
     }
     else
     {
         base.CollisionResponse(thisBox, otherBox, collisionResponseType);
     }
 }
 protected void Init(CollisionBox _cb)
 {
     cb = _cb;
 }
Esempio n. 35
0
 protected void AddCollision(CollisionBox box)
 {
     AddCollision(CoordinateMode.Real, box);
 }
Esempio n. 36
0
        /// <summary>
        /// Carga de contenido gráfico
        /// </summary>
        protected override void LoadContent()
        {
            base.LoadContent();

            // Información del componente
            VehicleComponentInfo componentInfo = VehicleComponentInfo.Load(Path.Combine(this.AssetsFolder, this.ComponentInfoName));

            // Modelo
            this.m_ModelName = componentInfo.Model;

            if (!g_ModelDictionary.ContainsKey(componentInfo.Model))
            {
                Model         model      = Content.Load <Model>(Path.Combine(this.AssetsFolder, this.m_ModelName));
                PrimitiveInfo primitives = model.Tag as PrimitiveInfo;

                GeometryInfo geometry = new GeometryInfo()
                {
                    Model      = model,
                    Primitives = primitives,
                };

                g_ModelDictionary.Add(this.m_ModelName, geometry);
            }

            CollisionBox box = new CollisionBox(this.TriangleInfo.AABB, 1000f);

            this.m_CollisionPrimitive = box;
            this.m_Offset             = Matrix.CreateTranslation(new Vector3(0f, -box.HalfSize.Y, 0f));

            // Integridad
            this.BaseHull = this.Hull = componentInfo.Hull;
            // Blindaje
            this.BaseArmor = this.Armor = componentInfo.Armor;

            // Altura máxima de vuelo
            this.Engine.InitialMaxFlightHeight = componentInfo.MaxFlightHeight;
            // Altura mínima de vuelo
            this.Engine.InitialMinFlightHeight = componentInfo.MinFlightHeight;

            // Velocidad máxima que puede alcanzar el vehículo hacia delante
            this.Engine.MaxForwardVelocity = componentInfo.MaxForwardVelocity;
            // Velocidad máxima que puede alcanzar el vehículo marcha atrás
            this.Engine.MaxBackwardVelocity = componentInfo.MaxBackwardVelocity;
            // Modificador de aceleración
            this.Engine.AccelerationModifier = componentInfo.AccelerationModifier;
            // Modificador de frenado
            this.Engine.BrakeModifier = componentInfo.BrakeModifier;
            // Velocidad angular
            this.Engine.AngularVelocityModifier = MathHelper.ToRadians(componentInfo.AngularVelocityModifier);
            // Vehículo volador
            this.Engine.Skimmer = componentInfo.Skimmer;
            // Altura máxima
            this.Engine.MaxFlightHeight = componentInfo.MaxFlightHeight;
            // Altura mínima
            this.Engine.MinFlightHeight = componentInfo.MinFlightHeight;
            // Rotación ascendente del morro
            this.Engine.AscendingAngle = MathHelper.ToRadians(componentInfo.AscendingAngle);
            // Rotación descendente del morro
            this.Engine.DescendingAngle = MathHelper.ToRadians(componentInfo.DescendingAngle);
            // Controles de animación
            this.m_AnimationController.AddRange(Animation.Animation.CreateAnimationList(this.Model, componentInfo.AnimationControlers));
            // Posiciones
            this.m_PlayerControlList.AddRange(Animation.PlayerPosition.CreatePlayerPositionList(this.Model, componentInfo.PlayerPositions));
            // Armas
            this.m_WeapontList.AddRange(Weapon.CreateWeaponList(this.Model, componentInfo.Weapons));
            // Emisores de partículas
            this.m_ParticleEmitterList.AddRange(ParticleEmitter.CreateParticleEmitterList(this.Model, componentInfo.ParticleEmitters));

            // Transformaciones iniciales
            this.m_BoneTransforms = new Matrix[this.Model.Bones.Count];
        }
Esempio n. 37
0
        private static void Blink()
        {
            Player player = Player.Instance();

            float heading = player.GetDirection().GetHeading();

            float currentX = player.GetX();
            float currentY = player.GetY();

            float distance = 150.0f;

            CollisionBox       bounds      = UserInterface.ScrollTransformBounds;
            OrthographicCamera camera      = JustCombat.WorldCamera;
            Vector2            worldCoords = camera.ScreenToWorld(bounds.GetPosX(), bounds.GetPosY());

            float boundWest  = worldCoords.X;
            float boundNorth = worldCoords.Y;
            float boundEast  = boundWest + bounds.GetWidth();
            float boundSouth = boundNorth + bounds.GetHeight();

            float cameraDiffX = 0;
            float cameraDiffY = 0;

            // North
            if (heading == 0)
            {
                float newY = (currentY - distance);
                float diff = (boundNorth - (newY + player.GetHeight()));

                if (diff > 0)
                {
                    cameraDiffY = -(diff);
                }

                player.Teleport(currentX, newY);
                camera.Move(new Vector2(cameraDiffX, cameraDiffY));
            }

            // East
            if (heading == 90)
            {
                float newX = (currentX + distance);
                float diff = (newX - boundEast);

                if (diff > 0)
                {
                    cameraDiffX = diff;
                }

                player.Teleport(newX, currentY);
                camera.Move(new Vector2(cameraDiffX, cameraDiffY));
            }

            // South
            if (heading == 180)
            {
                float newY = (currentY + distance);
                float diff = (newY - boundSouth);

                if (diff > 0)
                {
                    cameraDiffY = diff;
                }

                player.Teleport(currentX, newY);
                camera.Move(new Vector2(cameraDiffX, cameraDiffY));
            }

            // West
            if (heading == 270)
            {
                float newX = (currentX - distance);
                float diff = (boundWest - (newX + player.GetWidth()));

                if (diff > 0)
                {
                    cameraDiffX = -(diff);
                }

                player.Teleport(newX, currentY);
                camera.Move(new Vector2(cameraDiffX, cameraDiffY));
            }

            JustCombat.TransformMatrix = camera.GetViewMatrix();
        }
Esempio n. 38
0
        bool TryAttackEntity(double impactSpeed)
        {
            if (World is IClientWorldAccessor || World.ElapsedMilliseconds <= msCollide + 250)
            {
                return(false);
            }
            if (impactSpeed <= 0.01)
            {
                return(false);
            }

            EntityPos pos = SidedPos;

            Cuboidd projectileBox = CollisionBox.ToDouble().Translate(ServerPos.X, ServerPos.Y, ServerPos.Z);

            // We give it a bit of extra leeway of 50% because physics ticks can run twice or 3 times in one game tick
            if (ServerPos.Motion.X < 0)
            {
                projectileBox.X1 += 1.5 * ServerPos.Motion.X;
            }
            else
            {
                projectileBox.X2 += 1.5 * ServerPos.Motion.X;
            }
            if (ServerPos.Motion.Y < 0)
            {
                projectileBox.Y1 += 1.5 * ServerPos.Motion.Y;
            }
            else
            {
                projectileBox.Y2 += 1.5 * ServerPos.Motion.Y;
            }
            if (ServerPos.Motion.Z < 0)
            {
                projectileBox.Z1 += 1.5 * ServerPos.Motion.Z;
            }
            else
            {
                projectileBox.Z2 += 1.5 * ServerPos.Motion.Z;
            }

            Entity entity = World.GetNearestEntity(ServerPos.XYZ, 5f, 5f, (e) => {
                if (e.EntityId == this.EntityId || !e.IsInteractable)
                {
                    return(false);
                }

                if (FiredBy != null && e.EntityId == FiredBy.EntityId && World.ElapsedMilliseconds - msLaunch < 500)
                {
                    return(false);
                }

                Cuboidd eBox = e.CollisionBox.ToDouble().Translate(e.ServerPos.X, e.ServerPos.Y, e.ServerPos.Z);

                return(eBox.IntersectsOrTouches(projectileBox));
            });

            if (entity != null)
            {
                impactOnEntity(entity);
                return(true);
            }


            return(false);
        }
Esempio n. 39
0
    public Room(String roomFile)
    {
        TextAsset dataAsset = (TextAsset) Resources.Load (roomFile, typeof(TextAsset));

        if(!dataAsset) Debug.Log("missing room txt file.");

        Dictionary<string,object> hash = dataAsset.text.dictionaryFromJson();

        // Room Metadata
        _roomWidth = int.Parse(hash["width"].ToString());
        _roomHeight = int.Parse(hash["height"].ToString());
        _tileSize = int.Parse(hash["tilewidth"].ToString());

        //Debug.Log(_roomWidth +"||"+ _roomHeight +"||"+ _tileSize);

        //List<object> tilesetsList = (List<object>)hash["tilesets"];
        //Dictionary<string,object> tileset = (Dictionary<string,object>)tilesetsList[0];

        //string elementPath = tileset["image"].ToString();
        //string [] pathSplit = elementPath.Split(new Char [] {'/'});
        //string _tilesetElementName = pathSplit[pathSplit.Length-1];

        string[] pathSplit = roomFile.Split(new Char[] {'/'});
        roomName = pathSplit[pathSplit.Length -1];

        List<object> layersList = (List<object>)hash["layers"];

        for (int i=0; i < layersList.Count; i++)
        {
            Dictionary<string,object> layerHash = (Dictionary<string,object>)layersList[i];
            //int layerWidth = int.Parse (layerHash["width"].ToString());
            //int layerHeight = int.Parse (layerHash["height"].ToString());
            //int xOffset = int.Parse (layerHash["x"].ToString());
            //int yOffset = int.Parse (layerHash["y"].ToString());

            if (layerHash["name"].ToString().Equals("Objects"))
            {
                // Load object data if it exists...
                List<object> objectList = (List<object>)layerHash["objects"];

                for (int j=0; j < objectList.Count; j++)
                {
                    Dictionary<string,object> objHash = (Dictionary<string,object>)objectList[j];

                    if (objHash["type"].ToString().ToUpper().Equals("COLLISION"))
                    {
                        CollisionBox _cbox = new CollisionBox();
                        _cbox.name = objHash["name"].ToString();
                        _cbox.box.x = int.Parse(objHash["x"].ToString()) - (GetRoomWidth() / 2);
                        _cbox.box.y = -(int.Parse(objHash["y"].ToString()) - (GetRoomHeight() / 2));
                        _cbox.box.width = int.Parse(objHash["width"].ToString());
                        _cbox.box.height = int.Parse(objHash["height"].ToString());
                        _cbox.box.y = _cbox.box.y - _cbox.box.height;
                        _cbox.active = true;
                        collisionBoxList.Add(_cbox);
                    }

                    if (objHash["type"].ToString().ToUpper().Equals("PASSAGE"))
                    {
                        CollisionBox _cbox = new CollisionBox();
                        _cbox.name = objHash["name"].ToString();
                        _cbox.box.x = int.Parse(objHash["x"].ToString()) - (GetRoomWidth() / 2);
                        _cbox.box.y = -(int.Parse(objHash["y"].ToString()) - (GetRoomHeight() / 2));
                        _cbox.box.width = (int.Parse(objHash["width"].ToString()) == 0) ? 1 : int.Parse(objHash["width"].ToString());
                        _cbox.box.height = (int.Parse(objHash["height"].ToString()) == 0) ? 1 : int.Parse(objHash["height"].ToString());
                        _cbox.box.y = _cbox.box.y - _cbox.box.height;
                        _cbox.active = true;
                        passageBoxList.Add(_cbox);
                    }

                    if (objHash["type"].ToString().ToUpper().Equals("PASSAGE_OBJECT"))
                    {
                        CollisionBox _cbox = new CollisionBox();
                        _cbox.name = objHash["name"].ToString();
                        _cbox.box.x = int.Parse(objHash["x"].ToString()) - (GetRoomWidth() / 2);
                        _cbox.box.y = -(int.Parse(objHash["y"].ToString()) - (GetRoomHeight() / 2));
                        _cbox.box.width = int.Parse(objHash["width"].ToString());
                        _cbox.box.height = int.Parse(objHash["height"].ToString());
                        _cbox.box.y = _cbox.box.y - _cbox.box.height;
                        _cbox.active = true;
                        passageObjectBoxList.Add(_cbox);
                    }

                    if (objHash["type"].ToString().ToUpper().Equals("ENEMY_SPAWN"))
                    {
                        ObjectBox obox = new ObjectBox();
                        obox.name = objHash["name"].ToString();
                        obox.box.x = int.Parse(objHash["x"].ToString()) - (GetRoomWidth() / 2);
                        obox.box.y = -(int.Parse(objHash["y"].ToString()) - (GetRoomHeight() / 2));
                        obox.box.width = (int.Parse(objHash["width"].ToString()) == 0) ? 1 : int.Parse(objHash["width"].ToString());
                        obox.box.height = (int.Parse(objHash["height"].ToString()) == 0) ? 1 : int.Parse(objHash["height"].ToString());
                        obox.box.y = obox.box.y - obox.box.height;
                        enemySpawnBoxList.Add(obox);
                    }

                    if (objHash["type"].ToString().ToUpper().Equals("PLAYER_SPAWN"))
                    {
                        ObjectBox spawn = new ObjectBox();
                        spawn.name = objHash["name"].ToString();
                        spawn.box.x = int.Parse(objHash["x"].ToString()) - (GetRoomWidth() / 2);
                        spawn.box.y = -(int.Parse(objHash["y"].ToString()) - (GetRoomHeight() / 2));
                        spawn.box.width = (int.Parse(objHash["width"].ToString()) == 0) ? 1 : int.Parse(objHash["width"].ToString());
                        spawn.box.height = (int.Parse(objHash["height"].ToString()) == 0) ? 1 : int.Parse(objHash["height"].ToString());
                        spawn.box.y = spawn.box.y - spawn.box.height;
                        playerSpawnBox = spawn;
                    }
                }
            }
        }

        // non json related initiotion
        _floorSprite = new FSprite(roomName + ".png");
        AddChild(_floorSprite);

        // add mobs
        foreach(ObjectBox spawner in enemySpawnBoxList)
        {
            int mx = (int)spawner.box.x;
            int my = (int)spawner.box.y;
            Skeleton skeleton = new Skeleton(mx, my);
            mobList.Add(skeleton);
            AddChild(skeleton);
        }
    }
Esempio n. 40
0
        protected void ManageInput()
        {
            if (!IsUnableToMove)
            {
                IsIdle = true;
            }

            // Interaction
            if (Engine.InputManager.IsKeyDown(Key.F) && !IsUnableToMove)
            {
                if (!IsInteracting)
                {
                    IsMovingLeft  = false;
                    IsMovingRight = false;
                    IsIdle        = true;
                    IsInteracting = true;
                    Interact();
                    return;
                }
                else if (GameContext.Scene.CurrentInteration.Finished)
                {
                    IsInteracting  = false;
                    InteractTarget = null;
                    return;
                }
            }

            if (IsInteracting)
            {
                return;
            }

            // Movement
            if (Engine.InputManager.IsKeyHeld(Key.A) && !IsUnableToMove)
            {
                if (RunTimer.Progress == 0 && !IsMovingLeft && !IsMovingRight)
                {
                    RunTimer.GoNormal();
                    Sprite.Reset();
                }
                IsMovingLeft  = true;
                IsMovingRight = false;
                IsIdle        = false;
                IsFacingRight = false;
            }
            else
            {
                IsMovingLeft = false;
                if (!IsMovingLeft && !IsMovingRight)
                {
                    RunTimer.GoInReverse();
                    RunTimer.End();
                }
            }

            if (Engine.InputManager.IsKeyHeld(Key.D) && !IsUnableToMove)
            {
                if (RunTimer.Progress == 0 && !IsMovingLeft && !IsMovingRight)
                {
                    RunTimer.GoNormal();
                    Sprite.Reset();
                }
                IsMovingRight = true;
                IsMovingLeft  = false;
                IsIdle        = false;
                IsFacingRight = true;
            }
            else
            {
                IsMovingRight = false;
                if (!IsMovingLeft && !IsMovingRight)
                {
                    RunTimer.GoInReverse();
                    RunTimer.End();
                }
            }

            // Jumping
            if (Engine.InputManager.IsKeyHeld(Key.Space) && IsGrounded && !IsUnableToMove)
            {
                IsGrounded = false;
                IsJumping  = true;
                JumpTimer.GoInReverse();
                VelocityY = _jumpVelocity;
            }

            // Gravity Push
            if (Engine.InputManager.IsKeyHeld(Key.G) && IsGrounded && !IsUnableToMove)
            {
                IsIdle              = false;
                IsMovingLeft        = false;
                IsMovingRight       = false;
                IsUnableToMove      = true;
                IsGravityPushActive = true;

                Sprite.Reset();
            }

            // Magic Flow
            if (Engine.InputManager.IsKeyHeld(Key.H) && !IsUnableToMove && !IsMagicFlowActive)
            {
                // Set CurrentMagicFlow
                CurrentMagicFlow = CollisionUtils.RectangleIntesectsWithMagicFlow(CollisionBox.ToRectangle());
                if (CurrentMagicFlow == null)
                {
                    return;
                }

                if (CurrentMagicFlow.TraverseFirstToLast)
                {
                    // If traversing from first to last => start from Point A of the first segment
                    CurrentMagicFlowSegmentIndex = 0;
                    SetCollisionBoxX(CurrentMagicFlow.Segments[CurrentMagicFlowSegmentIndex].PointA.X - (CollisionBox.Width / 2));
                    SetCollisionBoxY(CurrentMagicFlow.Segments[CurrentMagicFlowSegmentIndex].PointA.Y - (CollisionBox.Height / 2));
                }
                else
                {
                    // If traversing from last to first => start from Point B of the last segment
                    CurrentMagicFlowSegmentIndex = CurrentMagicFlow.Segments.Count - 1;
                    SetCollisionBoxX(CurrentMagicFlow.Segments[CurrentMagicFlowSegmentIndex].PointB.X - (CollisionBox.Width / 2));
                    SetCollisionBoxY(CurrentMagicFlow.Segments[CurrentMagicFlowSegmentIndex].PointB.Y - (CollisionBox.Height / 2));
                }

                // TODO: Reset timers
                IsIdle            = false;
                IsMovingLeft      = false;
                IsMovingRight     = false;
                IsJumping         = false; // Reset jump timer
                IsFalling         = false;
                IsUnableToMove    = true;  // ?
                IsMagicFlowActive = true;

                Sprite.Reset();
            }

            // Debug
            // Teleport to X
            if (Engine.InputManager.IsKeyHeld(Key.LeftControl))
            {
                IsGrounded = true;
                IsFalling  = false;
                IsJumping  = false;
                JumpTimer.End();
                SetCollisionBoxY(500);
                SetCollisionBoxX(700);
            }
            else if (Engine.InputManager.IsKeyHeld(Key.RightControl))
            {
                IsGrounded = true;
                IsFalling  = false;
                IsJumping  = false;
                JumpTimer.End();
                SetCollisionBoxY(5100);
                SetCollisionBoxX(550);
            }

            if (Engine.InputManager.IsKeyDown(Key.Q))
            {
                CodeSwitch = !CodeSwitch;
                Console.WriteLine(CodeSwitch);
            }
        }
Esempio n. 41
0
        public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
        {
            IPhysicsObj absParent = otherBox.AbsParent as IPhysicsObj;

            if (collisionResponseType == Consts.COLLISIONRESPONSE_FIRSTBOXHIT)
            {
                if ((absParent.CollisionTypeTag == GameTypes.CollisionType_PLAYER || absParent.CollisionTypeTag == GameTypes.CollisionType_GLOBAL_DAMAGE_WALL || absParent.CollisionTypeTag == GameTypes.CollisionType_GLOBAL_DAMAGE_WALL && IsWeighted) &&
                    (!(otherBox.AbsParent is RogueAPI.Projectiles.ProjectileObj) && m_invincibleCounter <= 0f ||
                     otherBox.AbsParent is RogueAPI.Projectiles.ProjectileObj && (m_invincibleCounterProjectile <= 0f || (otherBox.AbsParent as RogueAPI.Projectiles.ProjectileObj).IgnoreInvincibleCounter))
                    )
                {
                    //Show demented question mark and return
                    if (IsDemented)
                    {
                        m_invincibleCounter           = InvincibilityTime;
                        m_invincibleCounterProjectile = InvincibilityTime;
                        RogueAPI.Effects.QuestionMarkEffect.Display(this);
                        //m_levelScreen.ImpactEffectPool.DisplayQuestionMark(new Vector2(X, Bounds.Top));
                        return;
                    }

                    int damage;
                    if (absParent is RogueAPI.Projectiles.ProjectileObj)
                    {
                        damage = (absParent as RogueAPI.Projectiles.ProjectileObj).Damage;
                    }
                    else
                    {
                        damage = (absParent as IDealsDamageObj).Damage;
                    }

                    //Apply critical damage
                    bool isPlayer = absParent == m_target;
                    if (isPlayer)
                    {
                        if (CDGMath.RandomFloat(0f, 1f) <= m_target.TotalCritChance && !NonKillable)
                        {
                            RogueAPI.Effects.CriticalTextEffect.Display(this);
                            //m_levelScreen.ImpactEffectPool.DisplayCriticalText(new Vector2(X, Bounds.Top));
                            damage = (int)(damage * m_target.TotalCriticalDamage);
                        }
                        m_invincibleCounter = InvincibilityTime;
                    }

                    //Destroy projectile
                    var projectileObj = otherBox.AbsParent as RogueAPI.Projectiles.ProjectileObj;
                    if (projectileObj != null)
                    {
                        m_invincibleCounterProjectile = InvincibilityTime;
                        if (projectileObj.DestroysWithEnemy && !NonKillable)
                        {
                            projectileObj.RunDestroyAnimation(false);
                        }
                    }

                    if (projectileObj != null || absParent.CollisionTypeTag != GameTypes.CollisionType_GLOBAL_DAMAGE_WALL || absParent.CollisionTypeTag == GameTypes.CollisionType_GLOBAL_DAMAGE_WALL && IsWeighted)
                    {
                        var allow = true;
                        if (projectileObj != null)
                        {
                            var kbAmount = CanBeKnockedBack && !IsPaused ? (KnockBack != Vector2.Zero ? KnockBack : m_target.EnemyKnockBack) : Vector2.Zero;
                            allow = projectileObj != null?projectileObj.OnCollision(this, false, kbAmount) : true;
                        }

                        if (allow)
                        {
                            Point center = (thisBox.AbsRotation != 0f || otherBox.AbsRotation != 0f)
                                ? Rectangle.Intersect(thisBox.AbsParent.Bounds, otherBox.AbsParent.Bounds).Center
                                : Rectangle.Intersect(thisBox.AbsRect, otherBox.AbsRect).Center;

                            HitEnemy(damage, new Vector2(center.X, center.Y), isPlayer);
                        }
                    }

                    ////Apply shout knockback
                    //if (projectileObj != null && projectileObj.Spell == SpellType.Shout)
                    //{
                    //    if (CanBeKnockedBack && !IsPaused)
                    //    {
                    //        float inertia = 3f;
                    //        var knockback = KnockBack != Vector2.Zero ? KnockBack : m_target.EnemyKnockBack;

                    //        CurrentSpeed = 0f;
                    //        AccelerationX = knockback.X * (X >= m_target.X ? inertia : -inertia);
                    //        AccelerationY = -knockback.Y * inertia;
                    //    }
                    //}
                    //else if (projectileObj != null || absParent.CollisionTypeTag != GameTypes.CollisionType_GLOBAL_DAMAGE_WALL || absParent.CollisionTypeTag == GameTypes.CollisionType_GLOBAL_DAMAGE_WALL && IsWeighted)
                    //{
                    //    Point center = (thisBox.AbsRotation != 0f || otherBox.AbsRotation != 0f)
                    //        ? Rectangle.Intersect(thisBox.AbsParent.Bounds, otherBox.AbsParent.Bounds).Center
                    //        : Rectangle.Intersect(thisBox.AbsRect, otherBox.AbsRect).Center;

                    //    HitEnemy(damage, new Vector2(center.X, center.Y), isPlayer);
                    //}
                }
            }
            else if (collisionResponseType == Consts.COLLISIONRESPONSE_TERRAIN)
            {
                if ((absParent.CollisionTypeTag == GameTypes.CollisionType_WALL || absParent.CollisionTypeTag == GameTypes.CollisionType_WALL_FOR_ENEMY || absParent.CollisionTypeTag == GameTypes.CollisionType_GLOBAL_DAMAGE_WALL) &&
                    CollisionTypeTag != GameTypes.CollisionType_ENEMYWALL)
                {
                    Vector2 vector2 = CollisionMath.CalculateMTD(thisBox.AbsRect, otherBox.AbsRect);

                    if (CurrentSpeed != 0f && vector2.X != 0f && Math.Abs(vector2.X) > 10f && (vector2.X > 0f && absParent.CollidesRight || vector2.X < 0f && absParent.CollidesLeft))
                    {
                        CurrentSpeed = 0f;
                    }


                    if (m_numTouchingGrounds <= 1 && CurrentSpeed != 0f && vector2.Y < 0f && !CanFallOffLedges)
                    {
                        if (Bounds.Left < absParent.Bounds.Left && HeadingX < 0f)
                        {
                            X            = absParent.Bounds.Left + (AbsX - Bounds.Left);
                            CurrentSpeed = 0f;
                        }
                        else if (Bounds.Right > absParent.Bounds.Right && HeadingX > 0f)
                        {
                            X            = absParent.Bounds.Right - (Bounds.Right - AbsX);
                            CurrentSpeed = 0f;
                        }

                        m_isTouchingGround = true;
                    }


                    if (AccelerationX != 0f && m_isTouchingGround)
                    {
                        AccelerationX = 0f;
                    }

                    bool flag1 = false;
                    if (Math.Abs(vector2.X) < 10f && vector2.X != 0f && Math.Abs(vector2.Y) < 10f && vector2.Y != 0f)
                    {
                        flag1 = true;
                    }

                    if (m_isTouchingGround && !absParent.CollidesBottom && absParent.CollidesTop && absParent.TerrainBounds.Top < TerrainBounds.Bottom - 30)
                    {
                        flag1 = true;
                    }

                    if (!absParent.CollidesRight && !absParent.CollidesLeft && absParent.CollidesTop && absParent.CollidesBottom)
                    {
                        flag1 = true;
                    }

                    Vector2 vector22 = CollisionMath.RotatedRectIntersectsMTD(thisBox.AbsRect, thisBox.AbsRotation, Vector2.Zero, otherBox.AbsRect, otherBox.AbsRotation, Vector2.Zero);
                    if (!flag1)
                    {
                        base.CollisionResponse(thisBox, otherBox, collisionResponseType);
                    }

                    if (vector22.Y < 0f && otherBox.AbsRotation != 0f && IsWeighted)
                    {
                        X -= vector22.X;
                    }
                }
            }
        }
 public override void SetDefaultValues()
 {
     Box = new CollisionBox();
     collidesWith = new List<string>();
     Origin = Vector2.Zero;
 }
 public override void SetDefaultValues()
 {
     Box = new CollisionBox();
 }
 public double radiantTo(CollisionBox target)
 {
     double deg = Math.Atan2(target.getCenter().X - cb.getCenter().X, target.getCenter().Y - cb.getCenter().Y ) - Math.PI / 2;
     return deg < 0 ? deg + Math.PI * 2 : deg > Math.PI * 2 ? deg - Math.PI * 2 : deg;
 }
 public override void SetDefaultValues()
 {
     Box = new CollisionBox();
 }
 public void Add(Sprite owner, CollisionBox box)
 {
     activeCollisionBoxes.Add(new CollisionBoxInfo{owner = owner, box = box});
 }
Esempio n. 47
0
 void Start()
 {
     _collisionBox = gameObject.GetComponent <CollisionBox>();
     _colManager   = FindObjectOfType <CollisionManager>();
     _colManager.AddEntity(0, _collisionBox);
 }
Esempio n. 48
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     Vector2 vector = CollisionMath.CalculateMTD(thisBox.AbsRect, otherBox.AbsRect);
     PlayerObj playerObj = otherBox.AbsParent as PlayerObj;
     if (playerObj != null && otherBox.Type == 0 && !playerObj.IsInvincible && playerObj.State != 3)
     {
         playerObj.HitPlayer(this);
     }
     if (this.m_isTouchingGround && this.m_isHurt)
     {
         this.m_isHurt = false;
         if (!this.m_inSecondForm)
         {
             this.ChangeSprite("PlayerIdle_Character");
         }
     }
     if (!(otherBox.AbsParent is EnemyObj_Platform))
     {
         base.CollisionResponse(thisBox, otherBox, collisionResponseType);
     }
     TerrainObj terrainObj = otherBox.AbsParent as TerrainObj;
     if (terrainObj != null && !this.m_isTouchingGround && !(terrainObj is DoorObj) && !this.m_inSecondForm)
     {
         if (this.m_currentActiveLB != null && this.m_currentActiveLB.IsActive)
         {
             this.m_currentActiveLB.StopLogicBlock();
         }
         if (vector.X > 0f)
         {
             base.RunLogicBlock(true, this.m_firstFormDashAwayLB, new int[]
             {
                 0,
                 100
             });
             return;
         }
         if (vector.X < 0f)
         {
             bool arg_11D_1 = true;
             LogicBlock arg_11D_2 = this.m_firstFormDashAwayLB;
             int[] array = new int[2];
             array[0] = 100;
             base.RunLogicBlock(arg_11D_1, arg_11D_2, array);
         }
     }
 }
Esempio n. 49
0
        public override void Input()
        {
            if (!ModalActive)
            {
                return;
            }

            IInputMap inputMap = Woofer.Controller.InputManager.ActiveInputMap;

            if (inputMap.Pulse.Consume())
            {
                Mode++;
                if ((MultipleAllowed && Mode > 3) || (!MultipleAllowed && Mode > 1))
                {
                    Mode = 0;
                }
                SelectionLocked = false;
            }

            if (Mode == Edit)
            {
                if (!SelectionLocked)
                {
                    UpdateSelected();
                    if (SelectedBox != null && inputMap.Jump.Consume())
                    {
                        SelectionLocked = true;
                    }
                }
                if (SelectionLocked)
                {
                    if (!CursorSystem.Dragging)
                    {
                        DraggingSide = -1;
                    }
                    FaceOutline.Bounds = new Rectangle(FaceOutline.Bounds?.X ?? 0, FaceOutline.Bounds?.Y ?? 0, 0, 0);

                    Rectangle selectedBounds = SelectedBox.ToRectangle() + Pivot;

                    if (CursorSystem.StartedDragging)
                    {
                        PreResizeBounds = selectedBounds;
                    }

                    int highlightedSide = UpdateSelectedFace();
                    if (highlightedSide != -1 && DraggingSide == -1 && CursorSystem.Dragging)
                    {
                        DraggingSide = highlightedSide;
                    }

                    if (CursorSystem.Dragging && DraggingSide == -1 && selectedBounds.Contains(CursorSystem.CursorPos))
                    {
                        DraggingSide = 4;
                    }

                    if (CursorSystem.Dragging && DraggingSide != -1 && PreResizeBounds != Rectangle.Empty)
                    {
                        if (DraggingSide == 3) //Left
                        {
                            double prevRight = SelectedBox.Right;
                            SelectedBox.X     = (CursorSystem.CursorPos.X - Pivot.X);
                            SelectedBox.Width = prevRight - SelectedBox.X;
                            if (SelectedBox.Width < 0)
                            {
                                double min = Math.Min(SelectedBox.Left, SelectedBox.Right);
                                double max = Math.Max(SelectedBox.Left, SelectedBox.Right);
                                SelectedBox.X     = min;
                                SelectedBox.Width = max - min;
                                DraggingSide      = 1;
                            }
                        }
                        else if (DraggingSide == 1) //Right
                        {
                            SelectedBox.Width = (CursorSystem.CursorPos.X - SelectedBox.X) - Pivot.X;

                            if (SelectedBox.Width < 0)
                            {
                                double min = Math.Min(SelectedBox.Left, SelectedBox.Right);
                                double max = Math.Max(SelectedBox.Left, SelectedBox.Right);
                                SelectedBox.X     = min;
                                SelectedBox.Width = max - min;
                                DraggingSide      = 3;
                            }
                        }
                        else if (DraggingSide == 2)   //Bottom
                        {
                            double prevTop = SelectedBox.Top;
                            SelectedBox.Y      = (CursorSystem.CursorPos.Y - Pivot.Y);
                            SelectedBox.Height = prevTop - SelectedBox.Y;
                            if (SelectedBox.Height < 0)
                            {
                                double min = Math.Min(SelectedBox.Bottom, SelectedBox.Top);
                                double max = Math.Max(SelectedBox.Bottom, SelectedBox.Top);
                                SelectedBox.Y      = min;
                                SelectedBox.Height = max - min;
                                DraggingSide       = 0;
                            }
                        }
                        else if (DraggingSide == 0) //Top
                        {
                            SelectedBox.Height = (CursorSystem.CursorPos.Y - SelectedBox.Y) - Pivot.Y;

                            if (SelectedBox.Height < 0)
                            {
                                double min = Math.Min(SelectedBox.Bottom, SelectedBox.Top);
                                double max = Math.Max(SelectedBox.Bottom, SelectedBox.Top);
                                SelectedBox.Y      = min;
                                SelectedBox.Height = max - min;
                                DraggingSide       = 2;
                            }
                        }
                        else if (DraggingSide == 4)  //Middle
                        {
                            SelectedBox.X = PreResizeBounds.X + (CursorSystem.CursorPos.X - CursorSystem.SelectionStart.X) - Pivot.X;
                            SelectedBox.Y = PreResizeBounds.Y + (CursorSystem.CursorPos.Y - CursorSystem.SelectionStart.Y) - Pivot.Y;
                        }
                    }
                }
            }
            else if (Mode == Create)
            {
                if (CursorSystem.StartedDragging)
                {
                    CollisionBox newBox = new CollisionBox(CursorSystem.SelectionRectangle - Pivot);
                    Boxes.Add(newBox);
                    IOutline newOutline = new CollisionBoxOutline(Pivot, newBox, Color.Orange);
                    Outlines.Add(newOutline);
                    Owner.Events.InvokeEvent(new BeginOverlay(newOutline));
                    Creating = true;
                }
                if (CursorSystem.Dragging && Creating)
                {
                    CollisionBox newBox = Boxes.Last();
                    newBox.X      = CursorSystem.SelectionRectangle.X - Pivot.X;
                    newBox.Y      = CursorSystem.SelectionRectangle.Y - Pivot.Y;
                    newBox.Width  = CursorSystem.SelectionRectangle.Width;
                    newBox.Height = CursorSystem.SelectionRectangle.Height;
                }
                if (CursorSystem.StoppedDragging && Creating)
                {
                    CollisionBox newBox = Boxes.Last();
                    if (newBox.Area == 0)
                    {
                        RemoveBox(newBox);
                    }
                    Creating = false;
                }
            }
            else if (Mode == Delete)
            {
                UpdateSelected();
                if (SelectedBox != null)
                {
                    IOutline associatedOutline = null;
                    foreach (IOutline outline in Outlines)
                    {
                        if (outline is CollisionBoxOutline boxOutline)
                        {
                            if (boxOutline.Box == SelectedBox)
                            {
                                boxOutline.Color     = Color.Red;
                                boxOutline.Thickness = 4;
                                associatedOutline    = outline;
                            }
                        }
                    }
                    if (inputMap.Jump.Consume())
                    {
                        RemoveBox(SelectedBox);
                    }
                }
            }
            else if (Mode == TweakFaces)
            {
                if (!SelectionLocked)
                {
                    UpdateSelected();
                    if (SelectedBox != null && inputMap.Jump.Consume())
                    {
                        SelectionLocked = true;
                    }
                }
                if (SelectionLocked)
                {
                    FaceOutline.Bounds = new Rectangle(FaceOutline.Bounds?.X ?? 0, FaceOutline.Bounds?.Y ?? 0, 0, 0);

                    int highlightedFace = UpdateSelectedFace();

                    if (highlightedFace != -1 && inputMap.Jump.Consume())
                    {
                        Owner.Events.InvokeEvent(new CollisionFaceSelectEvent(SelectedBox, highlightedFace));
                        Owner.Events.InvokeEvent(new ForceModalChangeEvent("collision_face_view", null));
                        CursorSystem.ModalActive = false;
                        ModalActive = false;
                    }
                }
            }
        }
Esempio n. 50
0
 public void TestCreate()
 {
     var cb = new CollisionBox(null, 1f, 1f);
 }
 public double degreeTo(CollisionBox target)
 {
     double deg = MathHelper.ToDegrees((float)(Math.Atan2(target.getCenter().X - cb.getCenter().X, target.getCenter().Y - cb.getCenter().Y) - Math.PI / 2));
     return deg < 0 ? deg + 360 : deg > 360 ? deg - 360 : deg;
 }
Esempio n. 52
0
 public CollisionFaceSelectEvent(CollisionBox box, int faceIndex) : base(null)
 {
     Box       = box;
     FaceIndex = faceIndex;
 }
Esempio n. 53
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
 }
Esempio n. 54
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     if (base.Difficulty == GameTypes.EnemyDifficulty.MINIBOSS && !this.m_bossVersionKilled)
     {
         PlayerObj playerObj = otherBox.AbsParent as PlayerObj;
         if (playerObj != null && otherBox.Type == 1 && !playerObj.IsInvincible && playerObj.State == 8)
         {
             playerObj.HitPlayer(this);
         }
     }
     base.CollisionResponse(thisBox, otherBox, collisionResponseType);
 }
Esempio n. 55
0
    public Room(String roomFile)
    {
        TextAsset dataAsset = (TextAsset)Resources.Load(roomFile, typeof(TextAsset));

        if (!dataAsset)
        {
            Debug.Log("missing room txt file.");
        }

        Dictionary <string, object> hash = dataAsset.text.dictionaryFromJson();

        // Room Metadata
        _roomWidth  = int.Parse(hash["width"].ToString());
        _roomHeight = int.Parse(hash["height"].ToString());
        _tileSize   = int.Parse(hash["tilewidth"].ToString());

        //Debug.Log(_roomWidth +"||"+ _roomHeight +"||"+ _tileSize);

        //List<object> tilesetsList = (List<object>)hash["tilesets"];
        //Dictionary<string,object> tileset = (Dictionary<string,object>)tilesetsList[0];

        //string elementPath = tileset["image"].ToString();
        //string [] pathSplit = elementPath.Split(new Char [] {'/'});
        //string _tilesetElementName = pathSplit[pathSplit.Length-1];

        string[] pathSplit = roomFile.Split(new Char[] { '/' });
        roomName = pathSplit[pathSplit.Length - 1];

        List <object> layersList = (List <object>)hash["layers"];

        for (int i = 0; i < layersList.Count; i++)
        {
            Dictionary <string, object> layerHash = (Dictionary <string, object>)layersList[i];
            //int layerWidth = int.Parse (layerHash["width"].ToString());
            //int layerHeight = int.Parse (layerHash["height"].ToString());
            //int xOffset = int.Parse (layerHash["x"].ToString());
            //int yOffset = int.Parse (layerHash["y"].ToString());

            if (layerHash["name"].ToString().Equals("Objects"))
            {
                // Load object data if it exists...
                List <object> objectList = (List <object>)layerHash["objects"];

                for (int j = 0; j < objectList.Count; j++)
                {
                    Dictionary <string, object> objHash = (Dictionary <string, object>)objectList[j];

                    if (objHash["type"].ToString().ToUpper().Equals("COLLISION"))
                    {
                        CollisionBox _cbox = new CollisionBox();
                        _cbox.name       = objHash["name"].ToString();
                        _cbox.box.x      = int.Parse(objHash["x"].ToString()) - (GetRoomWidth() / 2);
                        _cbox.box.y      = -(int.Parse(objHash["y"].ToString()) - (GetRoomHeight() / 2));
                        _cbox.box.width  = int.Parse(objHash["width"].ToString());
                        _cbox.box.height = int.Parse(objHash["height"].ToString());
                        _cbox.box.y      = _cbox.box.y - _cbox.box.height;
                        _cbox.active     = true;
                        collisionBoxList.Add(_cbox);
                    }

                    if (objHash["type"].ToString().ToUpper().Equals("PASSAGE"))
                    {
                        CollisionBox _cbox = new CollisionBox();
                        _cbox.name       = objHash["name"].ToString();
                        _cbox.box.x      = int.Parse(objHash["x"].ToString()) - (GetRoomWidth() / 2);
                        _cbox.box.y      = -(int.Parse(objHash["y"].ToString()) - (GetRoomHeight() / 2));
                        _cbox.box.width  = (int.Parse(objHash["width"].ToString()) == 0) ? 1 : int.Parse(objHash["width"].ToString());
                        _cbox.box.height = (int.Parse(objHash["height"].ToString()) == 0) ? 1 : int.Parse(objHash["height"].ToString());
                        _cbox.box.y      = _cbox.box.y - _cbox.box.height;
                        _cbox.active     = true;
                        passageBoxList.Add(_cbox);
                    }

                    if (objHash["type"].ToString().ToUpper().Equals("PASSAGE_OBJECT"))
                    {
                        CollisionBox _cbox = new CollisionBox();
                        _cbox.name       = objHash["name"].ToString();
                        _cbox.box.x      = int.Parse(objHash["x"].ToString()) - (GetRoomWidth() / 2);
                        _cbox.box.y      = -(int.Parse(objHash["y"].ToString()) - (GetRoomHeight() / 2));
                        _cbox.box.width  = int.Parse(objHash["width"].ToString());
                        _cbox.box.height = int.Parse(objHash["height"].ToString());
                        _cbox.box.y      = _cbox.box.y - _cbox.box.height;
                        _cbox.active     = true;
                        passageObjectBoxList.Add(_cbox);
                    }

                    if (objHash["type"].ToString().ToUpper().Equals("ENEMY_SPAWN"))
                    {
                        ObjectBox obox = new ObjectBox();
                        obox.name       = objHash["name"].ToString();
                        obox.box.x      = int.Parse(objHash["x"].ToString()) - (GetRoomWidth() / 2);
                        obox.box.y      = -(int.Parse(objHash["y"].ToString()) - (GetRoomHeight() / 2));
                        obox.box.width  = (int.Parse(objHash["width"].ToString()) == 0) ? 1 : int.Parse(objHash["width"].ToString());
                        obox.box.height = (int.Parse(objHash["height"].ToString()) == 0) ? 1 : int.Parse(objHash["height"].ToString());
                        obox.box.y      = obox.box.y - obox.box.height;
                        enemySpawnBoxList.Add(obox);
                    }

                    if (objHash["type"].ToString().ToUpper().Equals("PLAYER_SPAWN"))
                    {
                        ObjectBox spawn = new ObjectBox();
                        spawn.name       = objHash["name"].ToString();
                        spawn.box.x      = int.Parse(objHash["x"].ToString()) - (GetRoomWidth() / 2);
                        spawn.box.y      = -(int.Parse(objHash["y"].ToString()) - (GetRoomHeight() / 2));
                        spawn.box.width  = (int.Parse(objHash["width"].ToString()) == 0) ? 1 : int.Parse(objHash["width"].ToString());
                        spawn.box.height = (int.Parse(objHash["height"].ToString()) == 0) ? 1 : int.Parse(objHash["height"].ToString());
                        spawn.box.y      = spawn.box.y - spawn.box.height;
                        playerSpawnBox   = spawn;
                    }
                }
            }
        }

        // non json related initiotion
        _floorSprite = new FSprite(roomName + ".png");
        AddChild(_floorSprite);

        // add mobs
        foreach (ObjectBox spawner in enemySpawnBoxList)
        {
            int      mx       = (int)spawner.box.x;
            int      my       = (int)spawner.box.y;
            Skeleton skeleton = new Skeleton(mx, my);
            mobList.Add(skeleton);
            AddChild(skeleton);
        }
    }
Esempio n. 56
0
 public bool Equals(CollisionBox box)
 {
     return(position == box.position && size == box.size);
 }
Esempio n. 57
0
 public override void CollisionResponse(CollisionBox thisBox, CollisionBox otherBox, int collisionResponseType)
 {
     if (this.Spell == 20)
     {
         ProjectileObj projectileObj = otherBox.AbsParent as ProjectileObj;
         if (projectileObj != null && projectileObj.CollisionTypeTag != 2 && projectileObj.CanBeFusRohDahed)
         {
             projectileObj.RunDestroyAnimation(false);
         }
     }
     TerrainObj terrainObj = otherBox.Parent as TerrainObj;
     if (this.CollidesWithTerrain && !(otherBox.Parent is DoorObj) && terrainObj != null && ((terrainObj.CollidesTop && terrainObj.CollidesBottom && terrainObj.CollidesLeft && terrainObj.CollidesRight) || this.CollidesWith1Ways))
     {
         int spell = this.Spell;
         if (spell != 3)
         {
             if (spell == 7)
             {
                 base.CollisionResponse(thisBox, otherBox, collisionResponseType);
                 base.IsWeighted = false;
                 this.ActivateEffect();
                 return;
             }
             if (spell != 12)
             {
                 if (this.DestroysWithTerrain)
                 {
                     this.RunDestroyAnimation(false);
                     return;
                 }
                 base.AccelerationY = 0f;
                 base.AccelerationX = 0f;
                 base.IsWeighted = false;
                 return;
             }
             else
             {
                 Vector2 value = CollisionMath.RotatedRectIntersectsMTD(thisBox.AbsRect, thisBox.AbsRotation, Vector2.Zero, otherBox.AbsRect, otherBox.AbsRotation, Vector2.Zero);
                 if (value != Vector2.Zero)
                 {
                     SoundManager.Play3DSound(this, Game.ScreenManager.Player, new string[]
                     {
                         "Spike_Bounce_01",
                         "Spike_Bounce_02",
                         "Spike_Bounce_03"
                     });
                     Vector2 heading = base.Heading;
                     Vector2 vector = new Vector2(value.Y, value.X * -1f);
                     Vector2 pt = 2f * (CDGMath.DotProduct(heading, vector) / CDGMath.DotProduct(vector, vector)) * vector - heading;
                     base.X += value.X;
                     base.Y += value.Y;
                     base.Orientation = MathHelper.ToRadians(CDGMath.VectorToAngle(pt));
                     return;
                 }
             }
         }
         else if (terrainObj.CollidesBottom && terrainObj.CollidesTop && terrainObj.CollidesLeft && terrainObj.CollidesRight)
         {
             Vector2 vector2 = CollisionMath.RotatedRectIntersectsMTD(thisBox.AbsRect, thisBox.AbsRotation, Vector2.Zero, otherBox.AbsRect, otherBox.AbsRotation, Vector2.Zero);
             base.CollisionResponse(thisBox, otherBox, collisionResponseType);
             if ((vector2.Y <= 0f && vector2.X == 0f) || otherBox.AbsRotation != 0f)
             {
                 base.AccelerationY = 0f;
                 base.AccelerationX = 0f;
                 base.IsWeighted = false;
                 return;
             }
         }
         else if (!terrainObj.CollidesBottom && terrainObj.CollidesTop && !terrainObj.CollidesLeft && !terrainObj.CollidesRight)
         {
             Vector2 vector3 = CollisionMath.RotatedRectIntersectsMTD(thisBox.AbsRect, thisBox.AbsRotation, Vector2.Zero, otherBox.AbsRect, otherBox.AbsRotation, Vector2.Zero);
             if (vector3.Y <= 0f && base.AccelerationY > 0f)
             {
                 base.CollisionResponse(thisBox, otherBox, collisionResponseType);
                 if ((vector3.Y <= 0f && vector3.X == 0f) || otherBox.AbsRotation != 0f)
                 {
                     base.AccelerationY = 0f;
                     base.AccelerationX = 0f;
                     base.IsWeighted = false;
                     return;
                 }
             }
         }
     }
     else if (otherBox.Type != 0)
     {
         int spell2 = this.Spell;
         if (spell2 == 5)
         {
             if (otherBox.AbsParent == this.Target)
             {
                 base.CollisionTypeTag = 2;
                 return;
             }
         }
         else
         {
             base.CollisionResponse(thisBox, otherBox, collisionResponseType);
         }
     }
 }
        public override void HandleCollisionWithObject(Vector2 currentObjectOffset, CollisionBox collidingBox, GameObject otherObject,
                                                       Vector2 otherObjectOffset, CollisionBox otherCollidingBox)
        {
            _rebounded = false; // don't know if we need this here

            if (otherObject is TerrainObject)
            {
                var somethingNew = false;

                var directions = collidingBox.GetCollisionDirections(currentObjectOffset, otherCollidingBox, otherObjectOffset);
                var onTheFloor = false;

                var reboundDistance = otherCollidingBox.ReboundInShallowest(otherObjectOffset, collidingBox, currentObjectOffset);

                _totalReboundDistance += reboundDistance;
                _position             += reboundDistance;
                _rebounded             = true;

                if (directions.Contains(Directions.Up))
                {
                    _velocityPerFrame.Y = 0;
                }
                else if (directions.Contains(Directions.Down))
                {
                    _velocityPerFrame.Y = 0;
                    onTheFloor          = true;

                    if (_state == CharacterStates.Jump)
                    {
                        somethingNew = true;
                        ExecuteLand();
                    }

                    if (_velocityPerFrame.X != 0)
                    {
                        DecayXVelocity(((TerrainObject)otherObject).Friction);
                    }
                    else
                    if (_state != CharacterStates.Recoil && _okStand && _state != CharacterStates.Attack)     // this isn't going to work but just do this for now
                    {
                        // need to find some good way to get to stand without relying on velocity magnitude
                        _state = CharacterStates.Stand;
                        SetStandingAnimation();
                    }
                }

                if (directions.Contains(Directions.Left))
                {
                    _velocityPerFrame.X = 0;

                    if (onTheFloor)
                    {
                        if (_state == CharacterStates.Walk)
                        {
                            somethingNew = true;
                            BeginPush(Directions.Left);
                        }
                    }
                }
                else if (directions.Contains(Directions.Right))
                {
                    _velocityPerFrame.X = 0;

                    if (onTheFloor)
                    {
                        if (_state == CharacterStates.Walk)
                        {
                            somethingNew = true;
                            BeginPush(Directions.Right);
                        }
                    }
                }

                if (!somethingNew)
                {
                    ContinueCurrentExecution();
                }
            }
        }
Esempio n. 59
0
 public CollisionBoxOutline(Vector2D pivot, CollisionBox bounds, Color color) : this(pivot, bounds, color, 2)
 {
 }
Esempio n. 60
0
        bool TryAttackEntity(double impactSpeed)
        {
            if (World is IClientWorldAccessor || World.ElapsedMilliseconds <= msCollide + 250)
            {
                return(false);
            }
            if (impactSpeed <= 0.01)
            {
                return(false);
            }

            EntityPos pos = LocalPos;

            Cuboidd projectileBox = CollisionBox.ToDouble().Translate(ServerPos.X, ServerPos.Y, ServerPos.Z);

            if (ServerPos.Motion.X < 0)
            {
                projectileBox.X1 += ServerPos.Motion.X;
            }
            else
            {
                projectileBox.X2 += ServerPos.Motion.X;
            }
            if (ServerPos.Motion.Y < 0)
            {
                projectileBox.Y1 += ServerPos.Motion.Y;
            }
            else
            {
                projectileBox.Y2 += ServerPos.Motion.Y;
            }
            if (ServerPos.Motion.Z < 0)
            {
                projectileBox.Z1 += ServerPos.Motion.Z;
            }
            else
            {
                projectileBox.Z2 += ServerPos.Motion.Z;
            }


            Entity entity = World.GetNearestEntity(ServerPos.XYZ, 5f, 5f, (e) => {
                if (e.EntityId == this.EntityId || !e.IsInteractable)
                {
                    return(false);
                }

                if (FiredBy != null && e.EntityId == FiredBy.EntityId && World.ElapsedMilliseconds - msLaunch < 500)
                {
                    return(false);
                }

                Cuboidd eBox = e.CollisionBox.ToDouble().Translate(e.ServerPos.X, e.ServerPos.Y, e.ServerPos.Z);

                return(eBox.IntersectsOrTouches(projectileBox));
            });

            if (entity != null)
            {
                msCollide = World.ElapsedMilliseconds;

                entity.ReceiveDamage(new DamageSource()
                {
                    Source = EnumDamageSource.Entity, SourceEntity = this, Type = EnumDamageType.PiercingAttack
                }, Damage);

                float kbresist = entity.Properties.KnockbackResistance;
                entity.LocalPos.Motion.Add(kbresist * pos.Motion.X * Weight, kbresist * pos.Motion.Y * Weight, kbresist * pos.Motion.Z * Weight);

                World.PlaySoundAt(new AssetLocation("sounds/arrow-impact"), this, null, false, 32);

                int leftDurability = ProjectileStack == null ? 1 : ProjectileStack.Attributes.GetInt("durability", 1);

                if (World.Rand.NextDouble() < DropOnImpactChance && leftDurability > 0)
                {
                    pos.Motion.Set(0, 0, 0);
                }
                else
                {
                    Die();
                }
                return(true);
            }


            return(false);
        }