繁体   English   中英

UNITY 2d使用宽度控制将Input.GetAxis(“ Horizo​​ntal”)转换为触摸拖动

[英]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);
 }

MOBILE的触摸式控制中,如何更改FixedUpdate()中的代码。 因此,当我拖动对象(我的播放器)时,它将仅沿水平轴移动,但! 它不会超出摄像机的范围,而且不会像此代码中那样可控制宽度。 如果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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM