krix
krix

Reputation: 23

How to make limited camera movement in Unity C#

I am making a FNAF fan game using Unity, and I need limited camera movement, like shown in this video. I've been trying to figure this out but I found no tutorials nor any answers. If you could link a script for this I would be very greatful!

https://vimeo.com/710535461

Upvotes: 1

Views: 1610

Answers (1)

KiynL
KiynL

Reputation: 4266

Attach this code to the camera and you can limit the camera movement by setting two angles in the inspector. Remember that this code limits localEulerAngles values and always must set the camera rotation to zero, To adjust its rotation, place the camera as child of an empty object and then rotate the parent.

public class LimitedCamera : MonoBehaviour
{
    public float LimitAngleX = 10f;
    public float LimitAngleY = 10f;

    private float AngleX;
    private float AngleY;
    public void Update()
    {
        var angles = transform.localEulerAngles;

        var xAxis = Input.GetAxis("Mouse X");
        var yAxis = Input.GetAxis("Mouse Y");
        
        AngleX = Mathf.Clamp (AngleX-yAxis, -LimitAngleX, LimitAngleX);
        AngleY = Mathf.Clamp (AngleY+xAxis, -LimitAngleY, LimitAngleY);

        angles.x = AngleX;
        angles.y = AngleY;
        
        transform.localRotation = Quaternion.Euler (angles);

        transform.localEulerAngles = angles;
    }
}

Upvotes: 1

Related Questions