说明
在Canvas下生成。
需配置相邻格子的间距,地图的位置(中央位置的坐标)
传入格子地图的宽、高。
外界可传入格子id(x,y),获取该格子在格子地图中的位置。
使用grid标识各格子的位置(实际如果不用可隐藏或直接不创建)


代码
GridMapView.ts
import { _decorator, Component, Node, Vec3, instantiate, CurveRange, GbufferStage, CCFloat, randomRangeInt } from 'cc';
const { ccclass, property } = _decorator;
// 在Canvas下生成格子地图
@ccclass('GridMapView')
export class GridMapView extends Component
{
@property({type:CCFloat, visible:true, displayName:'格子间距'})
private _gridInterval: number = 100;
@property({ type: Node, visible: true, displayName: '地图中点位置' })
private _centerNode: Node;
private _curW: number;
public get curW(): number { return this._curW; }
private _curH: number;
public get curH(): number { return this._curH; }
@property({ type: Node, visible: true, displayName: '格子背景模板' })
private _gridTemplateNode: Node;
private _grids: Node[];
private _originalPos: Vec3;
start()
{
this.init();
this.createGripMap(randomRangeInt(2, 6), randomRangeInt(2, 6));
}
onDestroy()
{
this.myDestroy();
}
private init(): void
{
this._gridTemplateNode.active = false;
this._grids = new Array<Node>();
}
private myDestroy(): void
{
this.clearGrids();
this._grids = null;
}
// 生成x*y的格子地图
public createGripMap(w: number, h: number): void
{
this.clearGrids();
this._curW = w;
this._curH = h;
this._originalPos = new Vec3(
this._centerNode.getWorldPosition().x - ((this._curW - 1) / 2) * this._gridInterval,
this._centerNode.getWorldPosition().y - ((this._curH - 1) / 2) * this._gridInterval,
this._centerNode.getWorldPosition().z);
for (let x = 0; x < this._curW; x++)
{
for (let y = 0; y < this._curH; y++)
{
const curGrid = instantiate(this._gridTemplateNode);
curGrid.setParent(this._gridTemplateNode.parent);
curGrid.setWorldPosition(this.getPos(x, y));
curGrid.active = true;
curGrid.name = `grid_${x}_${y}`;
this._grids.push(curGrid);
}
}
}
public getPos(x: number, y: number): Vec3
{
return new Vec3(this._originalPos.x + x * this._gridInterval,
this._originalPos.y + y * this._gridInterval,
this._originalPos.z);
}
private clearGrids(): void
{
for (const g of this._grids)
{
g.destroy();
}
this._grids.splice(0, this._grids.length);
}
}
网友评论