Drag object in Unity 2D

半世苍凉 提交于 2019-12-03 05:28:47

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.

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