- Home /
Unity 2D Scripted Movement
I was wondering how I could get it so that if I say:
WalkUp(3,5)
where 3 is the distance in meters and 5 is the time in seconds, that I could have an object move linearly and uniformly upward for 3 meters/5 seconds and have the method stop moving the character after that command, which may require a stationary Idle method.
Any insight would be great.
Answer by Tomer-Barkan · Nov 25, 2013 at 06:39 AM
In simple code without external libraries (sometimes I prefer my own code for simple things, easier to understand and debug than someone else's)
 public class ObjectMover {
     private Vector3 target;
     private Vector3 start;
     private float totalTime = 0; // when set to 0, will not move
     private float currentPosition = 0;
 
     public void Update() {
         if (totalTime > 0) {
             currentPosition += Time.deltaTime / totalTime; // advance position by the fraction of the total time that passed this last frame
             if (currentPosition >= 1) {
                 currentPosition = 1; // don't pass the target
                 totalTime = 0; // end the movement when reaching the target
             }
             transform.position = Vector3.Slerp(start, target, currentPosition); // position the object between the start and the target relative to the time passed out of the total time
         }
     }
 
     public void MoveTowards(Vector3 direction, float distance, float time) {
         target = transform.position + direction.normalized * distance; // set destination location
         totalTime = time; // set time to perform the movement
         if (time == 0) {
             transform.position = target;
         }
     }
 
     public void CancelMove() {
         totalTime = 0;
     }
 }
Not to use it, you would attach the ObjectMover script to any object you wish to be movable this way, and then call it this way to move it up 3 units in 5 seconds, as in your example:
 GameObject objectToMove = GameObject.Find("SomeObjectName");
 objectToMove.GetComponent<ObjectMover>().MoveTowards(Vector3.up, 3, 5);
Of course you can use object references instead of GameObject.Find. 
sorry it took long to respond, I will definitely check this one out!
i applied it to a separate class of $$anonymous$$e, and it works like a charm!
Answer by Eric5h5 · Nov 23, 2013 at 02:47 AM
 function Start () {
     yield MoveObject.use.Translation(transform, Vector3.up*3, 5.0, MoveType.Time);
 }
Please read the usage instructions on the page I linked to.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                