Unable to fully rotate GameObject on tap

Hi guys,

I’ve got this bit of code in a script named TapRotationLogic.cs attached to a wall:

// Called when tapped
	void OnTap () {

		Debug.Log("Tapped to rotate");
        Quaternion newRot = transform.rotation;
		newRot.y += Mathf.Lerp(0.0f, 45.0f, 2.0f);
		transform.rotation = newRot;

The above method is called from TBTap.cs, which is set to call the OnTap method. However, even though OnTap is getting called (I can tell from the debugging console), the wall is only rotating in a choppy manner a few degrees, back and forth. And that’s if it even bothers to rotate at all, despite the relevant function firing perfectly fine.

The wall should rotate exactly 45 degrees relative to the y axis on every tap, and it should rotate smoothly.

What am I doing wrong? Please help.


You don’t mess with the components of Quaternions directly. They are sufficiently unrelated to angles. Never set or query something like transform.rotation.y directly, it won’t help you.

Read up on how to use a Quaternion in the docs, or what it is on Wikipedia, if you’re interested.

Convert to and from a Quaternion using convenience functions:

Vector3 angles=myquaternion.eulerAngles;

EDIT: or, in case of transform.rotation, use transform.eulerAngles instead, for both query and assignment.

function OnTap only executes once. You only rotate it what it would on 1 game frame.

and as iwaldrop said, the “t” of Mathf.Lerp (which is 2.0f in your case) controls the PROGRESS of the lerp.

So what you want to do is to setup a coroutine (look it up). And then run from 0 - 1 in t, where 0 is the start and the value one being the targeted rotation.

like shown in the docs:

// Fades from minimum to maximum in one second

var minimum = 10.0;
var maximum = 20.0;

function Update () {
    transform.position = Vector3(Mathf.Lerp(minimum, maximum, Time.time), 0, 0);

notice that this works because it is inside update(which executes 1 time per game frame. And because of Time.time which will make this lerp finish after 1 second.

But you want it to happen OnTap, so call a COROUTINE function from there.