- Home /
Coincide Input.mousePosition with UI element position to be on same coordinate system
I am working on my own dragging slider for audio controls. I am currently having the issue of getting the Input.mousePosition when I detect dragging and the rect transform of the detecting UI element to be on the same 'scale' so to speak. I have tried many solutions such as using Transform.transformPoint which doesnt do anything to value, Camera.main.WorldToScreenPosition and just using the position values all together.
It just seems I am unable to get the who coordinates to be on the same scale. It all works when the RangeSlider is the only thing on the Canvas but when it is in a more complex and expected environment, the scales don't match and I can't figure out the proper conversion.
Here is the code I am using at the moment (which does not work).
public class RangeSlider: MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
private RectTransform _rectTransform;
private RangeFill _rangeFill;
private Text _text;
private float _pointerX;
private bool _dragging = false;
private void Awake()
{
_rectTransform = GetComponent<RectTransform>();
_rangeFill = GetComponentInChildren<RangeFill>();
_text = GetComponentInChildren<Text>();
}
private void Update()
{
if (!_dragging) return;
_pointerX = Input.mousePosition.x;
UpdateSlider();
}
public void OnPointerDown(PointerEventData eventData)
{
_dragging = true;
}
public void OnPointerUp(PointerEventData eventData)
{
_dragging = false;
}
private void UpdateSlider()
{
var minX = Camera.main.WorldToScreenPoint(_rectTransform.position).x;
var xProg = _pointerX - minX;
var percent = Mathf.Clamp(xProg / _rectTransform.rect.width, 0, 1);
// Sets the X scale to whatever 0-1 percent value
_rangeFill.ChangeFillPercent(percent);
_text.text = $"{Mathf.Clamp((int)(percent * 100), 0, 100)}";
}
}
Your answer
Follow this Question
Related Questions
Locking Object To Screen 1 Answer
Scaling a menu bar 1 Answer
Change position and scale of objects according to mobile screen size 0 Answers
Scaling game to fit screen size 2 Answers
Worldspace UI in wrong position/scale after scene change 0 Answers