You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity安卓无尽跑酷检测双UI按钮同时按下触发跳跃功能问询

实现同时按住左右UI按钮触发跳跃的修改方案

核心逻辑说明:默认的Horizontal虚拟轴同时按左右会返回0,无法直接判断同时触发状态,因此改为单独检测两个按钮的按下状态,同步处理移动和跳跃逻辑。

前置配置操作

  • 打开左右移动UI按钮对应的CrossPlatformInput组件,将左侧按钮的虚拟按钮名称设为Left,右侧按钮的虚拟按钮名称设为Right,不再共用原来的Horizontal轴配置
  • 将场景中所有地面对象的Layer设置为Ground,用于地面检测避免空中重复跳跃

修改后的完整代码

using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerMovement : MonoBehaviour
{
    public float speed = 15;
    public float diSpeed = 20; 
    // 新增跳跃相关可调参数
    public float jumpForce = 7f;
    public LayerMask groundLayer;
         
    public Rigidbody rb;
    CharacterController characterController;

    Vector3 moveVector = Vector3.zero;
    // 新增地面状态标记
    private bool isGrounded;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void FixedUpdate()
    {
        // 脚下球形检测判断是否触碰地面
        isGrounded = Physics.CheckSphere(transform.position - new Vector3(0, 1f, 0), 0.3f, groundLayer);
        
        Vector3 forwardMove = transform.forward * speed * Time.fixedDeltaTime;
        Vector3 horizontalMove = transform.right * moveVector.x * diSpeed * Time.fixedDeltaTime;
        rb.MovePosition(rb.position + forwardMove + horizontalMove);
    }

    void Update()
    {
        // 单独获取左右按钮的按下状态
        bool leftPressed = CrossPlatformInputManager.GetButton("Left");
        bool rightPressed = CrossPlatformInputManager.GetButton("Right");

        // 同时按住左右按钮+处于地面时触发跳跃
        if (leftPressed && rightPressed && isGrounded)
        {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            moveVector.x = 0; // 跳跃时停止左右移动,不需要可删除该行
            return;
        }

        // 普通左右移动逻辑
        if (leftPressed)
        {
            moveVector.x = -1;
        }
        else if (rightPressed)
        {
            moveVector.x = 1;
        }
        else
        {
            moveVector.x = 0;
        }
    }
}

效果调整说明

  • 可直接在Inspector面板修改jumpForce数值调整跳跃高度
  • 地面检测的球形范围可以根据你的玩家模型尺寸调整,避免触发误判

原游戏界面按钮参考

展示UI按钮的游戏界面视图

内容的提问来源于stack exchange,提问作者Meer Azmaan Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:54:03