using UnityEngine; using System.Collections; using System.Collections.Generic; using MoreMountains.Tools; namespace MoreMountains.Tools { /// /// Add this component to an object and it'll be able to move along a path defined from its inspector. /// [AddComponentMenu("More Mountains/Tools/Movement/MMPathMovement")] public class MMPathMovement : MonoBehaviour { /// the possible movement types public enum PossibleAccelerationType { ConstantSpeed, EaseOut, AnimationCurve } /// the possible cycle options public enum CycleOptions { BackAndForth, Loop, OnlyOnce, StopAtBounds, Random } /// the possible movement directions public enum MovementDirection { Ascending, Descending } public enum UpdateModes { Update, FixedUpdate, LateUpdate } [Header("Path")] [MMInformation("Here you can select the 'Cycle Option'. Back and Forth will have your object follow the path until its end, and go back to the original point. If you select Loop, the path will be closed and the object will move along it until told otherwise. If you select Only Once, the object will move along the path from the first to the last point, and remain there forever.",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)] public CycleOptions CycleOption; [MMInformation("Add points to the Path (set the size of the path first), then position the points using either the inspector or by moving the handles directly in scene view. For each path element you can specify a delay (in seconds). The order of the points will be the order the object follows.\nFor looping paths, you can then decide if the object will go through the points in the Path in Ascending (1, 2, 3...) or Descending (Last, Last-1, Last-2...) order.",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)] /// the initial movement direction : ascending > will go from the points 0 to 1, 2, etc ; descending > will go from the last point to last-1, last-2, etc public MovementDirection LoopInitialMovementDirection = MovementDirection.Ascending; /// the points that make up the path the object will follow public List PathElements; [Header("Movement")] [MMInformation("Set the speed at which the path will be crawled, and if the movement should be constant or eased.",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)] /// the movement speed public float MovementSpeed = 1; /// returns the current speed at which the object is traveling public Vector3 CurrentSpeed { get; protected set; } /// the movement type of the object public PossibleAccelerationType AccelerationType = PossibleAccelerationType.ConstantSpeed; /// the acceleration to apply to an object traveling between two points of the path. public AnimationCurve Acceleration = new AnimationCurve(new Keyframe(0,1f),new Keyframe(1f,0f)); /// the chosen update mode (update, fixed update, late update) public UpdateModes UpdateMode = UpdateModes.Update; [Header("Settings")] [MMInformation("The MinDistanceToGoal is used to check if we've (almost) reached a point in the Path. The 2 other settings here are for debug only, don't change them.",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)] /// the minimum distance to a point at which we'll arbitrarily decide the point's been reached public float MinDistanceToGoal = .1f; /// the original position of the transform, hidden and shouldn't be accessed protected Vector3 _originalTransformPosition; /// internal flag, hidden and shouldn't be accessed protected bool _originalTransformPositionStatus=false; /// if this is true, the object can move along the path public virtual bool CanMove { get; set; } protected bool _active=false; protected IEnumerator _currentPoint; protected int _direction = 1; protected Vector3 _initialPosition; protected Vector3 _finalPosition; protected Vector3 _previousPoint = Vector3.zero; protected float _waiting=0; protected int _currentIndex; protected float _distanceToNextPoint; protected bool _endReached = false; /// /// Initialization /// protected virtual void Awake () { Initialization (); } /// /// On Start we store our initial position /// protected virtual void Start() { _originalTransformPosition = transform.position; } /// /// A public method you can call to reset the path /// public virtual void ResetPath() { Initialization(); CanMove = false; transform.position = _originalTransformPosition; } /// /// Flag inits, initial movement determination, and object positioning /// protected virtual void Initialization() { // on Start, we set our active flag to true _active=true; _endReached = false; CanMove = true; // if the path is null we exit if(PathElements == null || PathElements.Count < 1) { return; } // we set our initial direction based on the settings if (LoopInitialMovementDirection == MovementDirection.Ascending) { _direction=1; } else { _direction=-1; } // we initialize our path enumerator _currentPoint = GetPathEnumerator(); _previousPoint = _currentPoint.Current; _currentPoint.MoveNext(); // initial positioning if (!_originalTransformPositionStatus) { _originalTransformPositionStatus = true; _originalTransformPosition = transform.position; } transform.position = _originalTransformPosition + _currentPoint.Current; } protected virtual void FixedUpdate() { if (UpdateMode == UpdateModes.FixedUpdate) { ExecuteUpdate(); } } protected virtual void LateUpdate() { if (UpdateMode == UpdateModes.LateUpdate) { ExecuteUpdate(); } } protected virtual void Update() { if (UpdateMode == UpdateModes.Update) { ExecuteUpdate(); } } /// /// Override this to describe what happens when a point is reached /// protected virtual void PointReached() { } /// /// Override this to describe what happens when the end of the path is reached /// protected virtual void EndReached() { } /// /// On update we keep moving along the path /// protected virtual void ExecuteUpdate () { // if the path is null we exit, if we only go once and have reached the end we exit, if we can't move we exit if(PathElements == null || PathElements.Count < 1 || _endReached || !CanMove ) { return; } Move (); } /// /// Moves the object and determines when a point has been reached /// protected virtual void Move() { // we wait until we can proceed _waiting -= Time.deltaTime; if (_waiting > 0) { CurrentSpeed = Vector3.zero; return; } // we store our initial position to compute the current speed at the end of the udpate _initialPosition=transform.position; // we move our object MoveAlongThePath(); // we decide if we've reached our next destination or not, if yes, we move our destination to the next point _distanceToNextPoint = (transform.position - (_originalTransformPosition + _currentPoint.Current)).magnitude; if(_distanceToNextPoint < MinDistanceToGoal) { //we check if we need to wait if (PathElements.Count > _currentIndex) { _waiting = PathElements[_currentIndex].Delay; } PointReached(); _previousPoint = _currentPoint.Current; _currentPoint.MoveNext(); } // we determine the current speed _finalPosition = transform.position; if (Time.deltaTime != 0f) { CurrentSpeed = (_finalPosition - _initialPosition) / Time.deltaTime; } if (_endReached) { EndReached(); CurrentSpeed = Vector3.zero; } } /// /// Moves the object along the path according to the specified movement type. /// public virtual void MoveAlongThePath() { switch (AccelerationType) { case PossibleAccelerationType.ConstantSpeed: transform.position = Vector3.MoveTowards (transform.position, _originalTransformPosition + _currentPoint.Current, Time.deltaTime * MovementSpeed); break; case PossibleAccelerationType.EaseOut: transform.position = Vector3.Lerp (transform.position, _originalTransformPosition + _currentPoint.Current, Time.deltaTime * MovementSpeed); break; case PossibleAccelerationType.AnimationCurve: float distanceBetweenPoints = Vector3.Distance (_previousPoint, _currentPoint.Current); if (distanceBetweenPoints <= 0) { return; } float remappedDistance = 1 - MMMaths.Remap (_distanceToNextPoint, 0f, distanceBetweenPoints, 0f, 1f); float speedFactor = Acceleration.Evaluate (remappedDistance); transform.position = Vector3.MoveTowards (transform.position, _originalTransformPosition + _currentPoint.Current, Time.deltaTime * MovementSpeed * speedFactor); break; } } /// /// Returns the current target point in the path /// /// The path enumerator. public virtual IEnumerator GetPathEnumerator() { // if the path is null we exit if(PathElements == null || PathElements.Count < 1) { yield break; } int index = 0; _currentIndex = index; while (true) { _currentIndex = index; yield return PathElements[index].PathElementPosition; if(PathElements.Count <= 1) { continue; } // if the path is looping switch(CycleOption) { case CycleOptions.Loop: index = index + _direction; if (index < 0) { index = PathElements.Count - 1; } else if (index > PathElements.Count - 1) { index = 0; } break; case CycleOptions.BackAndForth: if (index <= 0) { _direction = 1; } else if (index >= PathElements.Count - 1) { _direction = -1; } index = index + _direction; break; case CycleOptions.OnlyOnce: if (index <= 0) { _direction = 1; } else if (index >= PathElements.Count - 1) { _direction = 0; CurrentSpeed = Vector3.zero; _endReached = true; } index = index + _direction; break; case CycleOptions.Random: int newIndex = index; if (PathElements.Count > 1) { while (newIndex == index) { newIndex = Random.Range(0, PathElements.Count); } } index = newIndex; break; case CycleOptions.StopAtBounds: if (index <= 0) { if (_direction == -1) { CurrentSpeed = Vector3.zero; _endReached = true; } _direction = 1; } else if (index >= PathElements.Count - 1) { if (_direction == 1) { CurrentSpeed = Vector3.zero; _endReached = true; } _direction = -1; } index = index + _direction; break; } } } /// /// Call this method to force a change in direction at any time /// public virtual void ChangeDirection() { _direction = - _direction; _currentPoint.MoveNext(); } /// /// On DrawGizmos, we draw lines to show the path the object will follow /// protected virtual void OnDrawGizmos() { #if UNITY_EDITOR if (PathElements==null) { return; } if (PathElements.Count==0) { return; } // if we haven't stored the object's original position yet, we do it if (_originalTransformPositionStatus==false) { _originalTransformPosition=transform.position; _originalTransformPositionStatus=true; } // if we're not in runtime mode and the transform has changed, we update our position if (transform.hasChanged && _active==false) { _originalTransformPosition=transform.position; } // for each point in the path for (int i=0;i /// Updates the original transform position. /// /// New original transform position. public virtual void UpdateOriginalTransformPosition(Vector3 newOriginalTransformPosition) { _originalTransformPosition = newOriginalTransformPosition; } /// /// Gets the original transform position. /// /// The original transform position. public virtual Vector3 GetOriginalTransformPosition() { return _originalTransformPosition; } /// /// Sets the original transform position status. /// /// If set to true status. public virtual void SetOriginalTransformPositionStatus(bool status) { _originalTransformPositionStatus = status; } /// /// Gets the original transform position status. /// /// true, if original transform position status was gotten, false otherwise. public virtual bool GetOriginalTransformPositionStatus() { return _originalTransformPositionStatus ; } } }