我想用libgdx绘制一些(填充的)多边形用于Android游戏.它不应该充满图形/纹理.我只有多边形(闭合路径)的顶点,并试图与网格的可视化,但在某些时候,这不是最好的解决办法,我想.
我的矩形代码是:
private Mesh mesh;
@Override
public void create() {
if (mesh == null) {
mesh = new Mesh(true, 4, 0,
new VertexAttribute(Usage.Position, 3, "a_position")
);
mesh.setVertices(new float[] { -0.5f, -0.5f, 0
0.5f, -0.5f, 0,
-0.5f, 0.5f, 0,
0.5f, 0.5f, 0 });
}
}
...
@Override
public void render() {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
mesh.render(GL10.GL_TRIANGLE_STRIP, 0, 4);
}
Run Code Online (Sandbox Code Playgroud)
是否有一个函数或东西以更简单的方式绘制填充多边形?
Mik*_*yer 26
自从最近更新LibGDX以来,@ Rus的答案正在使用已弃用的函数.但是,我将为他/她提供以下新版本的学分:
PolygonSprite poly;
PolygonSpriteBatch polyBatch = new PolygonSpriteBatch(); // To assign at the beginning
Texture textureSolid;
// Creating the color filling (but textures would work the same way)
Pixmap pix = new Pixmap(1, 1, Pixmap.Format.RGBA8888);
pix.setColor(0xDEADBEFF); // DE is red, AD is green and BE is blue.
pix.fill();
textureSolid = new Texture(pix);
PolygonRegion polyReg = new PolygonRegion(new TextureRegion(textureSolid),
new float[] { // Four vertices
0, 0, // Vertex 0 3--2
100, 0, // Vertex 1 | /|
100, 100, // Vertex 2 |/ |
0, 100 // Vertex 3 0--1
}, new short[] {
0, 1, 2, // Two triangles using vertex indices.
0, 2, 3 // Take care of the counter-clockwise direction.
});
poly = new PolygonSprite(polyReg);
poly.setOrigin(a, b);
polyBatch = new PolygonSpriteBatch();
Run Code Online (Sandbox Code Playgroud)
对于良好的三角测量算法,如果多边形不是凸面,请参阅Toussaint(1991)的几乎线性的咬合算法
Rus*_*lan 10
这是一个绘制2D凹多边形的LIBGDX示例.
//为PolygonSprite PolygonSpriteBatch定义类成员
PolygonSprite poly;
PolygonSpriteBatch polyBatch;
Texture textureSolid;
Run Code Online (Sandbox Code Playgroud)
//创建实例,1x1大小纹理与红色像素一起使用作为变通方法,(x,y)用于初始化poly的coords数组
ctor() {
textureSolid = makeTextureBox(1, 0xFFFF0000, 0, 0);
float a = 100;
float b = 100;
PolygonRegion polyReg = new PolygonRegion(new TextureRegion(textureSolid),
new float[] {
a*0, b*0,
a*0, b*2,
a*3, b*2,
a*3, b*0,
a*2, b*0,
a*2, b*1,
a*1, b*1,
a*1, b*0,
});
poly = new PolygonSprite(polyReg);
poly.setOrigin(a, b);
polyBatch = new PolygonSpriteBatch();
}
Run Code Online (Sandbox Code Playgroud)
//绘制并旋转多边形
void draw() {
super.draw();
polyBatch.begin();
poly.draw(polyBatch);
polyBatch.end();
poly.rotate(1.1f);
}
Run Code Online (Sandbox Code Playgroud)