Exemplo n.º 1
0
 /// <summary>
 /// Renders the sprite to the screen
 /// </summary>
 /// <param name="spriteBatch">SpriteBatch object used to render the sprite</param>
 /// <param name="positionOffset">Offset to render the object at</param>
 public override void render(SpriteBatch spriteBatch, Vector2 positionOffset)
 {
     spriteBatch.Draw(this.texture, Vector2.Add(base.position, positionOffset), null, base.lightColour, base.rotation,
                      base.origin, base.scale, base.spriteEffect, base.layer);
 }
Exemplo n.º 2
0
    static public Vector2 CalculatePosition(Vector2 pos, Vector2 velocity)
    {
        Vector2 newPos = Vector2.Add(pos, velocity);

        return(newPos);
    }
 public static BoundingBox getCharacterBBox(Vector2 position)
 {
     return(new BoundingBox(
                new Vector3(Vector2.Add(position, new Vector2(-(Constants.TILE_SIZE / 3), Constants.TILE_SIZE / 4)), 0f),
                new Vector3(Vector2.Add(position, new Vector2(Constants.TILE_SIZE / 3, Constants.TILE_SIZE / 2)), 0f)));
 }
Exemplo n.º 4
0
        /// <summary>
        /// This method causes an entity to move a certain distance away from the
        /// center of the toEntity.
        /// </summary>
        /// <param name="toEntity">Entity to move to.</param>
        /// <param name="distance">Distance to move away.</param>
        public virtual void MoveDistanceInFrontOfEntity(GameEntity toEntity, int distance)
        {
            if (toEntity == null)
            {
                return;
            }
            Vector2   targetPos = Vector2.Add(toEntity.m_WorldPosition, toEntity.m_EntityCenter);
            DIRECTION movementDir;

            FaceEntity(toEntity);

            m_MovementDelta.X = 0;
            m_MovementDelta.Y = 0;
            if (m_WorldPosition.Y < targetPos.Y)
            {
                movementDir       = DIRECTION.DOWN;
                m_MovementDelta.X = 0;
                m_MovementDelta.Y = 1;

                targetPos.Y -= distance;
                //targetPos.Y -= m_SpriteSize.Y / 2;

                if (m_WorldPosition.X < targetPos.X)
                {
                    movementDir       = DIRECTION.DOWN_RIGHT;
                    m_MovementDelta.X = 1;
                    targetPos.X      -= distance;
                    //targetPos.X -= m_SpriteSize.X;
                }
                else if (m_WorldPosition.X > targetPos.X)
                {
                    movementDir       = DIRECTION.DOWN_LEFT;
                    m_MovementDelta.X = -1;
                    targetPos.X      += distance;
                    //targetPos.X += m_SpriteSize.X / 8;
                }
            }
            else if (m_WorldPosition.Y == targetPos.Y)
            {
                movementDir       = m_EntityDircetion;
                m_MovementDelta.X = 0;
                m_MovementDelta.Y = 0;


                if (m_WorldPosition.X < targetPos.X)
                {
                    movementDir       = DIRECTION.RIGHT;
                    m_MovementDelta.X = 1;
                    targetPos.X      -= distance;
                    //targetPos.X -= m_SpriteSize.X;
                }
                else if (m_WorldPosition.X > targetPos.X)
                {
                    movementDir       = DIRECTION.LEFT;
                    m_MovementDelta.X = -1;
                    targetPos.X      += distance;
                    //targetPos.X += m_SpriteSize.X / 8;
                }
            }
            else
            {
                movementDir = DIRECTION.UP;

                m_MovementDelta.X = 0;
                m_MovementDelta.Y = -1;
                targetPos.Y      += distance;
                //targetPos.Y += m_SpriteSize.Y / 2;

                if (m_WorldPosition.X < targetPos.X)
                {
                    movementDir       = DIRECTION.UP_RIGHT;
                    m_MovementDelta.X = 1;
                    targetPos.X      -= distance;
                    //targetPos.X -= m_SpriteSize.X;
                }
                else if (m_WorldPosition.X > targetPos.X)
                {
                    movementDir       = DIRECTION.UP_LEFT;
                    m_MovementDelta.X = -1;
                    targetPos.X      += distance;
                    //targetPos.X += m_SpriteSize.X / 8;
                }
            }
            m_EntityDircetion     = movementDir;
            m_DestinationPosition = targetPos;
        }
Exemplo n.º 5
0
        public void ExecuteTest(Operations operation, int innerIterations, Vector2 v1, Vector2 v2)
        {
            Vector2 res;

            switch (operation)
            {
            case Operations.Add_Operator:
                for (int i = 0; i < innerIterations; i++)
                {
                    res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2;
                }
                break;

            case Operations.Add_Function:
                for (int i = 0; i < innerIterations; i++)
                {
                    Vector2.Add(v1, v2); Vector2.Add(v1, v2); Vector2.Add(v1, v2); Vector2.Add(v1, v2); Vector2.Add(v1, v2); Vector2.Add(v1, v2); Vector2.Add(v1, v2); Vector2.Add(v1, v2); Vector2.Add(v1, v2); Vector2.Add(v1, v2);
                }
                break;

            case Operations.Sub_Operator:
                for (int i = 0; i < innerIterations; i++)
                {
                    res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2;
                }
                break;

            case Operations.Sub_Function:
                for (int i = 0; i < innerIterations; i++)
                {
                    Vector2.Subtract(v1, v2); Vector2.Subtract(v1, v2); Vector2.Subtract(v1, v2); Vector2.Subtract(v1, v2); Vector2.Subtract(v1, v2); Vector2.Subtract(v1, v2); Vector2.Subtract(v1, v2); Vector2.Subtract(v1, v2); Vector2.Subtract(v1, v2); Vector2.Subtract(v1, v2);
                }
                break;

            case Operations.Mul_Operator:
                for (int i = 0; i < innerIterations; i++)
                {
                    res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2;
                }
                break;

            case Operations.Mul_Function:
                for (int i = 0; i < innerIterations; i++)
                {
                    Vector2.Multiply(v1, v2); Vector2.Multiply(v1, v2); Vector2.Multiply(v1, v2); Vector2.Multiply(v1, v2); Vector2.Multiply(v1, v2); Vector2.Multiply(v1, v2); Vector2.Multiply(v1, v2); Vector2.Multiply(v1, v2); Vector2.Multiply(v1, v2); Vector2.Multiply(v1, v2);
                }
                break;

            case Operations.Dot:
                for (int i = 0; i < innerIterations; i++)
                {
                    Vector2.Dot(v1, v2); Vector2.Dot(v1, v2); Vector2.Dot(v1, v2); Vector2.Dot(v1, v2); Vector2.Dot(v1, v2); Vector2.Dot(v1, v2); Vector2.Dot(v1, v2); Vector2.Dot(v1, v2); Vector2.Dot(v1, v2); Vector2.Dot(v1, v2);
                }
                break;

            case Operations.SquareRoot:
                for (int i = 0; i < innerIterations; i++)
                {
                    Vector2.SquareRoot(v1); Vector2.SquareRoot(v1); Vector2.SquareRoot(v1); Vector2.SquareRoot(v1); Vector2.SquareRoot(v1); Vector2.SquareRoot(v1); Vector2.SquareRoot(v1); Vector2.SquareRoot(v1); Vector2.SquareRoot(v1); Vector2.SquareRoot(v1);
                }
                break;

            case Operations.Length_Squared:
                for (int i = 0; i < innerIterations; i++)
                {
                    v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared();
                }
                break;

            case Operations.Normalize:
                for (int i = 0; i < innerIterations; i++)
                {
                    Vector2.Normalize(v1); Vector2.Normalize(v1); Vector2.Normalize(v1); Vector2.Normalize(v1); Vector2.Normalize(v1); Vector2.Normalize(v1); Vector2.Normalize(v1); Vector2.Normalize(v1); Vector2.Normalize(v1); Vector2.Normalize(v1);
                }
                break;

            case Operations.Distance_Squared:
                for (int i = 0; i < innerIterations; i++)
                {
                    Vector2.DistanceSquared(v1, v2); Vector2.DistanceSquared(v1, v2); Vector2.DistanceSquared(v1, v2); Vector2.DistanceSquared(v1, v2); Vector2.DistanceSquared(v1, v2); Vector2.DistanceSquared(v1, v2); Vector2.DistanceSquared(v1, v2); Vector2.DistanceSquared(v1, v2); Vector2.DistanceSquared(v1, v2); Vector2.DistanceSquared(v1, v2);
                }
                break;
            }
        }
