예제 #1
0
        public void Intersects(ref BoundingCircle circle, out bool result)
        {
            float distSq;

            Vector2Helper.DistanceSq(ref Center, ref circle.Center, out distSq);
            result = distSq <= (Radius * Radius + circle.Radius * circle.Radius);
        }
        public static void FromNormalVectors(Vector2[] vectors, ref Matrix4 matrix, out BoundingRectangle result)
        {
            Vector2 current;

            Vector2Helper.TransformNormal(ref vectors[0], ref matrix, out current);
            result.Max = current;
            result.Min = current;
            for (var index = 1; index < vectors.Length; ++index)
            {
                Vector2Helper.TransformNormal(ref vectors[index], ref matrix, out current);
                if (current.X > result.Max.X)
                {
                    result.Max.X = current.X;
                }
                else if (current.X < result.Min.X)
                {
                    result.Min.X = current.X;
                }
                if (current.Y > result.Max.Y)
                {
                    result.Max.Y = current.Y;
                }
                else if (current.Y < result.Min.Y)
                {
                    result.Min.Y = current.Y;
                }
            }
            result.Max.X += matrix.M13;
            result.Max.Y += matrix.M23;
            result.Min.X += matrix.M13;
            result.Min.Y += matrix.M23;
        }
예제 #3
0
        public override void Draw(GameTime gameTime)
        {
            // Wait for the loader to complete before attempting to get backgrounds, etc.
            var babyPackpageProvider = this.Game.Services.GetService <IBabyPackageProvider>();

            this.Game.GraphicsDevice.Clear(babyPackpageProvider.GetBackgroundColour());

            // Show the background image.
            var background = babyPackpageProvider.GetBackground();

            if (background != null)
            {
                // Resize to fit to the screen.
                var       resized = Vector2Helper.ResizeKeepingAspectRatio(this.Game.GraphicsDevice.Viewport.Bounds, background.Bounds);
                Rectangle r;
                if (resized.X == this.Game.GraphicsDevice.Viewport.Bounds.Width)
                {
                    r = new Rectangle(0, (int)((this.Game.GraphicsDevice.Viewport.Bounds.Height - resized.Y) / 2), (int)resized.X, (int)resized.Y);
                }
                else
                {
                    r = new Rectangle((int)((this.Game.GraphicsDevice.Viewport.Bounds.Width - resized.X) / 2), 0, (int)resized.X, (int)resized.Y);
                }
                this._SpriteBatch.Begin();
                this._SpriteBatch.Draw(background, r, Color.White);
                this._SpriteBatch.End();
            }
        }
        public static void GetDistanceSq(ref Vector2 vertex1, ref Vector2 vertex2, ref Vector2 point,
                                         out float result)
        {
            float   edgeLength;
            Vector2 edge, local;

            Vector2.Subtract(ref point, ref vertex2, out local);
            Vector2.Subtract(ref vertex1, ref vertex2, out edge);
            Vector2Helper.Normalize(ref edge, out edgeLength, out edge);

            var nProj = local.Y * edge.X - local.X * edge.Y;
            var tProj = local.X * edge.X + local.Y * edge.Y;

            if (tProj < 0)
            {
                result = tProj * tProj + nProj * nProj;
            }
            else if (tProj > edgeLength)
            {
                tProj -= edgeLength;
                result = tProj * tProj + nProj * nProj;
            }
            else
            {
                result = nProj * nProj;
            }
        }
