Question by
DaPizzaKing · Apr 29 at 09:37 PM ·
ui
My UI Element is not following the mouse accurately, and I'm a bit lost on what I'm missing
I have been looking for a solution for a while and I've managed to have my UI element follow the mouse on click, but it follows at a distance. I'm not sure how to fix the problem :/ Here is my code:
private void Update()
{
Vector3 mouse = Camera.main.ScreenToViewportPoint(Input.mousePosition);
mouse = new Vector3(mouse.x * scaler.referenceResolution.x, mouse.y * scaler.referenceResolution.y, mouse.z);
if (dragging)
{
itemSlotRectTransform.anchoredPosition = new Vector3(mouse.x, mouse.y, mouse.z);
}
}
Here is the result: Video Demonstration
Comment
Best Answer
Answer by DaPizzaKing · Apr 29 at 11:16 PM
I found a solution after taking a break for a little while. For whatever reason if you take the x and y vectors and subtract the width and height of the screen divided by 1.5, it centers the transform of the object on the mouse.
Completed code for those who might stumble on this question as I could not find a solution online:
private void Update()
{
Vector2 mousePosition = Camera.main.ScreenToViewportPoint(Input.mousePosition);
mousePosition = new Vector2((mouse.x * scaler.referenceResolution.x) - (Screen.width / 1.5f),( mouse.y * scaler.referenceResolution.y) - (Screen.height / 1.5f));
if (dragging)
{
itemSlotRectTransform.anchoredPosition = mouse;
}
}
Your answer
