2022-12-06 01:28:15 +00:00

94 lines
2.2 KiB
C#

using Godot;
using System;
public class WorldGrid : Node2D
{
[Export]
private PackedScene TileScene { get; set; }
[Export]
public int Size { get; set; }
[Export]
public int CellSize { get; set; }
private struct Tile
{
public float data;
public ShaderMaterial material;
}
private Tile[,] _tiles;
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
GenerateGrid(Size);
}
public override void _Process(float delta)
{
base._Process(delta);
for (int x = 0; x < Size; x++)
{
for (int y = 0; y < Size; y++)
{
var tile = _tiles[x, y];
var material = tile.material;
material.SetShaderParam("c", tile.data);
}
}
}
public void GetGridPos(Vector2 position, out int x, out int y)
{
int GetCoord(float f) =>
Mathf.Clamp(Mathf.FloorToInt(f / CellSize), 0, CellSize -1);
x = GetCoord(position.x);
y = GetCoord(position.y);
}
private void Clear()
{
_tiles = null;
int children = this.GetChildCount();
GD.Print(children);
for (int i = 0; i < children; i++)
{
var child = this.GetChild(i);
child.QueueFree();
}
}
private void GenerateGrid(int size)
{
this.Clear();
_tiles = new Tile[size, size];
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
var tile = new Tile();
tile.data = (float)(y * size + x) / 100f;
var node = TileScene.Instance<Node2D>();
this.AddChild(node);
var position = new Vector2
{
x = (x + .5f) * CellSize,
y = (y + .5f) * CellSize
};
node.Position = position;
var canvasItem = (CanvasItem)node;
tile.material = (ShaderMaterial)canvasItem.Material;
_tiles[x, y] = tile;
}
}
}
}