I am trying to rotate a GameObject with the help of slider input. I created a slider properly. I am able to change the position of GameObject, but when I am trying to rotate this GameObject with the Slider, it is not happening. Here is my code:

public GameObject gameObject;
private float m_currentValue = 20.0f;
void OnGUI() {
    m_currentValue  = GUI.HorizontalSlider(new Rect(35, 75, 200, 30), m_currentValue , 0.0F,  50.0F);
}

void Update(){}

How can I rotate a GameObject based on a slider's value?

有帮助吗?

解决方案

If you want to rotate a GameObject, your best bet is to use a Transform's localEulerAngles. Don't go modifying the rotation directly. That is a quaternion, not a rotation in degrees. Even if you know what quaternions do, manipulating them directly is unintuitive at the very best.

So knowing that, you don't need to do a while lot more to your code. Just make sure it's a proper MonoBehaviour and do something like the following:

using UnityEngine;
using System.Collections;

public class Rotator : MonoBehaviour 
{
    private float currentRotation = 20.0f;

    void OnGUI() 
    {
        currentRotation = GUI.HorizontalSlider(new Rect(35, 75, 200, 30), currentRotation , 0.0f,  50.0f);
        transform.localEulerAngles = new Vector3(0.0f, currentRotation, 0.0f);
    }

}

This, in line with your pseudo-code, rotates the object which as that script between 0 and 50 degrees around its Y axis, based on the slider input.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top