- Home /
Shift gear from 2 sliders?
Greetings,
How would I go about creating something like a shift gear from sliders? I need them to go up, down, left or right, and center. They can clamp to the max values. Check picture for what I mean.
shift.jpg
(7.2 kB)
Comment
Answer by hu90 · May 19, 2015 at 09:39 PM
Here's a hack to achieve what you want:
Create a new Slider
Drop the script below on the GameObject named Handle (not Handle Slide Area)
Duplicate the GameObject named Background and rotate it 90° just like you probably did in the picture (just for the looks).
You may want to disable the Fill Area (also for the looks)
???
Profit
ShiftGearHack.cs :
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class ShiftGearHack : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
Slider slider;
public void OnBeginDrag(PointerEventData eventData)
{
var canvas = FindInParents<Canvas>(gameObject);
if (canvas == null)
return;
SetDraggedPosition(eventData);
slider = FindInParents<Slider>(gameObject);
}
public void OnDrag(PointerEventData data)
{
slider.OnDrag (data);
SetDraggedPosition(data);
}
private void SetDraggedPosition(PointerEventData data)
{
Vector2 globalMousePos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent as RectTransform, data.position, data.pressEventCamera, out globalMousePos))
{
if (transform.localPosition.sqrMagnitude < 5f*5f) {
slider.value = (slider.minValue + slider.maxValue) * 0.5f;
float horizDelta = Mathf.Abs (globalMousePos.x - transform.localPosition.x);
float vertDelta = Mathf.Abs (globalMousePos.y - transform.localPosition.y);
if (horizDelta > 5f && horizDelta > vertDelta) {
slider.SetDirection (Slider.Direction.LeftToRight, true);
}
else if (vertDelta > 5f && vertDelta > horizDelta) {
slider.SetDirection (Slider.Direction.TopToBottom, true);
}
}
}
}
public void OnEndDrag(PointerEventData eventData)
{
}
static public T FindInParents<T>(GameObject go) where T : Component
{
if (go == null) return null;
var comp = go.GetComponent<T>();
if (comp != null)
return comp;
Transform t = go.transform.parent;
while (t != null && comp == null)
{
comp = t.gameObject.GetComponent<T>();
t = t.parent;
}
return comp;
}
}