- Home /
Trying to program a custom slider
I'm programming a game menu for a smartphone game. I'm trying to program a custom slider for that purpose. The idea is that the selector is stationary and instead the user moves the bar around. (Which snaps to the closest position, once deselected)
My problem is a rather basic and stupid one. How do I actually make a rect transform move vertically or horizontally exactly as far as I'm moving the pointer? (It would be rather helpful if it worked both for mouse and touch)
Answer by SlowCircuit · Jan 25, 2019 at 08:40 AM
Input.mousePosition is a vector that can tell you the mouse position in pixel coordinates.
Option 1: Save it's position each frame to a variable. Before updating it, check the difference between it's current position and it's position last frame. Use this value to determine how far it's moved and move the slider an equivalent amount. This will require some fiddling to get feeling right.
Option 2 (Better): Make so that when you press a certain key, a Debug.Log is sent containing the current mouse position. Do this at the left, top, right and bottom of the slider. Record the values as their min-max ranges both horizontally and vertically. Then when the player is dragging the slider, get the mouse position relative to that range and set the slider's position to that position relative to it's own positional range.
Your answer
![](https://koobas.hobune.stream/wayback/20220612190409im_/https://answers.unity.com/themes/thub/images/avi.jpg)