Godot 3.4新手无法生成棋盘:方块重叠显示异常求助
问题分析与解决
1. 颜色交替逻辑错误
当前代码每生成一个方块就翻转isLight,但国际象棋棋盘的规则是每行的颜色起始与上一行相反。当前逻辑仅在单行内交替颜色,换行后未额外翻转状态,最终导致所有浅色方块位置重叠、深色方块位置重叠,出现“两个大区块”的现象。
正确的颜色判断应基于行号与列号的和:当(x + y) % 2 == 0时使用浅色材质,否则使用深色材质,无需维护额外的状态变量。
2. 方块位置计算错误
原代码的Translate计算逻辑混乱,导致同色方块的位置完全重叠,出现闪烁问题。正确的位置计算应让每个方块在x/z轴上按行列均匀分布,比如每个方块占据1单位空间,可通过偏移值让棋盘居中在原点。
修改后的完整代码
using Godot; using System; public class TileSpawner : Spatial { [Export] private readonly Material lightSquare; [Export] private readonly Material darkSquare; public override void _Ready() { for (int y = 0; y < 8; y++) { for (int x = 0; x < 8; x++) { AddChild(MakeTile(x, y)); } } } private MeshInstance MakeTile(int x, int y) { MeshInstance mesh = new MeshInstance() { Mesh = new CubeMesh() { Material = (x + y) % 2 == 0 ? lightSquare : darkSquare } }; // -3.5f 让棋盘居中在原点,每个方块按行列均匀分布 mesh.Transform = new Transform(Basis.Identity, new Vector3(x - 3.5f, 0, y - 3.5f)); mesh.Scale = new Vector3(1.0f, 0.2f, 1.0f); return mesh; } }
额外说明
- 使用
Transform直接设置位置比多次Translate更直观,避免累积偏移错误 - 去掉冗余的
Vector2 coordinates变量,直接传入行列索引更清晰 - 基于
x+y的颜色判断逻辑完全符合国际象棋棋盘的交替规则,不会出现跨行后的颜色错误
内容的提问来源于stack exchange,提问作者Kroco Dail
相关产品推荐
相关产品推荐

