Unity2019中如何自制第一人称控制器(简单暴力版)

       在Unity2019中做项目时,发现其中没有自带的第一人称控制器,于是我在网上参考多种教程,最终做出第一人称控制器,下面分享给大家。

       新建一个空物体,重命名为 Player,并为其添加组件 Character Controller。将场景中的相机拖到 Player 下面,在 Player 下面放一个立方体,以便于观察。

       在 Player 下面创建一个空物体,重命名为 GroundCheck,这个空物体用于检查人物是否与地面接触,以实现按下空格键产生弹跳效果。

       为 Player 创建一个脚本 FirstPersonController。

using UnityEngine; 
public class FirstPersonController : MonoBehaviour 
{ 
public CharacterController controller; 
public float speed = 12f; 
public float gravity = -9.81f; 
public float jumpHeight = 3f; 
public Transform groundCheck; 
public float groundDistance = 0.4f; 
public LayerMask groundMask; 
Vector3 _velocity; 
bool _isGrounded; 
// Start is called before the first frame update 
void Start() 
{ 
} 
// Update is called once per frame 
void Update() 
{ 
_isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, 
groundMask); 
if (_isGrounded && _velocity.y < 0) 
{ 
_velocity.y = -2f; 
} 
float x = Input.GetAxis("Horizontal"); 
float z = Input.GetAxis("Vertical"); 
Vector3 move = transform.right * x + transform.forward * z; 
controller.Move(move * speed * Time.deltaTime); 
if (Input.GetButtonDown("Jump") && _isGrounded) 
{ 
_velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity); 
}
_velocity.y += gravity * Time.deltaTime;controller.Move(_velocity * Time.deltaTime); 
} 
}

       为地形添加一个层 Ground。

       FirstPersonController 脚本具体界面如下,Ground Mask 选择刚刚创建的 Ground 层,将 Player 身上的角色控制器 Character Controller 拖到 Controller 处。

       为 Player 身上的相机创建脚本 MouseLook。

using UnityEngine;

public class MouseLook : MonoBehaviour
{
    public float mouseSensitivity = 100f;
    public Transform playerBody;
    float xRotation = 0f;
    // Start is called before the first frame update
    // void Start()
    //{
    //  Cursor.lockState = CursorLockMode.Locked;
    // }

    // Update is called once per frame
    void Update()
    {
        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);
        playerBody.Rotate(Vector3.up * mouseX);
    }
}

       将 Player 拖到 Player Body 处。

       至此第一人称控制器已完成制作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值