Question by
thegamerx8469 · Feb 01, 2016 at 10:57 AM ·
c#rotate objectacceleration
Rotating an object
Hello, I'm new to unity. I know how to rotate an object when I press a key using the (transform.Rotate) function, but what I really want is to make the object's rotation speed increase when I press that key and when I release the key the speed begins to decrease until the object stops rotating, can you help me with that?
thanks
Comment
Best Answer
Answer by BackslashOllie · Feb 01, 2016 at 04:29 PM
This script will slowly increment a float to 5 when the key is pressed and will decrement back to 0 when released. Assign the float to your rotation speed and tweak the variables to suit your need.
Hope it's helpful!
float delay = 0.3f; //Delay between each increment of speed
float speedIncrement = 0.3f; //Amount of speed to increment
float maxSpeed = 5f; //Maximum rotation speed
float rotationSpeed;
bool buttonPressed;
IEnumerator IncreaseSpeed(float delay)
{
while (buttonPressed)
{
while (rotationSpeed < maxSpeed)
{
yield return new WaitForSeconds (delay);
rotationSpeed += speedIncrement;
}
rotationSpeed = maxSpeed;
yield return null;
}
}
IEnumerator DecreaseSpeed(float delay)
{
while (rotationSpeed > 0)
{
yield return new WaitForSeconds (delay);
rotationSpeed -= speedIncrement;
}
rotationSpeed = 0;
yield return null;
}
void Update ()
{
if (Input.GetKeyDown(KeyCode.K)) //Change to your assigned button
{
buttonPressed = true;
StartCoroutine(IncreaseSpeed(delay));
}
if(Input.GetKeyUp(KeyCode.K)) //Change to your assigned button
{
buttonPressed = false;
StartCoroutine(DecreaseSpeed(delay));
}
Debug.Log(rotationSpeed);
}
Thank you, it's really complex though,, but it works!
Your answer