Hello, I’m reading the book “Unity in Action: Multiplatform Game Development in C#”, and I can’t understand how the “-=” operator works with angles to perform a rotation , and the author doesn’t explain this either. I know what the “-=” operator does (subtract an assign a value to the left variable), but why is used here:
...
public float sensitivityHor = 9.0f;
public float sensitivityVert = 9.0f;
public float minimumVert = -45.0f;
public float maximumVert = 45.0f;
private float _rotationX = 0;
void Update() {
if (axes == RotationAxes.MouseX) {
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityHor, 0);
}
else if (axes == RotationAxes.MouseY) {
_rotationX -= Input.GetAxis("Mouse Y")*sensitivityVert;//Why I can't use the "+= operator"?
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float rotationY = transform.localEulerAngles.y;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0); //Values of _rotationX
//are all negatives?
}
...
I think that has to do with how unity handles the angles of rotation. What not use the “+=” compound assignment operator that is in fact the operator to ADD a value, an instead uses the “-=” operator that is for subtract a value, what is subtracting? Then all the values of “_rotationX” are negatives? inclusive the posives that the input function “GetAxis” retrieves?
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float rotationY = transform.localEulerAngles.y;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
I have checked an the script only works with the “-=” operator, something is going on behind the scenes that the book doesn’t explain, can anyone tell me how this work in unity?
Her is what the book says about this:
“The Rotate() method increments the current rotation, whereas this code sets the
rotation angle directly. In other words, it’s the difference between saying “add 5 to the
angle” and “set the angle to 30.” We do still need to increment the rotation angle, but
that’s why the code has the -= operator: to subtract a value from the rotation angle,
rather than set the angle to that value. By not using Rotate() we can manipulate the
rotation angle in various ways aside from only incrementing it.”
Any help would be greatly appreciated!
Thanks