Length() public method

Calculates the length of the vector.
public Length ( ) : float
return float
コード例 #1
0
        /// <summary>
        /// Update to chase the player.
        /// </summary>
        /// <param name="playerPos">The position of player. Basically the direction it's heading.</param>
        public void Update(Vector2 playerPos, GameTime gameTime)
        {
            distance = new Vector2(playerPos.X - position.X, playerPos.Y - position.Y);
            speed.X = (playerPos.X - position.X) * speedLength / distance.Length();
            speed.Y = (playerPos.Y - position.Y) * speedLength / distance.Length();

            timeSinceLastSwitch += gameTime.ElapsedGameTime.Milliseconds;
            if (timeSinceLastSwitch > millisecondPerSwitch)
            {
                timeSinceLastSwitch -= millisecondPerSwitch;
                isChasing = !isChasing;
            }

            if (isChasing)
            {
                speed *= 1;     // chase
            }
            else
            {
                speed *= -0.5f;       // evade
            }
            // Prevent EvadingEnemies from moving out of window
            if (position.X < 0) position.X = 0;
            if (position.Y < 0) position.Y = 0;
            if (position.X > windowWidth)
                position.X = windowWidth;
            if (position.Y > windowHeight)
                position.Y = windowHeight;
            base.Update();
        }
コード例 #2
0
ファイル: InputManager.cs プロジェクト: njustesen/local-rts
        public static Vector2 ThumbMovement(Vector2 state)
        {
            float xb = state.X;
            float yb = state.Y;

            Vector2 direction = new Vector2(xb, yb);

            float deadZone = 0.3f;
            if (direction.Length() < deadZone)
            {
                direction = Vector2.Zero;
            }
            else
            {
                direction = direction.GetNormalized() * ((direction.Length() - deadZone) / (1 - deadZone));
            }

            //if (direction.Length() > 0.95f)
            //{
            //    float magnitude = 0.95f;
            //    direction.Normalize();
            //    direction.X = direction.X * magnitude;
            //    direction.Y = direction.Y * magnitude;
            //}
            return direction;
        }
コード例 #3
0
        public override Vector2 Execute(Vector2 source, Vector2 target)
        {
            //return source;

            // Todo: Optimize, remove jitter and avoid walls.
            var circleCenter = velocity;
            circleCenter.Normalize();
            circleCenter = Vector2.Multiply(circleCenter, CircleDistance);

            var displacement = new Vector2(0, -1);
            displacement = Vector2.Multiply(displacement, CircleRadius);

            displacement.X = (float)Math.Cos(wanderAngle) * displacement.Length();
            displacement.Y = (float)Math.Sin(wanderAngle) * displacement.Length();

            wanderAngle += random.Next(0, 359) * AngleChange * 5;

            // steering aka wanderForce
            var steering = Vector2.Add(circleCenter, displacement);

            steering = steering.Truncate(MaxForce);
            steering = Vector2.Divide(steering, Mass);

            this.velocity = Vector2.Add(this.velocity, steering);
            this.velocity = this.velocity.Truncate(MaxVelocity);

            return source + this.velocity;
        }
コード例 #4
0
 public static Vector2 GetNormal(Vector2 src)
 {
     Vector2 result = new Vector2();
     result.Y = src.X / src.Length();
     result.X = -src.Y /src.Length();
     return result;
 }
コード例 #5
0
        public override GraphicsToolkit.Physics._3D.Contact3D GenerateContact(RigidBody3D rb, float dt)
        {
            if (rb as SphereBody != null)
            {
                SphereBody c = rb as SphereBody; //sphere that this body is colliding with
                Vector3 pa = c.Pos; //point on this body closest to the sphere

                Vector2 XYVec = new Vector2(pa.X - 0.5f, pa.Y - 0.5f);
                if (XYVec.LengthSquared() < 1) //if inside bounding box but outside actual block
                {
                    pa.X = ((pa.X - 0.5f) / XYVec.Length()) + 0.5f;
                    pa.Y = ((pa.Y - 0.5f) / XYVec.Length()) + 0.5f;
                }

                pa.X = MathHelper.Clamp(pa.X, -0.5f, 0.5f);
                pa.Y = MathHelper.Clamp(pa.Y, -0.5f, 0.5f);
                pa.Z = MathHelper.Clamp(pa.Z, -0.5f, 0.5f);

                Vector3 normal = rb.Pos - pa;
                float normLen = normal.Length();
                float dist = normLen - c.Radius; //distance from block to sphere
                normal /= normLen; //normalize normal
                Vector3 pb = rb.Pos - normal * c.Radius; //closest point on sphere

                return new Contact3D(normal, dist, this, rb, pa, pb);
            }
            else
            {
                throw new NotImplementedException();
            }
        }
