簡體   English   中英

在基於網格的游戲中放置牆壁/道路

[英]Placing walls/roads in a grid-based game

我正在制作一個基於網格的游戲。

在這個游戲中你可以放置建築物、牆壁、道路。

當某物被放置在網格中時,我將單元格 id 設置為該對象 id。 到目前為止一切順利,這一切都有效。

當我需要對我的牆壁/道路(通過拖動鼠標放置)進行位掩碼時,我的問題就出現了。

目前我進行位掩碼的方式是檢查所有相鄰cells是否匹配,並相應地設置正確的模型。 即,如果西部和北部匹配,我會創建一個彎曲。

當我將牆壁放在已被占用的cells頂部時,我的問題就出現了。 我仍然想以圖形方式顯示牆(着色為紅色),但我不能覆蓋該cell當前的內容。

這意味着我的位掩碼不起作用,因為牆不在實際grid ,它僅在世界空間中。

牆壁將單元格設置為id 0 ,房屋將單元格設置為id 1 我無法覆蓋房屋單元中的 id,因此位掩碼(正確)最終會破壞。

如何管理這樣的場景?

細胞:

public class Cell
{
    public int x, z;
    public int id;
    public GameObject go
}

您可以將圖層添加到網格,並僅合並同一圖層上的單元格。

  • 道路與道路匯合。
  • 牆與牆合並。

如果您想避免重疊單元格,請檢查任何其他圖層中是否已存在某些內容。 從其他層查找值也將允許您交叉合並單元格,盡管它增加了很多復雜性。

這是一些偽代碼:

enum Layer {
  Building,
  Wall,
  Road
}

struct Point {
  int x,y;
}

class Cell {
  Point point;
  int value;
}

class Cells {
  Dictionary<Point, Cell> cells; // mapping position to the cell object

  Cells(int width, int height) {
    for x in width
      for y in height
        Point point = new Point(x,y);
        cells.Add(point, new Cell(point, default))
  }

  Cell Get(Point point) => cells[point];
}

class Grid {
  Dictionary<Layer, Cells> layers; // mapping the layer enum to the cells group object

  Grid(int width, int height) {
    foreach layer in Layer
      layers.Add(layer, new Cells(width, height));
  }

  Cells GetLayer(Layer layer) {
    return layers[layer]
  }

  int GetValue(Point point, Layer layer) {
    return GetLayer(layer).Get(point).value;
  }

  bool IsValueInAllLayers(Point point, int value) {
    foreach layer in Layers
      if layer.Get(point).value != value
        return false;
    return true;
  }
}

// program entry point
void Main() {
  // construct a 10x10 grid
  Grid grid = new Grid(10, 10);

  Point mousePoint = new Point(2,2);

  // to place a building all layers have to be empty (0)
  if(grid.IsValueInAllLayers(mousePoint, 0)) {
    grid.SetValue(mousePoint, Layer.Building);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM