1
\$\begingroup\$

I have created a very short piece of code to make the camera look at a transform object. I locked the rotation of the x and z axis as it is only supposed to rotate on the y axis. I would like to add some damping to this and make it rotate slowly, thanks. Here is my Code:

public Camera Camera;


public void lookAt (Transform target)   {
    Camera.main.transform.LookAt (target);
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

To do this you'll want to use a routine that runs every frame, like Update, LateUpdate, or a coroutine, so you can adjust the camera's position repeatedly.

You'll also want to store information about where you're supposed to be looking so you can keep turning towards it (particularly if you want to use this to follow a moving object)

Here's one way to do it:

Transform _lookTarget;

// Cache the target we're supposed to look at.  
public void LookAt(Transform target)
{
   _lookTarget = target;
}

// LateUpdate so it runs after any scripts/animation 
// that might move _lookTarget this frame.
void LateUpdate()
{
   if(_lookTarget != null)
   {
       Transform camera = Camera.main.transform;
       Vector3 toTarget = _lookTarget.position - camera.position;

       // This constructs a rotation looking in the direction of our target,
       Quaternion targetRotation = Quaternion.LookRotation(toTarget);

       // This blends the target rotation in gradually.
       // Keep sharpness between 0 and 1 - lower values are slower/softer.
       float sharpness = 0.1f;
       camera.rotation = Quaternion.Lerp(camera.rotation, targetRotation, sharpness);

       // This gives an "stretchy" damping where it moves fast when far
       // away and slows down as it gets closer. You can also use 
       // Quaternion.RotateTowards() to get a more consistent speed.
   }
}
\$\endgroup\$
3
  • \$\begingroup\$ I actually found another way to do it. But thanks anyway. \$\endgroup\$
    – alexo1001
    Commented Jun 9, 2016 at 12:54
  • 2
    \$\begingroup\$ By all means, @alexo1001, post your method as a second answer. That way future visitors can see their options and pick the one that suits them. \$\endgroup\$
    – DMGregory
    Commented Jun 9, 2016 at 12:55
  • \$\begingroup\$ Unfortunately @alexo1001 didn't post it. And I'm also looking for an simple alternative \$\endgroup\$
    – Lukis
    Commented Apr 12, 2017 at 11:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .