我怎样才能让一个物体只对玩家旋转?

How can I make an objects rotatable only for the player?

问题是,如果玩家触摸了旋转的东西,玩家也会自动开始旋转,因为现在正在旋转的物体推动了玩家的碰撞器,并且玩家开始旋转。我想让我的玩家无法旋转到游戏中的另一个对象,但如果玩家自己旋转则可以旋转

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

public class camera : MonoBehaviour
{

    public enum RotationAxis
    {
        MouseX = 1,
        MouseY = 2
    }

    public RotationAxis axes = RotationAxis.MouseX;

    public float minimumVert = -45.0f;
    public float maximumVert = 45.0f;

    public float sensHorizontal = 10.0f;
    public float sensVertical = 10.0f;

    public float _rotationX = 0;

    // Update is called once per frame
    void Update()
    {
        if (axes == RotationAxis.MouseX)
        {
            transform.Rotate(0, Input.GetAxis("Mouse X") * sensHorizontal, 0);
        }
        else if (axes == RotationAxis.MouseY)
        {
            _rotationX -= Input.GetAxis("Mouse Y") * sensVertical;
            _rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert); //Clamps the vertical angle within the min and max limits (45 degrees)

            float rotationY = transform.localEulerAngles.y;

            transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
        }
    }
}

您可以将旋转存储在一个字段中,从而确保唯一改变它的是您的脚本:

移至LateUpdate in order for it to be the last thing called in a frame (also see Order of Execution for Event Functions)

float xRotation;
float yRotation;

void Start()
{
    xRotation = transform.localEulerAngles.x;
    yRotation = transform.localEulerAngles.y;
}

void LateUpdate()
{
    if (axes == RotationAxis.MouseX)
    {
        yRotation += Input.GetAxis("Mouse X") * sensHorizontal;

    }
    else if (axes == RotationAxis.MouseY)
    {
        xRotation -= Input.GetAxis("Mouse Y") * sensVertical;
        //Clamps the vertical angle within the min and max limits (45 degrees)
        xRotation= Mathf.Clamp(lastXRotation , minimumVert, maximumVert); 
    }

    // always overwrite with fixed values instead of using transform.rotation based ones
    transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0);
}

只是为了确保您也可以另外将其设置为 FixedUpdate 以便也重置 Physics 的更改。如果有任何 RigidBody 在玩,这应该是无论如何都要走的路,但是不要使用 Transform 而是 Rigidbody 组件。

void FixedUpdate()
{
    transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0);
}

注意 然而:由于您当前已设置它,您将获得意想不到的旋转。这里绕两个轴旋转有同样沿局部坐标系旋转的问题

一般来说,您应该有一个用于 Y 旋转的父对象,而只对对象本身进行 X 旋转。