Search code examples
c#unity-game-enginecamerarotation

Camera follow object, rotate EXCEPT z axis


I have a camera that is following an aeroplane object, that can rotate left/right. I want to prevent the camera from rotating on this axis (z-axis).

this.transform.rotation = Cube.transform.rotation;

This obviously rotates the camera in all directions the plane can move in.

I've been trying various things with zAxis etc, only rotating on x and y...

this.transform.Rotate(Cube.transform.rotation.xAngle, 0, 0, Space.Self);

https://docs.unity3d.com/ScriptReference/Transform.Rotate.html

But I can't work it out. Can anyone help?


Solution

  • The simpliest way would probably be to just use LookAt which allows you to rotate the Camera in a way that looks at the target object, without changing it's up direction (=> Z rotation)

    I just added a simple smoothing of the position and a position offset - you can of course also scratch what you don't need and set the position directly.

    public class Example : MonoBehaviour
    {
       // the target to follow
       [SerializeField] private Transform followTarget;
       // local offset to e.g. place the camera behind the target object etc
       [SerializeField] private Vector3 positionOffset;
       // how smooth the camera position is updated, smaller value -> slower
       [SerializeField] private float interpolation = 5f;
       
       private void Update()
       {
          // target position taking the targets rotation and the offset into account
          var targetPosition = followTarget.position + followTarget.forward * positionOffset.z + followTarget.right * positionOffset.x + followTarget.up * positionOffset.y;
    
          // move smooth towards this target position
          transform.position = Vector3.Lerp(transform.position, targetPosition, interpolation * Time.deltaTime);
          
          // rotate to look at the target without rotating in Z
          transform.LookAt(followTarget);
       }
    }
    

    enter image description here