简体   繁体   中英

Need help clamping camera rotation

I am really new to coding and made this code to rotate my camera around the player object but I do not know how I would proceed to clamp the rotation on the X axis.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowPlayer : MonoBehaviour
{
    public float speed;
    public Transform target;

    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        transform.RotateAround(target.position, transform.right, -Input.GetAxis("Mouse Y") * speed);
        transform.RotateAround(target.position, Vector3.up, -Input.GetAxis("Mouse X") * speed);
    }
}

This is my code to rotate the camera, I want to clamp the Mouse Y one.

The trick here is to keep track of the accumulated input and clamping that before doing the transformations. This is easier and less error-prone than trying to decompose the camera's rotation into the correct axes.

public class FollowPlayer : MonoBehaviour
{
    public float speed;
    public Transform target;

    float vertical;
    float horizontal;
    Quaternion initalRotation;
    Vector3 initialOffset;

    // Start is called before the first frame update
    void Start()
    {
        initialRotation = transform.rotation;
        initialOffset = transform.position - target.position;
    }
    // Update is called once per frame
    void Update()
    {
        horizontal += - Input.GetAxis("Mouse X") * speed;
        vertical += - Input.GetAxis("Mouse Y") * speed;
        vertical = Mathf.Clamp(vertical, -20f, 20f);

        //always rotate from same origin
        transform.rotation = initialRotation;
        transform.position = target.position + initialOffset;
        transform.RotateAround(target.position, transform.right, vertical);
        transform.RotateAround(target.position, Vector3.up, horizontal);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM