- Home /
Pan-Lerp a camera
Hi, I am new here, and I hope that anyone help me. I am trying to pan a camera with a scipt that I am placing in the main camera. But the camera just jumps a little between the 2 points and it doesn't arrive to the newPosition. I will copy my script, thank you:
void Update () {
if (Input.GetMouseButtonDown (0)) {
Vector3 newPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Vector3 currentPosition = transform.position;
transform.position = Vector3.Lerp (currentPosition, newPosition, Time.deltaTime);
}
}
Answer by Zodiarc · Jun 03, 2014 at 07:32 AM
I assume you're pressing the left mouse button only once. That would explain this behavior.
The way the code works is like this: You press the LMB and immediatelly let go. What happens is (assuming your press was exactly 1 frame long), the if clause will be entered only once and never again. Consider that everything within the Update function is called once every frame.
Te effect is, that the camera moves a bit every time you press the LMB.
I see two solutions to this:
You change the GetMouseButtonDown to GetMouseButton and hold the LMB longer or
You control it with a bool variable like this
boolean isMoving = false;
Vector3 newPosition;
void Update () {
if (Input.GetMouseButtonDown (0)) { isMoving = true; newPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition); } if (isMoving){ transform.position = Vector3.Lerp (transform.position, newPosition, Time.deltaTime); } // To avoid the camera lock on one position if(transform.position == newPosition){ isMoving = false; } }
Hope this helps