Convert function into a While loop

Hi,

I have this function that rotates the top half of the Mech back facing forward to match the bottom half after an attack -

function rotateTurret(){

    var lookPos = transform.forward;
    var rotation = Quaternion.LookRotation(lookPos);

    rotation *= Quaternion.FromToRotation(Vector3.up, Vector3.right);
    rotation *= Quaternion.Euler(XattackDegrees, YattackDegrees, 0);
    mechTurret.rotation = Quaternion.Slerp(mechTurret.rotation, rotation, Time.deltaTime * 2);
}

What I want to do is covert it into a while function, I thought I could add something like -

while(mechTurret.rotation != transform.forward){

But Unity wont allow that, or -

while(mechTurret.rotation != transform.rotation){

But Unity wont allow that ether, can someone point me in the right direction please, thanks.

transform.forward is a Vector3 and mechTurret.rotation is a Quaternion. You cannot compare these against each other.

What about - while(mechTurret.rotation != transform.rotation){

1 Answer

1

Firstly checking for an equality will likely never work (or take far longer than you expect).

Also your syntax for the condition is trying to do a !mechTurret.rotation - which makes no sense :slight_smile:

I think you meant:

     while(mechTurret.rotation != transform.rotation) //Still not a good idea

Or

     while(!(mechTurret.rotation == transform.rotation))

You can try:

     while((mechTurret.eulerAngles - transform.eulerAngles).sqrMagnitude > 0.1f)

whydoidoit, thanks for that, sorry about the syntax error I've corrected it now, I've tried you suggestion but it won't yield just keeps on going, I've tried raising the value but still wont yield.

You've used StartCoroutine to start it? and have a yield in the body?

I thought in UnityScript, StartCoroutine is not necessary as the compiler does for you, for testing reasons I'm calling it from the Start function so there is no confusion of it being called again, and yes it has a yield.

I've just made a test scene with 2 cubes, top one for the turret offset at 90 degrees, and a very basic script with this code in and calling it from the start function, and I'm glad to say it's working, so it's something in my AI script attached to the Mech that's causing the problem, so thanks for the help, much appreciated.

Ok so I think your problem is that the "correction" is altering mechTurrent.eulerAngles so the while loop goes nuts. It sounds to me like you would be better off putting the head inside another game object that fixes the rotation issue - that's often possible with other people's stuff, if not then we also need to correct the calculation of transform.eulerAngles I think...