コード例 #6
0
 /// <summary>
 /// Update to chase the player.
 /// </summary>
 /// <param name="playerPos">The position of player. Basically the direction it's heading.</param>
 public void Update(Vector2 playerPos)
 {
     distance = new Vector2(playerPos.X - position.X, playerPos.Y - position.Y);
     speed.X = (playerPos.X - position.X) * speedLength / distance.Length();
     speed.Y = (playerPos.Y - position.Y) * speedLength / distance.Length();
     base.Update();
 }
コード例 #7
0
        public override void Update(GameTime gameTime)
        {
            Vector2 direction = new Vector2(0, 0);

            mFixture.Body.ResetDynamics();
            mFixture.Body.LinearVelocity = new Vector2(0, 0);
            mFixture.Body.Rotation = 0;

            UpdateInput();

            //base.Update(gameTime);
            if (mControllable)
            {
                direction = DetermineDesiredDirection();

                if (direction.Length() > .065f)
                {
                    mFixture.Body.LinearVelocity = (direction * mMaxSpeed);
                }

                if (direction.Length() > 0)
                {
                    direction.Normalize();
                    mDirection = direction;
                }
            }

            mPosition = new Vector2(mFixture.Body.Position.X, mFixture.Body.Position.Y); // converts Body.Position (meters) into pixels

            UpdateAnimation(gameTime, direction);
        }
コード例 #8
0
 public static Vector2 MaxLimit(Vector2 vector, float limit)
 {
     if (vector.Length() > limit)
     {
         float factor = vector.Length() / limit;
         vector = vector / factor;
     }
     return vector;
 }
コード例 #9
0
ファイル: BloodManager.cs プロジェクト: martinvium/ngj2012
        public float AngleBetween(Vector2 a, Vector2 b)
        {
            float dotProd = Vector2.Dot(a, b);
            float lenProd = a.Length() * b.Length();
            float cos = dotProd / lenProd;

            a = new Vector2(a.Y, -a.X);
            dotProd = Vector2.Dot(a, b);
            lenProd = a.Length() * b.Length();
            float sin = dotProd / lenProd;

            return (float)Math.Atan2(sin, cos);
        }
コード例 #10
0
        /// <summary>
        /// Creates a conic light texture with fov and near plane distance
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="size">The size.</param>
        /// <param name="fov">The fov.</param>
        /// <param name="nearPlaneDistance">The near plane distance.</param>
        /// <returns>
        /// A Texture
        /// </returns>
        public static Texture2D CreateConic(GraphicsDevice device, int size, float fov, float nearPlaneDistance)
        {
            var data1D = new Color[size * size];

            var halfSize = size / 2f;

            fov /= 2;

            for (var x = 0; x < size; x++)
            {
                for (var y = 0; y < size; y++)
                {
                    var vector = new Vector2(x - halfSize, y - halfSize);

                    var distance = vector.Length();

                    var angle = Math.Abs(Math.Atan2(vector.Y, vector.X));

                    var illumination = 0f;

                    if (distance <= halfSize && distance >= nearPlaneDistance && angle <= fov)
                    {
                        illumination = (halfSize - distance) / halfSize;
                    }

                    data1D[x + (y * size)] = new Color(illumination, illumination, illumination, illumination);
                }
            }

            var tex = new Texture2D(device, size, size);

            tex.SetData(data1D);

            return tex;
        }
