UNITY 2d 将 Input.GetAxis("Horizontal") 转换为具有宽度控制的触摸拖动

UNITY 2d Convert Input.GetAxis("Horizontal") to Touch Drag with Width Control

public float speed = 15f;
public float mapWidth = 5f;
private Rigidbody2D rb;

private void FixedUpdate()
 {
     float x = Input.GetAxis("Horizontal") * Time.fixedDeltaTime * speed;
     Vector2 newPosition = rb.position + Vector2.right * x;
     newPosition.x = Mathf.Clamp(newPosition.x, -mapWidth, mapWidth);
     rb.MovePosition(newPosition);
 }

如何更改 FixedUpdate() 中的代码 MOBILE 的触摸控制。所以当我拖动对象(我的播放器)时,它只会沿着水平轴移动但是!它不会超出相机的边界,但也可以像这段代码中那样控制宽度。如果 mapWidth 中的数字很高,它只会左右移动一点。

问题的答案显示了如何使用 WorldToViewportPoint 在屏幕上移动对象和应用边界。

您可以通过在 Input.GetAxis("Horizontal") 下添加 Input.touches.deltaPosition.xInput.touches.deltaPosition.y 来为其添加触摸支持。

添加了边界和输入支持后,它应该如下所示:

public float speed = 100;
public Rigidbody2D rb;

public void Update()
{
    float h = Input.GetAxis("Horizontal");
    float v = Input.GetAxis("Vertical");

    //Add touch support
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        Touch touch = Input.touches[0];
        h = touch.deltaPosition.x;
        v = touch.deltaPosition.y;
    }

    //Move only if we actually pressed something
    if ((h > 0 || v > 0) || (h < 0 || v < 0))
    {
        Vector3 tempVect = new Vector3(h, v, 0);
        tempVect = tempVect.normalized * speed * Time.deltaTime;

        //rb.MovePosition(rb.transform.position + tempVect);

        Vector3 newPos = rb.transform.position + tempVect;
        checkBoundary(newPos);
    }
}

void checkBoundary(Vector3 newPos)
{
    //Convert to camera view point
    Vector3 camViewPoint = Camera.main.WorldToViewportPoint(newPos);

    //Apply limit
    camViewPoint.x = Mathf.Clamp(camViewPoint.x, 0.04f, 0.96f);
    camViewPoint.y = Mathf.Clamp(camViewPoint.y, 0.07f, 0.93f);

    //Convert to world point then apply result to the target object
    Vector3 finalPos = Camera.main.ViewportToWorldPoint(camViewPoint);
    rb.MovePosition(finalPos);
}