Easy Straight Motion Class

From XNAWiki
Jump to: navigation, search


This class shows how to create a Vector3 that will move a object straight to a other position until it reaches it:

class Motion
    {
        /// <summary>
        /// This returns a vector which lets the object fly straight to the target position.
        /// </summary>
        /// <param name="ActualPosition">Actual position of the moving object</param>
        /// <param name="TargetPosition">Position of the traget</param>
        /// <param name="Speed">Distance per frame</param>
        public static Vector3 Straight(Vector3 ActualPosition, Vector3 TargetPosition, float Speed)
        {
            // A Vector3 to hold the result velocity:
            Vector3 Velocity = Vector3.Zero;
 
            //The Direction to the TargetPosition:
            Vector3 Direction = ActualPosition - TargetPosition;
 
            //The distance between the two vectors:
            float Distance = Direction.Length();
 
            //This changes Direction into a Vector which points into the same Direction, but with the value '1'.
            Direction.Normalize(); 
 
            if (ActualPosition != TargetPosition)
            {
                //Velocity Calculation:
                if (Distance >= Speed)
                    Velocity = Direction * Speed;
                else
                    Velocity = Direction * Distance;
            }
 
            return Velocity;
        }
    }