- Home /
Drawing a (debug) line between anchored UI element and mouse?
I'm making a game mechanic that moves UI elements based on the mouse position. Simply but, I want a button to be harder to click on because it moves away from the mouse. It is tethered to it's original position.
Because I haven't really done any UI manipulation before I first started out with a really simple piece of code that draws two debug lines between the mouse and the button. One to the current position of the button (center) and the other to the tether point. However when I ran it I realized that it draws a line to the absolute world position and not to the button itself, which is anchored and relative to the canvas.
This is the code that I have:
private Vector3 tether;
private RectTransform rt;
private void Start() {
rt = GetComponent<RectTransform>();
tether = rt.localPosition;
}
private void Update() {
Vector3 mPos = Input.mousePosition;
Debug.DrawLine(mPos, tether, Color.blue);
Debug.DrawLine(mPos, rt.localPosition, Color.red);
}
One solution to this problem would be to write a function that uses that anchor of the RectTransform to calculate the position of the buttons relative to the canvas. However, this feels like a lot of manual work for a seemingly common operation. My question is if there is a more sophisticated or built-in way to deal with this.