如何使播放器以相机的外观旋转(带有代码)

时间:2019-01-27 14:35:51

标签: c# unity3d

我试图更改一些东西,例如添加旋转变量等,但是我似乎无法使它正常工作(应该澄清两个单独的脚本)。救命?

using UnityEngine;

public class camfollow : MonoBehaviour
{
    public float mouseSensitivity = 10;

    public Transform target;

    public float distFromTarg = 2f;
    private Vector2 pitchminmax = new Vector2(-21.7f, 88.2f);

    float yaw;
    float pitch;

    public float rotationSmoothTime = 0.12f;
    Vector3 velocity;
    Vector3 rotation;

    // Update is called once per frame
    public void Update()
    {

        yaw += Input.GetAxis("Mouse X") * mouseSensitivity;
        pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;
        pitch = Mathf.Clamp(pitch, pitchminmax.x, pitchminmax.y);

        rotation = Vector3.SmoothDamp(rotation, new Vector3(pitch, yaw), ref 
        velocity, rotationSmoothTime);

        Vector3 targetrotation = new Vector3(pitch, yaw);
        transform.eulerAngles = targetrotation;

        transform.position = target.position - transform.forward * 
        distFromTarg;
        Lookie();
    }

 Weird indent here when I posted it, ignore please
        public void Lookie()
        {
        Vector3 mousePos = new Vector3(Input.mousePosition.x, 
        Input.mousePosition.z, 10) + rotation;
        Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos) + 
        rotation;

        lookPos = lookPos - transform.position + rotation;
        float angle = Mathf.Atan2(lookPos.z, lookPos.x) * Mathf.Rad2Deg + 
        pitch 
        + yaw;
        transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

      }
   }
}

我希望播放器能够根据鼠标移动相机的位置来转动,相机已经跟随播放器。现在,它不会旋转-只需跟随播放器即可。

编辑:我试图做第一个答案,但在第40行上得到的对象引用未设置为对象错误的实例:

Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos) + rotation;

0 个答案:

没有答案