Question by
Bloodmorph · Jul 06, 2020 at 09:18 AM ·
uimouseposition
Mouse Position in UI elements seems to be way off, no idea why.
Hello,
So I have a scaling canvas based on screen size that scales properly. However, I seem to be having issues with mouse position and showing elements based on mouse position. Here is my code:
public void OnPointerEnter(PointerEventData eventData)
{
StartGame gh = GameObject.FindGameObjectWithTag("GameHandler").GetComponent<StartGame>();
GameObject obj = gh.EquipmentToolTip;
RectTransform cnvs = GameObject.FindGameObjectWithTag("GameCanvas").GetComponent<RectTransform>();
obj.SetActive(true);
//get the tooltip position with offset
Vector2 offSet = new Vector2(cnvs.sizeDelta.x / 2f, cnvs.sizeDelta.y / 2f);
Vector2 viewPort = Camera.main.WorldToViewportPoint(Input.mousePosition);
Vector2 position = new Vector2(cnvs.sizeDelta.x * viewPort.x, cnvs.sizeDelta.y * viewPort.y);
obj.transform.localPosition = Vector2.Scale(position-offSet, cnvs.transform.localScale);
}
Here is the image where my tool-tip is going crazy: http://prntscr.com/tcm5ob
Comment
Answer by Bloodmorph · Jul 06, 2020 at 09:39 AM
I finally figured it out, new code:
public void OnPointerEnter(PointerEventData eventData)
{
StartGame gh = GameObject.FindGameObjectWithTag("GameHandler").GetComponent<StartGame>();
GameObject obj = gh.EquipmentToolTip;
RectTransform rect = obj.GetComponent<RectTransform>();
RectTransform cnvs = GameObject.FindGameObjectWithTag("GameCanvas").GetComponent<RectTransform>();
obj.SetActive(true);
//get the tooltip position with offset
Vector2 offSet = new Vector2(cnvs.sizeDelta.x / 2f, cnvs.sizeDelta.y / 2f);
Vector2 viewPort = Camera.main.ScreenToViewportPoint(Input.mousePosition);
Vector2 position = new Vector2(cnvs.sizeDelta.x * viewPort.x - rect.rect.width / 2, cnvs.sizeDelta.y * viewPort.y + rect.rect.height / 2 + 10f);
obj.transform.localPosition = position-offSet;
}
Your answer
Follow this Question
Related Questions
How to Show UI Menu on mouse clicked position on a cube or 3d object ? 1 Answer
All UI elements break when setting resolution through script. [please help] 0 Answers
Instantiating UI element at mouse position on click 1 Answer
UI elements flickering 1 Answer
TextMeshpro arabic fonts stop displaying more than one word(last one) 1 Answer