簡體   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