Exemplo n.º 6
0
        SystemPosition4 VS(Position4 input)
        {
            Vector2 r2 = Vector2.Abs(VH.V2);

            r2 = Vector2.Add(VH.V2, VH.V2);
            r2 = Vector2.Clamp(VH.V2, VH.V2, VH.V2);
            float r = Vector2.Distance(VH.V2, VH.V2);

            r  = Vector2.DistanceSquared(VH.V2, VH.V2);
            r2 = Vector2.Divide(VH.V2, VH.V2);
            r2 = Vector2.Divide(VH.V2, r);
            r  = Vector2.Dot(VH.V2, VH.V2);
            r2 = Vector2.Lerp(VH.V2, VH.V2, 0.75f);
            r2 = Vector2.Max(VH.V2, VH.V2);
            r2 = Vector2.Min(VH.V2, VH.V2);
            r2 = Vector2.Multiply(VH.V2, VH.V2);
            r2 = Vector2.Multiply(VH.V2, r);
            r2 = Vector2.Multiply(r, VH.V2);
            r2 = Vector2.Negate(VH.V2);
            r2 = Vector2.Normalize(VH.V2);
            r2 = Vector2.Reflect(VH.V2, VH.V2);
            r2 = Vector2.SquareRoot(VH.V2);
            r2 = Vector2.Subtract(VH.V2, VH.V2);
            r  = VH.V2.Length();
            r  = VH.V2.LengthSquared();
            r2 = Vector2.Transform(VH.V2, VH.M4x4);

            Vector3 V3 = new Vector3(1, 2, 3);
            Vector3 r3 = Vector3.Abs(VH.V3);

            r3 = Vector3.Add(VH.V3, VH.V3);
            r3 = Vector3.Clamp(VH.V3, VH.V3, VH.V3);
            r3 = Vector3.Cross(VH.V3, VH.V3);
            r  = Vector3.Distance(VH.V3, VH.V3);
            r  = Vector3.DistanceSquared(VH.V3, VH.V3);
            r3 = Vector3.Divide(VH.V3, VH.V3);
            r3 = Vector3.Divide(VH.V3, r);
            r  = Vector3.Dot(VH.V3, VH.V3);
            r3 = Vector3.Lerp(VH.V3, VH.V3, 0.75f);
            r3 = Vector3.Max(VH.V3, VH.V3);
            r3 = Vector3.Min(VH.V3, VH.V3);
            r3 = Vector3.Multiply(VH.V3, VH.V3);
            r3 = Vector3.Multiply(VH.V3, r);
            r3 = Vector3.Multiply(r, VH.V3);
            r3 = Vector3.Negate(VH.V3);
            r3 = Vector3.Normalize(VH.V3);
            r3 = Vector3.Reflect(VH.V3, VH.V3);
            r3 = Vector3.SquareRoot(VH.V3);
            r3 = Vector3.Subtract(VH.V3, VH.V3);
            r  = VH.V3.Length();
            r  = VH.V3.LengthSquared();
            r3 = Vector3.Transform(VH.V3, VH.M4x4);

            Vector4 V4 = new Vector4(1, 2, 3, 4);
            Vector4 r4 = Vector4.Abs(VH.V4);

            r4 = Vector4.Add(VH.V4, VH.V4);
            r4 = Vector4.Clamp(VH.V4, VH.V4, VH.V4);
            r  = Vector4.Distance(VH.V4, VH.V4);
            r  = Vector4.DistanceSquared(VH.V4, VH.V4);
            r4 = Vector4.Divide(VH.V4, VH.V4);
            r4 = Vector4.Divide(VH.V4, r);
            r  = Vector4.Dot(VH.V4, VH.V4);
            r4 = Vector4.Lerp(VH.V4, VH.V4, 0.75f);
            r4 = Vector4.Max(VH.V4, VH.V4);
            r4 = Vector4.Min(VH.V4, VH.V4);
            r4 = Vector4.Multiply(VH.V4, VH.V4);
            r4 = Vector4.Multiply(VH.V4, r);
            r4 = Vector4.Multiply(r, VH.V4);
            r4 = Vector4.Negate(VH.V4);
            r4 = Vector4.Normalize(VH.V4);
            r4 = Vector4.SquareRoot(VH.V4);
            r4 = Vector4.Subtract(VH.V4, VH.V4);
            r  = VH.V4.Length();
            r  = VH.V4.LengthSquared();
            r4 = Vector4.Transform(VH.V2, VH.M4x4);
            r4 = Vector4.Transform(VH.V3, VH.M4x4);
            r4 = Vector4.Transform(VH.V4, VH.M4x4);

            SystemPosition4 output;

            output.Position = input.Position;
            return(output);
        }
        /// <summary>
        /// Gets the intersection between the convex shape and the ray.
        /// </summary>
        /// <param name="ray">Ray to test.</param>
        /// <param name="transform">Transform of the convex shape.</param>
        /// <param name="maximumLength">Maximum distance to travel in units of the ray direction's length.</param>
        /// <param name="hit">Ray hit data, if any.</param>
        /// <returns>Whether or not the ray hit the target.</returns>
        public override bool RayTest(ref Ray ray, ref RigidTransform transform, float maximumLength, out RayHit hit)
        {
            //Put the ray into local space.
            Quaternion conjugate;

            Quaternion.Conjugate(ref transform.Orientation, out conjugate);
            Ray localRay;

            Vector3.Subtract(ref ray.Position, ref transform.Position, out localRay.Position);
            Vector3.Transform(ref localRay.Position, ref conjugate, out localRay.Position);
            Vector3.Transform(ref ray.Direction, ref conjugate, out localRay.Direction);

            //Check for containment.
            if (localRay.Position.Y >= -halfHeight && localRay.Position.Y <= halfHeight && localRay.Position.X * localRay.Position.X + localRay.Position.Z * localRay.Position.Z <= radius * radius)
            {
                //It's inside!
                hit.T        = 0;
                hit.Location = localRay.Position;
                hit.Normal   = new Vector3(hit.Location.X, 0, hit.Location.Z);
                float normalLengthSquared = hit.Normal.LengthSquared();
                if (normalLengthSquared > 1e-9f)
                {
                    Vector3.Divide(ref hit.Normal, (float)Math.Sqrt(normalLengthSquared), out hit.Normal);
                }
                else
                {
                    hit.Normal = new Vector3();
                }
                //Pull the hit into world space.
                Vector3.Transform(ref hit.Normal, ref transform.Orientation, out hit.Normal);
                RigidTransform.Transform(ref hit.Location, ref transform, out hit.Location);
                return(true);
            }

            //Project the ray direction onto the plane where the cylinder is a circle.
            //The projected ray is then tested against the circle to compute the time of impact.
            //That time of impact is used to compute the 3d hit location.
            Vector2 planeDirection = new Vector2(localRay.Direction.X, localRay.Direction.Z);
            float   planeDirectionLengthSquared = planeDirection.LengthSquared();

            if (planeDirectionLengthSquared < Toolbox.Epsilon)
            {
                //The ray is nearly parallel with the axis.
                //Skip the cylinder-sides test.  We're either inside the cylinder and won't hit the sides, or we're outside
                //and won't hit the sides.
                if (localRay.Position.Y > halfHeight)
                {
                    goto upperTest;
                }
                if (localRay.Position.Y < -halfHeight)
                {
                    goto lowerTest;
                }


                hit = new RayHit();
                return(false);
            }
            Vector2 planeOrigin = new Vector2(localRay.Position.X, localRay.Position.Z);
            float   dot;

            Vector2.Dot(ref planeDirection, ref planeOrigin, out dot);
            float closestToCenterT = -dot / planeDirectionLengthSquared;

            Vector2 closestPoint;

            Vector2.Multiply(ref planeDirection, closestToCenterT, out closestPoint);
            Vector2.Add(ref planeOrigin, ref closestPoint, out closestPoint);
            //How close does the ray come to the circle?
            float squaredDistance = closestPoint.LengthSquared();

            if (squaredDistance > radius * radius)
            {
                //It's too far!  The ray cannot possibly hit the capsule.
                hit = new RayHit();
                return(false);
            }



            //With the squared distance, compute the distance backward along the ray from the closest point on the ray to the axis.
            float backwardsDistance = radius * (float)Math.Sqrt(1 - squaredDistance / (radius * radius));
            float tOffset           = backwardsDistance / (float)Math.Sqrt(planeDirectionLengthSquared);

            hit.T = closestToCenterT - tOffset;

            //Compute the impact point on the infinite cylinder in 3d local space.
            Vector3.Multiply(ref localRay.Direction, hit.T, out hit.Location);
            Vector3.Add(ref hit.Location, ref localRay.Position, out hit.Location);

            //Is it intersecting the cylindrical portion of the capsule?
            if (hit.Location.Y <= halfHeight && hit.Location.Y >= -halfHeight && hit.T < maximumLength)
            {
                //Yup!
                hit.Normal = new Vector3(hit.Location.X, 0, hit.Location.Z);
                float normalLengthSquared = hit.Normal.LengthSquared();
                if (normalLengthSquared > 1e-9f)
                {
                    Vector3.Divide(ref hit.Normal, (float)Math.Sqrt(normalLengthSquared), out hit.Normal);
                }
                else
                {
                    hit.Normal = new Vector3();
                }
                //Pull the hit into world space.
                Vector3.Transform(ref hit.Normal, ref transform.Orientation, out hit.Normal);
                RigidTransform.Transform(ref hit.Location, ref transform, out hit.Location);
                return(true);
            }

            if (hit.Location.Y < halfHeight)
            {
                goto lowerTest;
            }
upperTest:
            //Nope! It may be intersecting the ends of the cylinder though.
            //We're above the cylinder, so cast a ray against the upper cap.
            if (localRay.Direction.Y > -1e-9)
            {
                //Can't hit the upper cap if the ray isn't pointing down.
                hit = new RayHit();
                return(false);
            }
            float   t = (halfHeight - localRay.Position.Y) / localRay.Direction.Y;
            Vector3 planeIntersection;

            Vector3.Multiply(ref localRay.Direction, t, out planeIntersection);
            Vector3.Add(ref localRay.Position, ref planeIntersection, out planeIntersection);
            if (planeIntersection.X * planeIntersection.X + planeIntersection.Z * planeIntersection.Z < radius * radius + 1e-9 && t < maximumLength)
            {
                //Pull the hit into world space.
                Vector3.Transform(ref Toolbox.UpVector, ref transform.Orientation, out hit.Normal);
                RigidTransform.Transform(ref planeIntersection, ref transform, out hit.Location);
                hit.T = t;
                return(true);
            }
            //No intersection! We can't be hitting the other sphere, so it's over!
            hit = new RayHit();
            return(false);

lowerTest:
            //Is it intersecting the bottom cap?
            if (localRay.Direction.Y < 1e-9)
            {
                //Can't hit the bottom cap if the ray isn't pointing up.
                hit = new RayHit();
                return(false);
            }
            t = (-halfHeight - localRay.Position.Y) / localRay.Direction.Y;
            Vector3.Multiply(ref localRay.Direction, t, out planeIntersection);
            Vector3.Add(ref localRay.Position, ref planeIntersection, out planeIntersection);
            if (planeIntersection.X * planeIntersection.X + planeIntersection.Z * planeIntersection.Z < radius * radius + 1e-9 && t < maximumLength)
            {
                //Pull the hit into world space.
                Vector3.Transform(ref Toolbox.DownVector, ref transform.Orientation, out hit.Normal);
                RigidTransform.Transform(ref planeIntersection, ref transform, out hit.Location);
                hit.T = t;
                return(true);
            }
            //No intersection! We can't be hitting the other sphere, so it's over!
            hit = new RayHit();
            return(false);
        }
