46 lines
1.3 KiB
C#
46 lines
1.3 KiB
C#
using UnityEngine;
|
|
|
|
namespace BlockSpace.Voxels
|
|
{
|
|
public static class GridRotationUtility
|
|
{
|
|
public static byte Pack(Vector3Int quarterTurns)
|
|
{
|
|
return (byte)(Normalize(quarterTurns.x) | (Normalize(quarterTurns.y) << 2) | (Normalize(quarterTurns.z) << 4));
|
|
}
|
|
|
|
public static Vector3Int Unpack(byte packedRotation)
|
|
{
|
|
return new Vector3Int(packedRotation & 3, (packedRotation >> 2) & 3, (packedRotation >> 4) & 3);
|
|
}
|
|
|
|
public static Quaternion ToQuaternion(byte packedRotation)
|
|
{
|
|
Vector3Int vector3Int = Unpack(packedRotation);
|
|
return Quaternion.Euler((float)vector3Int.x * 90f, (float)vector3Int.y * 90f, (float)vector3Int.z * 90f);
|
|
}
|
|
|
|
public static Vector3Int Rotate(Vector3Int localOffset, byte packedRotation)
|
|
{
|
|
Vector3 vector = ToQuaternion(packedRotation) * localOffset;
|
|
return new Vector3Int(Mathf.RoundToInt(vector.x), Mathf.RoundToInt(vector.y), Mathf.RoundToInt(vector.z));
|
|
}
|
|
|
|
public static Vector3Int InverseRotate(Vector3Int worldOffset, byte packedRotation)
|
|
{
|
|
Vector3 vector = Quaternion.Inverse(ToQuaternion(packedRotation)) * worldOffset;
|
|
return new Vector3Int(Mathf.RoundToInt(vector.x), Mathf.RoundToInt(vector.y), Mathf.RoundToInt(vector.z));
|
|
}
|
|
|
|
private static int Normalize(int turns)
|
|
{
|
|
turns %= 4;
|
|
if (turns >= 0)
|
|
{
|
|
return turns;
|
|
}
|
|
return turns + 4;
|
|
}
|
|
}
|
|
}
|