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

Unity 2D移动端角色按钮移动方向交替卡顿异常求助

问题分析与解决方案

核心问题

你的代码未处理触摸事件丢失和方向状态互斥的场景:

  • 移动端触摸时,若手指从按钮上滑开而非直接抬起,PointerUp事件可能无法触发,导致moveleft或moveRight一直保持true,角色会锁定在该方向移动。
  • 后续触发另一方向按钮事件时,原锁定状态未被重置,直到某次操作意外触发PointerUp,才会出现方向卡顿反转的现象。

修复代码

修改按钮事件方法,增加状态互斥和触摸离开的容错处理:

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

public class CharMovement : MonoBehaviour
{  
    private float HorizontalMove;
    private float speed = 6f;
    private bool moveleft;
    private bool moveRight; 
    private Rigidbody2D rb;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        moveleft = false;
        moveRight = false;
    }

    private void Update()
    { 
        movement();
    }

    public void PointerLeftDown(){
        moveleft = true;
        moveRight = false; // 按下左按钮时强制关闭右方向状态
    }

    public void PointerLeftUp(){
        moveleft = false;
    }

    // 新增:手指离开左按钮区域时重置状态
    public void PointerLeftExit(){
        moveleft = false;
    }

    public void PointerRightDown(){
        moveRight = true;
        moveleft = false; // 按下右按钮时强制关闭左方向状态
    }

    public void PointerRightUp(){
        moveRight = false;
    }

    // 新增:手指离开右按钮区域时重置状态
    public void PointerRightExit(){
        moveRight = false;
    }

    private void movement(){
        if(moveleft){
            HorizontalMove = -speed;
        }
        else if (moveRight){
            HorizontalMove = speed;
        }
        else {
            HorizontalMove = 0f;
        }
    }

    private void FixedUpdate() {
        rb.velocity = new Vector2(HorizontalMove, rb.velocity.y);
    }
}

额外设置

  1. 给左右按钮添加EventTrigger组件,绑定PointerExit事件到对应的方法(PointerLeftExit/PointerRightExit),确保手指滑开按钮时也能重置方向状态。
  2. 检查Rigidbody2D设置:勾选Freeze Rotation Z避免角色旋转干扰移动;确认Gravity Scale数值合理,排除物理层面的异常卡顿。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:55:07