Search code examples
c#unity-game-enginequaternions

How to divide by Quaternion in Unity


Using this tutorial https://www.youtube.com/watch?v=waEsGu--9P8&list=PLzDRvYVwl53uhO8yhqxcyjDImRjO9W722 and Quaternions I've made a function, that finds the World Position of the grid tiles for Isometric Tilemap.

private Vector3 GetWorldPosition(int x, int y, int r, int u, int f) {
        return Quaternion.AngleAxis(u, Vector3.up) * Quaternion.AngleAxis(r, Vector3.right)
            * Quaternion.AngleAxis(f, Vector3.forward) * new Vector3(x, y) * cellSize;
    }

It works perfectly well. It rotates a 2D grid to fit Unity isometric Tilemap. Now i need to do the opposite - get the tile, if i know the worldPosition. I supposed, if in the previous case I multiplied the Quaternions, now i need to divide the worldPosition.x and worldPosition.y by them. But this code

private void GetXY(Vector3 worldPosition, out int x, out int y,  int r = 60, int u = 0, int f = 45) {
        Quaternion rotation = Quaternion.AngleAxis(u, Vector3.up) * Quaternion.AngleAxis(r, Vector3.right)
            * Quaternion.AngleAxis(f, Vector3.forward);
        x = Mathf.FloorToInt(worldPosition.x / rotation /  cellSize);
        y = Mathf.FloorToInt(worldPosition.y / rotation /  cellSize); }

does not even run, because of the mistake

"Operator '/' cannot be applied to operands of type 'Quaternion' and 'float'"

So why could I multiply Quaternion and float cellSize in the first case, but can not divide or multiply them in the second case? And how to do the opposite operation?


Solution

  • Thank you for trying to help, but Inverse did not work out.

    So I had 2D grid, that was rotated -45 degrees Z and 60 degrees X. It made the grid isometric. So because it was rotated X by 60 degr., in 2D vision this grid had more than 90 degrees between its own X and Y (the tiles were rhombus). And i found out the exact angles, which i can use for the coordinates - different for x and y. This function got the tiles right for me.

    private Vector2Int GetXY(Vector3 worldPosition) {
    
        Vector3 positionX = Quaternion.AngleAxis(-65, Vector3.forward) * worldPosition / cellSize;
        Vector3 positionY = Quaternion.AngleAxis(-26, Vector3.forward) * worldPosition / cellSize;
        return new Vector2Int(Mathf.FloorToInt(positionX.x * 1.55f), Mathf.FloorToInt(positionY.y * 1.55f));
    }