AS3数组TileMap检查?

时间:2016-11-15 19:03:23

标签: actionscript-3 flash actionscript

我正在创建一个独立城市建筑游戏,我正在尝试编写一个系统,以检查供水是否已在设置瓷砖的4X4内构建。

 var blankMap: Array = [{0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
                       {0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, 
                       {0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, 
                       {0, 0, 0, 2, 0, 0, 2, 0, 0, 2}, 
                       {0, 0, 8, 0, 0, 0, 0, 0, 0, 0}, 
                       {0, 0, 0, 0, 0, 0, 0, 0, 2, 0}, 
                       {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}];

public function checkWater(mY, mX): void {
        // LEFT
        if (blankMap[mY][mX - 1] == 8) {
            trace("resource found left");
        }
        if (blankMap[mY][mX - 2] == 8) {
            trace("resource found left");
        }
        if (blankMap[mY][mX - 3] == 8) {
            trace("resource found left");
        }
        if (blankMap[mY][mX - 4] == 8) {
            trace("resource found left");
        }
}

// RIGHT
if (blankMap[mY][mX + 1] == 8) {
            trace("resource found right");
        }
        if (blankMap[mY][mX + 2] == 8) {
            trace("resource found right");
        }
        if (blankMap[mY][mX + 3] == 8) {
            trace("resource found right");
        }
        if (blankMap[mY][mX + 4] == 8) {
            trace("resource found right");
        }

该系统有效,但仅适用于东,南,西和北。有更简单的方法吗?它只会检查瓷砖1,2,3和4空间是否包含供水....这是瓷砖地图上的数字8。 mY和mX是单击的图块的位置。

任何建议都会很棒。我基本上需要能够检查NUMBER 8的瓦片区域/瓦片地图(4X4最大距离)而不是0,这意味着瓦片是草地。这听起来很容易,我确信它是,我只是无法理解这个数学。谢谢。

1 个答案:

答案 0 :(得分:0)

你的blankMap看起来是invlid - 它应该是一个数组数组?像

private var blankMap:Array = [[0, 0, 0, 0, 0, 1, 0, 0, 0, 0] ...

正如DodgerThud已经提到的那样,你还需要检查坐标是否在你的地图中,否则你将遇到索引越界异常。我会做一个通用的方法,这样你就可以检查是否有任何资源在给定的范围内,否则你需要为所有东西编写自己的函数:

// check if there is a water supply within 3 tiles starting at x = 3, y = 1
var waterSupplyExists:Boolean = checkForResourceWithinReach(3, 1, 8, 3);

// startX is the x coordinate of your tile that was clicked
// startY is the y coordinate of your tile that was clicked
// resource is th eresource to look for (8 = water supply)
// reach is the distance to look for. 3 would mean we look 3 tiles away around your start tile (7x7 square) 
public function checkForResourceWithinReach(startX:int, startY:int, resource:int, reach:int):Boolean
{
    for (var x:int = startX - reach; x < startX + reach + 1; x++)
    {
        for (var y:int = startY - reach; y < startY + reach + 1; y++)
        {
            // check if this coordinate exists and if it has the resource we are looking for
            if (isWithinMap(x, y) && blankMap[y][x] == resource)
            {
                // found the resource
                return true;
            }
        }
    }

    // nothing found
    return false;
}

// check if a x, y coordinate is within the bounds of the map arrays
private function isWithinMap(x:int, y:int):Boolean
{
    return x > 0 && y > 0 && x < blankMap[0].length && y < blankMap.length;
}