Transform rotate and stop object on the y axis

Hey guys,

I’m trying to create a page turn effect with a button press. I can’t this code to work. With out the button the page turns to 180 and slows down to a stop. Trouble is the reset doesn’t work. Also, when I add the code into the button press, the page turn doesnt work.

Any thoughts on how I can crack this.

Many thanks,

Rich

private var rotation1:float = 0;
var MainMenuCollider : GameObject;
  
function Reset () {
transform.rotation.y = 0;
}
 
function Update () {
	
		if (Input.GetMouseButtonDown (0)) {
		var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
		var hit:RaycastHit;
	
		if (Physics.Raycast (ray, hit, 20)) {
		if(hit.collider.name == "loadChapterPageCollider")
		
		
		transform.rotation.y = (transform.rotation.y + 1 * Time.deltaTime);	
		rotation1 = (transform.rotation.y);
		print(rotation1);
		if (rotation1 == 180) {
		Reset();
			}
		}
	}
}

There are a few issue here, and how to fix them depends on what you want to happen. The first is that you are directly accessing a component of Transform.rotation on line 19. Transform.rotation is Quaternion…a 4D, non-intuitive construct that does not behave like euler angles. You don’t want to directly manipulate them unless you have a firm understanding of the math behind Quaternions. You can use Transform.eulerAngles, but there are issues there as well. In particular, you don’t want to set one axis independently, and their underlying representation might change, so you don’t want to read them back if you can help it. Another issue is line 22. You don’t want to directly compare two floating point numbers. Time.deltaTime is a fraction that varies from frame to frame. The chance that you will hit 180 dead on is small. Best guess is that you should use ‘>=’ for this test.

Another issue is line 13. Input.GetMouseButtonDown() only returns true for a single frame, and since your rotation code is inside this ‘if’, you will only get a single frame of rotation. And finally line 15 does not have any brackets (‘{}’), so only line 17 will be executed when the ‘if’ is true.

I’m making some guesses, but I think you want something like:

var MainMenuCollider : GameObject;
var speed = 100.0;  // Degrees per second 
private var myEuler = Vector3.zero;
private var rotating = false;

 
function Update () {
 
   if (!rotating  && Input.GetMouseButtonDown (0)) {
		var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
		var hit:RaycastHit;
		
		if (Physics.Raycast (ray, hit, 20) && (hit.collider.name == "loadChapterPageCollider")) {
			rotating = true;
		}
	}
	
	if (rotating) {
		myEuler.y = Mathf.MoveTowardsAngle(myEuler.y, 180.0, Time.deltaTime * speed);
		if (myEuler.y >= 180.0) {
			myEuler.y = 0;
			rotating = false;
		}
		
		transform.eulerAngles = myEuler;
	}
}