如何根据屏幕位置计算矩阵中的位置(How to calculate the position in matrix based on screen position)

编程入门 行业动态 更新时间:2024-10-26 02:27:33
如何根据屏幕位置计算矩阵中的位置(How to calculate the position in matrix based on screen position)

所以我正在制作pacman的翻版,我正在使用XNA和.NET来构建它。

我设置了一个448x576的屏幕尺寸和一个28x36的矩阵,其中矩阵中的每个位置响应16px乘16px

448/16 = 28 576/16 = 36

这就是我根据矩阵中的位置计算屏幕位置的方法:

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

反向代码是:

float col = ((position.X - 8) / 16); float row = ((position.Y - 8) / 16); return new MatrixPosition((int)col, (int)row);

但这不起作用,因为仅当pacman位置位于矩阵中位置的中心时,位置才会更新。 我想在它接近新点时做出来。

让我用图片解释(抱歉无法发布图片): http : //imgur.com/a/CYekd

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): http://imgur.com/a/CYekd

最满意答案

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

如果你替换position.X = 8和position.Y = 18:

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

整数不按您希望的方式工作。 我理解为什么你使用-8来找到正方形的中心,但你不能简单地使用该方法正确划分。

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

但是你仍然需要考虑你在那个单元格中的位置。 不要过度计算它。

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.

更多推荐

本文发布于:2023-07-29 20:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1319437.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:位置   矩阵   屏幕   calculate   screen

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!