- Home /
Rotate dial to set values by dragging on the gameobject
Hi, I'm setting up a script to attach to a dial gameObject on a control panel. When the user clicks and drags over the dial, the dial rotates and snaps into predetermined positions.
Once the script is attached to a dial, I set the number of stop positions then enter the angles for each of those stops in a list.
The script I have is working fine, but I'm just wondering how to better code the messy IF statements I'm using. It works great for up to 5 preset positions.....but I want it to be able to work on dials requiring any number of stops.
Any ideas? Thanks!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DialRotate : MonoBehaviour {
public List<float> rotationStop = new List<float>();
public float sensitivity;
public float dialValue = 0;
// Update is called once per frame
void Update () {
// Set the maximun stop position to the total number of stops
dialValue = Mathf.Clamp(dialValue, 0, rotationStop.Count -1);
// Determine which stop is selected based on knob value from 0-1
if (dialValue >= 0 && dialValue < 1)
TurnDialTo(rotationStop[0]);
if (dialValue >= 1 && dialValue < 2)
TurnDialTo(rotationStop[1]);
if (dialValue >= 2 && dialValue < 3)
TurnDialTo(rotationStop[2]);
if (dialValue >= 3 && dialValue <= 4)
TurnDialTo(rotationStop[3]);
if (dialValue >= 4 && dialValue <= 5)
TurnDialTo(rotationStop[4]);
}
// Dragging on the gameobject increases or decreases dialvalue
void OnMouseDrag ()
{
float dragMove = Input.GetAxis("Mouse X") * sensitivity;
dialValue += dragMove;
}
// Rotates the knob to angle set in rotationStop
void TurnDialTo (float position)
{
transform.rotation = Quaternion.Euler(0, position, 0);
}
}
Answer by moverend · Dec 12, 2015 at 07:27 AM
Thanks to @Sose for solving this for me. He suggested casting the float value of the rotations to an int that could be used to pick the matching index.
void Update () {
// Set the maximun stop position to the total number of stops
dialValue = Mathf.Clamp(dialValue, 0, rotationStop.Count - 1);
// Cast dialValue float to int and use as index
int index = (int)dialValue;
TurnDialTo(rotationStop[index]);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612052315im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Have an object continuously rotate towards another 1 Answer
What´s wrong with my rotation function? 0 Answers
Bullet dissapears from screen when I use LookAt? 0 Answers
How to return gameobjects rotation to original Rotation / zero rotation? 1 Answer
How to rotate an object according to the camera's view? 1 Answer