Her har du et lille eksempel på, hvordan en containsPoint funktion kunne implementeres:
var Vector = function(x, y) {
this.x = x;
this.y = y;
};
Vector.prototype.set = function(x, y) {
this.x = x;
this.y = y;
};
Vector.prototype.dot = function(other) {
return this.x * other.x + this.y * other.y;
};
var Polygon = function(points) {
this.points = new Array(points.length);
for (i in points) {
this.points[i] = points[i];
}
//These two are used to avoid creating new vectors
//each time containsPoint is called
this.v1 = new Vector(0, 0);
this.v2 = new Vector(0, 0);
};
Polygon.prototype.containsPoint = function(point) {
var p = this.points, p1, p2, i,
v1 = this.v1, v2 = this.v2;
for (i = 0; i < p.length; i++) {
p1 = p[i];
p2 = p[(i + 1) % p.length];
v1.set(-(p2.y - p1.y), p2.x - p1.x);
v2.set(point.x - p2.x, point.y - p2.y);
if (v1.dot(v2) < 0) {
return false;
}
}
return true;
};
//Test
var p = new Polygon([
new Vector(1,1),
new Vector(2,1),
new Vector(2,2),
new Vector(1,2)
]);
var point = new Vector(0, 0);
for (var i = 0; i < 10; i++) {
point.set(Math.random() * 3, Math.random() * 3);
console.log(point, p.containsPoint(point));
}
Punkterne i polygonen SKAL listes i urets retning.
Indlæg senest redigeret d. 26.02.2015 09:33 af Bruger #2695