Exemplo n.º 8
0
 public void Update(Vector2 mousePosition, TouchLocation touch)
 {
     #region Right joystick touches
     normal = Vector2.Normalize(Vector2.Subtract(anchorPos, touch.Position)); //normal is vector of where joystick is pointing
     //check if user is moving joystick
     if (anchorPos != position)
     {
         //count the direction
         dir = Vector2.Normalize(Vector2.Subtract(anchorPos, position));
     }
     else
     {
         //otherwise moving direction is Zero
         dir = Vector2.Zero;
     }
     //check the overlapping touches for player and joystick, joystick always wins
     if (touchID == game.player.touchID)
     {
         touchID = -1;
         game.player.isPressed = false;
         isPressed             = false;
     }
     //if joystick is in use....
     //check if touch that we are checking now is indeed touch that is registered for joystick
     if (isPressed && touch.Id == touchID)
     {
         //check if touchs state is still moving
         if (touch.State != TouchLocationState.Released)
         {
             //handle joystick position. if movement isnt too far away from anchor
             if ((float)Vector2.Subtract(mousePosition, anchorPos).Length() < 100f)
             {
                 position = touch.Position;
             }
             //otherwise dont move it too far away
             else
             {
                 position = Vector2.Add(anchorPos, normal * -100f);
             }
         }
         //if touch is registered for joystick, but has been released
         else
         {
             isPressed = false;     //joystick is not in use anymore, looking for new touchID
             position  = anchorPos; //return joystick to its anchor
         }
     }
     //if joystick isn´t already in use...
     else
     {
         if (!isPressed)
         {
             //check if current touch is close enough to joystic, doenst matter if its in use of player
             if (Math.Abs(mousePosition.X - position.X) <= 80 &&
                 Math.Abs(mousePosition.Y - position.Y) <= 80)
             {
                 isPressed = true;
                 touchID   = touch.Id; //register this touch for joystick
             }
             //otherwise keep the joystick in anchor, if its not there already...
             else
             {
                 position = anchorPos;
             }
         }
     }
     #endregion
 }
Exemplo n.º 9
0
        public void ApplyForce(Vector2 force)
        {
            Vector2 f = Vector2.Divide(force, Mass);

            Acceleration = Vector2.Add(Acceleration, f);
        }
Exemplo n.º 10
0
 /// <summary>
 /// Gets the absolute position from a relative position and the origin of this emitter.
 /// </summary>
 /// <param name="relativePosition">The relative position.</param>
 /// <param name="absolutePosition">The resulting absolute position.</param>
 public void GetAbsoultePosition(ref Vector2 relativePosition, out Vector2 absolutePosition)
 {
     Vector2.Add(ref relativePosition, ref _origin, out absolutePosition);
 }
