简体   繁体   English

将位置映射到数组索引

[英]Mapping a position to an array index

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. 我将迷宫表示为房间的2D数组,其中4个布尔值存储房间的每个角是否都具有墙。 (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. (如果Room.south_wall == false,则表示该房间连接到其南部的房间。)每个房间都可以具有任意长度和宽度。 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. 播放器的位置使用2个浮点数存储,一个是其x坐标,一个是其y坐标。 The maze looks something like this (Thick black lines are the visible walls, thin red lines represent the 2d array): 迷宫看起来像这样(黑色的粗线是可见的墙,红色的细线表示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. 如您所见,每个房间的长度和宽度为3。我想做的就是根据玩家的位置确定玩家所在的房间。 So for example, in this instance: 因此,例如,在这种情况下:

在此处输入图片说明

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. 让我知道这是否还不够。

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 如果您的玩家位置pxpy和您的房间对齐,因此room(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_widthroom_height为常量,而不要使用“裸”(又称魔术)数字,以防万一您以后要更改它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM