Drag object in Unity 2D

后端 未结 2 1712

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

相关标签:
2条回答
  • 2021-02-07 12:22

    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.

    0 讨论(0)
  • 2021-02-07 12:39

    For the ones who have problem using this code, I used ScreenPointToRay to use algebraic raycasts (fast) to determine how far the object should be placed from the camera. This works in both orthographic and perspective cameras

    Also, the object could use Collider 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 {
        // 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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题