I’m trying to make a wheel spin when a button is pressed, but it doesn’t seem to work properly. before adding the button, the wheel spins just as I want it to, but, when I add the button and press it, the wheel moves, but only by an inch. Here is the code I’m using:
using UnityEngine;
using System.Collections;
public class Spinning : MonoBehaviour {
void OnGUI()
{
if (GUI.Button (new Rect (15, 15, 100, 50), "Spin"))
{
float rotationAmount = 270.0f;
Vector3 rot = transform.rotation.eulerAngles;
rot.z = rot.z + rotationAmount * Time.deltaTime;
if (rot.z > 360)
rot.z -= 360;
else if (rot.z < 360)
rot.z += 360;
transform.eulerAngles = rot;
}
}
}
I also want it to slow down and stop at a random location, so if you could help me with that too, that’s be awesome.
I think you will want to use a RepeatButton rather than just a button, the normal button will return true once while a repeat button will continue to return true as long as it is held down.
For slowing to a point, you can calculate the distance from the target rotation and if it’s less than some threshold start to lessen the speed based on that. If you limit a value to some range, you can divide it by the maximum to get it between 0&1 (though never 0), and multiply your rotation speed by that. 1 will be normal speed, 0.5 half, 0 none. For example (dist/maxDist=?): 10/10=1.0, 9/10=0.9, 1/10=0.1 and so on, if the distance is less than the minimum set it to zero to stop the rotation.
float targetRotation = 360f; //Rotation to stop at
float distanceToSlow = 50f; //How far from target to start slowing down
float minDistance = 1f; //How far from target to stop completely
Vector3 rot = transform.rotation.eulerAngles;
float d = targetRotation - rot.z; //Distance from target
if(d > minDistance){
if(d < distanceToSlow){
d = d / distanceToSlow;
}
else{
d = 1f;
}
}
else{
d = 0f;
}
//Or shorter
d = d > minDistance? d < distanceToSlow? d / distanceToSlow : 1f : 0f;
float rotationAmount = 270f * d;
rot.z = rot.z + rotationAmount * Time.deltaTime;
if (rot.z > 360)
rot.z -= 360;
else if (rot.z < 360)
rot.z += 360;
transform.eulerAngles = rot;