unity利用Rigibody实现第一人称移动

1. CameraRotation脚本,将它给MainCamera,实现上下视角旋转

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

public class CameraRotation : MonoBehaviour
{
    [Tooltip("鼠标灵敏度")]
    public float RotateSpeed = 5f;
    //x轴的旋转角度
    float xRotation = 0f;
    private void Awake() {
        //将玩家脚本上的旋转角度设为设置的旋转角度
        Player.tmp_rotateSpeed = RotateSpeed;
    }
    void Update()
    {
        //获取鼠标y轴上的移动量
        float mouseY = Input.GetAxis("Mouse Y");
        //将x轴旋转,注意是减mouseY,同时乘旋转速度
        xRotation -= mouseY * RotateSpeed;
        //将x轴的角度限定在一定范围内
        xRotation = Mathf.Clamp(xRotation, -90, 90);
        //设置localRotation,即旋转角度
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    }
}



2. Player脚本,将它给角色,它会自动添加组件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Player : MonoBehaviour
{
    //玩家的旋转角度,取决于CameraRotation上的RotateSpeed。
    public static float tmp_rotateSpeed;
    [Tooltip("旋转速度")]
    public float speed = 5f;
    [Tooltip("跳跃高度")]
    public float jumpForce = 5f;
    //玩家身上的刚体组件
    private Rigidbody rb;

    void Start()
    {
        //获取玩家的刚体组件
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        //获取鼠标在x轴的移动量
        float mouseX = Input.GetAxis("Mouse X");
        //根据移动量旋转
        transform.Rotate(Vector3.up, mouseX * Player.tmp_rotateSpeed);

        //获取WASD键的输入
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        //移动方向和速度
        Vector3 movement = (transform.forward * moveVertical * Time.deltaTime + 
        transform.right * moveHorizontal * Time.deltaTime) * speed;

        //根据计算出的movement移动
        rb.Move(rb.position + movement, transform.localRotation);

        //如果按下空格键,给刚体向上力,即跳跃
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        }
    }
}

posted @ 2023-05-03 22:03  三甲基烷  阅读(248)  评论(0)    收藏  举报