- Home /
Why doesn't this code move the object it is attached to to the center of the screen?[2d]
private Vector3 m_pos;
private Vector3 startingPosition;
// Start is called before the first frame update
void Start()
{
Vector3 m_center = new Vector3(Screen.width / 2f, Screen.height / 2f, Camera.main.nearClipPlane);
m_pos = Camera.main.ScreenToWorldPoint(m_center);
m_pos.z = 0f;
startingPosition = transform.position;
}
private void Update()
{
transform.position = Vector3.Lerp(startingPosition, m_pos, 0.1f);
}
It works when I put transform.position in instead of startingPosition it works, but it slows down before it reaches the center. how do I fix this?
Answer by bigvalthoss · Feb 23, 2021 at 09:49 PM
Try using Vector3.MoveTowards instead of Lerp. Lerp is percentage based, you are telling it to go 0.1 (10%) of the distance between starting position and m_pos. If you wanted it to take a certain amount of time to get to m_pos, you could use lerp for that :).
I changed LERP to MoveTowards but it still isn't doing anything
seems like it has something to do with startingPosition. I changed it to transform.position with MoveTowards and it works, perfectly. thanks.
Awesome, you might want to make it stop after its reached the position. Basically just copy from here: https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html