Previous Next |

## PolygonsYou can put solid polygons into two different categories: convex and concave, as show in Screenshot. Concave polygons have a part that bulges inward, like a cave. In the code in this chapter, you deal only with convex polygons because concave polygons have some complexities that make things harder than they should be. Of course, any concave polygon can be broken down into a series of convex polygons, so this isn't an issue if you want to simulate concave polygons in your game. ## Screenshot Two types of polygons: convex and concave. A polygon is concave if any part of it bulges inward.Looking at Screenshot, you can tell it's easy to describe a polygon mathematically: Polygons are just a series of points, or vertices. Polygons appear solid only once they are drawn on the screen. So, you start by creating the ## Listing 7.3 Polygon3D.javapackage com.brackeen.javagamebook.math3D; /** The Polygon3D class represents a polygon as a series of vertices. */ public class Polygon3D { private Vector3D[] v; private int numVertices; /** Creates an empty polygon that can be used as a "scratch" polygon for transforms, projections, etc. */ public Polygon3D() { numVertices = 0; v = new Vector3D[0]; } /** Creates a new Polygon3D with the specified vertices. */ public Polygon3D(Vector3D v0, Vector3D v1, Vector3D v2) { this(new Vector3D[] { v0, v1, v2 }); } /** Creates a new Polygon3D with the specified vertices. All the vertices are assumed to be in the same plane. */ public Polygon3D(Vector3D v0, Vector3D v1, Vector3D v2, Vector3D v3) { this(new Vector3D[] { v0, v1, v2, v3 }); } /** Creates a new Polygon3D with the specified vertices. All the vertices are assumed to be in the same plane. */ public Polygon3D(Vector3D[] vertices) { this.v = vertices; numVertices = vertices.length; } /** Sets this polygon to the same vertices as the specified polygon. */ public void setTo(Polygon3D polygon) { numVertices = polygon.numVertices; ensureCapacity(numVertices); for (int i=0; i<numVertices; i++) { v[i].setTo(polygon.v[i]); } } /** Ensures this polygon has enough capacity to hold the specified number of vertices. */ protected void ensureCapacity(int length) { if (v.length < length) { Vector3D[] newV = new Vector3D[length]; System.arraycopy(v,0,newV,0,v.length); for (int i=v.length; i<newV.length; i++) { newV[i] = new Vector3D(); } v = newV; } } /** Gets the number of vertices this polygon has. */ public int getNumVertices() { return numVertices; } /** Gets the vertex at the specified index. */ public Vector3D getVertex(int index) { return v[index]; } /** Projects this polygon onto the view window. */ public void project(ViewWindow view) { for (int i=0; i<numVertices; i++) { view.project(v[i]); } } } The |

Previous Next |