繁体   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