Unity 第一人称控制器(FirstPersonController)

第一人称结构

在这里插入图片描述

摄像机摆放位置

在这里插入图片描述

角色控制器(CharacterController)

在这里插入图片描述

基本思路:
控制摄像机围绕x轴旋转=>人物的上下视角旋转,
控制身体(圆柱体)的左右旋转=>的脚本控制人物的左右视角旋转。

在这里插入图片描述

模拟重力

使用Character的缺点
在这里插入图片描述

在这里插入图片描述

代码

MouseLook.cs

在这里插入图片描述

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

public class MouseLook : MonoBehaviour
{
    //sensitivity => 灵敏度
    public float MouseSensitivity = 100f;

    public Transform PlayerBody;

    private 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);

    }
}

PlayerMovement.cs

在这里插入图片描述

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

public class PlayerMovement : MonoBehaviour
{
    public CharacterController CharacterController;

    [Header("Move")]
    public float Speed = 12f;
    public float Gravity = 20f;
    private Vector3 m_Velocity;
    [Space]
    [Header("IsGrounded")]
    public Transform GroundCheck;
    public float GroundDistance;
    public LayerMask GroundMask;

    private bool m_IsGrounded;

    [Header("Jump")]
    public float JumpHeight;

    // Update is called once per frame
    void Update()
    {
        // 落地检测
        m_IsGrounded = Physics.CheckSphere(GroundCheck.position, GroundDistance, GroundMask);
        if (m_IsGrounded && m_Velocity.y < 0)
        {
            m_Velocity.y = -2;
        }

        //平面移动
        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");

        Vector3 MoveDir = transform.right * x + transform.forward * y;

        CharacterController.Move(MoveDir * Speed * Time.deltaTime);

        //自由落体
        m_Velocity.y -= Time.deltaTime * Gravity;

        CharacterController.Move(m_Velocity * Time.deltaTime);

        //跳跃
        if (Input.GetButtonDown("Jump")
            && m_IsGrounded)
        {
            m_Velocity.y = Mathf.Sqrt(JumpHeight * 2f * Gravity);
        }

    }
}

一些小拓展

Cursor.LockState

CursorLockMode
在这里插入图片描述

Locked: 将光标锁定在屏幕中心不可显示
Confined: 将光标锁定在游戏界面内,不可以移出,光标会显示

  • 5
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值