Hello everyone. I am a beginner in Unity 3D and C #, and I’m a very simple game where you play as the ball and have gathered yellow and red dice. It occurred to me to do something there like a moving platform or a large block will make you a pancake . I tried this:
void FixedUpdate ()
{
if (end == false)
{
transform.position = Vector3.Lerp(startPos,endPos,1000f);
}
if (end == true)
{
transform.position = Vector3.Lerp(endPos,startPos,1000f);
}
if (transform.position == endPos)
{
end = true;
}
if (transform.position == startPos)
{
end = false;
}
}
but the platform only flickered on points startPos and endPos as if was moving too fast, so fast that it was both points simultaneously.
does anyone know what is wrong or how to fix it?
thank you, it works … but only in one direction, how can a platform upon reaching the end to send back to the beginning, and this all over again in an endless chicle?
Lerp from start to end until percentage is 1 and then set percentage back to 0 and Lerp from end to start.
Or Lerp from start to end until percentage is 1 and then start subtracting from percentage instead of adding to it.
I looked at the syntax and finally made it.
otherwise the code of this contribution somehow does not work, I do not know why.
But I finally figured out how to do it, it’s simple … not to use Lerp
using UnityEngine;
using System.Collections;
public class MoveA : MonoBehaviour {
public Vector3 startPos;
public Vector3 endPos;
public float speed;
private float step;
private bool end;
void Update (){
if (transform.position == startPos) {
end = false;
}
if (transform.position == endPos) {
end = true;
}
if (end == false) {
step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, endPos, step); }
if (end == true) {
step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, startPos, step);
}
}
}
this is the worst way of doing something simple as looping between two vectors!
the Mathf.PingPong is right only used wrong in the example above.
try this:
using UnityEngine;
using System.Collections;
public class LoopBetweenVectors : MonoBehaviour {
public Transform pointA, pointB;
public float speed = 2;
void Update ()
{
transform.position = Vector3.Lerp(pointA.position, pointB.position, Mathf.PingPong(Time.time*speed, 1f));
}
}