Exemplo n.º 11
0
        /// <summary>
        /// Updates the <see cref="ParticleEmitter"/> and all <see cref="Particle"/>s it has created.
        /// </summary>
        /// <param name="currentTime">The current time.</param>>
        internal void Update(TickCount currentTime)
        {
            var forceEmit = false;

            // Get the elapsed time
            // On the first update, just assume 33 ms have elapsed
            int elapsedTime;

            if (_lastUpdateTime == TickCount.MinValue)
            {
                // This is the very first update
                forceEmit        = true;
                _nextReleaseTime = currentTime;
                elapsedTime      = 33;
            }
            else
            {
                // Not the first update
                elapsedTime = (int)Math.Min(MaxDeltaTime, currentTime - _lastUpdateTime);
            }

            _lastUpdateTime = currentTime;

            // Update the emitter modifiers
            EmitterModifiers.ProcessEmitter(this, elapsedTime);

            // Check if the sprite is loaded
            if (Sprite == null || Sprite.GrhData == null)
            {
                EmitterModifiers.RestoreEmitter(this);
                return;
            }

            // Update the current time on the modifiers
            ParticleModifiers.UpdateCurrentTime(currentTime);

            // Update the sprite
            Sprite.Update(currentTime);

            // Check to spawn more particles
            if (forceEmit || (RemainingLife != 0 && ReleaseAmount.Max > 0 && ReleaseRate.Max > 0))
            {
                // Do not allow the releasing catch-up time to exceed the _maxDeltaTime
                if (_nextReleaseTime < currentTime - MaxDeltaTime)
                {
                    _nextReleaseTime = currentTime - MaxDeltaTime;
                }

                // Keep calculating the releases until we catch up to the current time
                var amountToRelease = 0;
                while (_nextReleaseTime <= currentTime)
                {
                    amountToRelease  += ReleaseAmount.GetNext();
                    _nextReleaseTime += ReleaseRate.GetNext();
                }

                // Release the particles, if there are any
                if (amountToRelease > 0)
                {
                    ReleaseParticles(currentTime, amountToRelease);
                }
            }
            else
            {
                // Set the next release time to now so that if the emitter starts releasing, it won't release a ton
                // as it catches back up
                _nextReleaseTime = currentTime - MaxDeltaTime;
            }

            // Update the particles
            var     hasUpdateModifiers = ParticleModifiers.HasUpdateModifiers;
            var     i = 0;
            Vector2 minParticlePosition = Vector2.Zero;
            Vector2 maxParticlePosition = Vector2.Zero;
            Vector2 spriteSize          = Sprite.Size;

            while (i <= _lastAliveIndex)
            {
                var particle = _particles[i];

                // Check if the particle has expired
                if (particle.LifeEnd <= currentTime)
                {
                    // We do NOT increment because once we expire the particle, this slot will become in use by
                    // another particle, so we will have to update at this index again
                    ExpireParticle(i);
                    continue;
                }

                // Process the particle with the modifiers
                if (hasUpdateModifiers)
                {
                    ParticleModifiers.ProcessUpdatedParticle(this, particle, elapsedTime);
                }

                // Update the particle
                particle.Update(elapsedTime);

                // Update the min/max origin offsets
                Vector2 posMin = particle.Position;

                Vector2 particleSize;
                Vector2.Multiply(ref spriteSize, particle.Scale, out particleSize);

                Vector2 posMax;
                Vector2.Add(ref posMin, ref particleSize, out posMax);

                if (posMin.X < minParticlePosition.X)
                {
                    minParticlePosition.X = posMin.X;
                }
                if (posMin.Y < minParticlePosition.Y)
                {
                    minParticlePosition.Y = posMin.Y;
                }

                if (posMax.X > maxParticlePosition.X)
                {
                    maxParticlePosition.X = posMax.X;
                }
                if (posMax.Y > maxParticlePosition.Y)
                {
                    maxParticlePosition.Y = posMax.Y;
                }

                ++i;
            }

            _minParticlePosition = minParticlePosition;
            _maxParticlePosition = maxParticlePosition;

            EmitterModifiers.RestoreEmitter(this);
        }
Exemplo n.º 12
0
 public override void Update(float timestep)
 {
     this.Position = Vector2.Add(this.Position,
                                 Vector2.Multiply(timestep, this.Velocity));
 }
Exemplo n.º 13
0
        public void add() {
            var a = new Vector2(1, 3);
            var b = new Vector2(5, 7);

            Assert.Equal(new Vector2(6, 10), a.Add(b));
        }
Exemplo n.º 14
0
        //uses second point to determine direction of the line, should be within 1 distance of center
        public Dictionary<Vector2, Tile> GetLineTiles(Vector2 center, Vector2 secondPoint, int distance, bool bothDirections)
        {
            var xDiff = secondPoint.x - center.x;
            var zDiff = secondPoint.y - center.y;

            var ret = new Dictionary<Vector2, Tile>()
            {
                { center, mapModel.tiles.Get(center) }
            };
            Tile neighborTile = null;
            for (var d = 1; d <= distance; d++)
            {
                var toCheck = new List<Vector2>(){
                  center.Add(xDiff * d, zDiff * d)
                };
                if (bothDirections)
                {
                    toCheck.Add(center.Add(-xDiff * d, -zDiff * d));
                }

                foreach (var currentDirection in toCheck)
                {
                    //check it's not off the map
                    neighborTile = mapModel.tiles.Get(currentDirection);
                    if (neighborTile != null)
                    {
                        ret[currentDirection] = neighborTile;
                    }
                }
            }
            return ret;
        }
Exemplo n.º 15
0
 public override void Draw(SpriteBatch spriteBatch)
 {
     spriteBatch.Draw(texture, Vector2.Add(parentContainer.boundingBox.Location.ToVector2(), this.boundingBox.Location.ToVector2()), spriteLocation, color);
 }
Exemplo n.º 16
0
 private void UpdatePosition()
 {
     Position = Vector2.Add(Position, Velocity);
 }
Exemplo n.º 17
0
        public Dictionary<Vector2, Tile> GetKingNeighbors(Vector2 center)
        {
            var toCheck = new Vector2[8]{
                center.AddX(1f),
                center.AddX(-1f),
                center.AddY(1f),
                center.AddY(-1f),
                center.Add(-1, -1),
                center.Add(-1, 1),
                center.Add(1, -1),
                center.Add(1, 1)
            };

            return CheckNeighbors(toCheck);
        }
Exemplo n.º 18
0
        public static void Update(GameTime gameTime)
        {
            lock (syncLock)
            {
                if (timer.Elapsed.Seconds > AdDelayTillNext && AdShowing)
                {
                    GetNewAd();
                }

                // calculate new ball position
                position = Vector2.Add(position, direction);
                if ((position.X + 100) > 480 || position.X < 0)
                {
                    direction.X *= -1;
                }
                if ((position.Y + 100) > 720 || position.Y < 0)
                {
                    direction.Y *= -1;
                }
            }
            // if there is a new ad, get it from Isolated Storage and  show it
            if (somaAd.Status == "success" && somaAd.AdImageFileName != null && somaAd.ImageOK)
            {
                try
                {
                    if (currentAdImageFileName != somaAd.AdImageFileName)
                    {
                        adLoadThread = new System.Threading.Thread(LoadNewAd);
                        adLoadThread.Start();
                    }
                }
                catch (IsolatedStorageException ise)
                {
                    string message = ise.Message;
                }
            }
            IsVisible = true;

            if (IsVisible)
            {
                if (false)//TargetTop)
                {
                    AdTargetPosY = -AdSprite.Height / 2.0f;
                }
                else
                {
                    if (timer.Elapsed.Seconds > AdDelayTillNext - 2 || !AdShowing)
                    {
                        AdTargetPosY = -BaseGame.Get.BackBufferHeight - AdSprite.Height / 2.0f;

                        float distToTarget    = AdSprite.PosY - AdTargetPosY;
                        float maxDistToTarget = -BaseGame.Get.BackBufferHeight + AdSprite.Height / 2.0f - AdTargetPosY;
                        float prop            = 1.0f - distToTarget / maxDistToTarget;
                        AdSprite.Colour = Color.White * prop;
                    }
                    else
                    {
                        AdTargetPosY = -BaseGame.Get.BackBufferHeight + AdSprite.Height / 2.0f;


                        float distToTarget    = AdSprite.PosY - AdTargetPosY;
                        float maxDistToTarget = -BaseGame.Get.BackBufferHeight - AdSprite.Height / 2.0f - AdTargetPosY;
                        float prop            = 1.0f - distToTarget / maxDistToTarget;
                        AdSprite.Colour = Color.White * prop;
                    }
                }
            }

            AdSprite.PosY = JabMath.MoveTowards(AdSprite.PosY, AdTargetPosY, gameTime.ElapsedGameTime.Milliseconds / 1000.0f * 3.5f, 3);
        }
