Reputation: 37
I'm trying to count the rotation that an object makes on the z axis when the player presses space, and I want to be able to reset it, so I made this code for it.
float lastRotation;
float amountRotated = 0;
void Start()
{
lastRotation = transform.rotation.z;
}
void Update() {
if (Input.GetKey(KeyCode.Space)) {
amountRotated += Mathf.Abs(transform.rotation.z - lastRotation);
lastRotation = transform.rotation.z;
print(amountRotated);
} else {
amountRotated = 0f;
lastRotation = transform.rotation.z;
}
}
But when I run it and rotate the object wile pressing space, it gives me a number close to zero, like 0.012345, then it gives me some weird number, like 9.25E, then keeps giving me numbers like these over and over again. Any help would be much appreciated.
Upvotes: 0
Views: 94
Reputation: 1007
We are not rotating the player, so the amountRotated
will not increase. We should add a rotate function.
public float rotSpeed;
float lastRotation;
float amountRotated = 0;
void Start()
{
lastRotation = transform.rotation.z;
}
void Update() {
if (Input.GetKey(KeyCode.Space)) {
transform.Rotate(transform.up * rotSpeed);
amountRotated += Mathf.Abs(transform.rotation.z - lastRotation);
} else {
amountRotated = 0f;
}
lastRotation = transform.rotation.z;
}
This way, amountRotated
will be increasing because we are changing the rotation. You set amountRotated
to a - b, where a is the rotation, and b is the lastRotation, so if you didn’t rotate at all, a = b, and a - b = 0.
Upvotes: 1