Next dumb question

Sorry for these kind of questions, but this is something that I spend the whole afternoon searching without any success.

I have a rigidbody which is controlled by AddForce (through keyboard input). I want to rotate this rigidbody 180 degrees just by hitting one key. That means, the moment I hit and release my key, the rigidbody will should rotate 180 degrees without any pause and stop at 180. If I hit the same key again, I want the rigidbody to rotate -180, to the original position.

I have tried combining with transform.Rotate, but, first, I think that is not allowed (within unity) and second, I can’t get that fixed 180 degrees done!.

Thanks everyone for your time.

This should work without a problem:

function Update () {
	if (Input.GetKeyDown("a")) transform.Rotate(0,180,0);
}

Or if you want it to show the rotation instead of it being instant:

var deg = 180;
function FixedUpdate () {
	if (Input.GetKeyDown("a")) deg = 0;
        if (deg < 180) {
                deg++;
                transform.Rotate(0,1,0);
        }
}

or you could directly set transform.rotation.y

Hello TJB,

Thank you for the quick reply. I tried the code, but without luck. I think this has to do with the “translate.Rotate” not being able to influence on a rigidbody. Is this correct?

hmm… something like these might work better for you:

smoothed:

var deg = 541;
function FixedUpdate () {
	if (Input.GetKeyDown("a")  deg == 541) deg = 0;
	else if (Input.GetKeyDown("a")  deg == 181) deg = 360;
	
	if (deg <= 180) {
		transform.rotation.y ++;
		deg++;
	}
	
	if (deg > 200  deg <=540) {
		transform.rotation.y --;
		deg++;
	}
}

instant:

var rot = false;
function Update () {
	if (Input.GetKeyDown("a")  rot == false) {
		transform.rotation.y = 180;
		rot = true;
	}
	else if (Input.GetKeyDown("a")  rot == true) {
		transform.rotation.y = 0;
		rot = false;
	}
}

don’t have the right computer in front of me to check them, but they should work.

I’m pretty sure transform.Rotate works with rigidbodies. Although it might be that only capsule colliders will work well with transform.Rotate when they’re rigidbodies and in contact with another collider. Just thinking logically given the shape… this is just a guess