コード例 #11
0
        public bool Update()
        {
            if (Game1.currentRoom.Freeroam)
                return false;

            if (this.hitBox.Intersects(Game1.currentRoom.ViewBox))
            {
                Vector2 direction = new Vector2(Game1.currentRoom.Runner.hitBox.X - hitBox.X, Game1.currentRoom.Runner.hitBox.Y - hitBox.Y);
                angle = (float)Math.Acos(direction.X / direction.Length());
                if (direction.Y < 0)
                    angle *= -1;

                if (pause != pauseTime)
                    pause++;
                else
                {
                    if (Game1.currentRoom.Runner.position.Y <= Game1.currentRoom.roomHeight)
                    {
                        Game1.rocketLaunch.Play(0.5f * Settings.soundVol, 0f, 0f);
                        rocket.position.X = hitBox.X + 8;
                        rocket.position.Y = hitBox.Y + 16;
                        rocket.angle = angle;
                        pause++;
                    }
                }
            }
            return rocket.Update();
        }
コード例 #12
0
ファイル: Ball.cs プロジェクト: obcilion/xnaKanonSpill
 public void update()
 {
     wallCollisionCheck();
     Velocity *= friction;
     if (Velocity.Length() < 0.1)  Velocity = Vector2.Zero;
     Position += Velocity;
 }
コード例 #13
0
ファイル: Particle.cs プロジェクト: foolmoron/Retroverse
        public void Update(double currentTimeAbsoluteSecs, Emitter e)
        {
            time = (float)(currentTimeAbsoluteSecs - creationTimeAbsoluteSecs);
            posShift = time * velocity;
            dist = posShift.Length() * ((time < 0) ? -1 : 1);

            if (e == null)
                position = originalPos + posShift;
            else
                position = e.position + e.startDistance * vUnit + posShift;
            switch (deathMode)
            {
                case ParticleDeathMode.Seconds:
                    lifecycle = time / valueToDeath;
                    break;
                case ParticleDeathMode.Distance:
                    lifecycle = dist / valueToDeath;
                    break;
            }
            if (lifecycle > 1 || lifecycle < 0)
            {
                return;
            }
            float r, g, b, a;
            a = (startColor.A * (1 - lifecycle) + endColor.A * lifecycle);
            color.A = (byte) a;
            r = (startColor.R * (1 - lifecycle) + endColor.R * lifecycle);
            g = (startColor.G * (1 - lifecycle) + endColor.G * lifecycle);
            b = (startColor.B * (1 - lifecycle) + endColor.B * lifecycle);
            color.R = (byte)Math.Min(a, r);
            color.G = (byte)Math.Min(a, g);
            color.B = (byte)Math.Min(a, b);
            size = startSize * (1 - lifecycle) + endSize * lifecycle;
        }
コード例 #14
0
 public void sendInput(Vector2 pInput, float pBreak )
 {
     _inputs = pInput;
     _normalizedInputs = _inputs;
     _normalizedInputs.Normalize();
     _inputsLength = _inputs.Length()- pBreak;
 }
コード例 #15
0
ファイル: Manifestant.cs プロジェクト: huardca/jampack_xna
        public void Update(float dt)
        {
            if (m_Recrutable.Target == null)
            {
                m_PickedUp = false;
                return;
            }

            if (m_PickedUp == false)
            {
                m_PickedUp = true;
                m_GM.InfluenceRadius += 0.05f;
            }

            Vector3 playerPos = m_Recrutable.Target.GetWorldTranslation();

            Vector3 current = Owner.GetWorldTranslation();

            Vector3 toplayer3D = playerPos - current;
            Vector2 toplayer = new Vector2(toplayer3D.X, toplayer3D.Y);

            m_Joint.TargetAngle = (float)Math.Atan2((double)toplayer.Y, (double)toplayer.X) - (float)Math.Atan2(1, 0);

            if (toplayer.Length() < 0.6f)
            {
                m_Physics.LinearVelocity = new Vector2(0,0);
            }
            else
            {
                toplayer.Normalize();
                m_Physics.ApplyForce(m_Force * toplayer);
            }
        }
