两人移动触摸统一问题

时间:2020-05-14 07:03:02

标签: c# unity3d

我正在尝试创建一个具有两个可玩角色的平台游戏。当用户单击屏幕的右侧时,第一个字符跳,而单击屏幕的左侧时,其他字符跳。这是我到目前为止的代码:

public enum WhichPlayer
{
   Player1,
   Player2
};

public WhichPlayer whichPlayer;

void Update()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began && !IsDead)
    {
        Touch touch = Input.GetTouch(0);

        Vector2 position = touch.position;

        bool leftHalf = position.x <= Screen.width / 2;

        if (whichPlayer == WhichPlayer.Player1 && !leftHalf || whichPlayer == WhichPlayer.Player2 && leftHalf)
        {
            jump = true;
            animator.SetBool("Jump", true);                
        }
     }  else
          {
           jump = false;
           animator.SetBool("Jump", false)
          }

问题是,如果我在屏幕的右侧轻按5次,然后在左侧轻按1次,则右侧的播放器会跳转5次,然后左侧的播放器会跳转一次。有什么方法可以确保玩家在轻按任意一侧时就跳起来,而不是等待所有其他轻拍完成。我尝试使用GetMouseButtonDown(0),但在移动设备上无法正常工作。

1 个答案:

答案 0 :(得分:1)

我建议您测试此解决方案:(重构您的解决方案) 您可以分析所有触摸,然后选择每侧的触摸。

我想您为每个玩家都有一个脚本。

//Left player
void Update()
{
    var touched = Input.touches.Any(t => t.position.x <= Screen.width / 2 && t.phase == TouchPhase.Began);
    if (!isDead && touched)
    {
        //ok left player side 
    }


//Right player
void Update()
{
    var touched = Input.touches.Any(t => !(t.position.x <= Screen.width / 2) && t.phase == TouchPhase.Began);
    if (!isDead && touched)
    {
        //ok right player side 
    }

如果您希望所有玩家使用相同的脚本,则可以这样做:

void Update()
{

    if(!isDead)
    {
        var touchedL = Input.touches.Any(t => t.position.x <= Screen.width / 2 && t.phase == TouchPhase.Began);
        var touchedR = Input.touches.Any(t => !(t.position.x <= Screen.width / 2) && t.phase == TouchPhase.Began);
        if (whichPlayer == WhichPlayer.Player2 && touchedL )
       {
          //ok left player side tapped
       }    

        if (whichPlayer == WhichPlayer.Player1 && touchedR )
       {
          //ok right player side tapped
       }    
    }
}

我为您提供了没有linq的解决方案:

var touched = Input.touches.Any(t => t.position.x <= Screen.width / 2 && t.phase == TouchPhase.Began);

可以替换为:

    bool touched = false;
    foreach(var touch in Input.touches)
    {
       if(touch.position.x <= Screen.width / 2 && touch.phase == TouchPhase.Began)
       {
            touched = true;
            break;
       }
    }
    if (!isDead && touched)
    {
        //ok left player side 
    }

与其他样品相同。