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?