Backstory: I'm making a simple maze game, where the maze is procedurally generated. I represent the maze as a 2D array of rooms, with 4 booleans storing whether or not each corner of a room has a wall. (if Room.south_wall == false, than the room is connected to the room to its south.) Each room and can have an arbitrary length and width. For simplicity's sake, I set it so that the length and width is determined at the beginning of generation and applied to all rooms. The position of the player is stored using 2 floats, one is their x coordinates, one is their y coordinates. The maze looks something like this (Thick black lines are the visible walls, thin red lines represent the 2d array):
背景故事:我正在制作一个简单的迷宫游戏,其中迷宫是程序生成的。我把迷宫描绘成一个二维阵列的房间,有4个布尔值存储房间的每个角落是否有墙。 (如果Room.south_wall == false,则房间连接到南面的房间。)每个房间都可以有任意长度和宽度。为简单起见,我将其设置为在生成开始时确定长度和宽度并应用于所有房间。使用2个浮点存储玩家的位置,一个是他们的x坐标,一个是他们的y坐标。迷宫看起来像这样(粗黑线是可见的墙,细红线代表2d阵列):
As you can see, each room has a length and width of 3. What I want to be able to do is determine what room the player is in, given their position. So for example, in this instance:
正如你所看到的,每个房间的长度和宽度都是3.我想要做的是确定玩家所处的位置,给定他们的位置。例如,在这个例子中:
The player is in room (1,0) (I've marked the origin and the center of room (1,0) to help see this)
玩家在房间(1,0)(我已经标记了房间的原点和中心(1,0)以帮助看到这个)
I know this should be a simple question, but I've been unable to come up with anything for a few days now. Any suggestions would be greatly appreciated. Let me know if this isn't enough information.
我知道这应该是一个简单的问题,但我几天都无法想出任何东西。任何建议将不胜感激。如果这还不够,请告诉我。
1 个解决方案
#1
1
If you have the player position px
,py
and your rooms are aligned so that room(0,0) is centred at (0.0, 0.0) then the index of the room would be
如果您有玩家位置px,py和您的房间对齐,以便房间(0,0)居中(0.0,0.0),那么房间的索引将是
#include<cmath>
ix = int(std::round(px / room_width));
iy = int(std::round(py / room_height));
Also, as a general rule it's best to make room_width
and room_height
a constant rather than use a 'bare' (aka magic) number just in case you want to change it later.
此外,作为一般规则,最好将room_width和room_height设为常数,而不是使用“裸”(又称魔术)数字,以防您以后想要更改它。
#1
1
If you have the player position px
,py
and your rooms are aligned so that room(0,0) is centred at (0.0, 0.0) then the index of the room would be
如果您有玩家位置px,py和您的房间对齐,以便房间(0,0)居中(0.0,0.0),那么房间的索引将是
#include<cmath>
ix = int(std::round(px / room_width));
iy = int(std::round(py / room_height));
Also, as a general rule it's best to make room_width
and room_height
a constant rather than use a 'bare' (aka magic) number just in case you want to change it later.
此外,作为一般规则,最好将room_width和room_height设为常数,而不是使用“裸”(又称魔术)数字,以防您以后想要更改它。