我需要一种方法来将自定义3D多边形围绕它的位置(质心)居中。我制作了一个获取质心的方法,但我需要一种方法将多边形移动到指定的质心。
我想这样做,所以PerspectiveProjection类只需要投射1个Vector3(位置)而不是所有多边形的结。
Polygon3D类:
public class Polygon3D extends Colored implements Shape {
private List<Vector3> knots;
// Position = center of polygon.
private Vector3 position;
private Polygon poly;
public Polygon3D() {
this(new ArrayList<Vector3>());
}
public Polygon3D(List<Vector3> knots) {
this(knots, new Vector3());
}
public Polygon3D(List<Vector3> knots, Vector3 position) {
this(knots, position, Color.GRAY);
}
public Polygon3D(List<Vector3> knots, Vector3 position, Color color) {
this.knots = knots;
setColor(color);
this.position = position;
ShapeManager.registerShape(this);
this.poly = toPolygon();
}
public List<Vector3> getKnots() {
return this.knots;
}
public void setKnots(List<Vector3> knots) {
this.knots = knots;
this.poly = toPolygon();
}
public void addKnot(Vector3 knot) {
if (this.knots.contains(knot))
return;
this.knots.add(knot);
this.poly = toPolygon();
}
public void removeKnot(Vector3 knot) {
this.knots.remove(knot);
this.poly = toPolygon();
}
public Vector3 getPosition() {
return this.position;
}
public void setPosition(Vector3 position) {
this.position = position;
}
public Vector3 getCentroid() {
double centroidX = 0, centroidY = 0, centroidZ = 0;
for (Vector3 knot : this.knots) {
centroidX += knot.getX();
centroidY += knot.getY();
centroidZ += knot.getZ();
}
return new Vector3(centroidX / this.knots.size(), centroidY / this.knots.size(),
centroidZ / this.knots.size());
}
public List<Vector2> get2DKnots() {
List<Vector2> knots = new ArrayList<>();
Camera camera = PaintPanel.mainCamera;
Projection3D project = camera.getProjection();
OrthographicProjection op = null;
PerspectiveProjection pp = null;
if (project instanceof OrthographicProjection)
op = (OrthographicProjection) project;
else
pp = (PerspectiveProjection) project;
// Get knots from orthographic projection
if (op != null) {
for (Vector3 knot : this.knots) {
knots.add(op.project(knot, new Vector3(1, 1, 1), new Vector3(0, 0, 0)));
}
}
// Get knots from perspective projection
else {
for (Vector3 knot : this.knots) {
knots.add(pp.project(knot, camera));
}
}
return knots;
}
public Polygon toPolygon() {
// Converts all the 3D knots to 2D points on the screen and adds them to a new polygon.
Polygon poly = new Polygon();
for (Vector2 vec : get2DKnots()) {
poly.addPoint(vec.toPoint().x, vec.toPoint().y);
}
return poly;
}
public void draw(Graphics g) {
g.setColor(Color.BLACK);
g.drawPolygon(this.poly);
g.setColor(getColor());
g.fillPolygon(this.poly);
}
}
(顺便说一下,我在8年级:p)