How can I add a system that detects if the character has flipped?

I would like to implement a system that detects if the character has flipped and then attach a particle effect to it and maybe a counter that goes up every time. I don’t know how to implement this though.

I think it should go something like this: (pseudocode)
if (Transform.Rotate(z-axis) = 180)
{
Debug.Log(“Flip!”)
}

I don’t know how to actually single out the z-axis variable on the rotation to make this work.

I know this mechanic is not a part of the course, but I think it would help make the game into an actually fun game.

If somebody could help me on this, that would be greatly appreciated.

Hi,

I guess something like that could work, if you use Transform.eulerAngles.
I dont think you can read out values from Rotate anyways.

But what rotates your character? Isnt it by keypresses? cant you simply add it in the input then?

Your angle is (almost) never going to be exactly 180 degrees. One thing you could do is check if the character’s up is pointing in the opposite direction of the world’s up. You can use Vector2.Dot to check. It will give you a value between 1 and -1 where -1 is upside down but, again, it will almost never be exactly -1. Give it some space:

float check = Vector2.Dot(character.transform.up, Vector2.up);
if (check < -0.9f)
{
    Debug.Log("Flipped!");
}

A value of 1 will mean the character is completely upright, 0 means the character is on it’s side, and -1 means that it’s completely upside down. All relative to the world’s up vector

I wanted to do this as well for my game. After a lot of digging around I found this code which worked for me. Just create a new Script and attach this to your character. I have no idea why this worked, but I guess it worked.

// keeps the last frames right vector
Vector2 _previousRight;

// keeps the already rotated angle
float _angle;

void Start()
{
    _previousRight = transform.right;
}

void Update()
{
    // get this frame's right vector
    var currentRight = transform.right;

    // compare it to the previous frame's right vector and sum up the delta angle
    _angle += Vector2.SignedAngle(_previousRight, currentRight);

    // store the current right vector for the next frame to compare
    _previousRight = currentRight;

    // did the angle reach +/- 360 ?
    if (Mathf.Abs(_angle) >= 360f)
    {
        Debug.Log("Completed Full Spin!");

        // if _angle > 360 subtract 360
        // if _angle < -360 add 360
        _angle -= 360f * Mathf.Sign(_angle);
    }
}



}

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms