簡體   English   中英

在 Unity 2D 中拖動對象

[英]Drag object in Unity 2D

我已經為 Unity 2D 尋找了一個對象拖動腳本。 我在互聯網上找到了一個很好的方法,但它似乎只適用於 Unity 3D。 這對我不利,因為我正在制作 2D 游戲並且它不會以這種方式與“牆壁”發生碰撞。

我曾嘗試將其重寫為 2D,但我遇到了 Vectors 錯誤。

如果您能幫我將其重寫為 2D,我將非常高興。

這是在 3D 中工作的代碼:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider))]

public class Drag : MonoBehaviour {
    private Vector3 screenPoint;
    private Vector3 offset;

void OnMouseDown() {

    offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}

void OnMouseDrag()
{
    Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
    transform.position = curPosition;
}
}

對於那些使用此代碼有問題的人,我使用 ScreenPointToRay 使用代數光線投射(快速)來確定對象應該離相機多遠。 這適用於正交和透視相機

此外,對象可以使用Collider來拖動。 所以沒有必要使用[RequireComponent(typeof(BoxCollider2D))]

對我來說效果很好的最終代碼是:

using UnityEngine;
using System.Collections;

public class DragDrop : MonoBehaviour {
    // The plane the object is currently being dragged on
    private Plane dragPlane;

    // The difference between where the mouse is on the drag plane and 
    // where the origin of the object is on the drag plane
    private Vector3 offset;

    private Camera myMainCamera; 

    void Start()
    {
        myMainCamera = Camera.main; // Camera.main is expensive ; cache it here
    }

    void OnMouseDown()
    {
        dragPlane = new Plane(myMainCamera.transform.forward, transform.position); 
        Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition); 

        float planeDist;
        dragPlane.Raycast(camRay, out planeDist); 
        offset = transform.position - camRay.GetPoint(planeDist);
    }

    void OnMouseDrag()
    {   
        Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition); 

        float planeDist;
        dragPlane.Raycast(camRay, out planeDist);
        transform.position = camRay.GetPoint(planeDist) + offset;
    }
}

您快到了。

將代碼中的 RequireComponent 行更改為:

[RequireComponent(typeof(BoxCollider2D))]

並將 BoxCollider2D 組件添加到您添加腳本的對象。 我剛剛測試了它,它工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM