【问题标题】:Smooth touch movement on axis only while going up?仅在上升时在轴上平滑触摸运动?
【发布时间】:2018-12-27 18:56:49
【问题描述】:

我是 Unity 和 c# 的新手。我正在为手机创建一个项目。我只想在 Jet 上升时通过左右触摸来移动 jet Axis 位置

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

                 switch (touch.phase)
                 {
                    case TouchPhase.Began:
          if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
            {
                    //side to side movement
                     if (touch.position.x < Screen.width / 2)
                        rb.velocity = new Vector2(- 2f, transform.position.y);
                     if (touch.position.x > Screen.width / 2)
                        rb.velocity = new Vector2(+ 2f, transform.position.y);
                }
                   break;
                  case TouchPhase.Ended:
                      rb.velocity = new Vector2(0f, 0f);
                      break;
          }

Jet 具有 Addforce,因此当我左右触摸时,Jet 会减慢速度。

喷射代码:

switch (JetOn)
        {
            case true:
             StartCoroutine(BurnFuel());
             rb.AddForce(new Vector2(0f, JumpForce), ForceMode2D.Force);
                break;
            case false:
                rb.AddForce(new Vector2(0f, 0f), ForceMode2D.Force);
                break;
       }

【问题讨论】:

    标签: c# unity3d touch game-physics


    【解决方案1】:

    您不应混合使用AddForce 和手动分配给velocity。直接分配给velocity 会使AddForce 行为不可预测,并且通常会导致它永远无法工作。

    选择一个或另一个,并将其用于制作该帧所需的每次速度变化。

    这是您的代码示例,仅分配给velocity

    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
    
        switch (touch.phase)
        {
            case TouchPhase.Began:
                if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
                {
                    //side to side movement
                    if (touch.position.x < Screen.width / 2)
                        // I think you mean rb.velocity.y here instead of transform.position.y 
                        rb.velocity = new Vector2(- 2f, rb.velocity.y);
                    if (touch.position.x > Screen.width / 2)
                        rb.velocity = new Vector2(+ 2f, rb.velocity.y);
                }
                break;
            case TouchPhase.Ended:
                rb.velocity = new Vector2(0f, 0f);
                break;
        }
    }
    
    ...
    
    switch (JetOn)
    {
        case true:
            StartCoroutine(BurnFuel());
            rb.velocity += new Vector2(0f, JumpForce) / rb.mass;
            break;
        case false:
            // unnecessary but included for example purposes
            // rb.velocity += new Vector2(0f, 0f) / rb.mass;
            break;
    }
    

    【讨论】:

    • 我还在 rb.velocity = new Vector2(0f, 0f); 的 Y 位置添加了 rb.velocity
    猜你喜欢
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多