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

Unity数学游戏UI滑动动画自动触发问题求助

Unity数学游戏滑动动画自动触发问题求助

我正在用Unity做一款数学游戏,本来设定是用户答对题目之后,才能左右滑动UI。但测试的时候发现,滑动动画会自己触发,根本不用用户动手——明明已经设置了X轴滑动距离超过50才触发动画的。试了好几种调试方法都找不到问题出在哪,把相关代码和Animator状态机的截图说明放下面,麻烦帮忙看看问题到底在哪。

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

public class MathGameController : MonoBehaviour
{
    public GameObject answer1, answer2; // 答题UI元素
    public Animator answer1Animator, answer2Animator; // 答题UI的动画控制器

    private Vector2 startTouchPosition, endTouchPosition;
    private bool isSwiping = false;
    private float swipeThreshold = 50f; // 触发动画的最小滑动距离

    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);

            switch (touch.phase)
            {
                case TouchPhase.Began:
                    startTouchPosition = touch.position;
                    isSwiping = true;
                    break;

                case TouchPhase.Ended:
                    endTouchPosition = touch.position;
                    if (isSwiping)
                    {
                        FinishSwipe();
                        isSwiping = false;
                    }
                    break;
            }
        }
    }

    void FinishSwipe()
    {
        Vector2 swipeDirection = endTouchPosition - startTouchPosition;

        if (Mathf.Abs(swipeDirection.x) > swipeThreshold)
        {
            if (swipeDirection.x > 0)
            {
                // 检测到向右滑动
                answer1Animator.SetTrigger("swipeRight");
                answer2Animator.SetTrigger("swipeRight");
            }
            else
            {
                // 检测到向左滑动
                answer1Animator.SetTrigger("swipeLeft");
                answer2Animator.SetTrigger("swipeLeft");
            }
        }
    }
}

补充说明:动画本身功能是正常的,但滑动逻辑有问题。已经设置了Idle初始状态,过渡条件也和代码里的触发器关联上了,但滑动动画每次都会自动触发,不是等用户输入才触发。

Animator状态机截图说明

  • 截图1:Idle为初始状态,分别设置了指向swipeLeft和swipeRight动画状态的过渡,过渡条件对应同名的触发器参数
  • 截图2:展示了动画状态的具体配置细节,包括过渡的触发条件和动画片段的设置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 19:03:18