Reputation: 576
I have asked this question once before, but I still did not figure out how to solve this issue. I am trying to move the position of 4 unity gameobjects and a SteamVR player by changing the transform.position. This is working really good, but it just does not looks so nice since it feels like u are teleporting instant to the new postion.
So what I want is to move the objects with Vector3.MoveTowards. But I have tried multiple things and it is just not working. I've had the following situations with different code: -> Object does not even move -> Object moves instant
What I am using currently is the following.
Update method:
private void Update()
{
if (Condition)
{
ZoomIn();
}
}
Zoomin method:
private void ZoomIn()
{
switch (ZoomLevel)
{
case 1:
SetZoomLevel(20, 40);
ZoomLevel++;
break;
case 2:
SetZoomLevel(40, 60);
ZoomLevel++;
break;
case 3:
break;
}
}
SetZoomLevel (Where the movement actually starts, so where the problem is):
private void SetZoomLevel(float height, float distance)
{
Fade(ObjectToMove1, height, distance);
Fade(ObjectToMove2, height, distance);
Fade(ObjectToMove3, height, distance);
Fade(ObjectToMove4, height, distance);
}
This should trigger the animation
IEnumerator Fade(GameObject teleportObject, float height, float distance)
{
while (Vector3.Distance(teleportObject.transform.position, new Vector3(0, height, distance)) > 0.001f)
{
// Speed = Distance / Time => Distance = speed * Time. => Adapt the speed if move is instant.
teleportObject.transform.position = Vector3.MoveTowards(teleportObject.transform.position, new Vector3(0, height, distance), 10 * Time.deltaTime);
yield return null;
}
}
Somehow this is not working.
I am hoping that someone can help me out.
Thanks in advance.
Upvotes: 0
Views: 1268
Reputation: 694
Fade is a coroutine, but you don't call it as such, you should use StartCoroutine()
instead. (See : StartCoroutine).
You also can use a for loop on your objects, so you got the code :
private void SetZoomLevel(float height, float distance)
{
foreach (GameObject obj in your_objects)
{
StartCoroutine(Fade(obj, height, distance));
}
}
Now, about the Fade()
coroutine, I don't see anything strange in there, if it's still not moving as you want it, maybe try to change the speed value (your 10 in the third parameter of the MoveTowards).
Upvotes: 1
Reputation: 548
I think your while
statement should be an if
statement.
I think your code moves the object to its final position in 1 frame other than doing it in a smooth way across multiple frames. The calls to Vector3.MoveTowards
should happen in different frames.
Your Fade
method would look like this:
void Fade(GameObject teleportObject, float height, float distance)
{
if (Vector3.Distance(teleportObject.transform.position, new Vector3(0, height, distance)) > 0.001f)
{
teleportObject.transform.position = Vector3.MoveTowards(teleportObject.transform.position, new Vector3(0, height, distance), 10 * Time.deltaTime);
}
}
Upvotes: 1