Hello! In my game I have the ability to rotate the character 180 degrees by pressing a button. This works fine, except I want to be able to determine in which direction it is rotating.
When I press the button the first time it rotates CW 180 degrees, the next time I press the button it rotates CCW 180 degrees (i.e. back t 0 degrees).
I’m using Quaternion.LookRotation
to calculate the target, and Quaternion.RotateTowards
for the actual rotation. See source below.
Is it possible to tell it in which direction to rotate? Or is there a better way? Thanks!
void TurnAround()
{
if (!isTurning && (Input.GetButtonDown("TurnAround") || Input.GetAxisRaw("TurnAround") > 0))
{
turnAroundTarget = Quaternion.LookRotation(-transform.forward);
isTurning = true;
}
if (isTurning)
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, turnAroundTarget, turnAroundSensivity);
if (transform.rotation == turnAroundTarget)
{
isTurning = false;
}
}
}
Hi there
If you’d like to apply CW/CCW rotation simply, you can use Quaternion.EulerAngles, which is a Vector3 and represents what you see in the Editor for “rotation” on a Transform. If you’d always like to rotate 180 CW for example, you can take this approach. The code can be written in a cleaner way, but it’s easier to read like this:
// Need to acquire the full Vector3 even for rotating < 3 axes - you
// can't individually set the x,y,z members
Vector3 rot = transform.rotation.EulerAngles;
// This is your angle to adjust by. Positive values for CW rotation,
// negative values for CCW.
float angleAdjust = -90.0f; // 90 degrees CCW
// Apply rotation. Unity allows "infinite" rotation - passing 360
// results in 361, rather than 1 degree. Passing 0 CCW results in -1. This may
// or may not be desirable, but it does allow you to just keep adding positive
// numbers for CW rotation, or adding negative numbers for CCW rotation.
rot.y += angleToAdjust;
// If you want to remove the infinite rotation behaviour, you can do so here.
// For CW rotation, limit is 360.
// For CCW rotation, limit is 0
if (rot.y > 360.0f)
rot.y -= 360.0f;
if (rot.y < 0.0f)
rot.y += 360.0f;
// Now you can apply the new rotation back to the transform in one step
transform.rotation.EulerAngles = rot;