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

Unity中如何实现仅向上滑动(含左上、右上)时才调用AddForce方法

实现方案

这个需求完全可以实现,核心逻辑是判断滑动的Y轴位移方向:移动端触摸坐标的Y轴默认从屏幕底部向上递增,只要滑动结束位置的Y值大于起始位置的Y值,就属于向上滑动(包含左上、右上的斜向滑动),只有满足这个条件时才执行施加力的逻辑即可。

具体修改步骤

你只需要在原代码的滑动结束逻辑里新增方向判断即可,还可以额外加最小滑动距离阈值避免误触,修改后的完整代码如下:

public class SwipeScript : MonoBehaviour
{
    Vector2 startPos, endPos, direction;
    float touchTimeStart, touchTimeFinish, timeInterval;
    [Range(0.05f, 1f)]
    public float throwForce = 0.5f;
    // 新增最小滑动距离,避免点击误触发,单位是像素
    public float minSwipeDistance = 50f;


    void Update()
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
            touchTimeStart = Time.time;
            startPos = Input.GetTouch(0).position;
        }
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
        {
            touchTimeFinish = Time.time;
            timeInterval = touchTimeFinish - touchTimeStart;
            endPos = Input.GetTouch(0).position;
            direction = startPos - endPos;

            // 新增判断:只有向上滑动才触发
            float yOffset = endPos.y - startPos.y;
            float swipeTotalDistance = Vector2.Distance(startPos, endPos);
            if (yOffset > 0 && swipeTotalDistance >= minSwipeDistance)
            {
                GetComponent<Rigidbody2D>().AddForce(-direction / timeInterval * throwForce);
            }
        }
    }
}

修改说明

  • 新增了minSwipeDistance参数,你可以在Inspector面板自行调整数值,过滤掉点击、轻微滑动的误操作
  • 核心判断yOffset > 0就保证了只有滑动结束位置比起始位置更靠上时才会触发逻辑,斜向滑动只要Y轴位移是正的,不管X轴是向左还是向右都会生效,符合你要的左上、右上都支持的需求
  • 顺便修正了原代码里throwForse的拼写错误,如果你不想改原有参数名可以保留原来的拼写

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 22:51:03