예제 #5
0
        public bool Equals(BoundingPolygon other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }
            if (Vertices == null || other.Vertices == null || Vertices.Length != other.Vertices.Length)
            {
                return(false);
            }

            for (var index = 0; index < Vertices.Length; index++)
            {
                var vertex1 = Vertices[index];
                var vertex2 = other.Vertices[index];
                if (!Vector2Helper.Equals(ref vertex1, ref vertex2))
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #6
0
        public static void GetInertia(Vector2[] vertices, out float result)
        {
            if (vertices.Length == 1)
            {
                result = 0;
                return;
            }

            float   denom = 0;
            float   numer = 0;
            var     v1    = vertices[vertices.Length - 1];
            Vector2 v2;

            for (var index = 0; index < vertices.Length; index++, v1 = v2)
            {
                v2 = vertices[index];
                float a, b, c, d;
                Vector2.Dot(ref v2, ref v2, out a);
                Vector2.Dot(ref v2, ref v1, out b);
                Vector2.Dot(ref v1, ref v1, out c);
                Vector2Helper.ZCross(ref v1, ref v2, out d);
                d      = MathF.Abs(d);
                numer += d;
                denom += (a + b + c) * d;
            }
            result = denom / (numer * 6);
        }
        /// <summary>Returns current  <see cref="Vector2" /> with absolute values.</summary>
        /// <param name="current">The current  <see cref="Vector2" />.</param>
        /// <returns>Current  <see cref="Vector2" /> with absolute values.</returns>
        public static Vector2 Abs(this Vector2 current)
        {
            Vector2 result;

            Vector2Helper.Abs(ref current, out result);
            return(result);
        }
예제 #8
0
        protected override void Initialize()
        {
            camera.position = Vector2Helper.GetViewportCenter(GraphicsDevice.Viewport);

            Rectangle worldRect = camera.getWorldRect(Window);

            renderArea = new Rectangle(worldRect.Location.X - renderAreaExtend, worldRect.Y + renderAreaExtend, worldRect.Width + renderAreaExtend, worldRect.Height + renderAreaExtend);
            base.Initialize();
        }
예제 #9
0
        protected override Vector2 CalculateMinimumSize()
        {
            var min = Vector2.Zero;

            foreach (var child in Children)
            {
                min = Vector2Helper.ComponentMax(min, child.CombinedMinimumSize);
            }

            return(min + ActualStyleBox.MinimumSize / UIScale);
        }
예제 #10
0
        public void Intersects(ref BoundingRectangle rect, out bool result)
        {
            // Find the closest point to the circle within the rectangle
            var     x       = MathF.Clamp(Center.X, rect.Min.X, rect.Max.X);
            var     y       = MathF.Clamp(Center.Y, rect.Min.Y, rect.Max.Y);
            Vector2 closest = new Vector2(x, y);

            // Calculate the distance between the circle's center and this closest point
            float distanceSquared;

            Vector2Helper.DistanceSq(ref Center, ref closest, out distanceSquared);
            // If the distance is less than the circle's radius, an intersection occurs
            result = (distanceSquared < Radius * Radius);
        }
예제 #11
0
        /// <summary>
        ///     Calculates the area of a polygon.
        /// </summary>
        /// <param name="vertices">The vertices of the polygon.</param>
        /// <param name="result">the area.</param>
        public static void GetArea(Vector2[] vertices, out float result)
        {
            float   area = 0;
            var     v1   = vertices[vertices.Length - 1];
            Vector2 v2;

            for (var index = 0; index < vertices.Length; ++index, v1 = v2)
            {
                v2 = vertices[index];
                float temp;
                Vector2Helper.ZCross(ref v1, ref v2, out temp);
                area += temp;
            }
            result = MathF.Abs(area * .5f);
        }
예제 #12
0
        public void Initialize()
        {
            for (int i = 0; i < ContactCount; ++i)
            {
                Vector2 ra = Contacts[i] - (Vector2)A.transform.position;
                Vector2 rb = Contacts[i] - (Vector2)B.transform.position;

                Vector2 rv = B.Velocity + Vector2Helper.Cross(B.AngularVelocity, rb) - A.Velocity - Vector2Helper.Cross(A.AngularVelocity, ra);

                if (rv.sqrMagnitude - (Core.PhysicsEngine.DeltaTime * Core.PhysicsEngine.Gravity).sqrMagnitude < Mathf.Epsilon)
                {
                    AverageRestitution = 0.0f;
                }
            }
        }
예제 #13
0
        protected override Vector2 CalculateMinimumSize()
        {
            var top    = MarginTopOverride ?? 0;
            var bottom = MarginBottomOverride ?? 0;
            var left   = MarginLeftOverride ?? 0;
            var right  = MarginRightOverride ?? 0;

            var childMinSize = Vector2.Zero;

            foreach (var child in Children)
            {
                childMinSize = Vector2Helper.ComponentMax(child.CombinedMinimumSize, childMinSize);
            }

            return(childMinSize + new Vector2(left + right, top + bottom));
        }
예제 #14
0
        public override IEnumerator Begin(ProjectileSpawner projectileSpawner)
        {
            yield return(WaitYieldInstruction.Create(_delay));

            while (true)
            {
                var degreesPerSpawn = 360 / _count;
                for (int r = 0; r < _count; r++)
                {
                    var a = degreesPerSpawn * r;
                    projectileSpawner.Spawn(Vector2Helper.FromAngle(MathHelper.ToRadians(a)));
                    yield return(WaitYieldInstruction.Create(_sequenceFrequencyInMS));
                }
                yield return(WaitYieldInstruction.Create(_frequencyInMS));
            }
        }
예제 #15
0
        public static void FromVectors(Vector2[] vertices, out BoundingCircle result)
        {
            BoundingPolygon.GetCentroid(vertices, out result.Center);
            result.Radius = -1;
            for (var index = 0; index < vertices.Length; ++index)
            {
                float distSq;
                Vector2Helper.DistanceSq(ref result.Center, ref vertices[index], out distSq);
                if (result.Radius == -1 || (distSq < result.Radius))
                {
                    result.Radius = distSq;
                }
            }

            result.Radius = MathF.Sqrt(result.Radius);
        }
예제 #16
0
        protected override void Draw(GameTime gameTime)
        {
            this.GraphicsDevice.Clear(Color.Black);


            this._SpriteBatch.Begin();
            var drawingPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X + 20, GraphicsDevice.Viewport.TitleSafeArea.Y + 20);

            if (this._State == ScreenState.GeneralMessageCountdown)
            {
                // Draw the message.
                this._SpriteBatch.DrawString(this._LargeFont, this._Message, drawingPosition, Color.White);

                // And the bug!
                var resized  = Vector2Helper.ResizeKeepingAspectRatio(Vector2Helper.GetProportionalSize(0.5f, this.GraphicsDevice.Viewport), this._Bug.Bounds);
                var location = new Vector2((float)this.GraphicsDevice.Viewport.Bounds.Center.X, (float)(this.GraphicsDevice.Viewport.Bounds.Bottom - (resized.Y + 10)));
                var rect     = new Rectangle((int)location.X, (int)location.Y, (int)resized.X, (int)resized.Y);
                var centre   = new Vector2((float)this._Bug.Width, (float)this._Bug.Height) / 2;
                this._SpriteBatch.Draw(this._Bug, rect, null, Color.White, 0f, centre, SpriteEffects.None, 0);
            }
            else if (this._State == ScreenState.TechnicalDisplay)
            {
                // Draw the exception message.
                this._SpriteBatch.DrawString(this._LargeFont, this._Message, drawingPosition, Color.White);
                this._SpriteBatch.DrawString(this._SmallFont, this._TheExceptionDump, drawingPosition + new Vector2(0, 30), Color.White);
            }
            else if (this._State == ScreenState.PublishException)
            {
                // Draw the publishing message.
                this._SpriteBatch.DrawString(this._LargeFont, this._Message, drawingPosition, Color.White);

                // And the bug!
                var resized  = Vector2Helper.ResizeKeepingAspectRatio(Vector2Helper.GetProportionalSize(0.5f, this.GraphicsDevice.Viewport), this._Bug.Bounds);
                var location = new Vector2((float)this.GraphicsDevice.Viewport.Bounds.Center.X, (float)(this.GraphicsDevice.Viewport.Bounds.Bottom - (resized.Y + 10)));
                var rect     = new Rectangle((int)location.X, (int)location.Y, (int)resized.X, (int)resized.Y);
                var centre   = new Vector2((float)this._Bug.Width, (float)this._Bug.Height) / 2;
                this._SpriteBatch.Draw(this._Bug, rect, null, Color.White, 0f, centre, SpriteEffects.None, 0);
            }
            this._SpriteBatch.End();

            base.Draw(gameTime);
        }
