项目实训(九)FPS游戏之使用Rigidbody&Capsule Collider制作FPS角色控制器


前言

FPS游戏之使用Rigidbody&Capsule Collider制作FPS角色控制器,即角色视角和位置移动控制器,将相关的脚本添加到控制器上实现对角色的控制。


一、三种方法实现FPS Controller的区别

1.Transform Translate

允许物体移动,但无物理碰撞,会穿透墙壁以及其他的障碍物。

2.Rigid body +Capsule

符合物理学运动,不会鬼穿墙,无法滞空运动,可与Physics Object交互

3.CharacterController

不会鬼穿墙,可实现滞空运动(太空人),提供的API相对多,无法与Physics Object交互,提供多种运动效果例如:slopes steps等

二、使用Rigidbody&Capsule Collider制作FPS角色控制器

1.创建一个新物体,建立一个新的脚本FPMouseLook 用来根据鼠标的位置获取相应的坐标,从而实现视角跟随鼠标位置进行变化,同时使得角色根据相应的鼠标位置完成方向的转动。

在这里插入图片描述

private void Start()
    {
    
    
        cameraTransform = transform;
        cameraSpring = GetComponentInChildren<CameraSpring4>();

    }

    void Update()
    {
    
    
        var tmp_MouseX = Input.GetAxis("Mouse X");
        var tmp_MouseY = Input.GetAxis("Mouse Y");


        CameraRotation.y += tmp_MouseX * MouseSensitivity;
        CameraRotation.x -= tmp_MouseY * MouseSensitivity;


        CalculateRecoilOffset();
        

        CameraRotation.y += currentRecoil.y;
        CameraRotation.x -= currentRecoil.x;

        CameraRotation.x = Mathf.Clamp(CameraRotation.x, MaxminAngle.x, MaxminAngle.y);
        characterTransform.rotation = Quaternion.Euler(0, CameraRotation.y, 0);
        cameraTransform.rotation = Quaternion.Euler(CameraRotation.x, CameraRotation.y, 0);
    }


    private void CalculateRecoilOffset()
    {
    
    
        currentRecoilTime += Time.deltaTime;
        float tmp_RecoilFraction = currentRecoilTime / RecoilFadeOutTime;
        float tmp_RecoilValue = RecoilCurve.Evaluate(tmp_RecoilFraction);
        currentRecoil = Vector2.Lerp(Vector2.zero, currentRecoil, tmp_RecoilValue);
    }

2.SimpleCameraController 脚本控制在unity中设置的camera的角度和位置,根据玩家的操作获取键盘和鼠标的输入,对camera的position,rotation等进行转换和计算,实现游戏中角色视角和位置的控制。

Vector3 GetInputTranslationDirection()
        {
    
    
            Vector3 direction = new Vector3();
            if (Input.GetKey(KeyCode.W))
            {
    
    
                direction += Vector3.forward;
            }
            if (Input.GetKey(KeyCode.S))
            {
    
    
                direction += Vector3.back;
            }
            if (Input.GetKey(KeyCode.A))
            {
    
    
                direction += Vector3.left;
            }
            if (Input.GetKey(KeyCode.D))
            {
    
    
                direction += Vector3.right;
            }
            if (Input.GetKey(KeyCode.Q))
            {
    
    
                direction += Vector3.down;
            }
            if (Input.GetKey(KeyCode.E))
            {
    
    
                direction += Vector3.up;
            }
            return direction;
        }

猜你喜欢

转载自blog.csdn.net/qq_45856546/article/details/125174645