コード例 #16
0
ファイル: CollisionCylinder.cs プロジェクト: Jemeyr/ELTMC
        public Vector3 intersects(CollisionCylinder other)
        {
            float yDiff = this.position.Y - other.position.Y;
            float combinedHeight = this.Height + other.Height;
            float combinedRadius = this.Radius + other.Radius;

            //first check if height intersects
            if (Math.Abs(yDiff) < combinedHeight )
            {
                Vector2 xzDiff = new Vector2(this.position.X - other.position.X,this.position.Z - other.position.Z);
                if (xzDiff.LengthSquared() < combinedRadius * combinedRadius)
                {
                    float intersectY = combinedHeight - yDiff;
                    Vector2 intersectXZ = Vector2.Normalize(xzDiff) * (combinedRadius - xzDiff.Length());

                    if (intersectY * intersectY < intersectXZ.LengthSquared())
                    {
                        return  Vector3.Up * (combinedHeight - yDiff);
                    }
                    else
                    {
                        return new Vector3(intersectXZ.X,0f, intersectXZ.Y);
                    }
                }

            }
            return Vector3.Zero;
        }
コード例 #17
0
ファイル: Arrow.cs プロジェクト: DaveEmmerson/SpaceWar2
        private Arrow(Vector2 position, Vector2 direction, Color color, float radius)
        {
            _vertices = new VertexPositionColor[6];

            var length = 3f * (float)Math.Sqrt(direction.Length());

            direction.Normalize();

            var arrowHeadSize = radius / 3f;
            var perpendicular = new Vector3(-direction.Y, direction.X, 0);
            var arrowBase = new Vector3(position + (direction * radius), 0);
            var arrowHead = new Vector3(position + (direction * (radius + length)), 0);
            var arrowPoint = new Vector3(position + (direction * (radius + length + arrowHeadSize)), 0);

            _vertices[0].Position = arrowBase;
            _vertices[1].Position = arrowHead;
            _vertices[2].Position = arrowHead - (perpendicular * arrowHeadSize);
            _vertices[3].Position = arrowPoint;
            _vertices[4].Position = arrowHead + (perpendicular * arrowHeadSize);
            _vertices[5].Position = arrowHead;

            for (var i = 1; i <=5; i++)
            {
                _vertices[i].Color = color;
            }
            _vertices[0].Color = Color.Transparent;
        }
コード例 #18
0
ファイル: Sampler.cs プロジェクト: Lin20/isosurface
 public static float CappedCylinder(Vector3 p, Vector2 h)
 {
     Vector2 d = new Vector2((float)Math.Abs(Math.Sqrt(p.X * p.X + p.Z * p.Z)), Math.Abs(p.Y)) - h;
     d = new Vector2(Math.Max(d.X, 0), Math.Max(d.Y, 0));
     float f = Math.Min(Math.Max(d.X, d.Y), 0.0f) + d.Length();
     return f;
 }
コード例 #19
0
ファイル: ArtParticle.cs プロジェクト: Lambosaurus/StarPixel
        public void Load(ContentManager content)
        {
            sprite = content.Load<Texture2D>(sprite_name);

            Vector2 size = new Vector2(sprite.Bounds.Width, sprite.Bounds.Height);
            sprite_center = size / 2;

            float rad_start = size_start.Length();
            float rad_end = size_end.Length();
            
            float visual_particle_size;

            // if we say the particles visual impact is its size multiplied by its transparency,
            // then we can solve for the maximum visual impact.
            if (rad_start > rad_end) { visual_particle_size = rad_start; }
            else
            {
                float rsr = rad_start / rad_end;
                float maxima_alpha = (rsr - 0.5f) / (rsr - 1);
                visual_particle_size = (rad_start*(1-maxima_alpha) + (rad_end * maxima_alpha)) * (1-maxima_alpha);
            }

            // we div the below by 2, because the sprite_center.Length() and the particle size .Lenght()'s are both
            // larger than the actual radiuses they represent by root(2)
            max_particle_radius = (sprite_center.Length() * visual_particle_size / 2);
        }
コード例 #20
0
        public override void Update(GameTime gameTime)
        {
            
            enginePower = 3;


            delta = Target.Position - Position;
            delta.Normalize();

            delta *= enginePower;

            Rotation = (float)(Math.Atan2(delta.Y,delta.X));

            var currentSpeed = delta.Length();
            if (currentSpeed > MaxSpeed)
            {
                currentSpeed = MaxSpeed;
            }
            if (currentSpeed > 0)
            {
                currentSpeed -= Friction;
            }
            else currentSpeed = 0;
            delta *= currentSpeed;


            Move(delta);

            base.Update(gameTime);
        }
