Drag and drop w Unity

W tym przykładzie będziemy przesuwać obiekty na scenie za pomocą OnMouse events.

Pamiętaj, że obiekty na których chcemy wywołać OnMouse eventy, muszą być elementami typu GUI albo mieć na sobie komponent Collider.

    Camera cam;
    Vector3 offset;
    void Awake()
    {
        cam = Camera.main;
    }

    private void OnMouseDown()
    {
        offset = transform.position - GetMousePos();
    }

    private void OnMouseDrag()
    {
        transform.position = GetMousePos() + offset;
    }

    Vector3 GetMousePos()
    {
        Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
        mousePos.z = 0f;
        return mousePos;
    }

Kursy GameDev Unity

Scroll to Top