如何“压平"或“索引"1D 阵列中的 3D 阵列? [英] How to "flatten" or "index" 3D-array in 1D array?

查看:27
本文介绍了如何“压平"或“索引"1D 阵列中的 3D 阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 3D 阵列展平为我游戏中的块"系统的 1D 阵列.这是一款 3D 方块游戏,基本上我希望区块系统与 Minecraft 的系统几乎相同(但是,无论如何,这都不是 Minecraft 的克隆).在我之前的 2D 游戏中,我使用以下算法访问了扁平数组:

I am trying to flatten 3D array into 1D array for "chunk" system in my game. It's a 3D-block game and basically I want the chunk system to be almost identical to Minecraft's system (however, this isn't Minecraft clone by any measure). In my previous 2D-games I have accessed the flattened array with following algorithm:

Tiles[x + y * WIDTH]

但是,这显然不适用于 3D,因为它缺少 Z 轴.我不知道如何在 3D 空间中实现这种算法.宽度、高度和深度都是常数(宽度和高度一样大).

However, this obviously doesn't work with 3D since it's missing the Z-axis. I have no idea how to implement this sort of algorithm in 3D-space. Width, height and depth are all constants (and width is just as large as height).

它只是 x + y*WIDTH + Z*DEPTH 吗?我的数学很差,我刚刚开始 3D 编程,所以我很迷茫:|

Is it just x + y*WIDTH + Z*DEPTH ? I am pretty bad with math and I am just beginning 3D-programming so I am pretty lost :|

附注.这样做的原因是我正在循环并通过索引从中获取很多东西.我知道一维数组比多维数组快(原因我不记得了 :P ).尽管这可能不是必需的,但我想要尽可能好的性能:)

PS. The reason for this is that I am looping and getting stuff by index from it quite a lot. I know that 1D arrays are faster than multi-dimensional arrays (for reasons I cant remember :P ). Even though this may not be necessary, I want as good performance as possible :)

推荐答案

算法大致相同.如果你有一个 3D 数组 Original[HEIGHT, WIDTH, DEPTH] 那么你可以把它变成 Flat[HEIGHT * WIDTH * DEPTH] by

The algorithm is mostly the same. If you have a 3D array Original[HEIGHT, WIDTH, DEPTH] then you could turn it into Flat[HEIGHT * WIDTH * DEPTH] by

Flat[x + WIDTH * (y + DEPTH * z)] = Original[x, y, z]

顺便说一句,在 .NET 中,您应该更喜欢数组数组而不是多维数组.性能差异显着

As an aside, you should prefer arrays of arrays over multi-dimensional arrays in .NET. The performance differences are significant

这篇关于如何“压平"或“索引"1D 阵列中的 3D 阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