Dragging a circle with mouse input into worldspace UI - Getting the correct angles
Howdy folks, I'm struggling with what should be a pretty simple math problem.
I'm essentially trying to create a system to drag a handle in a radial UI element that's positioned in world space. Hopefully, you can kinda see what I mean in this gif:
So, it's a bit hard to see in the gif, but the problem seems to be that every frame the angle flip flops between two angles on the circle. So, somewhere in the code the math is almost working, because I'm getting a passable result minus the flip-flopping in the positions. I'm thinking that there's maybe an extraneous calculation happening here every other frame causing the rotation to jump back somehow. But I can't find anything in the code that would cause that, so I'm kinda at a loss.
I'm using eulerangles here instead of quaternions cause they're easier to understand conceptually.
This is the code that calculates the angle I'm looking for based on the mouse input. I have a bad habit of not marking up code until I need to show it to someone, so it might be a bit confusing. If you have any questions please let me know.
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class RadialSlider: MonoBehaviour
{
//angle of dragged mouse drag input
public float angle;
//player controlled camera input
public CameraMouseInput mouseInput;
//ui element we're outputting angles to
public DegreeIndicator dI;
//checking if lclick is held down
public ClickHeld cH;
Camera mainCam;
// mainloop
public void Update()
{
mainCam = Camera.main;
var input = FindObjectOfType<StandaloneInputModule>();
if(input != null ) //if input exists
{
if (cH.held) //if player is holding down lclick
{
mouseInput.CanOrbit = false;
Vector2 localPos; // Mouse position
//Suspected problem with this line in particular
RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RectTransform>(), Input.mousePosition, mainCam, out localPos);
//localPos = Input.mousePosition;
// local pos is the mouse position.
angle = (Mathf.Atan2(-localPos.y, localPos.x) * 180f / Mathf.PI + 180f);
//assigning angle to UI indicator
dI.desiredAngle = (int)(angle);
//currentValue = angle;
//Debug.Log(localPos+" : "+angle);
}
else
mouseInput.CanOrbit = true;
}
else
UnityEngine.Debug.LogWarning( "Could not find GraphicRaycaster and/or StandaloneInputModule" );
}
}
I've adapted the code from this wonderful person's work. Without them I probably wouldn't have gotten so far.
Thanks so much for any help! I appreciate all that you amazing people do for this community :)
Your answer

Follow this Question
Related Questions
Math: How to rotate a wheel by drag&drop (Canvas, 2D)? 0 Answers
Rotating a game object to match the surface of a 2D Line 0 Answers
How to detect when an object is within an arc? 2 Answers
How to tell if a RectTransform is within the visible area of a ScrollRect 1 Answer
Image fillAmount from 0.9 to 1 1 Answer