Kyojin
Kyojin

Reputation: 159

How to calculate the position in matrix based on screen position

So I'm making a remake of pacman and I'm using XNA and .NET to build it.

I've setup a screen size of 448x576 and a matrix with 28x36, where each position in the matrix responds to 16px by 16px

448 / 16 = 28 576 / 16 = 36

This is how I calculate screen position based off the position in the matrix:

public Vector2 GetPositionAt(int col, int row)
    {
        int X = ((col) * 16) + 8;
        int Y = ((row) * 16) + 8;

        return new Vector2(X, Y);
    }

the reverse code would be:

float col = ((position.X - 8) / 16);
float row = ((position.Y - 8) / 16);

return new MatrixPosition((int)col, (int)row);

but this does not work, because the position updates only when the pacman position is at the center of the position in the matrix. I want to make it when it's close to the new point.

Let me explain with pictures (Sorry can't post yet pictures): https://i.sstatic.net/T7kpH.jpg

Upvotes: 3

Views: 397

Answers (1)

insidesin
insidesin

Reputation: 743

float col = ((position.X - 8) / 16);
float row = ((position.Y - 8) / 16);

If you substitute position.X = 8 and position.Y = 18:

col = ((8 - 8) / 16)
    = 0 / 16
    = 0
row = ((18 - 8) / 16)
    = 10 / 16
    = 0

Integers do not work the way you want them to. I understand why you're using -8 to find the centre of the square, but you cannot simply divide correctly using that method.

col = position.X / 16
row = position.Y / 16

But you'll still need to account for WHERE you are in that cell. Don't over calculate it.

Upvotes: 2

Related Questions