- Home /
Question about moving an object technique
So i'm trying to move my player specific amount of units in a direction. Let's say i want to move my cube to the right with 2 units but, i want it to slide it to that position, not to teleport. I've tryied several methods but my player just teleports and i don't want that. I'm guessing that i should use the Lerp function but i don't really know how it works.
Answer by Kapel · Nov 09, 2016 at 11:13 PM
 using UnityEngine;
 using System.Collections;
 
 public class cube : MonoBehaviour {
     Vector3 tag;
     int speed = 2;
 
     // Use this for initialization
     void Start () {
         tag = new Vector3(transform.position.x + 2, transform.position.y, transform.position.z);
     }
     
     // Update is called once per frame
     void Update () {
             transform.position = Vector3.MoveTowards(transform.position, tag, speed * Time.deltaTime);
     }
 }
@dxddda4 you can also use Lerp instead of MoveTowards in the same way. Diffrence is that Lerp will slow down approaching target.
Thanks, but what i needed was something like this: When you press down the key d , the cube should slide 2 units. So if i add an if structure at line 14 the cube just teleports to that position. Sorry if i wasn't too specific.
Answer by doublemax · Nov 09, 2016 at 10:40 PM
You can use the following coroutine. Call it with
 StartCoroutine( MoveObjectToPosition( transform, target_position, 1.0f) );
Code:
 IEnumerator MoveObjectToPosition( Transform trans, Vector3 end_position, float duration )
 {
   Vector3 start_position = trans.position;
   float elapsed = 0.0f;
   while( elapsed < duration )
   {
     trans.position = Vector3.Lerp(start_position, end_position, elapsed / duration );
     elapsed += Time.deltaTime;
     yield return null;
   }
   trans.position = end_position;
 }
Alternatively check out the free assets LeanTween or iTween which do the same and much more.
Your answer
 
 
             Follow this Question
Related Questions
Smooth jump script? 1 Answer
The Camera is facing backwards of the Character 1 Answer
Slime script? 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How to I put a speed limit on my character's movement? 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                