I am trying to get back to learning how Lerps works, however I am having an issue that I can’t seem to understand why. I am trying to have a box sprite move from 0,0 to the cameras width. This is working, but when I first start the game the sprite jumps a few pixels on the x axis before its smooth movement.
Here’s what I have done:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SmoothMove : MonoBehaviour {
private Vector2 _to;
private Vector2 _current;
private float _speed = 1.5f;
public void Start() {
var cam = Camera.main;
_to = new Vector2(cam.aspect * cam.orthographicSize, 0);
}
//I changed Update to FixedUpdate to see if I can spot a diff.
public void FixedUpdate() {
transform.position = Vector2.Lerp(transform.position, _to, Time.fixedDeltaTime * _speed);
}
}
Never mind, I got it, I was looking at Lerp’s time wrong. The document states When t = 0.5 returns the midpoint of a and b.
So I had to calculate the distance between the start position and end position. Here’s my final result:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SmoothMove : MonoBehaviour {
private Vector2 _to;
private Vector2 _current;
private float _speed = 1.5f;
private float _startTime;
private float distanceToDest;
public void Start() {
var cam = Camera.main;
_startTime = Time.time;
_to = new Vector2(cam.aspect * cam.orthographicSize, 0);
distanceToDest = Vector2.Distance(transform.position, _to);
}
public void Update() {
float currentTime = (Time.time - _startTime);
float distToTime = currentTime / distanceToDest;
transform.position = Vector2.Lerp(transform.position, _to, Time.deltaTime * distToTime);
}
}
Really, This video truly helped me understand it while going back and forth to the document to see where I failed to understand Vector2.Lerp.