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

Unity 3D:如何在玩家停止弹跳时重置蹦床的弹跳计数器

问题分析与解决办法

核心问题

你把重置jumpCount的逻辑放在了OnTriggerEnter方法里,但这个方法只有当碰撞体进入蹦床触发器时才会执行。玩家落地时并没有接触蹦床的触发器,所以那个else if (playerFP.groundCheck == true)分支永远不会被触发。

解决方法

以下是两种简单可行的实现方式:

方法1:在Update中检测玩家落地状态

把重置逻辑移到Update方法里,这样每一帧都会检查玩家是否落地,一旦落地就重置计数:

public class Trampoline : MonoBehaviour
{
    public PlayerMovement1stPerson playerFP;
    [SerializeField] int jumpCount = 0;

    private void Update()
    {
        // 当玩家落地时重置弹跳计数
        if (playerFP.groundCheck == true)
        {
            jumpCount = 0;
        }
    }

    private void OnTriggerEnter(Collider collision) 
    { 
        // 先过滤非玩家的碰撞,简化后续逻辑
        if (collision.gameObject.tag != "Player") return;

        if (jumpCount == 0)
        {
            Debug.Log("Bounce 1 activated");
            playerFP.velocity.y = 5;
            jumpCount ++;
        }
        else if (jumpCount == 1)
        {
            playerFP.velocity.y = 10;
            jumpCount ++;
        }
        else if (jumpCount == 2)
        {
            playerFP.velocity.y = 15;
            jumpCount ++;
        }
        else if (jumpCount >= 3)
        {
            Debug.Log("Max Bounce");
            playerFP.velocity.y = 15;
        }
    }
}

这个方法修改量小,逻辑直观,适合新手快速解决问题。

方法2:在玩家脚本中主动通知蹦床重置

如果你的PlayerMovement1stPerson脚本里有处理落地的逻辑,可以在那里直接调用蹦床的重置方法,避免不必要的帧检测:

  1. 在蹦床脚本中添加公开的重置方法:
public void ResetJumpCount()
{
    jumpCount = 0;
}
  1. 在玩家脚本的落地逻辑中调用该方法(示例):
// 玩家脚本中的示例逻辑
private bool wasGroundedLastFrame = false;

private void Update()
{
    // 你的地面检测逻辑...
    if (groundCheck == true && !wasGroundedLastFrame)
    {
        // 找到场景中的蹦床(或提前在Inspector中引用)
        Trampoline trampoline = FindObjectOfType<Trampoline>();
        if (trampoline != null)
        {
            trampoline.ResetJumpCount();
        }
        wasGroundedLastFrame = true;
    }
    else if (groundCheck == false)
    {
        wasGroundedLastFrame = false;
    }
}

这个方法更符合面向对象设计,性能更高效。

额外优化建议

可以把弹跳高度做成可配置数组,替代多个if分支,让代码更简洁易维护:

[SerializeField] float[] bounceHeights = new float[]{5,10,15};
[SerializeField] int maxBounceIndex = 2;

// 在OnTriggerEnter中替换原有的if逻辑
int currentIndex = Mathf.Min(jumpCount, maxBounceIndex);
playerFP.velocity.y = bounceHeights[currentIndex];
if (jumpCount < maxBounceIndex) jumpCount++;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:24:16