- Home /
The question is answered, right answer was accepted
Ping pong position using lerp
Hi!
I'm trying to make some objects move from position A to position B and then back to position A. I'm using lerp with ping pong to achive that, but it doesn't work as the objects continue moving and never get back to position A. This is my code:
private float positionDisplacement;
private void Start()
{
positionDisplacement = Random.Range(-50f, 50f);
}
private void Update()
{
transform.position = new Vector3(Mathf.Lerp(transform.position.x, transform.position.x + positionDisplacement, Mathf.PingPong(Time.deltaTime, 1f)),
Mathf.Lerp(transform.position.y, transform.position.y + positionDisplacement, Mathf.PingPong(Time.deltaTime, 1f)),
Mathf.Lerp(transform.position.z, transform.position.z + positionDisplacement, Mathf.PingPong(Time.deltaTime, 1f)));
}
Answer by taoria123 · Jun 10, 2019 at 10:31 AM
yes it will not come back since the the transform.position.x/y/z is changed . consider record your original position at first then do the ping pong.The following code should work.
private Vector3 positionDisplacement;
private Vector3 positionOrigin;
private float _timePassed;
private void Start(){
float randomDistance = Random.Range(-50f, 50f);
positionDisplacement = new Vector3(randomDistance,randomDistance,randomDistance);
positionOrigin = transform.position;
}
private void Update(){
_timePassed += Time.deltaTime;
transform.position = Vector3.Lerp(positionOrigin, positionOrigin + positionDisplacement,
Mathf.PingPong(_timePassed, 1));
}
Answer by mansoor090 · Jun 10, 2019 at 10:23 AM
use liner equation with time. B(t) = P0 + t(P1 – P0) = (1-t) P0 + tP
for example;
float _time = 0;
Transform PointA:
Transform PointB:
void update(){
_time += time.deltatime;
transform.position = GetNewPosition(_time);
}
Vector3 GetNewPosition(float t){
somevector = PointA + t(PointB – PointA) = (1-t) PointA + tPointB
return somevector
}
this may not be error free. but this is how i did it
Answer by xxmariofer · Jun 10, 2019 at 10:29 AM
here is a code that should work, you need to assig the target in the oinspector
bool goingRight = true;
public float speed = 1;
public Vector3 endPosition;
Vector3 startPosition;
void Awake()
{
startPosition = transform.position;
}
private void Update()
{
transform.position = Vector3.Lerp(startPosition, endPosition, amount);
amount = speed ^Time.deltaTime;
if(amount >= 1 || amount <= 0) { speed = -speed; }
}
Follow this Question
Related Questions
Saving the starting position of a Lerp during Update 2 Answers
Mathf.Lerp not working 2 Answers
Vector3.Lerp works outside of Update() 3 Answers
mathf.pingpong 0 Answers