Trying to Rotate an Object with the Mouse (Unsuccessfully)

I’m trying to write what I though was a simple rotation function: Click on an object and rotate it using the mouse. But I can’t get it to work. Here’s the code attached to the object:

function Start () {

	myTransform = transform;
	myLoc.x = myTransform.position.x;
	myLoc.y = myTransform.position.y;
	isRotating = false;
}

//------------------------------------------------

function StartRotate () {
	var sMouse: Vector3;
	
	if (isRotating)
		return;
	
	isRotating = true;
	DoRotate();
}

//------------------------------------------------

function DoRotate () {
	var tMouse: Vector3;
	var newAngle: float;
	var oldAngle: float;
	
	var theMouse: Vector2;
	var newDir: Vector2;
		
	while (Input.GetMouseButton (0)) {
		
		tMouse = Input.mousePosition;
		theMouse.x = tMouse.x - (Screen.width / 2.0);
		theMouse.y = tMouse.y - (Screen.height / 2.0);
		
		newDir = theMouse - myLoc;
		newAngle = Vector2.Angle(newDir, transform.up);
		
		if (theMouse.x > myLoc.x)
			newAngle = 360.0 - newAngle; 
			
		myTransform.rotation.eulerAngles.z = newAngle;  // this is the problem line
		yield;
	}
	myTransform.rotation.eulerAngles.z = 0.0;
	isRotating = false;
}

When a mouse down is detected on the object, it calls StartRotate. When the mouse is released, the object reverts to its original rotation.

If I don’t actually change the object’s rotation (comment out the line with the comment), everything seems to work correctly. If that line’s not there, all the angles are correct. However, if that line is in, and the object’s rotation changes, the variable newAngle changes constantly, even while the mouse is perfectly still. This produces jitter in the rotation. Without that line, the variable newAngle stops changing when the mouse stops moving and is always the correct angle. Since newAngle has nothing to do with the object’s rotation, I don’t see how it can be affected by the presence of that line.

Any ideas about what I’m doing wrong? Why would changing the object’s rotation affect the variable newAngle?

This works perfectly if I rotate anything other than myTransform. In other words, if I don’t attach this to the rotating object. I don’t understand why.

I think newAngle does depend on the object’s rotation. You are using transform.up to determine newAngle, but you are then rotating along the world z-axis (by changing eulerAngles.z on the rotation).

If you use AngleAxis on quaternion to create the correct rotation along the “transform.up” axis then everything should always match up.

If all your objects are always aligned perfectly up and down, then this may not be causing the problem. So it could still be something else, but it might be worth a try.

Yes, that’s it. It should be Vector2.up. I wonder why transform didn’t give me a warning, since it’s a Vector3.