-1

enter image description here

private static final int gridWidth = 6;
private static final int firstHeight = 64;
private static final int secondHeight = 32;

public static Coords getXY(int cellNumber)
{
    int X = some math magic;
    int y = some math magic;

    int pixelX = some math magic;
    int pixelY = some math magic;

    return new Coords(x, y);
}

I need a function that returns X,Y coords from just the cell number. The problem here is that speed optimisation is very crutial so I'm not allowed to use any for loops. Only math equations.

To make things even worse, I need to multiply later those coords to get the cell's pixel location, but the height of the second row is always half the previous one. For example, the number '16' on the image above should return X=4,Y=3 and when converted to pixels should return X=192,Y=96.

How can I achieve this without using any loops ? Thank you.

Reacen
  • 2,312
  • 5
  • 23
  • 33

2 Answers2

1
public static Coords getXY(int cellNumber)
{
    int X = cellNumber % gridWidth;
    int y = cellNumber / gridWidth + 1;

    int pixelX = (y % 2 == 0) ? (x-1)*secondHeight : (x-1)*firstHeight //assuming firstHeight  row is the first column...

    int pixelY = (y % 2 == 0) ? (y/2)*firstHeight  + (y/2 -1)*secondHeight  : (y/2)*firstHeight  + (y/2)*secondHeight ; //assuming firstHeight is the first row...

    return new Coords(x, y);
}

EDIT: I know I'm wrong, my pixelY is from 0,0 not 6,6. I'm sure you can fix this by yourself. And I'm not sure why X=96 if Y=192...Either way, this is the way.

ZivS
  • 2,094
  • 2
  • 27
  • 48
1

This will do the trick: (you got the Xpixel and Ypixel the wrong way in your example; X=192, Y=96)

X = cellNumber % gridWidth;
Y = (cellNumber / gridWidth) + 1;

pixelX = ((cellNumber % gridWidth) - 1) * firstHeight;
pixelY = Math.ceil((cellNumber / gridWidth) * 1.5) * secondHeight;
Yarneo
  • 2,922
  • 22
  • 30