Created
August 30, 2020 18:46
-
-
Save ziriax/ffe861862e21a4d35040394300854c85 to your computer and use it in GitHub Desktop.
Unity3D mouse to canvas position (dragging item on canvas)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class MouseDrag : MonoBehaviour | |
{ | |
void Update() | |
{ | |
if (Input.GetMouseButton(0)) | |
{ | |
var canvas = transform.root.GetComponent<Canvas>(); | |
var canvasRect = canvas.GetComponent<RectTransform>(); | |
if (RectTransformUtility.ScreenPointToLocalPointInRectangle( | |
canvasRect, | |
Input.mousePosition, | |
canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : canvas.worldCamera, | |
out Vector2 mousePosInCanvasSpace)) | |
{ | |
var selfRect = GetComponent<RectTransform>(); | |
selfRect.localPosition = mousePosInCanvasSpace; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment