Golang渲染立方体时遇到问题如何解决
Golang渲染立方体时遇到问题如何解决 我有一个单元格生成函数,但似乎无法实现让坐标 (0,0) 显示在左上角的功能。目前 (0,0) 位于左下角。这段代码最初来源于这个 OpenGL 教程。
func newCell(x, y int) *Cell {
points := make([]float32, len(square), len(square))
copy(points, square)
for i := 0; i < len(points); i++ {
var position float32
var size float32
switch i % 3 {
case 0:
size = 2.0 / float32(columns)
position = float32(x) * size
case 1:
size = 2.0 / float32(rows)
position = float32(y) * size
default:
continue
}
if points[i] < 0 {
points[i] = position - 1
} else {
points[i] = position + size - 1
}
}
return &Cell{
obj: makeVao(points),
x: x,
y: y,
state: false,
}
}
更多关于Golang渲染立方体时遇到问题如何解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于Golang渲染立方体时遇到问题如何解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
要解决坐标 (0,0) 从左下角移动到左上角的问题,需要修改顶点坐标的 Y 轴计算方式。在 OpenGL 的标准化设备坐标中,Y 轴正方向向上,而屏幕坐标系通常 Y 轴正方向向下。可以通过反转 Y 坐标来实现这一转换。
以下是修改后的代码示例:
func newCell(x, y int) *Cell {
points := make([]float32, len(square))
copy(points, square)
for i := 0; i < len(points); i++ {
var position float32
var size float32
switch i % 3 {
case 0:
size = 2.0 / float32(columns)
position = float32(x) * size
case 1:
size = 2.0 / float32(rows)
// 反转 Y 坐标:将 y 替换为 (rows - 1 - y)
position = float32(rows - 1 - y) * size
default:
continue
}
if points[i] < 0 {
points[i] = position - 1
} else {
points[i] = position + size - 1
}
}
return &Cell{
obj: makeVao(points),
x: x,
y: y,
state: false,
}
}
关键修改在 case 1 部分:将 position = float32(y) * size 替换为 position = float32(rows - 1 - y) * size。这样,当 y=0 时,计算出的位置对应于顶部行;当 y=rows-1 时,对应于底部行,从而将 (0,0) 映射到左上角。
如果原始坐标系中单元格按行从下到上索引,此修改会反转 Y 轴方向,使顶部行对应较小的 y 值。确保 rows 变量正确表示网格中的总行数。

