Unity First Person Controller

I have to say that Unity's latest lightweight character controller is really easy to use with the new input system. But I won't (doge). Friends who want to learn can directly download the first-person controller template of unity in the Hub. I personally think it is very suitable for learning.

There are only three things that a simple first-person controller needs to do:

Character movement, camera rotation, gravity simulation.

For the rotation of the camera, we hope that it should be able to achieve 360 ​​degrees on the x-axis, because the rotation of the character's body is arbitrary on the x-axis, but in the up and down direction, that is, on the y-axis, we don't want to follow the rotation of the perspective The character can turn its head upside down, and it is reasonable to limit it to -90 degrees to 90 degrees. The following is the camera code part:

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

public class CameraFallow : MonoBehaviour
{

    public float mouseSensitivity = 100f;

    public Transform player;

    private float xRotation = 0f;
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked; //在游戏中隐藏鼠标
    }

    // Update is called once per frame
    void Update()
    {
        MoveMent();
    }

    void MoveMent()
    {
        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);
        player.Rotate(Vector3.up * mouseX);

    }
}

There is no difficulty in the code, and it can be dealt with directly.

Let's talk about the movement of characters and the simulation of gravity.

What we need to pay attention to when moving is that we should not let the movement of the character be based on the entire world coordinate system. The effect we want to achieve in the first person should be that when our character faces a certain direction, the front of the movement should face this direction. For the simulation of gravity, our function can be easily realized with two simple physical formulas and ground detection.

btw, although we know that the acceleration of gravity is -9.81, in fact, the whole process of jumping in the game can often be realized in a short period of time, so we should make this value 1.5 times larger than the original acceleration of gravity Between 2 times, this feeling is more comfortable.

Here is the part of the code for the role:

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

public class PlayerMovement : MonoBehaviour
{
    [Header("移动速度")]
    public float speed=12f;

    [Header("重力加速度")]
    public float gravity = -9.81f;

    [Header("地面检测")]
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask GroundMask;

    [Header("跳跃高度")]
    public float jumpHeight = 3f;

    private CharacterController controller;

    private Vector3 velocity;
    private bool isGround;
   
    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    
    void Update()
    {
        movement();
    }
    void movement()
    {
        //x跟z轴移动:
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z; //根据角色的朝向进行基于x轴与z轴的移动   

        //Vector3 move =new  Vector3(x, 0f, z); //错误的赋值。
        /*这里赋值的的 vector3 是面对整个世界坐标系的,无论角色面朝任何方向,都只会在世界坐标系的x轴跟z轴上移动。*/

        controller.Move(move * speed * Time.deltaTime);


        //考虑重力的y轴移动:
        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime );

        isGround = Physics.CheckSphere(groundCheck.position, groundDistance, GroundMask);

        if (isGround && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        //跳跃
        if (Input.GetButtonDown("Jump") && isGround)
        {
            velocity.y = Mathf.Sqrt(-2 * jumpHeight * gravity); //v=sqrt(2gh);
        }
    }
}

Awesome, this time I learned a simple first-person controller. Although compared with the official template of unity, its feel is not good, but it is official after all .

Guess you like

Origin blog.csdn.net/qq_62440805/article/details/124880515