【Juego de disparos UnityFPS】(1) Cómo hacer un controlador de personajes FPS①

Usa Rigbody y Capsule Collider para crear un controlador de personajes FPS

1.1 El mouse controla el ángulo de visión en el eje X y gira en el eje Y

El código para mover el ángulo de visión a través del mouse, este código se coloca en la cámara

Nueva secuencia de comandos [FPMouseLook]

    private Transform cameraTransform;   
    private Vector3 cameraRotation; //保存每一帧存储下的坐标信息
    public float mouseSesitivity;//修改鼠标灵敏度
    public Vector2 maxMinAngle;//限制垂直视角区域
    void Start()
    {
        cameraTransform = transform;
    }
    void Update()
    {
        var mouseX = Input.GetAxis("Mouse X");//将鼠标输入的X值赋予mouseX
        var mouseY = Input.GetAxis("Mouse Y"); //将鼠标输入的Y值赋予mouseY
        cameraRotation.y += mouseX * mouseSesitivity;//Y轴想要旋转需要在X轴移动
        cameraRotation.x -= mouseY * mouseSesitivity;//X轴想要旋转需要在Y轴移动
        cameraRotation.x = Mathf.Clamp(cameraRotation.x, maxMinAngle.x, maxMinAngle.y);//cameraRotation.x的值控制在maxMinAngle.x和maxMinAngle.y两个值之间
        cameraTransform.rotation = Quaternion.Euler(cameraRotation.x, cameraRotation.y, 0);//更新相机的旋转角度
    }

1.2 Guión para el movimiento del jugador

Agregue este script al jugador (nuevo objeto vacío ), el movimiento del jugador actual se está moviendo hacia la rotación que no puede seguir la dirección de la cámara, y los ejes X y Z están bloqueados.

objeto del juego del jugador

Bloquear eje X, Y

Nueva secuencia de comandos [FPMovement]
public class FPMovement : MonoBehaviour
{
    private Transform myTransform;
    public float speed;
    private Rigidbody myRigbody;
    void Start()
    {
        myTransform = transform;
        myRigbody = GetComponent<Rigidbody>();
    }
    private void FixedUpdate()
    {
        var h = Input.GetAxis("Horizontal");
        var v = Input.GetAxis("Vertical");
        var currentDirection= new Vector3(h, 0, v);
        //从自身坐标转为世界坐标
        currentDirection = myTransform.TransformDirection(currentDirection);
        currentDirection *= speed;//当前方向乘以速度 
        var currentVelocity = myRigbody.velocity;//获取当前的速度
        var velocityChange = currentDirection - currentVelocity;//得出需要以多少的速度进行行走
        velocityChange.y = 0;//不需要计算y轴的数值
        myRigbody.AddForce(velocityChange, ForceMode.VelocityChange);//添加力到刚体,让它随之移动
    }

1.3 El jugador se mueve con la dirección de rotación de la cámara

Modificar secuencia de comandos [FPMouseLook]
public class FPMouseLook : MonoBehaviour
{
    private Transform cameraTransform;
    [SerializeField] private Transform characterTransform;//记录玩家的位置,序列化到检视视图上或者使用public修饰
    private Vector3 cameraRotation; //保存每一帧存储下的坐标信息
    public float mouseSesitivity;//修改鼠标灵敏度
    public Vector2 maxMinAngle;//限制垂直视角区域
    void Start()
    {
        cameraTransform = transform;
    }
    void Update()
    {
        var mouseX = Input.GetAxis("Mouse X");//将鼠标输入的X值赋予mouseX
        var mouseY = Input.GetAxis("Mouse Y"); //将鼠标输入的Y值赋予mouseY
        cameraRotation.y += mouseX * mouseSesitivity;//Y轴想要旋转需要在X轴移动
        cameraRotation.x -= mouseY * mouseSesitivity;//X轴想要旋转需要在Y轴移动
        cameraRotation.x = Mathf.Clamp(cameraRotation.x, maxMinAngle.x, maxMinAngle.y);//cameraRotation.x的值控制在maxMinAngle.x和maxMinAngle.y两个值之间
        cameraTransform.rotation = Quaternion.Euler(cameraRotation.x, cameraRotation.y, 0);//更新相机的旋转角度
        characterTransform.rotation = Quaternion.Euler(0, cameraRotation.y, 0);//只需改变玩家旋转角度的Y值
    }
}

En este punto, se puede realizar el movimiento normal en primera persona.

1.4 Solo cuando el jugador está controlado se puede mover el suelo y el jugador puede saltar.

Modificar secuencia de comandos [FPMovement]
public class FPMovement : MonoBehaviour
{
    private Transform myTransform;
    public float speed;
    public float gravity;//定义一个重力,自己赋值
    public float jumpHeight;//定义跳跃的高度
    private Rigidbody myRigbody;
    private bool isGrounded;//判断是否玩家触地
    void Start()
    {
        myTransform = transform;
        myRigbody = GetComponent<Rigidbody>();
    }
    private void FixedUpdate()
    {
        if (isGrounded)
        {
            var h = Input.GetAxis("Horizontal");
            var v = Input.GetAxis("Vertical");
            var currentDirection = new Vector3(h, 0, v);
            //从自身坐标转为世界坐标
            currentDirection = myTransform.TransformDirection(currentDirection);
            currentDirection *= speed;//当前方向乘以速度 
            var currentVelocity = myRigbody.velocity;//获取当前的速度
            var velocityChange = currentDirection - currentVelocity;//得出需要以多少的速度进行行走
            velocityChange.y = 0;//不需要计算y轴的数值
            myRigbody.AddForce(velocityChange, ForceMode.VelocityChange);//添加力到刚体,让它随之移动
            if (Input.GetButtonDown("Jump"))//判断是否摁下跳跃键
            {
                myRigbody.velocity = new Vector3(currentVelocity.x, JumpHeightSpeed(), currentVelocity.z);//跳跃,玩家坐标的x与z轴均使用自身坐标,y轴为自己写的方法
            }
        }
        myRigbody.AddForce(new Vector3(0, -gravity * myRigbody.mass, 0));//如果未触地,则下坠
    }
    private float JumpHeightSpeed()//返回平方根,其数值作为玩家跳跃的y轴的值
    {
        return Mathf.Sqrt(2 * gravity * jumpHeight);
    }
    private void OnCollisionStay(Collision collision)
    {
        isGrounded = true;
    }
    private void OnCollisionExit(Collision collision)
    {
        isGrounded = false;
    }
}

Supongo que te gusta

Origin blog.csdn.net/Y1RV1NG/article/details/129508121
Recomendado
Clasificación