Game视图中实现类Scene中Camera的控制(自身中心)

在网上找了找,感觉这个还不错,并自己试了试,效果很不错,就是没有平滑效果,需要的自己加吧,哈哈。

下面就是网上找到的本版,还不错!!


Unity Game窗口中还原Scene窗口摄像机操作 强化版

之前写的那个版本看来真的是不行啊。最近研究了一下官方第一人称脚本,人家的平滑过渡真的是没得说。借鉴了一下,写出来了一个新的比较完美的控制。

之前我们的操作是通过鼠标输入的开始坐标和转动坐标。其实官方有一个函数~

1 float yRot = Input.GetAxis("Mouse X");
2 float xRot = Input.GetAxis("Mouse Y");

这就分别能获取到鼠标的X轴操作和Y轴操作了。

那为什么用yRot获取X轴,xRot获取Y轴呢?

左面是鼠标的顶视图,右边是Unity中的三维坐标。可以观察到,鼠标X轴的平移对应的就是Unity中Y轴的旋转。Y轴同理。

但是还是不能照搬官方的写法,因为官方的写法针对的是自身坐标,就是Local。(注:LocalPosition并不等于物体的Local坐标)

扫描二维码关注公众号,回复: 1729962 查看本文章

Scene窗口的摄像机是针对World的旋转。

这里就需要转换一下。


using UnityEngine;
using System.Collections;

public class TCamerCtrl : MonoBehaviour
{

    private float Speed = 20f;
    private Vector3 CameraR;

    void Start()
    {
        CameraR = Camera.main.transform.rotation.eulerAngles;
    }

    void Update()
    {
        Vector3 Face = transform.rotation * Vector3.forward;
        Face = Face.normalized;

        Vector3 Left = transform.rotation * Vector3.left;
        Left = Left.normalized;

        Vector3 Right = transform.rotation * Vector3.right;
        Right = Right.normalized;

        if (Input.GetMouseButton(1))
        {
            //官方脚本
            float yRot = Input.GetAxis("Mouse X")*2;
            float xRot = Input.GetAxis("Mouse Y")*2;

            Vector3 R = CameraR + new Vector3(-xRot, yRot, 0f);

            CameraR = Vector3.Slerp(CameraR, R, Speed * Time.deltaTime);

            transform.rotation = Quaternion.Euler(CameraR);
        }

        if (Input.GetKey("w"))
        {
            transform.position += Face * Speed * Time.deltaTime;
        }

        if (Input.GetKey("a"))
        {
            transform.position += Left * Speed * Time.deltaTime;
        }

        if (Input.GetKey("d"))
        {
            transform.position += Right * Speed * Time.deltaTime;
        }

        if (Input.GetKey("s"))
        {
            transform.position -= Face * Speed * Time.deltaTime;
        }

        if (Input.GetKey("q"))
        {
            transform.position -= Vector3.up * Speed * Time.deltaTime;
        }

        if (Input.GetKey("e"))
        {
            transform.position += Vector3.up * Speed * Time.deltaTime;
        }

    }
}
感谢原作者!

最后附上原链接:http://www.cnblogs.com/SHOR/p/5736596.html


猜你喜欢

转载自blog.csdn.net/sam_one/article/details/54022803