Exemplo n.º 19
0
    public override void Update()
    {
        var     speed = 0.25f;
        Vector2 delta = new Vector2();

        if (Input.isDown(Key.UP))
        {
            delta.Add(0, -1);
        }
        else if (Input.isDown(Key.DOWN))
        {
            delta.Add(0, 1);
        }

        if (Input.isDown(Key.LEFT))
        {
            delta.Add(-1, 0);
        }
        else if (Input.isDown(Key.RIGHT))
        {
            delta.Add(1, 0);
        }
        transform.Translate(delta * speed * Time.DeltaTime);
        bg.speed = -(delta * speed * 200f * Time.DeltaTime).y + 2f;

        if (Input.isDown(Key.A))
        {
            transform.scale -= Time.DeltaTime * 2;
        }
        else if (Input.isDown(Key.S))
        {
            transform.scale += Time.DeltaTime * 2;
        }

        if (Input.isDown(Key.W) && !spinning)
        {
            spinning = true;
            spinTime = 1.0f;
        }

        if (Input.isDown(Key.E) && hitCooldown <= 0.0f)
        {
            hitCooldown = 0.1f;
        }

        if (hitCooldown >= 0.0f)
        {
            hitCooldown -= Time.DeltaTime;
        }

        if (spinning)
        {
            spinTime -= Time.DeltaTime;
            if (spinTime <= 0.0f)
            {
                spinning           = false;
                transform.rotation = 0;
            }
            else
            {
                transform.Rotate(360 * 2 * Time.DeltaTime);
            }
        }

        fireCooldown -= Time.DeltaTime;
        if (Input.isDown(Key.FIRE) && fireCooldown <= 0.0f && !spinning)
        {
            Missile missile = new Missile(missileTexture, new Vector2(0, -1), new Vector2(1, 1), 0.5f, 5.0f);
            missile.transform.position = transform.DoTransform();             // + new Vector2(0, -transform.center.y*transform.scale);
            missile.transform.scale    = 0.8f;
            // missile.transform.scale = transform.scale;
            level.AddEntity(missile);
            fireCooldown = 0.1f;
        }
    }
Exemplo n.º 20
0
        internal void PreStepImpulse(float inverseDt)
        {
            if (!GeometryA.collisionResponseEnabled || !GeometryB.collisionResponseEnabled)
            {
                return;
            }

            for (int i = 0; i < _contactList.Count; i++)
            {
                Contact contact = _contactList[i];

                //calculate _contact offset from body position
                Vector2.Subtract(ref contact.Position, ref GeometryA.body.position, out _r1);
                Vector2.Subtract(ref contact.Position, ref GeometryB.body.position, out _r2);

                //project normal onto offset vectors
                Vector2.Dot(ref _r1, ref contact.Normal, out _rn1);
                Vector2.Dot(ref _r2, ref contact.Normal, out _rn2);

                //calculate mass normal
                float invMassSum = GeometryA.body.inverseMass + GeometryB.body.inverseMass;
                Vector2.Dot(ref _r1, ref _r1, out _float1);
                Vector2.Dot(ref _r2, ref _r2, out _float2);
                _kNormal = invMassSum + GeometryA.body.inverseMomentOfInertia * (_float1 - _rn1 * _rn1) +
                           GeometryB.body.inverseMomentOfInertia * (_float2 - _rn2 * _rn2);
                contact.MassNormal = 1f / _kNormal;

                //calculate mass _tangent
                _float1 = 1;
                Calculator.Cross(ref contact.Normal, ref _float1, out _tangent);
                Vector2.Dot(ref _r1, ref _tangent, out _rt1);
                Vector2.Dot(ref _r2, ref _tangent, out _rt2);
                _kTangent = GeometryA.Body.InverseMass + GeometryB.Body.InverseMass;

                Vector2.Dot(ref _r1, ref _r1, out _float1);
                Vector2.Dot(ref _r2, ref _r2, out _float2);
                _kTangent += GeometryA.body.inverseMomentOfInertia * (_float1 - _rt1 * _rt1) +
                             GeometryB.Body.InverseMomentOfInertia * (_float2 - _rt2 * _rt2);
                contact.MassTangent = 1f / _kTangent;

                //calc velocity bias
                _min = Math.Min(0, _physicsSimulator.allowedPenetration + contact.Separation);
                contact.NormalVelocityBias = -_physicsSimulator.biasFactor * inverseDt * _min;

                //Compute the _restitution, we average the _restitution of the two bodies
                //_restitution = (2.0f + _geometryA.RestitutionCoefficient + _geometryB.RestitutionCoefficient) * 0.5f;
                _restitution = (GeometryA.restitutionCoefficient + GeometryB.restitutionCoefficient) * .5f;

                //calc bounce velocity
                GeometryA.body.GetVelocityAtWorldOffset(ref _r1, out _vec1);
                GeometryB.body.GetVelocityAtWorldOffset(ref _r2, out _vec2);
                Vector2.Subtract(ref _vec2, ref _vec1, out _dv);

                //calc velocity difference along _contact normal
                Vector2.Dot(ref _dv, ref contact.Normal, out _vn);
                contact.BounceVelocity = _vn * _restitution;

                //apply accumulated _impulse
                Vector2.Multiply(ref contact.Normal, contact.NormalImpulse, out _vec1);
                Vector2.Multiply(ref _tangent, contact.TangentImpulse, out _vec2);
                Vector2.Add(ref _vec1, ref _vec2, out _impulse);

                GeometryB.body.ApplyImpulseAtWorldOffset(ref _impulse, ref _r2);

                Vector2.Multiply(ref _impulse, -1, out _impulse);
                GeometryA.body.ApplyImpulseAtWorldOffset(ref _impulse, ref _r1);

                contact.NormalImpulseBias = 0;
                _contactList[i]           = contact;
            }
        }
Exemplo n.º 21
0
 public Vector2 GetCenterPosition()
 {
     return(Vector2.Add(m_DrawPosition, m_EntityCenter));
 }
