- Home /
How to move the camera over time?
I'm (obviously) pretty new to Unity. I'm trying to move my camera to a new position. It's easy enough to have it jump straight to a new location, but I want it move to the new position over time.
I know that I'm looking for the Lerp function. This is the relevant script on my camera:
function Update () {
var destinationX = pageControl.CurrentPageNumber*pageControl.pageSize;
var target : Transform;
target.position = Vector3(destinationX, transform.position.y, transform.position.z);
transform.position = Vector3.Lerp(transform.position, target.position, Time.deltaTime * 5);
}
Unfortunately, I just get this error on the target.position line:
NullReferenceException: Object reference not set to an instance of an object
What am I doing wrong?
You might want to take a look at Vector3.$$anonymous$$oveTowards(). It will move a constant speed, rather than move over a fixed time.
Answer by Graham-Dunnett · Jan 24, 2013 at 09:37 PM
You're telling the compiler that you have a variable called target
, and that it's a Transform
. But you don't set target
to anything. So when you try to access its position on the next line (the one with the error) you get the error. You probably want target
to be a vector3 and not a transform.
You're right. Here's the code that's working:
var destinationX = pageControl.currentPageNumber*pageControl.pageSize;
var target = Vector3(destinationX, transform.position.y, transform.position.z);
transform.position = Vector3.Lerp(transform.position, target, Time.deltaTime * 5);
Thanks for your help.
Answer by TheCoolDog · Jan 24, 2013 at 09:43 PM
Put: var target : Transform;
Outside the Update function:
var target : Transform;
function Update () {
var destinationX = pageControl.CurrentPageNumber*pageControl.pageSize;
target.position = Vector3(destinationX, transform.position.y, transform.position.z);
transform.position = Vector3.Lerp(transform.position, target.position, Time.deltaTime * 5);
}
Then make sure you assign the variable inside the unity editor by dragging the target object into the variable slot under your script component.
Answer by Eric5h5 · Jan 24, 2013 at 09:48 PM
Use a coroutine such as MoveObject rather than Update, which isn't appropriate since it runs every frame and you only want the movement to occur for a set period of time.
Your answer
Follow this Question
Related Questions
2D game camera zoom in/out (JS) 1 Answer
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Camera Follow Mouse Issue 1 Answer
Rigidbody person 1 Answer