- Home /
Issue with implementing my own slider script.
Hi, I have made my own slider script using the following code. public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
public static GameObject itemBeingDragged;
Vector3 startPosition;
private RectTransform rectTransform;
void Awake(){
rectTransform = GetComponent<RectTransform> ();
}
public void OnBeginDrag(PointerEventData eventData){
itemBeingDragged = gameObject;
startPosition = rectTransform.localPosition;
GetComponent<CanvasGroup> ().blocksRaycasts = false;
}
public void OnDrag(PointerEventData eventData){
float clamp = Mathf.Clamp (Input.mousePosition.y, -100f, 100f);
rectTransform.localPosition = new Vector3 (startPosition.x, clamp, startPosition.z);
}
public void OnEndDrag(PointerEventData eventData){
itemBeingDragged = null;
rectTransform.localPosition = startPosition;
GetComponent<CanvasGroup>().blocksRaycasts = true;
}
}
However, when I dragged the slider down using localPosition, the slider is slower than my mouse; for example, my mouse and the slider start at the same position but when I dragged it down, my mouse is below the slider. So the question is how can I fix this? Any suggestion would be appreciated. Thanks!
PS. the reason I'm not using Unity Slider UI is that I want to trigger the event OnEndDrag and when I search, it seem to have some problems about responsive or something.
Answer by jmgek · May 24, 2017 at 08:20 PM
"The current mouse position in pixel coordinates." https://docs.unity3d.com/ScriptReference/Input-mousePosition.html
If your screen was 200px then the slider would stay in the same position as the mouse. You need to calculate the screen size if you want to do it this way.
The bottom-left of the screen or window is at (0, 0). The top-right of the screen or window is at (Screen.width, Screen.height).
So calculate the screen height and use that to drive the Sliders height.
Or use Camera.ScreenToWorldPoint: https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html