- Home /
Rotating a rigidbody on mouse click.
I'm trying to get a rigidbody to rotate 90 degrees when it's clicked. The code reports no errors and the debugs do show up, but the object does nothing at all. Any idea why?
public float state01 = 0;
private float speed = 90f; // degrees per second
private Vector3 currentRot, targetRot;
private bool rotating = false;
void start () {
currentRot = transform.eulerAngles;
}
void update () {
}
// Update is called once per frame
void OnMouseOver () {
if (Input.GetMouseButtonDown(0)) {
Rotate();
//Debug.Log("Clicked, rotating");
state01 += 1;
//Debug.Log(state01);
if (state01 > 3) state01 = 0;
}
}
void Rotate(){
if (rotating) return; // ignore calls to RotateAngle while rotating
rotating = true; // set the flag
targetRot.y = currentRot.y + 90; // calculate the new angle
while (currentRot.y < targetRot.y){
// move a little step at constant speed to the new angle:
currentRot.y = Mathf.MoveTowards(currentRot.y, targetRot.y, speed * Time.deltaTime);
transform.eulerAngles = currentRot;
Debug.Log("Hi!");
}
rotating = false;
}
Answer by robertbu · May 19, 2014 at 12:26 AM
Your code is working, but because you have not constructed it as a proper coroutine, you are getting an immediate 90 degree rotation. In C#, in function that is a coroutine must have a type of IEnumerator, and it must be called by StartCoroutine(). So your Rotate() function rewritten as coroutine becomes:
IEnumerator Rotate(){
if (!rotating) {
rotating = true; // set the flag
targetRot.y = currentRot.y + 90; // calculate the new angle
while (currentRot.y < targetRot.y){
// move a little step at constant speed to the new angle:
currentRot.y = Mathf.MoveTowards(currentRot.y, targetRot.y, speed * Time.deltaTime);
transform.eulerAngles = currentRot;
yield return null;
}
rotating = false;
}
}
And you need to call it like:
StartCoroutine(Rotate());
Note that 'yield return null' will yield for a single frame. Also because of the way you are doing the rotation, you will gain some extra rotation over time.
That did the trick beautifully, thank you very much! Guess I'll need to pick up a C# book sooner or later.
Your answer
![](https://koobas.hobune.stream/wayback/20220613145340im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Problems caused by non-unique Euler angle solutions 1 Answer
How to set an exact Local angle. 0 Answers
Instantiating an object in front of the player 3 Answers
Camera Zoom from rotation. 0 Answers