How can I move a polygon edge 1 unit away from the center?
Posted
by
Stephen
on Game Development
See other posts from Game Development
or by Stephen
Published on 2012-07-06T19:12:24Z
Indexed on
2012/07/06
21:25 UTC
Read the original article
Hit count: 385
Let's say I have a polygon class that is represented by a list of vector classes as vertices, like so:
var Vector = function(x, y) { this.x = x; this.y = y; },
Polygon = function(vectors) { this.vertices = vectors; };
Now I make a polygon (in this case, a square) like so:
var poly = new Polygon([
new Vector(2, 2),
new Vector(5, 2),
new Vector(5, 5),
new Vector(2, 5)
]);
So, the top edge would be [poly.vertices[0], poly.vertices[1]]
.
I need to stretch this polygon by moving each edge away from the center of the polygon by one unit, along that edge's normal. The following example shows the first edge, the top, moved one unit up:
The final polygon should look like this new one:
var finalPoly = new Polygon([
new Vector(1, 1),
new Vector(6, 1),
new Vector(6, 6),
new Vector(1, 6)
]);
It is important that I iterate, moving one edge at a time, because I will be doing some collision tests after moving each edge.
Here is what I tried so far (simplified for clarity), which fails triumphantly:
for(var i = 0; i < vertices.length; i++) {
var a = vertices[i],
b = vertices[i + 1] || vertices[0]; // in case of final vertex
var ax = a.x,
ay = a.y,
bx = b.x,
by = b.y;
// get some new perpendicular vectors
var a2 = new Vector(-ay, ax),
b2 = new Vector(-by, bx);
// make into unit vectors
a2.convertToUnitVector();
b2.convertToUnitVector();
// add the new vectors to the original ones
a.add(a2);
b.add(b2);
// the rest of the code, collision tests, etc.
}
This makes my polygon start slowly rotating and sliding to the left, instead of what I need.
Finally, the example shows a square, but the polygons in question could be anything. They will always be convex, and always with vertices in clockwise order.
© Game Development or respective owner