UNITY 2d将Input.GetAxis(“Horizo​​ntal”)转换为Touch with Width Control

时间:2018-04-09 06:22:35

标签: c# unity3d touch 2d

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中的数字很高,它只会左右移动。

1 个答案:

答案 0 :(得分:0)

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

您可以在Input.touches.deltaPosition.x下添加Input.touches.deltaPosition.yInput.GetAxis("Horizontal"),为其添加触控支持。

添加了边界和输入支持,下面是它应该是这样的:

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);
}