Skip to content

Instantly share code, notes, and snippets.

@kyktommy
Last active December 29, 2015 14:49
Show Gist options
  • Save kyktommy/7686971 to your computer and use it in GitHub Desktop.
Save kyktommy/7686971 to your computer and use it in GitHub Desktop.
cocos2d-html5 point in polygon
var H = Helper = {
pointInPolyon: function (n, vertices, touch) {
var i, j, c = false;
for (i = 0, j = n - 1; i < n; j = i++) {
if (((vertices[i].y > touch.y) != (vertices[j].y > touch.y)) &&
(touch.x < (vertices[j].x - vertices[i].x) * (touch.y - vertices[i].y) / (vertices[j].y - vertices[i].y) + vertices[i].x )) {
c = !c;
}
}
return c;
}
};
// Create sprite and vertices
var sprite1 = cc.Sprite.createWithSpriteFrameName('pyramid.png');
sprite1.setPosition(c.pp(200,200));
var vertices = [
[0, 1],
[0.5, 0],
[1, 1]
];
sprite1.setRelativeVertices(vertices);
// Layer Touch event
onTouchBegan: function (touch) {
var children = this.getChildren();
children.forEach(function (child) {
var touchPoint = touch.getLocation();
var rect = child.getBoundingBox();
if (cc.rectContainsPoint(rect, touchPoint)) {
if (child.isTouchableAtPoint(touchPoint)) {
child.setPosition(cc.p(H.random(320), H.random(480)));
console.log('touch ' + child.toString() + ' ' + new Date());
child.updateVertices();
}
}
});
},
// Usage: set vertices like: [ [0,0], [0.5, 0.5], [1,0] ]
// Generate vertices: [ cc.p(0,0), cc.p(50,50), cc.p(100,0) ]
cc.Sprite.prototype.setRelativeVertices = function (vertices) {
this._relativeVertices = vertices;
this.updateVertices();
};
// Usage: call this to update vertices when the position is changed
cc.Sprite.prototype.updateVertices = function () {
var vertices = this._relativeVertices;
this._vertices = new Array(vertices.length);
var rect = this.getBoundingBox();
for (var i = 0; i < vertices.length; ++i) {
var arr = vertices[i];
var x = arr[0] * rect.width + rect.origin.x;
var y = arr[1] * rect.height + rect.origin.y;
this._vertices[i] = cc.p(x, y);
}
};
// Usage: check whether touch point in polygon
cc.Sprite.prototype.isTouchableAtPoint = function (touch) {
if (!this._vertices) { throw "no vertices"; }
return H.pointInPolyon(this._vertices.length, this._vertices, touch);
};
@TheSean
Copy link

TheSean commented Apr 9, 2014

Thanks for sharing this, much appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment