- Home /
Moving the camera "on rails"
Hi guys I'm making a point and click adventure game with unity, and I'm trying to set the environment to be "semi" realtime. What I mean is, I want the camera to move only when the mouse is clicked on specific areas in the scene. I tried to do it with animation, but the results were less than expected. What I want to do is move the camera with code, but I'm not sure how to do it. I managed to create a script which "teleports" the camera to the area I clicked, but can't manage to make it move there smoothly. Thanks in advance.
Answer by Setzer22 · Jun 10, 2012 at 02:13 PM
Well, you could just simply modify the transform.position of the camera over time. Also using functions like Lerp or SmoothDamp could make that more easy.
I assume your code changes the transform.position of your camera to the new desiredPosition, like that
 transform.position = desiredPosition
What you could do instead, is to linearly interpolate between the two vectors over time
 function Update(){
    transform.position  Vector3.Lerp (transform.position,desiredPosition
                                      Time.deltaTime * timeInSeconds);
 }
This will gradually move your camera over time, so it gets to the desiredPosition (wich has to be a vector3) in the time of timeInSeconds (which should be a float)
Answer by syclamoth · Jun 10, 2012 at 02:11 PM
If you can manage a teleport, you can manage a smooth transition.
Teleport script:
 void PortToPosition(Vector3 targetPos)
 {
     transform.position = targetPos;
 }
Call this like so:
 PortToPosition(place to go to);
If you want it to move smoothly, replace it with this function:
 IEnumerator SlideToPosition(Vector3 targetPos, float time)
 {
     // Use an animation curve to make it look sweet!
     AnimationCurve smoothly = AnimationCurve.EaseInOut(0, 0, 1, 1);
     Transform myTrans = transform; // cache the transform for extra efficiency!
     float curTime = 0;
     Vector3 startPosition = myTrans.position;
     while(curTime < time)
     {
         myTrans.position = Vector3.Lerp(startPosition, targetPos, smoothly.Evaluate(curTime / time));
         curTime += Time.deltaTime;
         yield return null;
     }
      myTrans.position = targetPos;
 }
Call it like this:
 StartCoroutine(SlideToPosition(place to go, time to take));
Adapting this to manage rotation as well is pretty straightforward.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                