- Home /
ienumerator quaternion only rotating once
This script is for a overhead spotlight that is a child of a gameobject that is suppose to stimulate a searchlight. The rotation works perfectly the first time but, it will not rotate thereafter. i have a feeling it might have something to do with the "random.range" part pulling from the same seed value but other than that im out of ideas.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpotlightController : MonoBehaviour {
private IEnumerator Start()
{
while (Application.isPlaying) {
Quaternion randomRot = Quaternion.Euler (Random.Range (-10, 10), Random.Range (-20, 20), 0f);
while(Vector3.Distance(this.transform.root.localEulerAngles, randomRot.eulerAngles) > .1f)
{
this.transform.localRotation = Quaternion.Lerp(this.transform.localRotation, randomRot, Time.deltaTime);
yield return null;
}
yield return new WaitForSeconds(1f);
}
}
Answer by yummy81 · Feb 17, 2018 at 09:45 PM
As I understand it correctly, there are two gameobjects in the scene. The first one is the parent gameobject, and the second one is the child (and it is the spotlight). And the script is attached to the child? If so, then look at this line of code:
while(Vector3.Distance(this.transform.root.localEulerAngles, randomRot.eulerAngles) > .1f)
You passed here as the parameters the rotation of the parent gameobject (its euler representation) and the random rotation. As the parent gameobject is not rotating, so its rotation remains unchanged all the time. The same goes for randomRot - its value is calculated outside the nested while loop, so inside it the random rotation remains unaltered. Because of this, the distance is still the same, and as it is greater than .1f, the expression is constantly evaluating to true. So, the solution would be to pass as the first parameter the rotation of the spotlight (the child gameobject), which is the one which you want to rotate. So, modify this line of code like this:
while(Vector3.Distance(this.transform.localEulerAngles, randomRot.eulerAngles) > .1f)
Thank you so much! You are a life saver! This worked perfectly. The .1f was just a typo suppose to be 1f.