unity简易实现第一人称移动 视角移动 跳跃 奔跑

移动

// 当前速度
private float _speed = 6.0f;

// FixedUpdate 用于物理计算
void FixedUpdate()
{
    // 获取水平和垂直输入
    float horizontalInput = Input.GetAxisRaw("Horizontal");
    float verticalInput = Input.GetAxisRaw("Vertical");

    // 计算移动向量
    Vector3 direction = new Vector3(horizontalInput, 0, verticalInput);

    // 将移动向量规范化
    direction.Normalize();

    // 移动
    GetComponent<Rigidbody>().MovePosition(GetComponent<Rigidbody>().position + direction * _speed * Time.fixedDeltaTime);
}

跳跃

// 跳跃力
private float _jumpForce = 1000.0f;

void Update()
{
    // 如果按下了跳跃键
    if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
    {
        // 向上施加力
        GetComponent<Rigidbody>().AddForce(Vector3.up * _jumpForce);
    }
}

旋转视角

// 鼠标灵敏度
private float _sensitivity = 2.0f;

// FixedUpdate 用于物理计算
void FixedUpdate()
{
    // 获取鼠标输入
    float mouseX = Input.GetAxisRaw("Mouse X");
    float mouseY = Input.GetAxisRaw("Mouse Y");

    // 旋转相机
    transform.Rotate(Vector3.up * mouseX * _sensitivity);
    transform.Rotate(Vector3.left * mouseY * _sensitivity);
}

奔跑

// 跑步时的速度
private float _runSpeed = 10.0f;

void Update()
{
    // 如果按下了奔跑键
    if (Input.GetKey(KeyCode.LeftShift))
    {
        // 设置速度为奔跑速度
        _speed = _runSpeed;
    }
    else
    {
        // 设置速度为正常速度
        _speed = 6.0f;
    }
}

在地上判定

// 地面判定半径
private float _groundCheckRadius = 0.2f;

// 层级掩码(地面层)
private LayerMask _groundLayer;

bool IsGrounded()
{
    // 创建一个射线
    Ray ray = new Ray(transform.position + Vector3.up * _groundCheckRadius, Vector3.down);

    // 执行射线检测
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit, _groundCheckRadius, _groundLayer))
    {
        return true;
    }

    return false;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值