Home > Mobile >  How to calculate a full spin of a player in unity
How to calculate a full spin of a player in unity

Time:02-22

I have a 2D game and I want to give a score if the player rotates 360 degrees from its current rotation position. For example, let's say the player's current z rotation is 25 in the inspector. If the player's z rotation becomes 385, that means it makes a full spin.

By the way, since the player moves continuously, the current z value changes continuously too.

Here is what I do but it did not work as I expected.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpinScore : MonoBehaviour
{
    float currentZRotation;
    
    void Update()
    {
        currentZRotation = UnityEditor.TransformUtils.GetInspectorRotation(gameObject.transform).z;

        Debug.Log("z rotation: "   currentZRotation);
        if(currentZRotation >= 360 || currentZRotation <= -360)
        {
            Debug.Log("You spinned");
        }   
    }
}

CodePudding user response:

First of all I have to give hijinxbassist a one up: UnityEditor is NOT for runtime. But in 2D the axis "out of the screen" should correctly be the z-Axis. Second why do you check for >= 360 || <= -360? If you want the difference to be larger then 360 you have to check if the difference is >= 360 || <= -360. So you need a reference Rotation from the last frame or the last second or whatever. Could you please elaborate a little what ecxatly your problem is here because to me it's a little unclear.

CodePudding user response:

As was already mentioned UnityEditor is a namespace that is completely stripped of during the build process and is only available within the Unity editor itself!

Assuming a 2D game where you rotate around one single axis (Z) instead of actually checking rotations - which are Quaternion which is difficult to interpret and euler angles might not behave as you expected - I would rather simply use vectors.

In particular compare your current transform.right vector to the one from one frame before using Vector2.SignedAngle

// keeps the last frames right vector
private Vector2 _previousRight;

// keeps the already rotated angle
private float _angle;

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

private 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);
    }
}
  • Related