Esempio n. 1
0
        /// <summary>
        /// Frame Renewal, move actors and detect collisions
        /// </summary>
        /// <param name="gameTime">Snapshot of Timing values</param>
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            ICollidable[] activeCollidables = new ICollidable[_collidables.Count];
            _collidables.CopyTo(activeCollidables);

            foreach (ICollidable collider in activeCollidables)
            {
                foreach (ICollidable collidee in activeCollidables)
                {
                    if (collider.Equals(collidee))
                        continue;

                    // Boundingbox intersection using demorgen to see if two collidables overlap
                    if (collider.Position.X < (collidee.Position.X + collidee.Size.X) &&
                        (collider.Position.X + collider.Size.X) > collidee.Position.X &&
                        collider.Position.Y < (collidee.Position.Y + collidee.Size.Y) &&
                        (collider.Position.Y + collider.Size.Y) > collidee.Position.Y)
                        {
                            collider.HandleCollision(collidee);
                        }
                }
            }
        }
Esempio n. 2
0
        public override void Collided(ICollidable i_Collidable)
        {
            Bullet bullet = i_Collidable as Bullet;
            Enemy enemy = i_Collidable as Enemy;
            Sprite collidableSprite = i_Collidable as Sprite;
            List<Vector2> collidedPoints;
            bool autoPixelClear = true;
            if (bullet != null)
            {
                CollisionServices.eCollisionDirection collisionDirection = m_CollisionServices.GetCollisionDirection(this, collidableSprite);
                int halfBulletHeight = (int)(bullet.Height * 0.55);
                if (m_CollisionServices.IsPixelsIntersect(this, collidableSprite, out collidedPoints, !autoPixelClear))
                {
                    m_HitSound.Play();
                    Sprite barrier = this as Sprite;
                    m_CollisionServices.ClearPixelsInVerticalDirection(ref barrier, collidedPoints, collisionDirection, halfBulletHeight);
                    this.GameScreen.Remove(bullet);
                    bullet.Dispose();
                }
            }

            if (enemy != null)
            {
                m_CollisionServices.IsPixelsIntersect(this, collidableSprite, out collidedPoints, autoPixelClear);
            }
        }
 /// <summary>
 /// Determines whether the specified _other has collided.
 /// @see AddAsteroid
 /// @see CalculateNewRotations
 /// </summary>
 /// <param name="_other">The _other.</param>
 public override void HasCollided(ICollidable _other)
 {
     if (_other.GetType() == typeof(MediumAsteroid))
     {
         if (isMergeable)
         {
             drawn = false;
             MediumAsteroid other = (MediumAsteroid)_other;
             other.isMergeable = false;
             other.drawn = false;
             foreach (IObjectAdderObserver observer in objectObservers)
             {
                 observer.AddAsteroid(AsteroidFactory.createNewAsteroid(1, position, RandomGenerator.GetRandomFloat(0, 6.283)));
             }
         }
     }
     else if (_other.GetType() == typeof(Bullet))
     {
         drawn = false;
         float[] rotationsValue = CalculateNewRotations(this, (Bullet)_other);
         foreach (IObjectAdderObserver observer in objectObservers)
         {
             observer.AddAsteroid(AsteroidFactory.createNewAsteroid(3, position, rotationsValue[0] + Rotation));
             observer.AddAsteroid(AsteroidFactory.createNewAsteroid(3, position, rotationsValue[1] + Rotation));
         }
     }
 }
Esempio n. 4
0
        public override bool ActivateBlock(Vector2 direction, ICollidable ob)
        {

            IMario sender = ob as IMario;

            if (ob == null) return false;
            if (!(direction.Y > Utility.ZERO)) return false;
            
            if (sender != null && sender.IsBig())
            {
                SoundManager.PlayBreakingSound();
                SprintFourGame.GetInstance().Components.Remove(Block);
                if(!SprintFourGame.GetInstance().LevelIsInfinite)
                    Levels.Level.BlockGrid[(int)Block.Position.X / Utility.BLOCK_POSITION_SCALE, (int)Block.Position.Y / Utility.BLOCK_POSITION_SCALE] = new NullBlock();
            } 
            else 
            {
                nudged = true;
                delay = Utility.DELAY;
            }
            Block.Position = new Vector2(Block.Position.X, Block.Position.Y - Utility.BLOCK_NUDGED_DISTANCE);
            foreach (IEnemy enemy in CollisionDetectionManager.EnemyList.Where(enemy => enemy.Bounds.Intersects(Block.Bounds))) { 
                enemy.Kill();
                SoundManager.PlayKickSound();
                }
            return true;
        }
        public override bool CanCollide(ICollidable object1, ICollidable object2)
        {
            ICollidableCircle typeCorrectedObject1 = object1 as ICollidableCircle;
            ICollidableCircle typeCorrectedObject2 = object2 as ICollidableCircle;

            return (typeCorrectedObject1 != null && typeCorrectedObject2 != null);
        }
Esempio n. 6
0
 public Collider(ICollidable owner, Rectangle bounds, ColliderType type, int npc_id)
 {
     this.m_owner = owner;
     this.m_bounds = new DoubleRect(bounds.X, bounds.Y, bounds.Width, bounds.Height);
     this.m_type = type;
     this.m_npc_id = npc_id;
 }
Esempio n. 7
0
 public override bool ActivateBlock(Vector2 direction, ICollidable ob)
 {
     
     Mario mario = ob as Mario;
     if(mario != null) mario.Kill();
     return true;
 }
 void IBlockState.Collide(ICollidable otherObject)
 {
     if (CollisionHelper.GetCollisionSide(block, otherObject) == CollisionSide.Top)
     {
         otherObject.TakeDamage(otherObject, 0);
     }
 }
Esempio n. 9
0
        /// <summary>
        /// Creates a new primitive line object.
        /// </summary>
        public PrimitiveLine(ICollidable obj = null)
        {
            // create pixels
            pixel = new Texture2D(G.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            var pixels = new Color[1];
            pixels[0] = Color.White;
            pixel.SetData(pixels);

            Colour = Color.White;
            Position = new Vector2(0, 0);
            Depth = 0;

            vectors = new ArrayList();

            if (obj != null)
            {
                switch (obj.Shape.Type)
                {
                    case ShapeType.Circle:
                        CreateCircle((Circle) obj.Shape);
                        break;
                    case ShapeType.Rectangle:
                        CreateRectangle((Rectangle) obj.Shape);
                        break;
                }
                shape = obj.Shape;
                this.obj = obj;
            }
        }
        public override void Collided(ICollidable i_Collidable)
        {
            PixelSensitiveSprite pixelSensitiveSpriteHitRectangle = i_Collidable as PixelSensitiveSprite;
            if (pixelSensitiveSpriteHitRectangle is Bullet)
            {
                Rectangle bulletHitRectangle;
                if (pixelSensitiveSpriteHitRectangle.Velocity.Y < 0)
                {
                    bulletHitRectangle = new Rectangle(pixelSensitiveSpriteHitRectangle.Bounds.Left,
                        (int)(pixelSensitiveSpriteHitRectangle.Bounds.Top - k_BulletHitPercentage * pixelSensitiveSpriteHitRectangle.Bounds.Height), pixelSensitiveSpriteHitRectangle.Bounds.Width,
                        (int)(pixelSensitiveSpriteHitRectangle.Bounds.Height));

                }
                else
                {
                    bulletHitRectangle = new Rectangle(pixelSensitiveSpriteHitRectangle.Bounds.Left,
                        (int)(pixelSensitiveSpriteHitRectangle.Bounds.Top + k_BulletHitPercentage * pixelSensitiveSpriteHitRectangle.Bounds.Height), pixelSensitiveSpriteHitRectangle.Bounds.Width,
                        (int)(pixelSensitiveSpriteHitRectangle.Bounds.Height));

                }

                handleSpriteCollision(pixelSensitiveSpriteHitRectangle, bulletHitRectangle);
                m_SoundManager.PlaySoundEffect(Sounds.k_BarrierHit);
                onBarrierHit();
            }

            Invader invader = i_Collidable as Invader;
            if (invader != null)
            {
                RemoveFromTexture(invader.Bounds);
                onBarrierHit();
            }

            Texture.SetData(Pixels);
        }
Esempio n. 11
0
        public CollilisionPair(ICollidable object1, ICollidable object2)
        {
            if (object1 == object2) { throw new InvalidOperationException("Cannot collide an object with itself."); }

            this.Object1 = object1;
            this.Object2 = object2;
        }
Esempio n. 12
0
        public void Add(ICollidable obj)
        {
            if(!IsDivided())
            {
                Objects.Add(obj);

                if (obj.Primary)
                    PrimaryCount++;

                if (PrimaryCount > 0 && Objects.Count > Threshold && Divide())
                {
                    Add(Objects);
                    Objects.Clear();
                }

            }
            else
            {
                for (int i = 0; i < Children.Length; i++)
                {
                    if (Children[i].Enabled && Children[i].QuadIntersects(obj.Shape))
                    {
                        Children[i].Add(obj);
                    }
                }
            }
        }
Esempio n. 13
0
 // handles specific collisonbehaviour
 public void OnCollision(ICollidable collidable) {
     if (_t2.ElapsedMilliseconds <= 300) return;
     if (!(collidable is Apple)){
         SendDeath(this);
     }
     Body.Add(new Vector2D(Body[Body.Count - 1].X, Body[Body.Count - 1].Y));
 }
            /// <summary>
            /// Determines if two objects have collided using Axis-Aligned Bounding Box
            /// </summary>
            /// <param name="first">The first object to check.</param>
            /// <param name="second">The second object to check.</param>
            /// <returns>True if a collision was detected, false otherwise.</returns>
            /// <remarks>
            /// https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
            ///
            ///    Ax,Ay                    Bx,By
            ///      ---------------          ---------------
            ///      -             -          -             -
            ///      -             -          -             -
            ///      -             -          -             -
            ///      -             -          -             -
            ///      ---------------          ---------------
            ///                  AX,AY                     BX,BY
            ///
            /// They are seperate if any of these statements are true:
            ///
            ///  AX is less than Bx
            ///  BX is less than Ax
            ///  AY is less than By
            ///  BY is less than Ay
            ///
            /// </remarks>
            public static CollisionResult CheckForCollision(ICollidable first, ICollidable second, Vector2 velocity)
            {
                if (first == null)
                                {
                                        throw new ArgumentNullException("first");
                                }

                                if (second == null)
                                {
                                        throw new ArgumentNullException("second");
                                }

                                Rectangle a = first.BoundingBox;
                                Rectangle b = second.BoundingBox;

                                //bool haveCollided = !(a.Right < b.X
                                //         || b.Right < a.X
                                //         || a.Bottom < b.Y
                                //         || b.Bottom < a.Y);

                                bool haveCollided = (a.Right > b.X && b.Right > a.X && a.Bottom > b.Y && b.Bottom > a.Y);

                                a.Offset(Convert.ToInt32(velocity.X), Convert.ToInt32(velocity.Y));
                                bool willCollided = (a.Right > b.X && b.Right > a.X && a.Bottom > b.Y && b.Bottom > a.Y);

                                CollisionResult collisionResult = new CollisionResult();
                                collisionResult.HaveCollided = haveCollided;
                                collisionResult.WillCollide = willCollided;
                                collisionResult.CorrectionVector = null;
                                return collisionResult;
            }
Esempio n. 15
0
        public void Collided(ICollidable other)
        {
            if (other == _world)
            {
                //Console.WriteLine("Velocity " + _fsBody.LinearVelocity.Y);
                if (Math.Abs(_fsBody.LinearVelocity.Y) < 1 && behaviorState == BehaviorState.Flying)
                {
                    this.behaviorState = BehaviorState.Walking;
                }
                else if (_fsBody.LinearVelocity.Y < -20 && behaviorState == BehaviorState.Flying)
                {
                    this.behaviorState = BehaviorState.Dead;
                    myCorpse.SetAnimationState(CivvieSprite.AnimationState.Dead);
                }

                if (this.behaviorState == BehaviorState.Dead)
                {
                    _world.StopPhysicsing(_fsBody);
                }
            }

            if (other is CivvieController)
            {
                var otherCivvie = other as CivvieController;
                if (otherCivvie._fsBody.LinearVelocity.Length() > 50)
                {
                    otherCivvie.Die();
                    this.Die();
                }
            }
        }
Esempio n. 16
0
		public void Reset(double x, double y)
		{
			this.collider.X = x;
			this.collider.Y = y;
			this.grounded = false;
			this.groundCache = null;
			this.velocityY = 0;
		}
Esempio n. 17
0
 public void AddEntity(ICollidable entity)
 {
     if (!collidableEntities.Contains(entity))
     {
         collidableEntities.Add(entity);
         hashmap.Add(new TaggedVector { Position = new Vector2(entity.Hitbox.X, entity.Hitbox.Y),Identifier = entity });
     }
 }
Esempio n. 18
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="collider"></param>
        public override void StartTouch(ICollidable collider)
        {
            if (collider.GetType() != typeof(Player))
                return;

            if (State.WaterDropsLeft == 0)
                State.End();
        }
Esempio n. 19
0
 public override bool ActivateBlock(Vector2 direction, ICollidable ob)
 {
     if (!(ob is IMario)) return false;
     SoundManager.PlayItemSound(item);
     item.Spawn(Block.Position);
     Block.ChangeState(new UsedBlockState());
     return true;
 }
Esempio n. 20
0
        /// <summary>
        /// Handles a collision with a ball, removes a live from a player
        /// </summary>
        /// <param name="other"></param>
        public void HandleCollision(ICollidable other)
        {
            if (other.GetType() != typeof(Ball))
                return;

            this.Player.Lives--;
            this.Level.Reset();
        }
Esempio n. 21
0
 /// <summary>
 /// Removes Nodes in the graph that are within the bounds of <paramref name="collidable"/>
 /// </summary>
 /// <param name="collidable">the object within which to remove nodes</param>
 public void Cull(ICollidable collidable)
 {
     WorldObject obj = collidable.GetObject();
     Vector3 position = ZeroY(obj.GameObject.transform.position);
     Vector3 size = ZeroY(obj.Size);
     List<Node> culled = getCulledNodes(position, size);
     removeCulledNodes(culled);
 }
Esempio n. 22
0
 public override void Collide(ICollidable otherObject)
 {
     if (otherObject.AABB.Bottom > AABB.Top && active)
     {
         otherObject.BlockMovement(this);
         otherObject.TakeDamage(this, Damage);
     }
 }
Esempio n. 23
0
        public void CheckCollision(ICollidable target)
        {
            if (target is LaserBullet)
                CheckLaserBulletCollision((LaserBullet)target);

            if (target is Ship)
                CheckShipCollision((Ship)target);
        }
Esempio n. 24
0
 public Collider(ICollidable owner, Rectangle bounds, ColliderType type)
 {
     this.m_owner = owner;
     this.m_bounds = new DoubleRect(bounds.X, bounds.Y, bounds.Width, bounds.Height);
     this.m_bounds2 = new DoubleRect(bounds.X - 5, bounds.Y - 5, bounds.Width + 10, bounds.Height + 10);
     this.m_type = type;
     this.m_other = null;
 }
Esempio n. 25
0
        public override void CollisionOccured(ICollidable collisionObject)
        {
            if (collisionObject == SourceComponent) {
                return;
            }

            base.CollisionOccured(collisionObject);
        }
Esempio n. 26
0
        public List<ICollidable> CandidatePairs(ICollidable obj)
        {
            List<ICollidable> list;
            if (_candidatePairs.TryGetValue(obj, out list))
                return list;

            return _empty;
        }
Esempio n. 27
0
        public void DoObjectHit(ICollidable obj, ICollidable by)
        {
            Bullet b = by as Bullet;

            if (b == null)
                return;

            b.DoHit((ILivingObject) obj);
        }
Esempio n. 28
0
 public void collision(ICollidable other)
 {
     if (!collected)
     {
         collected = true;
         game.Components.Remove(this);
         game.getMusicPlayer().addTrack();
     }
 }
Esempio n. 29
0
 public void AddObjectToMonitor(ICollidable i_Collidable)
 {
     if (!m_Collidables.Contains(i_Collidable))
     {
         m_Collidables.Add(i_Collidable);
         i_Collidable.PositionChanged += collidable_PositionChanged;
         i_Collidable.Disposed += collidable_Disposed;
     }
 }
        public override void BlockMovement(ICollidable otherObject)
        {
            if (CollisionHelper.GetCollisionSide(megaman, otherObject) == CollisionSide.Top)
            {
                megaman.ActionStateMachine.GetActionState(ActionState.Falling).Enter();
            }

            base.BlockMovement(otherObject);
        }
Esempio n. 31
0
        /// <summary>
        /// Updates the values of this class and sends information back to the getSetEntity
        /// </summary>
        public override void Update()
        {
            if (DisplayM.timer.TotalGameTime.Seconds > startTime + timeDelay)
            {
                canAction = true;
            }

            //mouseDevice.getRotationFromEntity(getSetEntity);

            Vector2 p1Velocity = keyboardDevice.GetKeyboardInputDirection(PlayerIndex.One);

            getSetStateMachine.getSetCurrentState.RunBehaviour(this, p1Velocity);
            getSetMoveVector.Normalize();

            if (physicsCollide)
            {
                Vector2 temp = getSetMoveVector;

                if (getSetStateMachine.getSetPreviousState == BehaviourM.getInstance.GetState("WalkUp"))
                {
                    temp.Y = 1;
                }
                else if (getSetStateMachine.getSetPreviousState == BehaviourM.getInstance.GetState("WalkDown"))
                {
                    temp.Y = -1;
                }
                else if (getSetStateMachine.getSetPreviousState == BehaviourM.getInstance.GetState("WalkLeft"))
                {
                    temp.X = 1;
                }
                else if (getSetStateMachine.getSetPreviousState == BehaviourM.getInstance.GetState("WalkRight"))
                {
                    temp.X = -1;
                }
                //getSetMoveVector *= -1;

                getSetMoveVector = temp;
            }

            // Force equals Mass multiplied by Acceleration
            getSetAcceleration += PhysicsM.getInstance.getSetInputForce * inVerseMass; //* mePhysical.getSetMass;
            // Speed/Velocity equals acceleration multiplied by delta time in seconds
            getSetSpeed += getSetAcceleration;                                         //* (float)DisplayM.timer.ElapsedGameTime.TotalSeconds;
            getSetSpeed *= PhysicsM.damping;

            getSetAcceleration = 0;

            if (getSetSpeed < 0)
            {
                getSetSpeed = 0;
            }
            float rotation = 0.0f;

            if (rotation > Math.PI || rotation < -Math.PI)
            {
                rotation *= -1;
            }

            mPos += getSetMoveVector * getSetSpeed; //* (float)DisplayM.timer.ElapsedGameTime.TotalSeconds;

            physicsCollide = false;

            //getSetMoveVector = Vector2.Zero;

            ICollidable c = (ICollidable)getSetEntity;

            c.RaiseBoundsChanged();

            getSetLocation = mPos;
            base.Update(mPos);
        }
Esempio n. 32
0
 public MarioWithHiddenBlockRightCollisionResponse(ICollision collision)
 {
     firstEntity    = collision.FirstEntity;
     secondEntity   = (IBlock)collision.SecondEntity;
     this.collision = collision;
 }
Esempio n. 33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Collision"/> class.
 /// </summary>
 /// <param name="target">The target.</param>
 /// <param name="other">The other.</param>
 public Collision(ICollidable target, ICollidable other)
 {
     Target = target;
     Other  = other;
 }
Esempio n. 34
0
 public void OnCollidedWith(ICollidable collidableObject)
 {
     //npc collisions don't do anything but npcs must implement ientity
 }
Esempio n. 35
0
 public void ProjectileCollision(ICollidable collidable)
 {
     TakeDamage(((IProjectile)collidable).GetDamage());
 }
Esempio n. 36
0
        internal static bool CheckElementCollision(ICollidableElement element, ICollidable other)
        {
            #region Argument Check

            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            if (other == null)
            {
                throw new ArgumentNullException("other");
            }

            #endregion

            if (element.HasRoughPrimitives)
            {
                var canCollide      = false;
                var roughPrimitives = element.GetRoughPrimitives().EnsureNotNull();
                if (roughPrimitives.Count <= 0)
                {
                    throw new InvalidOperationException(
                              string.Format(
                                  "The element {{{0}}} has empty rough primitives collection.",
                                  element));
                }

                // ReSharper disable once LoopCanBeConvertedToQuery
                // ReSharper disable once ForCanBeConvertedToForeach
                for (var index = 0; index < roughPrimitives.Count; index++)
                {
                    var roughPrimitive = roughPrimitives[index];
                    if (roughPrimitive.HasCollision(other))
                    {
                        canCollide = true;
                        break;
                    }
                }

                if (!canCollide)
                {
                    return(false);
                }
            }

            var primitives = element.GetPrimitives().EnsureNotNull();
            if (primitives.Count <= 0)
            {
                throw new InvalidOperationException(
                          string.Format(
                              "The element {{{0}}} has empty primitives collection.",
                              element));
            }

            // ReSharper disable once LoopCanBeConvertedToQuery
            // ReSharper disable once ForCanBeConvertedToForeach
            for (var index = 0; index < primitives.Count; index++)
            {
                var primitive = primitives[index];
                if (CheckPrimitiveCollision(primitive, other))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 37
0
 private void SetUpCollider(ICollidable collider)
 {
     collider.SetAttachedPhysicsBody(this);
     collider.CalculateStaticParameters();
 }
Esempio n. 38
0
 public RTSUnitData(int i)
 {
     Index            = i;
     ICollidableShape = new CollisionCircle(1f, Vector2.Zero, false);
 }
Esempio n. 39
0
 public void ItemCollision(ICollidable collidable)
 {
     //default implentation: do nothing
 }
Esempio n. 40
0
 public void ProjectileCollision(ICollidable collidable)
 {
     //default implentation: do nothing
 }
Esempio n. 41
0
 public void WaterCollision(ICollidable collidable)
 {
     //do nothing, item won't spawn on water
 }
Esempio n. 42
0
 public void PlayerCollision(ICollidable collidable)
 {
     BlockCollision(collidable);
 }
Esempio n. 43
0
 public OnCollisionEventArgs(ICollidable collider, ICollidable with)
 {
     this.With     = with;
     this.Collider = collider;
 }
Esempio n. 44
0
 public void Collision(ICollidable gameObject)
 {
 }
Esempio n. 45
0
 private void OnBirdGroundCollided(ICollidable bird, ICollidable ground)
 {
     bird.OnCollideWith(ground);
     CheckGameOver();
 }
Esempio n. 46
0
 private void OnBirdPipesCollided(ICollidable bird, ICollidable pipe)
 {
     bird.OnCollideWith(pipe);
     CheckGameOver();
 }
Esempio n. 47
0
 public void ItemCollision(ICollidable collidable)
 {
 }
Esempio n. 48
0
 /// <summary>
 /// Called when a collision happens.
 /// </summary>
 /// <param name="targetOfCollision">The target of collision.</param>
 public void OnCollision(ICollidable targetOfCollision)
 {
     // Nothing happens... I WIN!
 }
Esempio n. 49
0
 public void EnemyCollision(ICollidable collidable)
 {
     BlockCollision(collidable);
 }
Esempio n. 50
0
 public void HandleCollision(ICollidable collider)
 {
 }
Esempio n. 51
0
 public override void PlayerCollision(ICollidable collidable)
 {
     ((IPlayer)collidable).GetInventory().Rupees++;
     Consume();
 }
Esempio n. 52
0
 /// <summary>
 /// Registers an object that can be added to this service.
 /// TODO: Must be removed from here if its marked for deletion
 /// </summary>
 /// <param name="name"></param>
 /// <param name="gameObject"></param>
 public void RegisterGameObject(string name, ICollidable gameObject)
 {
     //Console.WriteLine(name);
     Add(name, gameObject);
 }
Esempio n. 53
0
 public override void OnCollision(ICollidable collider)
 {
     Debug.WriteLine("Player collision");
 }
Esempio n. 54
0
 public Path(int x, int y, ICollidable member) : base(x, y)
 {
 }
Esempio n. 55
0
 /// <summary>
 /// Constructor instantiates the position in the base
 /// </summary>
 public PenPath(int x, int y) : base(x, y)
 {
     this.member = null;
 }
Esempio n. 56
0
 public override void CollisionResponseTop(ICollidable collidable)
 {
     base.CollisionResponseTop(collidable);
     //this is where he can go into the bonus level
 }
Esempio n. 57
0
        /// <summary>METHOD: to detect an instance of AABB collision</summary>
        /// <param name="item1">the first item colliding</param>
        /// <param name="item2">the second item colliding</param>
        /// <param name="velocity">the velocity of the player colliding</param>
        /// <returns>a bool that tells us whether a collision is occuring</returns>
        public bool Detect(ICollidable entity1, ICollidable entity2, Vector2 velocity)
        {
            // CREATE: a bool to check if the entities will ever collide
            bool WillIntersect = true;
            // CREATE: a bool to check if the entities are colliding
            bool Intersect = true;

            // STORE: the number of edges for each shape
            int edgeCount1 = entity1.Edges.Count;
            int edgeCount2 = entity2.Edges.Count;

            // CREATE: a vector to store the current edge
            Vector2 thisEdge;

            // SET: a minimum interval distance to be infinity
            float minIntervalDistance = float.PositiveInfinity;
            // CREATE: a translation axis
            Vector2 translationAxis = Vector2.Zero;

            // FOR: every edge of both shapes
            for (int edgeIndex = 0; edgeIndex < edgeCount1 + edgeCount2; edgeIndex++)
            {
                // IF: the edge index is less than the number of edges for the first shape
                if (edgeIndex < edgeCount1)
                {
                    // SET: the current edge to be this edge
                    thisEdge = entity1.Edges[edgeIndex];
                }
                else
                {
                    // OTHERWISE: set the current edge to be an edge on the second shape
                    thisEdge = entity2.Edges[edgeIndex - edgeCount1];
                }

                // CREATE: an axes the shapes will be drawn on, normalize it
                Vector2 axis = new Vector2(-thisEdge.Y, thisEdge.X);
                axis.Normalize();

                // DEFINE, some minimum and maximum points for the projection
                float min1 = 0;
                float min2 = 0;
                float max1 = 0;
                float max2 = 0;

                // PROJECT: the first shape onto the axis
                Projection(axis, entity1, ref min1, ref max1);
                // PROJECT: the second shape onto the axis
                Projection(axis, entity2, ref min2, ref max2);

                // IF: the interval distance is bigger than zero
                if (IntervalDistance(min1, max1, min2, max2) > 0)
                {
                    // THEN: they are not intersecting
                    Intersect = false;
                }

                //int speedOffset = 3;
                // CREATE: a velocity projection using the dot product of the axis and the current velocity
                float velocityProjection = Vector2.Dot(axis, velocity);    // + speedOffset;

                // IF: the velocity project is less than zero
                if (velocityProjection < 0)
                {
                    // THEN: the minimum will be set
                    min1 += velocityProjection;
                }
                else
                {
                    // ELSE: the maximum will be set
                    max1 += velocityProjection;
                }

                // CREATE a new interval distance, setting it with the new min/max
                float intervalDistance = IntervalDistance(min1, max1, min2, max2);

                // IF: the new interval distance is more than zero
                if (intervalDistance > 0)
                {
                    // THEN: they will not collide
                    WillIntersect = false;
                }

                // RESET: the new interval distance to an absolute float, so it can occur on all sides
                intervalDistance = Math.Abs(intervalDistance);
                // IF: the new interval distance is less than the minimum interval distance
                if (intervalDistance < minIntervalDistance)
                {
                    // SET: the minimum to eqaul the new interval distance
                    minIntervalDistance = intervalDistance;
                    // AND: set the translation axis to be the normal axis
                    translationAxis = axis;

                    // CREATE: a vector to store the distance of the two shapes, comparing their centre points
                    Vector2 distance = entity1.CentrePoint - entity2.CentrePoint;

                    // IF: the distance on the x axis, or y axis is shorted than zero
                    if (distance.X < 0 || distance.Y < 0)
                    {
                        // THEN: the overlap is equal to the inverted distance
                        overlap = -distance;
                    }

                    // IF: the dot product of the distance and the translation axis is less than 0
                    if (Vector2.Dot(distance, translationAxis) < 0)
                    {
                        // INVERT: the translation axis
                        translationAxis = -translationAxis;
                    }
                }
            }

            // IF: the shapes are going to intersect
            if (WillIntersect)
            {
                // THEN: set the MTV to equal the translation axis multiplied by the minimum interval distance
                MinimumTranslationVector = translationAxis * minIntervalDistance;
                // ADD: the current velocity to the MTV, so it can still move along the shape
                MinimumTranslationVector += velocity;
            }
            // IF: the shapes will intersect or are intersecting
            if (WillIntersect || Intersect)
            {
                // THEN: a collision is going to happen
                return(true);
            }

            // RESET: the MTV
            MinimumTranslationVector.X = 0;
            MinimumTranslationVector.Y = 0;

            // RETURN: false to break the method
            return(false);
        }
Esempio n. 58
0
 public Collider(Level level, ICollidable collidable)
 {
     Collidable = collidable;
     Level      = level;
 }
Esempio n. 59
0
 public MagicFireballProjectile(SpriteBatch spriteBatch, Texture2D texture, Vector2 startingPosition, Vector2 direction, Game1 game)
 {
     fireball       = new Fireball(spriteBatch, texture, startingPosition, direction, game);
     fireball.Speed = ItemConstants.MagicFireballSpeed;
     collidable     = new ProjectileCollidable(this, game);
 }
Esempio n. 60
0
 public abstract void PlayerCollision(ICollidable collidable);