Exemplo n.º 22
0
        void HandleJumping(Vector2 Gravity)
        {
            if (_playerState == Characters.PlayerState.Swinging)
            {
                return;
            }

            Vector2      force = Gravity;
            InputManager input = InputManager.Instance;

            //  First jump
            if (_canJump)
            {
                if (_playerState == PlayerState.Climbing)
                {
                    if (!(input.MoveLeft(false) || input.MoveRight(false)))
                    {
                        return;
                    }

                    force *= 3.0f;

                    if (input.MoveLeft(false))
                    {
                        Vector2 additionalForce = SpinAssist.ModifyVectorByUp(new Vector2(-150, -force.Y * 0.5f));
                        Vector2.Add(ref force, ref additionalForce, out force);
                        this._lookingDirection = SpriteEffects.FlipHorizontally;
                    }
                    else if (InputManager.Instance.MoveRight(false))
                    {
                        Vector2 additionalForce = SpinAssist.ModifyVectorByUp(new Vector2(150, -force.Y * 0.5f));
                        Vector2.Add(ref force, ref additionalForce, out force);
                        this._lookingDirection = SpriteEffects.None;
                    }

                    this.ToggleBodies(true);
                    this._wheelBody.ApplyLinearImpulse(force);
                    this.PlayerState = PlayerState.Jumping;
                    this._canJump    = false;
                }
                else
                {
                    force *= _jumpForce;
                    _wheelBody.FixtureList[0].Body.ApplyLinearImpulse(force);
                    this.PlayerState = PlayerState.Jumping;
                    this._canJump    = false;
                    this._airTime    = 0.0f;
                    AudioManager.Instance.PlayCue("Harland_Grunt", true);
                }
            }
            //  Second jump (steam jump)
            else if (GameSettings.Instance.DoubleJumpEnabled && _canDoubleJump)
            {
                //  We only want to 0 the Up/Down depending on the
                //  orientation.
                #region Reset the Y dynamics.
                if (Math.Abs(Gravity.Y) > 0)
                {
                    this._mainBody.LinearVelocity  = new Vector2(_mainBody.LinearVelocity.X, 0);
                    this._wheelBody.LinearVelocity = new Vector2(_mainBody.LinearVelocity.X, 0);
                }
                else
                {
                    this._mainBody.LinearVelocity  = new Vector2(0, _mainBody.LinearVelocity.Y);
                    this._wheelBody.LinearVelocity = new Vector2(0, _mainBody.LinearVelocity.Y);
                }

                #endregion

                force *= _jumpForce;

                // Apply 2 forces. Up and then direction
                if (Math.Abs(InputManager.Instance.LeftThumbstick.X) >= 0.2)
                {
                    Vector2 direction = new Vector2(InputManager.Instance.LeftThumbstick.X, 0);
                    direction.Normalize();
                    direction *= 15.0f;

                    _wheelBody.ApplyLinearImpulse(direction);
                }

                //  Disable the possibilty to double jump.
                this._canDoubleJump = false;

                //  Reset any previous jump/fall timers.
                this._airTime          = 0.0f;
                this._deadlyFall       = false;
                this._lastSafePosition = ConvertUnits.ToDisplayUnits(_mainBody.Position);

                //  Switch the animation and reset it incase the player
                //  is already jumping.
                this.PlayerState = PlayerState.Jumping;
                this.CurrentAnimation.ResetCurrentFrame();

                //  Apply the force
                this._wheelBody.FixtureList[0].Body.ApplyLinearImpulse(force);

                //  then create the steam plume.
                this.CreateSteamPlume();
                AudioManager.Instance.PlayCue("Harland_Jump_Steam", true);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// This method changes the direction of the entity
        /// to face the desired entity.
        /// </summary>
        /// <param name="entity"></param>
        public void FaceEntity(GameEntity entity)
        {
            if (entity == null)
            {
                return;
            }

            DIRECTION movementDir = DIRECTION.UP;
            Vector2   targetPos   = Vector2.Add(entity.m_WorldPosition, entity.m_EntityCenter);

            m_TargetEntity = entity;


            if (m_WorldPosition.Y < targetPos.Y)
            {
                movementDir = DIRECTION.DOWN;
            }
            else if (m_WorldPosition.Y > targetPos.Y)
            {
                movementDir = DIRECTION.UP;
            }
            else
            {
                if (m_WorldPosition.X < entity.m_WorldPosition.X)//targetPos.X)
                {
                    if (movementDir == DIRECTION.DOWN)
                    {
                        movementDir = DIRECTION.DOWN_RIGHT;
                    }
                    else if (movementDir == DIRECTION.UP)
                    {
                        movementDir = DIRECTION.UP_RIGHT;
                    }
                    else
                    {
                        movementDir = DIRECTION.RIGHT;
                    }
                }
                else if (m_WorldPosition.X > entity.m_WorldPosition.X)//targetPos.X)
                {
                    if (movementDir == DIRECTION.DOWN)
                    {
                        movementDir = DIRECTION.DOWN_LEFT;
                    }
                    else if (movementDir == DIRECTION.UP)
                    {
                        movementDir = DIRECTION.UP_LEFT;
                    }
                    else
                    {
                        movementDir = DIRECTION.LEFT;
                    }
                }
                else
                {
                    movementDir = m_EntityDircetion;
                }
            }

            m_EntityDircetion = movementDir;
        }
Exemplo n.º 24
0
 public void Update(GameTime gameTime)
 {
     UpdateVelocity(gameTime);
     playerSprite.Position = Vector2.Add(playerSprite.Position, Velocity);
 }
Exemplo n.º 25
0
        /// <summary>
        /// Constructs a Textbox based on the params object passed in
        /// </summary>
        /// <param name="parms">TextBoxParams object</param>
        public TextBox(TextBoxParams parms) : base(parms)
        {
            this.font = parms.Font;
            this.Text = parms.Text;
            this.SIZE_PER_CHARACTER = parms.SizePerCharacter;
            this.MAX_LENGTH         = parms.MaxLength;
            this.VALID_KEYS         = new List <Keys>();
            this.VALID_KEYS.AddRange(KeyLists.DIRECTIONAL_KEYS);
            this.VALID_KEYS.AddRange(KeyLists.LETTERS_KEYS);
            this.VALID_KEYS.AddRange(KeyLists.NUMBER_KEYS);
            this.VALID_KEYS.AddRange(KeyLists.NUMPAD_KEYS);

            Vector2 endsScale = new Vector2(1f, parms.Scale.Y);
            Vector2 midScale  = new Vector2(parms.Scale.X, 1f);

            this.imgs = new List <StaticDrawable2D>();
            // Starting edge
            StaticDrawable2DParams imgParms = new StaticDrawable2DParams {
                Position           = parms.Position,
                LightColour        = parms.LightColour,
                RenderingRectangle = Constants.TXT_BOX_END,
                Scale   = endsScale,
                Texture = LoadingUtils.load <Texture2D>(parms.Content, Constants.GUI_FILE_NAME)
            };

            this.imgs.Add(new StaticDrawable2D(imgParms));

            // Middle bars
            Vector2 start    = new Vector2(imgParms.Position.X - 30f, imgParms.Position.Y);
            Vector2 startBar = Vector2.Add(start, new Vector2(Constants.TXT_BOX_END.Width, 0f));

            START_BAR_X = startBar.X;
            float length = parms.MaxLength * parms.SizePerCharacter + parms.Scale.X;

            imgParms.Position           = startBar;
            imgParms.RenderingRectangle = Constants.TXT_BOX_MIDDLE;
            imgParms.Scale = new Vector2(length, parms.Scale.Y);
            this.imgs.Add(new StaticDrawable2D(imgParms));

            // Ending edge
            imgParms.Position           = Vector2.Add(start, new Vector2(Constants.TXT_BOX_END.Width + length, 0f));
            imgParms.RenderingRectangle = Constants.TXT_BOX_END;
            imgParms.Scale = endsScale;
            this.imgs.Add(new StaticDrawable2D(imgParms));

            this.bbox = new BoundingBox(new Vector3(start.X, start.Y, 0f), new Vector3(imgParms.Position.X + Constants.TXT_BOX_MIDDLE.Width,
                                                                                       imgParms.Position.Y + Constants.TXT_BOX_MIDDLE.Height, 0f));

            // Cursor indicator
            float x = START_BAR_X + text.Length * SIZE_PER_CHARACTER + 4f;

            imgParms.Position    = new Vector2(x, imgParms.Position.Y + 6f);
            imgParms.Scale       = new Vector2(1f, (parms.Scale.Y - .5f));
            imgParms.LightColour = parms.TextColour;
            this.cursorIndicator = new StaticDrawable2D(imgParms);
            updateIndicatorsPosition();

            Text2DParams txtParms = new Text2DParams {
                Position    = new Vector2(parms.Position.X + 2f, parms.Position.Y),
                Font        = parms.Font,
                Scale       = parms.TextScale,
                WrittenText = this.Text,
                LightColour = parms.TextColour
            };

            this.text2D = new Text2D(txtParms);
        }
        public static void UpdateParticle(ParticleManager <ParticleState> .Particle particle)
        {
            var   vel   = particle.State.Velocity;
            float speed = vel.Length();

            // using Vector2.Add() should be slightly faster than doing "x.Position += vel;" because the Vector2s
            // are passed by reference and don't need to be copied. Since we may have to update a very large
            // number of particles, this method is a good candidate for optimizations.
            Vector2.Add(ref particle.Position, ref vel, out particle.Position);

            // fade the particle if its PercentLife or speed is low.
            float alpha = Math.Min(1, Math.Min(particle.PercentLife * 2, speed * 1f));

            alpha *= alpha;

            particle.Tint.A = (byte)(255 * alpha);

            // the length of bullet particles will be less dependent on their speed than other particles
            if (particle.State.Type == ParticleType.Bullet)
            {
                particle.Scale.X = particle.State.LengthMultiplier * Math.Min(Math.Min(1f, 0.1f * speed + 0.1f), alpha);
            }
            else
            {
                particle.Scale.X = particle.State.LengthMultiplier * Math.Min(Math.Min(1f, 0.2f * speed + 0.1f), alpha);
            }

            particle.Orientation = vel.ToAngle();

            var pos    = particle.Position;
            int width  = (int)NeonShooterGame.ScreenSize.X;
            int height = (int)NeonShooterGame.ScreenSize.Y;

            // collide with the edges of the screen
            if (pos.X < 0)
            {
                vel.X = Math.Abs(vel.X);
            }
            else if (pos.X > width)
            {
                vel.X = -Math.Abs(vel.X);
            }
            if (pos.Y < 0)
            {
                vel.Y = Math.Abs(vel.Y);
            }
            else if (pos.Y > height)
            {
                vel.Y = -Math.Abs(vel.Y);
            }

            if (particle.State.Type != ParticleType.IgnoreGravity)
            {
                foreach (var blackHole in EntityManager.BlackHoles)
                {
                    var   dPos     = blackHole.Position - pos;
                    float distance = dPos.Length();
                    var   n        = dPos / distance;
                    vel += 10000 * n / (distance * distance + 10000);

                    // add tangential acceleration for nearby particles
                    if (distance < 400)
                    {
                        vel += 45 * new Vector2(n.Y, -n.X) / (distance + 100);
                    }
                }
            }

            if (Math.Abs(vel.X) + Math.Abs(vel.Y) < 0.00000000001f)             // denormalized floats cause significant performance issues
            {
                vel = Vector2.Zero;
            }
            else if (particle.State.Type == ParticleType.Enemy)
            {
                vel *= 0.94f;
            }
            else
            {
                vel *= 0.96f + Math.Abs(pos.X) % 0.04f;                 // rand.Next() isn't thread-safe, so use the position for pseudo-randomness
            }
            particle.State.Velocity = vel;
        }
 public static BoundingBox getBBox64(Vector2 position)
 {
     return(new BoundingBox(
                new Vector3(Vector2.Subtract(position, new Vector2(Constants.TILE_SIZE)), 0f),
                new Vector3(Vector2.Add(position, new Vector2(Constants.TILE_SIZE)), 0f)));
 }
Exemplo n.º 28
0
        public bool VelocityColision(Polygon moving, Polygon stationary, Vector2 velocity)
        {
            Rectangle roughBounds = moving.Bounds;

            roughBounds.Width  += (int)Math.Ceiling(Math.Abs(velocity.X));
            roughBounds.Height += (int)Math.Ceiling(Math.Abs(velocity.Y));
            if (velocity.X < 0)
            {
                roughBounds.X += (int)Math.Ceiling(velocity.X);
            }
            if (velocity.Y < 0)
            {
                roughBounds.Y += (int)Math.Ceiling(velocity.Y);
            }
            debug_bounds = roughBounds;
            if (!roughBounds.Intersects(stationary.Bounds))
            {
                return(false);
            }

            float MV  = Physics.ConvertToMA(velocity).X;
            float MV2 = MV * MV;

            List <Vector2[]> movingLines     = new List <Vector2[]>();
            List <Vector2[]> stationaryLines = new List <Vector2[]>();

            for (int i = 0; i < moving.NumberOfSides(); i++)
            {
                movingLines.Add(new Vector2[] { moving.GetCorner(i), Vector2.Add(moving.GetCorner(i), velocity) });
            }

            for (int i = 0; i < stationary.NumberOfSides(); i++)
            {
                stationaryLines.Add(new Vector2[] { Vector2.Subtract(stationary.GetCorner(i), velocity), stationary.GetCorner(i) });
            }
            float maxMove = (velocity.X * velocity.X) + (velocity.Y * velocity.Y);
            bool  colid   = false;

            for (int i = 0; i < movingLines.Count; i++)
            {
                foreach (Vector2 [] edge in stationary.GetEdges())
                {
                    Vector2?Colision = LocationManager.getIntersectionPoint(movingLines[i], edge);
                    switch (LocationManager.LinesIntersect_Precise(movingLines[i], edge))
                    {
                    case 1:
                        if (Colision.HasValue)
                        {
                            float newdist = LocationManager.getDistanceSquared(movingLines[i][0], Colision.Value);
                            if (newdist < maxMove)
                            {
                                maxMove = newdist;
                            }
                            colid   = true;
                            HITEDGE = edge;
                        }
                        else
                        {
                            Console.Out.WriteLine("? ? ? ?");
                        }
                        break;

                    case 2:
                        Cot = new Vector2[2][] { movingLines[i], edge };
                        Vector2[] edgecheck = new Vector2[] { movingLines[i][0], Vector2.Add(movingLines[i][0], Vector2.Multiply(velocity, 100000)) };
                        int       hitcount  = 0;
                        foreach (Vector2[] ec2 in stationary.GetEdges())
                        {
                            if (LocationManager.LinesIntersect_Precise(ec2, edgecheck) == 1)
                            {
                                hitcount++;
                            }
                        }
                        if (hitcount % 2 == 0)
                        {
                        }
                        else
                        {
                            if (Colision.HasValue)
                            {
                                float newdist = LocationManager.getDistanceSquared(movingLines[i][0], Colision.Value);
                                if (newdist < maxMove)
                                {
                                    maxMove = newdist;
                                }
                                colid   = true;
                                HITEDGE = edge;
                            }
                            else
                            {
                                Console.Out.WriteLine("? ? ? ?");
                            }
                        }
                        break;

                    default:
                    case 0:
                        break;
                    }
                }
            }

            for (int i = 0; i < stationaryLines.Count; i++)
            {
                foreach (Vector2[] edge in moving.GetEdges())
                {
                    Vector2?Colision = LocationManager.getIntersectionPoint(stationaryLines[i], edge);
                    switch (LocationManager.LinesIntersect_Precise(stationaryLines[i], edge))
                    {
                    case 1:
                        if (Colision.HasValue)
                        {
                            float newdist = MV2 - LocationManager.getDistanceSquared(stationaryLines[i][0], Colision.Value);
                            if (newdist < maxMove)
                            {
                                maxMove = newdist;
                            }
                            colid   = true;
                            HITEDGE = edge;
                        }
                        else
                        {
                            Console.Out.WriteLine("? ? ? ?");
                        }
                        break;

                    case 2:
                        Cot = new Vector2[2][] { stationaryLines[i], edge };
                        Vector2[] edgecheck = new Vector2[] { stationaryLines[i][0], Vector2.Add(stationaryLines[i][0], Vector2.Multiply(velocity, 100000)) };
                        int       hitcount  = 0;
                        foreach (Vector2[] ec2 in moving.GetEdges())
                        {
                            if (LocationManager.LinesIntersect_Precise(ec2, edgecheck) == 1)
                            {
                                hitcount++;
                            }
                        }
                        if (hitcount % 2 == 0)
                        {
                        }
                        else
                        {
                            if (Colision.HasValue)
                            {
                                float newdist = MV2 - LocationManager.getDistanceSquared(stationaryLines[i][0], Colision.Value);
                                if (newdist < maxMove)
                                {
                                    maxMove = newdist;
                                }
                                colid   = true;
                                HITEDGE = edge;
                            }
                            else
                            {
                                Console.Out.WriteLine("? ? ? ?");
                            }
                        }
                        break;

                    default:
                    case 0:
                        break;
                    }
                }
            }

            if (colid)
            {
                maxV = (float)Math.Sqrt(maxMove) / MV;
                return(true);
            }

            debug_AllLines = new List <Vector2[]>();
            debug_AllLines.AddRange(movingLines);
            debug_AllLines.AddRange(stationaryLines);

            return(false);
        }
Exemplo n.º 29
0
 public void Draw(SpriteBatch surface, Camera camera)
 {
     if (Hero == null)
     {
         surface.Draw(SimpleUtils.WhiteRect, new Rectangle(camera.WorldToWindow(Position.Add(0.5f) - new Vector2(WIDTH / 2f, VSize - 1.5f)), (new Vector2(WIDTH, VSize) * camera.Scale).ToPoint( )), Color.Green);
     }
     else
     {
         Hero.offset = new Vector2(camera.Scale.X / 2, camera.Scale.Y);
         Hero.Draw(camera);
     }
 }
Exemplo n.º 30
0
 /// <summary>
 /// Performs vector addition on <paramref name="a"/> and <paramref name="b"/>.
 /// </summary>
 /// <param name="a">Source <see cref="PointF"/> on the left of the add sign.</param>
 /// <param name="b">Source <see cref="PointF"/> on the right of the add sign.</param>
 /// <returns>Sum of the vectors.</returns>
 public static PointF operator +(PointF a, PointF b)
 {
     return((PointF)Vector2.Add(a, b));
 }
Exemplo n.º 31
0
 public override Vector2 Add(Vector2 from, Vector2 to)
 {
     return(Vector2.Add(from, to));
 }
Exemplo n.º 32
0
 /** Adjust this creature's velocity by adding the movement vector.
  *
  * This function will likely be where the logic for collision is implemented.
  *
  **/
 public void Move(Vector2 movement, GameTime gameTime)
 {
     this.velocity = Vector2.Add(this.velocity, movement);
 }
Exemplo n.º 33
0
        /// <summary>
        /// Calculates and applies corrective impulses.
        /// Called automatically by space.
        /// </summary>
        public override float SolveIteration()
        {
            #region Theory

            //lambda = -mc * (Jv + b)
            // PraT = [ bx by bz ] * [  0   raz -ray ] = [ (-by * raz + bz * ray) (bx * raz - bz * rax) (-bx * ray + by * rax) ]
            //        [ cx cy cz ]   [ -raz  0   rax ]   [ (-cy * raz + cz * ray) (cx * raz - cz * rax) (-cx * ray + cy * rax) ]
            //                       [ ray -rax   0  ]
            //
            // PrbT = [ bx by bz ] * [  0   rbz -rby ] = [ (-by * rbz + bz * rby) (bx * rbz - bz * rbx) (-bx * rby + by * rbx) ]
            //        [ cx cy cz ]   [ -rbz  0   rbx ]   [ (-cy * rbz + cz * rby) (cx * rbz - cz * rbx) (-cx * rby + cy * rbx) ]
            //                       [ rby -rbx   0  ]
            // Jv = [ bx by bz  PraT  -bx -by -bz  -Prbt ] * [ vax ]
            //      [ cx cy cz        -cx -cy -cz        ]   [ vay ]
            //                                               [ vaz ]
            //                                               [ wax ]
            //                                               [ way ]
            //                                               [ waz ]
            //                                               [ vbx ]
            //                                               [ vby ]
            //                                               [ vbz ]
            //                                               [ wbx ]
            //                                               [ wby ]
            //                                               [ wbz ]
            // va' = [ bx * vax + by * vay + bz * vaz ] = [ b * va ]
            //       [ cx * vax + cy * vay + cz * vaz ]   [ c * va ]
            // wa' = [ (PraT row 1) * wa ]
            //       [ (PraT row 2) * wa ]
            // vb' = [ -bx * vbx - by * vby - bz * vbz ] = [ -b * vb ]
            //       [ -cx * vbx - cy * vby - cz * vbz ]   [ -c * vb ]
            // wb' = [ -(PrbT row 1) * wb ]
            //       [ -(PrbT row 2) * wb ]
            // Jv = [ b * va + (PraT row 1) * wa - b * vb - (PrbT row 1) * wb ]
            //      [ c * va + (PraT row 2) * wa - c * vb - (PrbT row 2) * wb ]
            // Jv = [ b * (va + wa x ra - vb - wb x rb) ]
            //      [ c * (va + wa x ra - vb - wb x rb) ]
            //P = JT * lambda

            #endregion

#if !WINDOWS
            Vector2 lambda = new Vector2();
#else
            Vector2 lambda;
#endif
            //float va1, va2, wa1, wa2, vb1, vb2, wb1, wb2;
            //Vector3.Dot(ref worldAxis1, ref myParentA.myInternalLinearVelocity, out va1);
            //Vector3.Dot(ref worldAxis2, ref myParentA.myInternalLinearVelocity, out va2);
            //wa1 = prAT.M11 * myParentA.myInternalAngularVelocity.X + prAT.M12 * myParentA.myInternalAngularVelocity.Y + prAT.M13 * myParentA.myInternalAngularVelocity.Z;
            //wa2 = prAT.M21 * myParentA.myInternalAngularVelocity.X + prAT.M22 * myParentA.myInternalAngularVelocity.Y + prAT.M23 * myParentA.myInternalAngularVelocity.Z;

            //Vector3.Dot(ref worldAxis1, ref myParentB.myInternalLinearVelocity, out vb1);
            //Vector3.Dot(ref worldAxis2, ref myParentB.myInternalLinearVelocity, out vb2);
            //wb1 = prBT.M11 * myParentB.myInternalAngularVelocity.X + prBT.M12 * myParentB.myInternalAngularVelocity.Y + prBT.M13 * myParentB.myInternalAngularVelocity.Z;
            //wb2 = prBT.M21 * myParentB.myInternalAngularVelocity.X + prBT.M22 * myParentB.myInternalAngularVelocity.Y + prBT.M23 * myParentB.myInternalAngularVelocity.Z;

            //lambda.X = va1 + wa1 - vb1 - wb1 + biasVelocity.X + mySoftness * accumulatedImpulse.X;
            //lambda.Y = va2 + wa2 - vb2 - wb2 + biasVelocity.Y + mySoftness * accumulatedImpulse.Y;
            Vector3 dv;
            Vector3 aVel, bVel;
            Vector3.Cross(ref connectionA.angularVelocity, ref rA, out aVel);
            Vector3.Add(ref aVel, ref connectionA.linearVelocity, out aVel);
            Vector3.Cross(ref connectionB.angularVelocity, ref rB, out bVel);
            Vector3.Add(ref bVel, ref connectionB.linearVelocity, out bVel);
            Vector3.Subtract(ref aVel, ref bVel, out dv);
            Vector3.Dot(ref dv, ref worldRestrictedAxis1, out lambda.X);
            Vector3.Dot(ref dv, ref worldRestrictedAxis2, out lambda.Y);


            lambda.X += biasVelocity.X + softness * accumulatedImpulse.X;
            lambda.Y += biasVelocity.Y + softness * accumulatedImpulse.Y;

            //Convert to impulse
            Matrix2x2.Transform(ref lambda, ref negativeEffectiveMassMatrix, out lambda);

            Vector2.Add(ref lambda, ref accumulatedImpulse, out accumulatedImpulse);

            float x = lambda.X;
            float y = lambda.Y;
            //Apply impulse
#if !WINDOWS
            Vector3 impulse = new Vector3();
            Vector3 torque  = new Vector3();
#else
            Vector3 impulse;
            Vector3 torque;
#endif
            impulse.X = worldRestrictedAxis1.X * x + worldRestrictedAxis2.X * y;
            impulse.Y = worldRestrictedAxis1.Y * x + worldRestrictedAxis2.Y * y;
            impulse.Z = worldRestrictedAxis1.Z * x + worldRestrictedAxis2.Z * y;
            if (connectionA.isDynamic)
            {
                torque.X = x * angularA1.X + y * angularA2.X;
                torque.Y = x * angularA1.Y + y * angularA2.Y;
                torque.Z = x * angularA1.Z + y * angularA2.Z;

                connectionA.ApplyLinearImpulse(ref impulse);
                connectionA.ApplyAngularImpulse(ref torque);
            }
            if (connectionB.isDynamic)
            {
                impulse.X = -impulse.X;
                impulse.Y = -impulse.Y;
                impulse.Z = -impulse.Z;

                torque.X = x * angularB1.X + y * angularB2.X;
                torque.Y = x * angularB1.Y + y * angularB2.Y;
                torque.Z = x * angularB1.Z + y * angularB2.Z;

                connectionB.ApplyLinearImpulse(ref impulse);
                connectionB.ApplyAngularImpulse(ref torque);
            }
            return(Math.Abs(lambda.X) + Math.Abs(lambda.Y));
        }
Exemplo n.º 34
0
        public Dictionary<Vector2, Tile> GetDiagonalNeighbors(Vector2 center)
        {
            var toCheck = new Vector2[4]{
                center.Add(-1, -1),
                center.Add(-1, 1),
                center.Add(1, -1),
                center.Add(1, 1)
            };

            return CheckNeighbors(toCheck);
        }