Unity FPS旋转相机

13
在我的游戏中,我有一个相机,我想让它附带类似于FPS的旋转效果。
因此,如果我将光标向左移动,我希望我的相机向左旋转。如果我将光标向上移动,则相机应该向上看,以此类推。
目前,我已经部分实现了这个功能。我可以向左和向右看,向上和向下看。问题出现在我向下看然后将光标向左或向右移动时。这时会产生“翻滚”效果。
请观看以下视频,以了解我的意思: http://www.screencast.com/t/Phedh8H0K13 显然,当我向下看时,我仍然希望出现“偏航”效果而不是“翻滚”效果。有没有人知道如何做到这一点?这是我目前的代码:
// Update is called once per frame
public override void update ()
{
    this.camera.transform.rotation *= 
        Quaternion.AngleAxis( Time.deltaTime * sensitivityRoll * Input.GetAxis("Vertical"), Vector3.forward );

    this.camera.transform.rotation *= 
        Quaternion.AngleAxis( Time.deltaTime * sensitivityYaw * Input.GetAxis("Mouse X"), Vector3.up );

    this.camera.transform.rotation *= 
        Quaternion.AngleAxis( Time.deltaTime * sensitivityPitch * Input.GetAxis("Mouse Y"), Vector3.left );
}
4个回答

18

我在这个主题中找到了答案:

http://forum.unity3d.com/threads/109250-Looking-with-the-Mouse?highlight=person+camera


来自该主题的代码:

C# Mono 代码:

using UnityEngine;
using System.Collections;

/// MouseLook rotates the transform based on the mouse delta.
/// Minimum and Maximum values can be used to constrain the possible rotation

/// To make an FPS style character:
/// - Create a capsule.
/// - Add the MouseLook script to the capsule.
///   -> Set the mouse look to use LookX. (You want to only turn character but not tilt it)
/// - Add FPSInputController script to the capsule
///   -> A CharacterMotor and a CharacterController component will be automatically added.

/// - Create a camera. Make the camera a child of the capsule. Reset it's transform.
/// - Add a MouseLook script to the camera.
///   -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.)
[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour {

    public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
    public RotationAxes axes = RotationAxes.MouseXAndY;
    public float sensitivityX = 15F;
    public float sensitivityY = 15F;

    public float minimumX = -360F;
    public float maximumX = 360F;

    public float minimumY = -60F;
    public float maximumY = 60F;

    float rotationY = 0F;

    void Update ()
    {
        if (axes == RotationAxes.MouseXAndY)
        {
            float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;

            rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

            transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
        }
        else if (axes == RotationAxes.MouseX)
        {
            transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
        }
        else
        {
            rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

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

    void Start ()
    {
    //if(!networkView.isMine)
        //enabled = false;

        // Make the rigid body not change rotation
        //if (rigidbody)
            //rigidbody.freezeRotation = true;
    }
}

多年晚了,但还是谢谢你的答案,这正是我正在寻找的! - user1354784

0
using UnityEngine;

public class CameraRotator : MonoBehaviour
{
    [SerializeField] private Transform _head;
    [SerializeField] private float _sensitivity;
    [SerializeField] private bool _invertVertical;

    private void Update()
    {
        var deltaMouse = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y");
        
        Vector2 deltaRotation = deltaMouse * _sensitivity;
        deltaRotation.y *= _invertVertical ? 1.0f : -1.0f;

        float pitchAngle = _head.localEulerAngles.x;
        
        // turns 270 deg into -90, etc
        if (pitchAngle > 180)
            pitchAngle -= 360;

        pitchAngle = Mathf.Clamp(pitchAngle + deltaRotation.y, -90.0f, 90.0f);

        transform.Rotate(Vector3.up, deltaRotation.x);
        _head.localRotation = Quaternion.Euler(pitchAngle, 0.0f, 0.0f);
    }
}

虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - Abhishek Dutt

0

简单的脚本,不确定它是否适用于您,不妨试一试

using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Threading;
using UnityEngine;

public class mouse_lookat : MonoBehaviour
{
    public float mouseSensitivity = 100f;

    public Transform playerBody;

    float xRotation = 0f;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);
    }
}

1
为什么要使用 using System.Security.Cryptography; - Ruzihm

-1
我为我的FPS项目创建了两个脚本,它们对我的移动非常完美(目前还没有添加跳跃机制),而且似乎你过于复杂化了许多可以非常简单和直接的事情。我也是编码新手,如果我错了,请纠正我的代码。
// 这段代码在玩家脚本中,我将其放在相机和玩家精灵的空父对象上。
public class player : MonoBehaviour
{
    [Header("player Movement")]
    [SerializeField] float moveSpeed = 5f;
    [SerializeField] public float mouseSensitivity = 5f;

    
    Rigidbody rigidBody;
   
    // Use this for initialization
    void Start()
    {
        
    }

 void Update()
    {
        Move();
       
    }


    private void Move()
    {
        transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime);
        transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime);
        transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * mouseSensitivity);
    }

//这是我放在摄像机上的相机移动脚本(我还将使用此脚本添加一个功能,以便在某些能力中从第一人称切换到第三人称)

{

    player player;
    // Use this for initialization
    void Start()
    {
        player = FindObjectOfType<player>();
    }

    // Update is called once per frame
    void Update()
    {
        MoveView();
    }
    private void MoveView()
    {
        transform.Rotate(Vector3.left * Input.GetAxis("Mouse Y") * player.mouseSensitivity);
    }
}

1
在鼠标轴上调用GetAxis会返回自上一帧以来绝对鼠标移动的差异。除非你想让鼠标移动的速度比鼠标移动的距离更重要,否则请不要将鼠标轴的GetAxis乘以deltaTime。在大多数情况下,这真的很不直观,特别是在这种情况下!请注意,不要这样做! - Ruzihm
而且,即使你这样做了,你可能是想在那些情况下除以 deltaTime(因为速度 = 位移变化量 / 时间变化量)。 - Ruzihm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接