コード例 #21
0
        internal ControllerState Update(GameTime time)
        {
            lastState = currentState;
            currentState = GamePad.GetState(PlayerIndex.One);
            if (currentState.IsConnected == false) { _disconnected = true; }
            else if (currentState.IsConnected == true) { _disconnected = false; }

            // Allows the game to exit
            if (currentState.Buttons.Back == ButtonState.Pressed)
                return ControllerState.Exit;
            if (currentState.Buttons.Start == ButtonState.Pressed && lastState.Buttons.Start == ButtonState.Released)
                _paused = (_paused) ? false : true;

            if (!_paused)
            {
                Vector2 moveUnit = new Vector2(currentState.ThumbSticks.Left.X,
                    currentState.ThumbSticks.Left.Y);
                if (moveUnit.Length() > 0.1f)
                {
                    Console.Out.WriteLine(moveUnit.ToString());
                    unit.MoveUnit(moveUnit);
                }

                unit.MoveAimer(new Vector2(currentState.ThumbSticks.Right.X,
                    currentState.ThumbSticks.Right.Y));
            }

            if (currentState.Buttons.RightShoulder == ButtonState.Pressed)
            {
                unit.Fire();
            }

            return ControllerState.Normal;
        }
コード例 #22
0
		public override bool Perform(Point origin, GenAction action)
		{
			Vector2 vector = new Vector2((float)this._offset.X, (float)this._offset.Y);
			float num = vector.Length();
			int num2 = (int)(num / 6f);
			if (this._endPoints != null)
			{
				this._endPoints.Add(new Point(origin.X + this._offset.X, origin.Y + this._offset.Y));
			}
			if (!this.PerformSegment(origin, action, origin, new Point(origin.X + this._offset.X, origin.Y + this._offset.Y), num2))
			{
				return false;
			}
			int num3 = (int)(num / 8f);
			for (int i = 0; i < num3; i++)
			{
				float num4 = ((float)i + 1f) / ((float)num3 + 1f);
				Point point = new Point((int)(num4 * (float)this._offset.X), (int)(num4 * (float)this._offset.Y));
				Vector2 spinningpoint = new Vector2((float)(this._offset.X - point.X), (float)(this._offset.Y - point.Y));
				spinningpoint = spinningpoint.RotatedBy((double)(((float)GenBase._random.NextDouble() * 0.5f + 1f) * (float)((GenBase._random.Next(2) == 0) ? -1 : 1)), default(Vector2)) * 0.75f;
				Point point2 = new Point((int)spinningpoint.X + point.X, (int)spinningpoint.Y + point.Y);
				if (this._endPoints != null)
				{
					this._endPoints.Add(new Point(point2.X + origin.X, point2.Y + origin.Y));
				}
				if (!this.PerformSegment(origin, action, new Point(point.X + origin.X, point.Y + origin.Y), new Point(point2.X + origin.X, point2.Y + origin.Y), num2 - 1))
				{
					return false;
				}
			}
			return true;
		}
コード例 #23
0
        public static bool LineToRect(Lazer lazer, Rectangle box)
        {
            Vector2 rectDelta = new Vector2(box.Center.X, box.Center.Y) - lazer.Position;
            float boxAngle = (float)Math.Atan2(rectDelta.Y, rectDelta.X);

            float angle = lazer.Angle;

            if (angle < -180) angle += 360;
            if (angle > 180) angle -= 360;

            if (boxAngle > angle - 45 && boxAngle < angle + 45)
            {
                for (int i = 0; i < lazer.length; i++)
                {
                    if (i > rectDelta.Length() + 20) return false;

                    Vector2 walkersPos = lazer.Position + Globals.VectorFromAngle(lazer.Angle) * i;

                    if (box.Intersects(new Rectangle((int)(walkersPos.X - (lazer.width * 8) / 2), (int)(walkersPos.Y - (lazer.width * 8) / 2), (int)lazer.width * 8, (int)lazer.width * 8))) return true;
                }
            }
            else
                return false;

            return false;
        }
