简体   繁体   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);
 }

How do you change the code in FixedUpdate() be in touch control for MOBILE . MOBILE的触摸式控制中,如何更改FixedUpdate()中的代码。 so when I drag the object(my player) it will follow in the Horizontal axis only BUT! 因此,当我拖动对象(我的播放器)时,它将仅沿水平轴移动,但! it will not go off the boundaries of the camera but also controllable width like in this code. 它不会超出摄像机的范围,而且不会像此代码中那样可控制宽度。 If the number is high in mapWidth it will only move a little left and right. 如果mapWidth中的数字较高,则只会向左和向右移动一点。

The answer from this question shows how to move object and apply boundary on the screen with WorldToViewportPoint . 这个问题的答案显示了如何使用WorldToViewportPoint在屏幕上移动对象和应用边界。

You can add touch support to it by adding Input.touches.deltaPosition.x and Input.touches.deltaPosition.y under the Input.GetAxis("Horizontal") . 您可以通过在Input.GetAxis("Horizontal")下添加Input.touches.deltaPosition.xInput.touches.deltaPosition.y来为其添加触摸支持。

With both boundary and Input support added, below is what it should look like: 添加边界和输入支持后,其外观应如下所示:

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