第一人称视角创建

10 篇文章 0 订阅

在很多的游戏中我们都看到第一人称视角,下面是第一人称视角的创建

首先先新建一个场景,然后添加一个胶囊体,把摄像机放到胶囊体上调整位置并且把摄像机设置为胶囊体的子对象
这里写图片描述

新建C#脚本
命名为MouseLook.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseLook : MonoBehaviour
{

    public enum RotationAxex
    {
        MouseXAndY = 0,
        MouseX = 1,
        MouseY = 2
    }

    public RotationAxex axes = RotationAxex.MouseXAndY;
    //旋转速度
    public float sensitiveityHor = 9.0f;
    public float sensitiveityVert = 9.0f;

    //垂直旋转最大和最小值
    public float minimumVert = -45.0f;
    public float maximumVert = 45.0f;

    //垂直角度
    private float _rotationX = 0;

    // Use this for initialization
    void Start()
    {
        Rigidbody body = GetComponent<Rigidbody>();
        if (body != null)
        {
            body.freezeRotation = true;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (axes == RotationAxex.MouseX)
            transform.Rotate(0, Input.GetAxis("Mouse X") * sensitiveityHor, 0);
        else if (axes == RotationAxex.MouseY)
        {
            //基于鼠标增加垂直角度
            _rotationX -= Input.GetAxis("Mouse Y") * sensitiveityVert;
            _rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);

            //保持Y的角度一样
            float rotationY = transform.localEulerAngles.y;
            transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
        }
        else
        {
            _rotationX -= Input.GetAxis("Mouse Y") * sensitiveityVert;
            _rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);

            //旋转变化量
            float delta = Input.GetAxis("Mouse X") * sensitiveityHor;
            //使用delta递增旋转角度
            float rotationY = transform.localEulerAngles.y + delta;

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

Mathf.Clamp用于限制视角查看范围,限制_rotationX的值在minimumVert和maximumVert之间返回

在摄像机和胶囊体上分别挂上MouseLook脚本

选中摄像机,在Inspector面板上的MouseLook脚本上设置Axes值为Mouse Y
这里写图片描述

选中胶囊体,设置MouseLook脚本的Axes值为Mouse X
这里写图片描述

这么一来第一人称视角观察就完成了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值