HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Rotating a character upside down and vice versa

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
vicerotatingcharacterversadownandupside

Problem

I have a pretty straightforward task, but I find it hard to figure out how to improve it. The code is pretty straightforward, but rather bad. There are some clarifications / extra details at the bottom. Let's assume the direction of the positive Z axis is (from the screen) towards you, the reader. Let's say I have this character:

Its angle / rotation along the Z axis is 0 initially. What I want it to do is rotate (say anticlockwise) around the Z axis with a particular speed (adjusted by RotationRate). When it reaches a (cumulated/total) rotation of 180, the rotation should stop. At this point the character will be upside down. If I now tap the screen again, the rotation should start again, but in the opposite direction, until it reaches an angle of 0. Now the character will look again like in the original photo above.

private bool Rotating = false;
private bool IsNormalPosition = true;
private float CharacterTargetAngle = 0;
private float RotationRate = 180 * 5;
private float Threshold = 30;

private IEnumerator Rotate()
{
    while (Rotating)
    {
        var angle = transform.eulerAngles;

        if (Mathf.Abs(CharacterTargetAngle - angle.z) < Threshold)
        {
            angle.z = CharacterTargetAngle;
            Rotating = false;

            transform.eulerAngles = angle;
        }
        else
        {
            transform.Rotate(0, 0, RotationRate * Time.deltaTime);
        }

        yield return new WaitForFixedUpdate();
    }
}

// called when user taps screen
public void OnTap()
{
    if (IsNormalPosition)
    {
        CharacterTargetAngle = 180;
    }
    else
    {
        CharacterTargetAngle = 0;
    }

    IsNormalPosition = !IsNormalPosition;
    RotationRate *= -1;

    if (!Rotating)
    {
        Rotating = true;

        StartCoroutine("Rotate");
    }
    else
    {
        StopCoroutine("Rotate");
        StartCoroutine("Rotate");
    }
}


Other details / clarifications:

Note that if the character is still rotating and

Solution

Your code seems to be quite clear to me. The only thing I can offer as a suggestion is as follows:

if (IsNormalPosition)
{
    CharacterTargetAngle = 180;
}
else
{
    CharacterTargetAngle = 0;
}


This is a little more concise.

CharacterTargetAngle = IsNormalPosition ? 180 : 0;

Code Snippets

if (IsNormalPosition)
{
    CharacterTargetAngle = 180;
}
else
{
    CharacterTargetAngle = 0;
}
CharacterTargetAngle = IsNormalPosition ? 180 : 0;

Context

StackExchange Code Review Q#68217, answer score: 3

Revisions (0)

No revisions yet.