Unity第一人称移动和观察

创建一个可以自由移动的第一人称视角

人物通过WSAD进行前后左右移动,通过鼠标右键进行旋转

Step1:创建一个Player玩家,在节点下加两个子物体,一个摄像头和一个Capsule充当身体

Step2:创建一个脚本挂载在Player节点下,再在这个Player物体下加上Character Controller脚本

Step3:该脚本内容如下

using UnityEngine;

/// <summary>
/// 人物移动脚本
/// 直接引用Character的Move方法
/// </summary>
public class PlayerMove : MonoBehaviour
{
    //键盘
    public float speed = 30F;
    public float jumpSpeed = 5.0F;
    public float gravity = 5.0F;
    private Vector3 moveDirection;
    private CharacterController characterController;

    //鼠标
    public float mousespeed = 3f;
    public float minmouseY = -45f;
    public float maxmouseY = 45f;
    public Transform playerCamera;

    private Vector3 oldMousePos;
    private Vector3 newMousePos;

    private void OnEnable()
    {
        characterController = GetComponent<CharacterController>();
    }
    private void FixedUpdate()
    {
        if (Input.GetMouseButton(1))
        {
            //把当前右键鼠标点的位置先存储起来
            newMousePos = Input.mousePosition;

            //再把每一帧刚开始的位置和上一帧的位置做一个差值
            Vector3 dis = newMousePos - oldMousePos;

            //X,Y方向上位移的距离就是这个差值的x,y分量*鼠标移动速度
            float angleX = dis.x * mousespeed;
            float angleY = dis.y * mousespeed;

            //然后再根据分量差值进行旋转
            transform.Rotate(new Vector3(-angleY, 0, 0), Space.Self);
            transform.Rotate(new Vector3(0, angleX, 0), Space.World);
        }

        if(characterController.isGrounded)
        {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }
        }
        moveDirection.y = moveDirection.y - gravity * Time.deltaTime;

        //使用characterController的Move方法对物体进行移动,参数就是移动方向 * 时间
        characterController.Move(moveDirection * Time.deltaTime);

        //更新鼠标的下一帧位置
        oldMousePos = Input.mousePosition;
    }
}

运行即可

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Laker404

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值