MoveTowards and Lerp not working
I'm trying to make a script that make a block move in steps around another block on key down and it mostly seems to work only the movetowards and lerp don't seem to move the block smoothly towards the destination point. How can I fix that?
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour {
public GameObject target = null;
public GameObject emptyGameObjectPrefab;
private float distance;
// Update is called once per frame
void Update () {
distance = Vector3.Distance (target.transform.position, transform.position);
move();
}
void move (){
if (Input.GetKeyDown(KeyCode.UpArrow))
{
GameObject Mover;
Mover = Instantiate(emptyGameObjectPrefab, transform.position,Quaternion.identity) as GameObject;
Mover.transform.RotateAround (target.transform.position, Vector3.up, 45/distance);
StartCoroutine(moveTo(Mover.transform.position));
}
}
IEnumerator moveTo(Vector3 pos) {
//transform.position = Vector3.Lerp(transform.position, pos, 1);
transform.position = Vector3.MoveTowards (transform.position, pos , 1);
transform.LookAt(target.transform.position);
yield return null;
}
}
Answer by juippi112 · May 10, 2016 at 10:38 PM
The problem is in your coroutine. It runs only once. You just have to add a while loop in it.
I would probably go with the lerp here. Just read this.You are trying to interpolate between transform.position and pos. But you set your interpolant value to 1. Which means that your lerp is going to return pos. Interpolant value of 0 would return transform.position. 0.5 would return a vector midway from transform.position to pos.
So you just have to smoothly raise the interpolant value from 0 to 1. Then it moves smoothly. duh
float t = 0;
while(t < 1)
{
t += Time.deltaTime;
transform.position = Vector3.Lerp(transform.position, pos, t);
//transform.position = Vector3.MoveTowards (transform.position, pos , 1);
transform.LookAt(target.transform.position);
yield return null;
}
Now this coroutine will move you from start to pos in one second. If you want to make it move faster or slower just change it a little. very little.
float t = 0;
float delay = 1.5f;
while(t < 1)
{
t += Time.deltaTime/delay;
transform.position = Vector3.Lerp(transform.position, pos, t);
//transform.position = Vector3.MoveTowards (transform.position, pos , 1);
transform.LookAt(target.transform.position);
yield return null;
}
Your answer
Follow this Question
Related Questions
Coroutine: delay transform rotation but start transform movement immediately 2 Answers
Weapon does't meet the target position when using IK 1 Answer
Doesn't work MoveTowards and Lerp 1 Answer
How can I make smooth steps around an object? 0 Answers
Weird problem with simple boolean and "if" statement [C#] 0 Answers