【问题标题】:How can I make an objects rotatable only for the player?如何使对象只能为玩家旋转?
【发布时间】:2019-12-19 23:13:04
【问题描述】:

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

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);
        }
    }
}

【问题讨论】:

  • 我想你可以看看基于层的碰撞检测...

标签: unity3d camera rotation


【解决方案1】:

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

将其移至 LateUpdate 以使其成为框架中最后调用的内容(另请参阅 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,以便也重置物理的更改。如果有任何 RigidBody 在玩,这应该是要走的路,但不要使用Transform,而是使用Rigidbody 组件。

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

注意:但是,当您设置它时,您会得到意想不到的旋转。此处绕两轴旋转存在同时沿局部坐标系旋转的问题。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2018-05-26
    相关资源
    最近更新 更多