当前位置: 代码迷 >> 综合 >> [Java] [OpenGL ES3.2] 正多边形
  详细解决方案

[Java] [OpenGL ES3.2] 正多边形

热度:56   发布时间:2023-11-27 16:57:13.0

代码

RegularPolygon.java

package com.Diamond.gl04;import android.opengl.GLES32;
import java.nio.FloatBuffer;
import java.util.Random;
import android.util.Log;
import android.renderscript.Float4;public class RegularPolygon extends MyObject {
    public int sideNumber;public float[] vertices;public Float4 color;public RegularPolygon(int sideNum,Float4 col) {
    initVertices(sideNum);color = col;}public RegularPolygon draw(Program program) {
    program.setUniform("u_model",getModelMatrixArray());program.enableVertexAttrib(0,vertices);program.setUniform("u_pure_color",1);program.setUniform("u_color",color);GLES32.glDrawArrays(GLES32.GL_TRIANGLE_FAN,0,sideNumber + 2);return this;}public void initVertices(int sideNum) {
    sideNumber = Math.max(sideNum,3);int vertexNumber = sideNumber + 2;//加上圆心和第一个,不然会缺一角float centralAngle = 360 / sideNumber;//中心角double angleSpan = centralAngle;//每次增加的角度float radius = 0.5f;//半径,直径为1vertices = new float[vertexNumber * 3];int i = 0;//圆心vertices[i++] = 0;vertices[i++] = 0;vertices[i++] = 0;//圆for(double angle = 0;angle <= 360;angle += angleSpan) {
    vertices[i++] = radius * (float)Math.cos(Math.toRadians(angle));vertices[i++] = radius * (float)Math.sin(Math.toRadians(angle));vertices[i++] = 0;}}
}

Circle.java

package com.Diamond.gl04;import android.renderscript.Float4;public class Circle extends RegularPolygon {
    public Circle(Float4 color) {
    super(36,color);}
}

EquilateralTriangle.java

package com.Diamond.gl04;import android.renderscript.Float4;
import android.renderscript.Float3;public class EquilateralTriangle extends RegularPolygon {
    public EquilateralTriangle(Float4 color) {
    super(3,color);setRotate(new Float3(0,0,90));//设置边长为1float sqrt3 = (float)Math.sqrt(3);setScale(2 / sqrt3);}
}

Plane.java

package com.Diamond.gl04;import android.renderscript.Float4;
import android.renderscript.Float3;public class Plane extends RegularPolygon {
    public Plane(Float4 color) {
    super(4,color);setRotate(new Float3(0,0,-45));//设置边长为1float sqrt2 = (float)Math.sqrt(2);setScale(sqrt2);}
}

提示

用GeoGebra生成的
在平面直角坐标系DAC中,点F的坐标应为(AH,FH)
cos∠FAH = AH / AF
sin∠FAH = FH / AF
由此推出AH = cos∠FAH * AF,FH = sin∠FAH * AF
即F(cosα * r,sinα * r)
用GeoGebra生成的

最后生成的正多边形半径为0.5,但是正方形和等边三角形(正三角形)的边长分别为sqrt(2) / 2和是sqrt(3) / 2,所以要乘上sqrt(2)和2 / sqrt(3)

  相关解决方案