コード例 #24
0
ファイル: PolarCoordinate.cs プロジェクト: xxy1991/cozy
        /// <summary>
        /// Converts a Cartesian x-, y- coordinate pair to polar coordinates.
        /// </summary>
        /// <param name="cartesian"></param>
        /// <returns></returns>
        public static PolarCoordinate FromCartesian(Vector2 cartesian)
        {
            float angle = (float)Math.Atan2(cartesian.Y, cartesian.X);
            float distance = cartesian.Length();

            return new PolarCoordinate(angle, distance);
        }
コード例 #25
0
ファイル: Collision.cs プロジェクト: bluemagic123/Slip
 public static Vector2 MovePos(Vector2 position, float width, float height, Vector2 velocity, Room room, out bool collided)
 {
     collided = false;
     if (velocity == Vector2.Zero)
     {
         return position;
     }
     while (velocity != Vector2.Zero)
     {
         Hitbox box = new Hitbox(position, width, height);
         CollideLine? collision = GetNextCollision(box, velocity, room);
         float distance = collision.HasValue ? collision.Value.distance : velocity.Length();
         Vector2 move = velocity;
         move.Normalize();
         move *= distance;
         position += move;
         velocity -= move;
         if (collision.HasValue)
         {
             switch (collision.Value.type)
             {
                 case CollideType.X:
                     velocity.X = 0f;
                     break;
                 case CollideType.Y:
                     velocity.Y = 0f;
                     break;
             }
             collided = true;
         }
     }
     return position;
 }
コード例 #26
0
ファイル: EnemyVirus.cs プロジェクト: MarkCourtney/Bio-Cell
        public override void Update(GameTime gameTime)
        {
            float timeDelta = (float)gameTime.ElapsedGameTime.TotalSeconds;

            center = pos + new Vector2(sprite.Width / 2, sprite.Height / 2);

            sphere = new BoundingSphere(new Vector3(center.X, center.Y, 0), radius);

            target = new Vector2(Game1.Instance.PlayerCell.center.X - center.X, Game1.Instance.PlayerCell.center.Y - center.Y);

            comboRadius = (Game1.Instance.PlayerCell.radius + radius);
            distance = Vector2.Distance(Game1.Instance.PlayerCell.center, center) - comboRadius;

            look.X = (float)Math.Sin(rotation);
            look.Y = (float)-Math.Cos(rotation);

            rotation = (float)Math.Acos(Vector2.Dot(basis, target) / target.Length());

            if (Game1.Instance.PlayerCell.center.X < center.X)
            {
                rotation = -rotation;
            }

            CheckDistance(timeDelta);
        }
コード例 #27
0
ファイル: Wander.cs プロジェクト: Bigalan09/Evolution
 private Vector2 truncate(Vector2 v, float max_value)
 {
     float s = 0f;
     s = max_value / v.Length();
     s = (s < 1.0f) ? 1.0f : s;
     return new Vector2(v.X * s, v.Y * s);
 }
コード例 #28
0
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            // Calculate the timeDelta I.e. How much time has elapsed since the last time this function was called
            // We use this in the updates
            float timeDelta = (float) gameTime.ElapsedGameTime.TotalSeconds;
            float speed = 100.0f;

            Vector2 acceleration = arrive() / mass;
            velocity = velocity + acceleration * timeDelta;
            if (velocity.Length() > maxSpeed)
            {
                velocity = Vector2.Normalize(velocity) * maxSpeed;
            }
            Position += velocity * timeDelta;
            if (velocity.Length() > 0)
            {
                Look = Vector2.Normalize(velocity);
            }

            Vector2 basis = new Vector2(0, -1);
            Rotation = (float) Math.Acos(Vector2.Dot(basis, Look));
            if (Look.X < 0)
            {
                Rotation *= -1;
            }
        }
コード例 #29
0
ファイル: Ball.cs プロジェクト: romainbou/PongLegacy
        //Vérification de la collision entre la balle et un joueur
        public Boolean CheckPlayerColision(Player player)
        {
            if (!this.HitBox.Intersects(player.HitBox))
            {
                player.isInIntersection = false;
            }
            if (this.HitBox.Intersects(player.HitBox)&&!player.isInIntersection)
            {

                int middle = (int)player.position.Y + Conf.BAT_HEIGHT / 2;
                float coef = (-middle + this.position.Y) / (Conf.BAT_HEIGHT / 2);
                if (this.Speed.X > 0)
                {
                    coef = -1 * coef;
                }
                Vector2 vector = new Vector2(-this.Speed.X, this.Speed.Y);
                float angle = (float)(Math.PI / 180) * 45;
                Vector2 final = new Vector2();
                final.X = (int)(this.Acceleration * (vector.X * Math.Cos(coef * angle) - vector.Y * Math.Sin(coef * angle)) +(vector.X * Math.Cos(coef * angle) - vector.Y * Math.Sin(coef * angle)));
                final.Y = (int)(this.Acceleration * (vector.Y * Math.Cos(coef * angle) + vector.X * Math.Sin(coef * angle)) + (vector.Y * Math.Cos(coef * angle) + vector.X * Math.Sin(coef * angle)));
                if (final.Length() > 20)
                {
                    final.X = (int)((vector.X * Math.Cos(coef * angle) - vector.Y * Math.Sin(coef * angle)));
                    final.Y = (int)((vector.Y * Math.Cos(coef * angle) + vector.X * Math.Sin(coef * angle)));
                }
                this.Speed = final;
                this.correctSpeed();
                player.isInIntersection = true;
                return true;
            }

            return false;
        }
コード例 #30
0
ファイル: CommonFunctions.cs プロジェクト: BNHeadrick/Bros
 public static float distance(Vector2 point1, Vector2 point2)
 {
     point1.X -= point2.X;
     point1.Y -= point2.Y;
     return point1.Length();
     //return (float)Math.Sqrt(point1.X * point1.X + point1.Y * point1.Y);
 }
コード例 #31
0
ファイル: Coin.cs プロジェクト: wynaut-wastaken/ProjectTC
        public Coin(Vector2 pos, int type)
        {
            var rand = new Random();

            Velocity.X = rand.NextFloat(-5, 5) / 4;
            Velocity.Y = rand.NextFloat(1, 4) / -8;
            var len = Velocity.Length();

            Velocity.Normalize();
            Velocity *= len;
            Dimension.LoadGameObject(this);
            position = pos;
            coinType = type;
        }
コード例 #32
0
        /// <summary>
        /// Draws the sprite
        /// </summary>
        /// <param name="spriteBatch">batch to draw sprites with</param>
        /// <param name="position">position of the sprite</param>
        /// <param name="texture">texture to draw</param>
        /// <param name="camera">camera position</param>
        /// <param name="orientation">camera angle in degrees</param>
        public void RenderSprite(SpriteBatch spriteBatch, Vector2 position, Texture2D texture, Rectangle source,
                                 Vector2 camera, float orientation)
        {
            int   slices      = viewport.Width;
            int   halfSlice   = slices / 2;
            float halfFov     = FOV / 2;
            float cameraAngle = orientation * (float)(Math.PI / 180.0f);
            float focalLength = halfSlice / (float)Math.Tan(halfFov);

            Vector2 cameraForward     = new Vector2((float)Math.Cos(cameraAngle), (float)Math.Sin(cameraAngle));
            Vector2 spriteCameraSpace = position - camera;

            if (Vector2.Dot(cameraForward, spriteCameraSpace) <= 0)
            {
                return;
            }

            float angleToSprite     = (float)Math.Atan2(spriteCameraSpace.Y, spriteCameraSpace.X) - cameraAngle;
            float correctedDistance = (float)(spriteCameraSpace.Length() * Math.Cos(angleToSprite));
            int   spriteSize        = (int)(source.Width * focalLength / correctedDistance);
            int   spritePosition    = (int)(Math.Tan(angleToSprite) * focalLength + halfSlice);

            // draw slices for sprite
            int halfSprite    = spriteSize / 2;
            int startPosition = spritePosition - halfSprite;
            int endPosition   = spritePosition + halfSprite;
            int tileStart     = source.X;

            if (endPosition < 0 || startPosition >= slices)
            {
                return;
            }

            if (startPosition < 0)
            {
                startPosition = 0;
            }

            bool noOffsetNeeded = false;

            if (endPosition >= slices)
            {
                endPosition    = slices - 1;
                noOffsetNeeded = true;
            }

            int   spriteSizeRange = endPosition - startPosition;
            float spritePart      = source.Width / (float)spriteSize;
            float sourceOffset    = noOffsetNeeded ? 0 : source.Width - spriteSizeRange / (float)spriteSize * source.Width;

            source.Width = (int)Math.Ceiling(spritePart);
            for (int x = 0; x < spriteSizeRange; x++)
            {
                int screenColumn = startPosition + x;
                if (zBuffer[screenColumn] < correctedDistance)
                {
                    continue;
                }

                source.X = tileStart + (int)(sourceOffset + x * spritePart);

                spriteBatch.Draw(texture,
                                 new Rectangle(screenColumn, viewport.Height / 2 - halfSprite, 1, spriteSize),
                                 source, Color.White);
            }
        }
