Drag object in Unity 2D

人盡茶涼 提交于 2019-12-03 16:13:16

问题


I have looked for an object dragging script for Unity 2D. I have found a good method on the internet, but it seems it's just working in Unity 3D. It's not good for me as I'm making a 2D game and it's not colliding with the "walls" in that way.

I have tried to rewrite it to 2D, but I have crashed into errors, with Vectors.

I would be very glad if you could help me rewrite it to 2D.

Here's the code what's working in 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;
}
}

回答1:


You're almost there.

Change the RequireComponent line in your code to:

[RequireComponent(typeof(BoxCollider2D))]

And add a BoxCollider2D component to the object to which you add your script. I just tested it and it works fine.




回答2:


For the ones who have problem using this code, I removed screenPoint and replaced it with 10.0f (which is the distance of the object from the camera). You can use whatever float you need to. Now it works. Also the object need a BoxCollider or CircleCollider to able to be dragged around. So there's no point using [RequireComponent(typeof(BoxCollider2D))].

The final code which worked fine for me is:

using UnityEngine;
using System.Collections;


public class DragDrop : MonoBehaviour {

    private Vector3 offset;

    void OnMouseDown()
    {

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

    void OnMouseDrag()
    {
        Vector3 newPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f);
        transform.position = Camera.main.ScreenToWorldPoint(newPosition) + offset;
    }
}


来源:https://stackoverflow.com/questions/23152525/drag-object-in-unity-2d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!