视角跟随鼠标移动(第一人称视角)

效果:

鼠标水平左右平滑视角跟随左右转动,鼠标上下平滑视角上下转动(设置上下转动有限制)。思路是把摄像机当成头部眼睛,然后玩家物体相当于移动的身体。

上传不了太大的对动图,所以只是展示了旋转的效果。

摄像机代码:

(先将摄像机作为游戏玩家角色的子物体然后把代码挂载到摄像机身上即可)


using UnityEngine;
public class follow2 : MonoBehaviour
{
    private Transform head;
    private Transform body;
    private Rigidbody rigidbody;
    public float angle;
    void Start()
    {
        head = transform;
        body = transform.parent;
        rigidbody = GetComponent();
        Cursor.lockState = CursorLockMode.Locked;
    }
    void Update()
    {
        float hroitzonal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        Vector3 dir = new Vector3(hroitzonal, 0, vertical);
        if (dir != Vector3.zero)
        {
            body.Translate(dir * Time.deltaTime * 3);
        }
        float mousex = Input.GetAxis("Mouse X");
        if (mousex != 0)
        {
            body.Rotate(Vector3.up, mousex * 120 * Time.deltaTime);
        }
        float mousey = Input.GetAxis("Mouse Y");
        if (mousey != 0)
        {
            head.Rotate(Vector3.left, mousey * 120 * Time.deltaTime);
        }
        if (Vector3.Angle(body.forward, head.forward) > angle)
        {
            head.Rotate(Vector3.left, -mousey * 120 * Time.deltaTime);
        }
    }
}

视角跟随鼠标移动(第一人称视角)_第1张图片

视角跟随鼠标移动(第一人称视角)_第2张图片 

玩家代码:

可以放一些碰撞到相应物体弹出文本框提示的代码,本案例已经将玩家移动代码放到摄像机脚本,玩家脚本只添加了触发检测


using UnityEngine;
using UnityEngine.UI;

public class move_and_trriger : MonoBehaviour
{
    public Text text1;
    private void OnTriggerEnter(Collider other)
    {
        if (other.name.Equals("Tree"))
        {
            text1.text = "这是一颗热带雨林的大叔";
        }else if (other.name.Equals("pig"))
        {
            text1.text = "小子,这是个猪";
        }else if (other.name.Equals("home"))
        {
            text1.text = "这是房子啊";
        }
    }
    private void OnTriggerExit(Collider other)
    {
        text1.text = "";
    }
}

你可能感兴趣的:(计算机外设,c#,unity,游戏引擎,windows)