コード例 #33
0
        public MinkowskiSimplex FindMinkowskiSimplex(Microsoft.Xna.Framework.Vector2 start,
                                                     Func <Microsoft.Xna.Framework.Vector2, Microsoft.Xna.Framework.Vector2> supportA, Func <Microsoft.Xna.Framework.Vector2, Microsoft.Xna.Framework.Vector2> supportB)
        {
            simplex.Initialize();

            Microsoft.Xna.Framework.Vector2 d     = start;
            Microsoft.Xna.Framework.Vector2 dperp = new Microsoft.Xna.Framework.Vector2(-d.Y, d.X);

            double diff = double.MaxValue;

            simplex.Add(MinkowskiSimplex.Support(supportA, supportB, dperp));
            simplex.Add(MinkowskiSimplex.Support(supportA, supportB, d));
            simplex.Add(MinkowskiSimplex.Support(supportA, supportB, -d));

            d = LineSegmentPointNearestOrigin(simplex.Simplex[1], simplex.Simplex[2]);

            for (int i = 1; i <= 2; i++)
            {
                var newd = LineSegmentPointNearestOrigin(simplex.Simplex[0], simplex.Simplex[i]);
                if (newd.LengthSquared() < d.LengthSquared())
                {
                    d = newd;
                }
            }

            Iterations = 0;
            Converged  = false;
            while (Iterations < MaxIterations && diff > Tolerance)
            {
                Iterations++;

                if (simplex.ContainsOrigin)
                {
                    Converged = true;
                    simplex.DistanceFromOrigin = d.Length();
                    return(simplex);
                }

                d = -d;

                var c    = MinkowskiSimplex.Support(supportA, supportB, d);
                var dotc = Vector2.Dot(c.Difference, d);
                var dota = Vector2.Dot(simplex.Last(), d);

                diff = dotc - dota;
                if (diff < Tolerance)
                {
                    Converged = true;
                    simplex.DistanceFromOrigin = d.Length();
                    return(simplex);
                }

                var ia = simplex.Simplex.Count - 2;
                var ib = simplex.Simplex.Count - 1;

                var p1 = LineSegmentPointNearestOrigin(c.Difference, simplex.Simplex[ia]);
                var p2 = LineSegmentPointNearestOrigin(c.Difference, simplex.Simplex[ib]);

                if (p1.LengthSquared() < p2.LengthSquared())
                {
                    simplex.StaggerInsert(ib, c);
                    d = p1;
                }
                else
                {
                    simplex.StaggerInsert(ia, c);
                    d = p2;
                }
            }

            simplex.DistanceFromOrigin = d.Length();
            return(simplex);
        }
コード例 #34
0
ファイル: Game1.cs プロジェクト: andrecosta/Mini-Prey
        void DrawLine(KokoEngine.Vector2 start, KokoEngine.Vector2 end, KokoEngine.Color color, int size)
        {
            Vector2   start_ = start.ToMonoVector2();
            Vector2   end_   = end.ToMonoVector2();
            Vector2   edge   = end_ - start_;
            float     angle  = (float)Math.Atan2(edge.Y, edge.X);
            Color     color_ = color.ToMonoColor();
            Rectangle destinationRectangle = new Rectangle((int)start.X, (int)start.Y, (int)edge.Length(), size);

            // Draw call
            _spriteBatch.Draw(_dummyTexture, destinationRectangle, null, color_, angle, new Vector2(0, 0), SpriteEffects.None, 0.6f);
        }