1

目前,我在 3 维笛卡尔坐标系中有一个顶点数组列表。多边形是随机的。它可以是汽车、杯子甚至是龙。

假设密度不变,如何计算这个 3D 物体的质心 (x,y,z)?

我将面和顶点存储在 ArrayList 中。

public ArrayList<stlFace> StlFaces = new ArrayList<stlFace>();
public ArrayList<VertexGeometric> VertexList = new ArrayList<VertexGeometric>();
4

1 回答 1

1

我用来计算与每个面或三角形的质量成正比的表面。并计算每个三角形的质量中心和我使用的整个物体的质量中心。我在 Face 类中添加了辅助方法 getCenter() 和 getSurface() 来封装特定于一个面/三角形的计算。

public static class Vertex {

    public float x = 0;
    public float y = 0;
    public float z = 0;

    public Vertex(float x, float y, float z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}

public static class Face {

    public Vertex v1;
    public Vertex v2;
    public Vertex v3;

    public Face(Vertex v1, Vertex v2, Vertex v3) {
        this.v1 = v1;
        this.v2 = v2;
        this.v3 = v3;
    }

    public Vertex getCenter() {
        Vertex triangleCenter = new Vertex(0, 0, 0);
        triangleCenter.x += v1.x;
        triangleCenter.x += v2.x;
        triangleCenter.x += v3.x;
        triangleCenter.y += v1.y;
        triangleCenter.y += v2.y;
        triangleCenter.y += v3.y;
        triangleCenter.z += v1.z;
        triangleCenter.z += v2.z;
        triangleCenter.z += v3.z;
        triangleCenter.x /= 3;
        triangleCenter.y /= 3;
        triangleCenter.z /= 3;
        return triangleCenter;
    }

    public float getSurface() {
        float x1 = v1.x - v2.x;
        float x2 = v1.y - v2.y;
        float x3 = v1.z - v2.z;
        float y1 = v1.x - v3.x;
        float y2 = v1.y - v3.y;
        float y3 = v1.z - v3.z;
        return (float) Math.sqrt(
                Math.pow(x2 * y3 - x3 * y2, 2) + 
                Math.pow(x3 * y1 - x1 * y3, 2) + 
                Math.pow(x1 * y2 - x2 * y1, 2)
            ) / 2f;
    }
}

public static Vertex calculateMassCenter(List<Face> faces) {
    Vertex massCenter = new Vertex(0, 0, 0);
    float mass = 0;
    for (Face face : faces) {
        Vertex triangleCenter = face.getCenter();
        float faceMass = face.getSurface();
        mass += faceMass;
        massCenter.x += faceMass * triangleCenter.x;
        massCenter.y += faceMass * triangleCenter.y;
        massCenter.z += faceMass * triangleCenter.z;
    }
    massCenter.x /= mass;
    massCenter.y /= mass;
    massCenter.z /= mass;
    return massCenter;
}
于 2015-01-06T11:23:17.890 回答