Reputation: 873
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?
Upvotes: 0
Views: 957
Reputation: 90852
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);
}
}
Upvotes: 1
Reputation: 61
I believe you wanna try set the same rotation, and omit the Z axis, as such
Vector3 rotation = Cube.transform.rotation;
rotation.z = 0;
this.transform.eulerAngles = rotation;
This should set the rotation of the camera to be the same as your cube, without the Z axis.
Upvotes: 0