예제 #17
0
        public static bool Collide(BoundingCircle circle1, BoundingCircle circle2, out Vector2 contactPoint,
                                   out float distance, out Vector2 normal)
        {
            Vector2.Subtract(ref circle2.Center, ref circle1.Center, out normal);
            Vector2Helper.Normalize(ref normal, out distance, out normal);
            distance = distance - (circle1.Radius + circle2.Radius);
            bool collision = (distance <= 0);

            if (collision)
            {
                contactPoint.X = circle2.Center.X - normal.X * circle2.Radius;
                contactPoint.Y = circle2.Center.Y - normal.Y * circle2.Radius;
            }
            else
            {
                contactPoint = Vector2.Zero;
            }

            return(collision);
        }
예제 #18
0
        /// <summary> Calculates the centroid of a polygon.</summary>
        /// <param name="vertices">The vertices of the polygon.</param>
        /// <param name="centroid">The centroid of a polygon.</param>
        /// <remarks>This is also known as center of gravity/mass.</remarks>
        public static void GetCentroid(Vector2[] vertices, out Vector2 centroid)
        {
            centroid = Vector2.Zero;
            float   temp;
            float   area = 0;
            var     v1   = vertices[vertices.Length - 1];
            Vector2 v2;

            for (var index = 0; index < vertices.Length; ++index, v1 = v2)
            {
                v2 = vertices[index];
                Vector2Helper.ZCross(ref v1, ref v2, out temp);
                area       += temp;
                centroid.X += ((v1.X + v2.X) * temp);
                centroid.Y += ((v1.Y + v2.Y) * temp);
            }

            temp        = 1 / (MathF.Abs(area) * 3);
            centroid.X *= temp;
            centroid.Y *= temp;
        }
예제 #19
0
        /// <summary>
        /// Calculates an axis aligned rectangle which fully contains an arbitrarily transformed axis aligned rectangle.
        /// </summary>
        /// <param name="rectangle">Original bounding rectangle.</param>
        /// <param name="transform">World transform of the rectangle.</param>
        /// <returns>A new rectangle which contains the trasnformed rectangle.</returns>
        public static void CalculateBoundingRectangle(ref RectangleF rectangle, ref Matrix transform, out RectangleF boundingRect)
        {
            // Get all four corners in local space
            Vector2 leftTop;

            leftTop.X = rectangle.Left;
            leftTop.Y = rectangle.Top;

            Vector2 rightTop;

            rightTop.X = rectangle.Right;
            rightTop.Y = rectangle.Top;

            Vector2 leftBottom;

            leftBottom.X = rectangle.Left;
            leftBottom.Y = rectangle.Bottom;

            Vector2 rightBottom;

            rightBottom.X = rectangle.Right;
            rightBottom.Y = rectangle.Bottom;

            // Transform all four corners into work space
            Vector2Helper.Transform(ref leftTop, ref transform, out leftTop);
            Vector2Helper.Transform(ref rightTop, ref transform, out rightTop);
            Vector2Helper.Transform(ref leftBottom, ref transform, out leftBottom);
            Vector2Helper.Transform(ref rightBottom, ref transform, out rightBottom);

            // Find the minimum and maximum extents of the rectangle in world space
            Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop), Vector2.Min(leftBottom, rightBottom));
            Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop), Vector2.Max(leftBottom, rightBottom));

            // Return that as a rectangle
            boundingRect        = new RectangleF();
            boundingRect.X      = min.X;
            boundingRect.Y      = min.Y;
            boundingRect.Width  = (max.X - min.X);
            boundingRect.Height = (max.Y - min.Y);
        }
