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

Unity PC/移动端运动脚本如何限制玩家触控时最大跳跃次数

问题根因

  • 移动端原逻辑只要检测到触摸存在就每帧给Y轴赋值jumpForce,因此长按会持续给向上速度导致无限升高
  • 无跳跃次数限制逻辑,也没有落地判定重置跳跃次数的机制
  • 额外问题:原代码在未触发跳跃时会重复执行两次AddForce逻辑,导致移动速度不符合预期

完整修改后代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerBehaviour : MonoBehaviour
{
    /// <summary>
    /// 刚体组件引用
    /// </summary>
    private Rigidbody rb;

    [Tooltip("横向移动速度")]
    public float dodgeSpeed;
    [Tooltip("跳跃力度")]
    public float jumpForce;
    [Tooltip("向前移动速度")]
    public float rollSpeed;
    [Tooltip("最大跳跃次数,填1为单次跳,填2为二段跳")]
    public int maxJumpCount = 2;
    [Tooltip("地面检测点,拖到玩家脚底位置")]
    public Transform groundCheck;
    [Tooltip("地面对应的图层")]
    public LayerMask groundLayer;
    [Tooltip("地面检测半径")]
    public float groundCheckRadius = 0.2f;

    private float dirX;
    // 当前已使用的跳跃次数
    private int currentJumpCount;
    // 检测是否处于地面
    private bool isGrounded;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        // 初始化跳跃次数
        currentJumpCount = maxJumpCount;
    }

    // 输入检测放在Update执行
    void Update()
    {
        dirX = Input.acceleration.x * dodgeSpeed;
        var horizontalSpeed = Input.GetAxis("Horizontal") * dodgeSpeed;
        float finalHorizontal = horizontalSpeed + dirX;

        // 先检测是否落地,重置跳跃次数
        isGrounded = Physics.CheckSphere(groundCheck.position, groundCheckRadius, groundLayer);
        if (isGrounded && rb.velocity.y <= 0)
        {
            currentJumpCount = maxJumpCount;
        }

        bool jumpTriggered = false;
        // PC端空格跳跃检测,只检测按下的第一帧
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jumpTriggered = true;
        }
        // 移动端触摸跳跃检测,只检测触摸开始的第一帧
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
            jumpTriggered = true;
        }

        // 触发跳跃逻辑
        if (jumpTriggered && currentJumpCount > 0)
        {
            rb.velocity = new Vector3(finalHorizontal, jumpForce, rollSpeed);
            currentJumpCount--;
        }
        // 未触发跳跃时正常施加移动力
        else
        {
            rb.AddForce(finalHorizontal, 0, rollSpeed);
        }
    }
}

使用说明

  1. 打开Unity Inspector面板,给地面对象设置一个单独的图层,然后在groundLayer参数里选中这个图层
  2. 在玩家对象下新建一个空物体作为groundCheck,拖到玩家脚底位置,调整groundCheckRadius直到可以正常检测到地面
  3. 调整maxJumpCount参数即可切换单次/二段跳:填1是最多跳1次,填2是最多跳2次

内容的提问来源于stack exchange,提问作者andr3y38

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:24:00