예제 #20
0
        public override Vector2 Calculate()
        {
            // The detection box is the current velocity divided by the max velocity of the entity
            // range is the maximum size of the box
            Vector2 viewBox = this.Entity.Velocity / this.Entity.MaxSpeed * this.range;

            // Add the check points in front of the entity
            IEnumerable <Vector2> checkpoints = new[]
            {
                this.Entity.Position,
                this.Entity.Position + viewBox / 2f, // Halfway
                this.Entity.Position + viewBox,      // At the end
                this.Entity.Position + viewBox * 2   // Double
            };

            foreach (Rock o in this.world.Entities.OfType <Rock>())
            {
                // Add a circle around the obstacle which can't be crossed
                CircleF notAllowedZone = new CircleF(o.Position, o.Scale);

                if (checkpoints.Any(checkpoint => notAllowedZone.Contains(checkpoint)))
                {
                    Vector2 dist          = new Vector2(o.Position.X - this.Entity.Position.X, o.Position.X - this.Entity.Position.Y);
                    Vector2 perpendicular = Vector2Helper.PerpendicularRightAngleOf(dist);

                    Vector2 perpendicularPositivePos = o.Position + perpendicular;
                    Vector2 perpendicularNegativePos = o.Position - perpendicular;

                    float perpDistPositive = Vector2.DistanceSquared(this.Entity.Position + this.Entity.Velocity, perpendicularPositivePos);
                    float perpDistNegative = Vector2.DistanceSquared(this.Entity.Position + this.Entity.Velocity, perpendicularNegativePos);

                    Vector2 targetRelative = (perpDistPositive > perpDistNegative ? perpendicularNegativePos : perpendicularPositivePos) - this.Entity.Position;

                    return(Vector2Helper.PerpendicularRightAngleOf(targetRelative));
                }
            }

            // Return identity vector if there will be no collision
            return(new Vector2());
        }
        public static void Intersects(ref Vector2 vertex1, ref Vector2 vertex2, ref Ray2D ray, out float result,
                                      float tolerance = 0.0001f)
        {
            Vector2 tangent, normal;
            float   edgeMagnitude;

            Vector2.Subtract(ref vertex1, ref vertex2, out tangent);
            Vector2Helper.Normalize(ref tangent, out edgeMagnitude, out tangent);
            Vector2Helper.RightPerp(ref tangent, out normal);

            float dir;

            Vector2.Dot(ref normal, ref ray.Direction, out dir);
            if (MathF.Abs(dir) >= tolerance)
            {
                Vector2 originDiff;
                Vector2.Subtract(ref ray.Origin, ref vertex2, out originDiff);
                float actualDistance;
                Vector2.Dot(ref normal, ref originDiff, out actualDistance);
                var distanceFromOrigin = -(actualDistance / dir);
                if (distanceFromOrigin >= 0)
                {
                    Vector2 intersectPos;
                    Vector2.Multiply(ref ray.Direction, distanceFromOrigin, out intersectPos);
                    Vector2.Add(ref intersectPos, ref originDiff, out intersectPos);

                    float distanceFromSecond;
                    Vector2.Dot(ref intersectPos, ref tangent, out distanceFromSecond);

                    if (distanceFromSecond >= 0 && distanceFromSecond <= edgeMagnitude)
                    {   // Hit!
                        result = distanceFromOrigin;
                        return;
                    }
                }
            }
            // No hit.
            result = -1;
        }
예제 #22
0
 private Vector2 GetVelocity()
 {
     return(_dataController.Config.GameConfig.ballSpeed * Vector2Helper.GetRandomDirection());
 }
 public static bool Equals(ref LineSegment line1, ref LineSegment line2)
 {
     return(Vector2Helper.Equals(ref line1.Start, ref line2.Start) &&
            Vector2Helper.Equals(ref line1.End, ref line2.End));
 }
 public void ApplyImpulse(Vector2 impulse, Vector2 contact)
 {
     Velocity        += (InverseMass * impulse);
     AngularVelocity += InverseInertia * Vector2Helper.Cross(contact, impulse);
 }
 public static bool Equals(ref BoundingRectangle rect1, ref BoundingRectangle rect2)
 {
     return(Vector2Helper.Equals(ref rect1.Min, ref rect2.Min) && Vector2Helper.Equals(ref rect1.Max, ref rect2.Max));
 }
예제 #26
0
 public static bool Equals(ref Line line1, ref Line line2)
 {
     return(Vector2Helper.Equals(ref line1.Normal, ref line2.Normal) && line1.D.NearlyEquals(line2.D));
 }
 /// <summary>Clamps the specified point to be contained within the box.</summary>
 /// <param name="target">The target point.</param>
 /// <param name="clamped">The clamped point.</param>
 public void Clamp(ref Vector2 target, out Vector2 clamped)
 {
     Vector2Helper.Clamp(ref target, ref Min, ref Max, out clamped);
 }
예제 #28
0
        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            if (this.FadeInTime > TimeSpan.Zero && this.SpinTime > TimeSpan.Zero)
            {
                throw new InvalidOperationException("Unable to Fade In and Spin In at the same time. Set FadeInTime or SpinTime to TimeSpan.Zero.");
            }

            if (this.ActualSize == Vector2.Zero)
            {
                this.ActualSize = Vector2Helper.ResizeKeepingAspectRatio(this.Size, this.Texture.Bounds);
            }

            if (this.Location == Vector2.Zero)
            {
                // Choose a location for the shape to appear.
                this.Location = new Vector2(
                    (float)this.Game.RandomGenerator.Next(this.Game.GraphicsDevice.Viewport.X + (int)(this.ActualSize.X * 0.2f), this.Game.GraphicsDevice.Viewport.Width - (int)(this.ActualSize.X * 0.2f))
                    , (float)this.Game.RandomGenerator.Next(this.Game.GraphicsDevice.Viewport.Y + (int)(this.ActualSize.Y * 0.2f), this.Game.GraphicsDevice.Viewport.Height - (int)(this.ActualSize.Y * 0.2f))
                    );
            }

            // Update the state machine for this lifespan of this object.
            while (this.RemainingTimeInCurrentState <= TimeSpan.Zero && this.State != DrawingState.PostShow)
            {
                switch (this.State)
                {
                case DrawingState.PreShow:
                    if (this.FadeInTime > TimeSpan.Zero)
                    {
                        this.State = DrawingState.FadeIn;
                        this.RemainingTimeInCurrentState = this.FadeInTime;
                    }
                    else if (this.SpinTime > TimeSpan.Zero)
                    {
                        this.State = DrawingState.SpinIn;
                        this.RemainingTimeInCurrentState = this.SpinTime;
                    }
                    else
                    {
                        this.State = DrawingState.Solid;
                        this.RemainingTimeInCurrentState = this.SolidTime;
                    }
                    break;

                case DrawingState.FadeIn:
                    this.State = DrawingState.Solid;
                    this.RemainingTimeInCurrentState = this.SolidTime;
                    break;

                case DrawingState.SpinIn:
                    this.State = DrawingState.Solid;
                    this.RemainingTimeInCurrentState = this.SolidTime;
                    break;

                case DrawingState.Solid:
                    this.State = DrawingState.FadeOut;
                    this.RemainingTimeInCurrentState = this.FadeOutTime;
                    break;

                case DrawingState.FadeOut:
                    this.State = DrawingState.PostShow;
                    break;

                case DrawingState.PostShow:

                    break;

                default:
                    throw new ApplicationException("Forgot a DrawingState.");
                }
            }
            this.RemainingTimeInCurrentState = this.RemainingTimeInCurrentState.Subtract(gameTime.ElapsedGameTime);

            base.Update(gameTime);
        }
예제 #29
0
 public static bool Equals(ref Ray2D ray1, ref Ray2D ray2)
 {
     return(Vector2Helper.Equals(ref ray1.Origin, ref ray2.Origin) &&
            Vector2Helper.Equals(ref ray1.Direction, ref ray2.Direction));
 }
예제 #30
0
 protected override Vector2 CalculateMinimumSize()
 {
     return(Vector2Helper.ComponentMax(ContentsMinimumSize, base.CalculateMinimumSize()));
 }