Merge pull request #637 from 2youyouo2/collider

Collider
This commit is contained in:
Jare Guo
2016-04-29 16:19:08 +08:00
13 changed files with 1347 additions and 0 deletions
+23
View File
@@ -170,6 +170,15 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
this._animationManager = null;
}
// collision manager
if (cc.CollisionManager) {
this._collisionManager = new cc.CollisionManager();
this._scheduler.scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false);
}
else {
this._collisionManager = null;
}
// WidgetManager
cc._widgetManager.init(this);
},
@@ -451,6 +460,11 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
this._scheduler.scheduleUpdate(this._animationManager, cc.Scheduler.PRIORITY_SYSTEM, false);
}
// Collider manager
if (this._collisionManager) {
this._scheduler.scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false);
}
this.startAnimation();
},
@@ -1071,6 +1085,15 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
return this._animationManager;
},
/**
* Returns the cc.CollisionManager associated with this director.
* @method getCollisionManager
* @return {CollisionManager}
*/
getCollisionManager: function () {
return this._collisionManager;
},
/**
* Returns the delta time since last frame.
* @method getDeltaTime
+79
View File
@@ -0,0 +1,79 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Chukong Aipu reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* !#en Box Collider.
* !#zh 包围盒碰撞组件
* @class BoxCollider
* @extends Component
*/
var BoxCollider = cc.Class({
name: 'cc.BoxCollider',
extends: cc.Collider,
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.collider/Box Collider',
},
properties: {
_offset: cc.v2(0, 0),
_size: cc.size(100, 100),
/**
* !#en Position offset
* !#zh 位置偏移量
* @property offset
* @type {Vec2}
*/
offset: {
get: function () {
return this._offset;
},
set: function (value) {
this._offset = value;
},
type: cc.Vec2
},
/**
* !#en Box size
* !#zh 包围盒大小
* @property size
* @type {Size}
*/
size: {
get: function () {
return this._size;
},
set: function (value) {
this._size.width = value.width < 0 ? 0 : value.width;
this._size.height = value.height < 0 ? 0 : value.height;
},
type: cc.Size
}
}
});
cc.BoxCollider = module.exports = BoxCollider;
+77
View File
@@ -0,0 +1,77 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Chukong Aipu reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* !#en Circle Collider.
* !#zh 圆形碰撞组件
* @class CircleCollider
* @extends Component
*/
var CircleCollider = cc.Class({
name: 'cc.CircleCollider',
extends: require('./CCCollider'),
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.collider/Circle Collider',
},
properties: {
_offset: cc.v2(0, 0),
_radius: 50,
/**
* !#en Position offset
* !#zh 位置偏移量
* @property offset
* @type {Vec2}
*/
offset: {
get: function () {
return this._offset;
},
set: function (value) {
this._offset = value;
},
type: cc.Vec2
},
/**
* !#en Circle radius
* !#zh 圆形半径
* @property radius
* @type {Number}
*/
radius: {
get: function () {
return this._radius;
},
set: function (value) {
this._radius = value < 0 ? 0 : value;
}
}
}
});
cc.CircleCollider = module.exports = CircleCollider;
+121
View File
@@ -0,0 +1,121 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Chukong Aipu reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* !#en Collider component base class.
* !#zh 碰撞组件基类
* @class Collider
* @extends Component
*/
var Collider = cc.Class({
name: 'cc.Collider',
extends: cc.Component,
editor: CC_EDITOR && {
executeInEditMode: true
},
properties: {
_category: {
default: 1,
type: cc.Integer
},
_mask: {
default: 65535,
type: cc.Integer
},
editing: {
default: false,
serializable: false,
tooltip: 'i18n:COMPONENT.collider.editing'
},
/**
* !#en Collider component category.
* !#zh 碰撞组件所属类别
* @property category
* @type {Integer}
* @default 1
*/
category: {
get: function () {
return this._category;
},
set: function (value) {
if (!CC_EDITOR) {
cc.director.getCollisionManager().removeCollider(this);
}
this._category = value;
if (!CC_EDITOR) {
cc.director.getCollisionManager().addCollider(this);
}
},
range: [0, 65535],
type: cc.Integer,
tooltip: 'i18n:COMPONENT.collider.category'
},
/**
* !#en The collider mask can collide with this collider.
* !#zh 可以与碰撞组件相碰撞的组件掩码
* @property mask
* @type {Integer}
* @default 65535
*/
mask: {
get: function () {
return this._mask;
},
set: function (value) {
if (!CC_EDITOR) {
cc.director.getCollisionManager().removeCollider(this);
}
this._mask = value;
if (!CC_EDITOR) {
cc.director.getCollisionManager().addCollider(this);
}
},
range: [0, 65535],
type: cc.Integer,
tooltip: 'i18n:COMPONENT.collider.mask'
}
},
onDisable: function () {
cc.director.getCollisionManager().removeCollider(this);
},
onEnable: function () {
cc.director.getCollisionManager().addCollider(this);
}
});
cc.Collider = module.exports = Collider;
+395
View File
@@ -0,0 +1,395 @@
var Contact = require('./CCContact');
var CollisionType = Contact.CollisionType;
/**
* !#en
* A simple collision manager class.
* It will calculate whether the collider collides other colliders, if collides then call the callbacks.
* !#zh
* 一个简单的碰撞组件管理类,用于处理节点之间的碰撞组件是否产生了碰撞,并调用相应回调函数。
*
* @class ColliderManager
* @example
*
* // Get the collider manager.
* var manager = cc.director.getCollisionManager();
*
* // Enabled the colider manager.
* manager.enabled = true;
*
* // Enabled draw collider
* manager.enabledDebugDraw = true;
*
* // Enabled draw collider bounding box
* manager.enabledDrawBoundingBox = true;
*
*
* // Collider callback
* onCollisionEnter: function (other, self) {
* this.node.color = cc.Color.RED;
* this.touchingNumber ++;
*
* // var world = self.world;
* // var aabb = world.aabb;
* // var preAabb = world.preAabb;
* // var t = world.transform;
*
* // for circle collider
* // var r = world.radius;
* // var p = world.position;
*
* // for box collider and polygon collider
* // var ps = world.points;
* },
*
* onCollisionStay: function (other, self) {
* console.log('on collision stay');
* },
*
* onCollisionExit: function (other, self) {
* this.touchingNumber --;
* if (this.touchingNumber === 0) {
* this.node.color = cc.Color.WHITE;
* }
* }
});
*
*/
var CollisionManager = cc.Class({
mixins: [cc.EventTarget],
properties: {
/**
* !#en
* !#zh
* 是否开启碰撞管理,默认为不开启
* @property {Boolean} enabled
* @default false
*/
enabled: false,
/**
* !#en
* !#zh
* 是否绘制碰撞组件的包围盒,默认为不绘制
* @property {Boolean} enabledDrawBoundingBox
* @default false
*/
enabledDrawBoundingBox: false
},
ctor: function () {
this.__instanceId = cc.ClassManager.getNewInstanceId();
this._contacts = [];
this._colliders = [];
this._updating = false;
this._removeList = [];
this._debugDrawer = null;
this._enabledDebugDraw = false;
},
update: function (dt) {
if (!this.enabled) {
return;
}
this._updating = true;
var i, l;
// update collider
var colliders = this._colliders;
for (i = 0, l = colliders.length; i < l; i++) {
this.updateCollider(colliders[i]);
}
// do collide
var contacts = this._contacts;
for (i = 0, l = contacts.length; i < l; i++) {
this.collide(contacts[i]);
}
// do remove collider
var removeList = this._removeList;
for (i = 0, l = removeList.length; i < l; i++) {
this.removeCollider( removeList[i] );
}
removeList.length = 0;
// draw colliders
this.drawColliders();
this._updating = false;
},
collide: function (contact) {
var collisionType = contact.updateState();
if (collisionType === CollisionType.None) {
return;
}
this._doCollide(collisionType, contact);
},
_doCollide: function (collisionType, contact) {
var contactFunc;
switch (collisionType) {
case CollisionType.CollisionEnter:
contactFunc = 'onCollisionEnter';
break;
case CollisionType.CollisionStay:
contactFunc = 'onCollisionStay';
break;
case CollisionType.CollisionExit:
contactFunc = 'onCollisionExit';
break;
}
var collider1 = contact.collider1;
var collider2 = contact.collider2;
var comps1 = collider1.node._components;
var comps2 = collider2.node._components;
var i, l, comp;
for (i = 0, l = comps1.length; i < l; i++) {
comp = comps1[i];
if (comp[contactFunc]) {
comp[contactFunc](collider2, collider1);
}
}
for (i = 0, l = comps2.length; i < l; i++) {
comp = comps2[i];
if (comp[contactFunc]) {
comp[contactFunc](collider1, collider2);
}
}
},
shouldCollide: function (c1, c2) {
return c1.node !== c2.node && (c1.mask & c2.category) && (c1.category & c2.mask);
},
initCollider: function (collider) {
if (!collider.world) {
var world = collider.world = {};
world.aabb = cc.rect();
world.preAabb = cc.rect();
world.radius = 0;
if (collider instanceof cc.BoxCollider) {
world.position = null;
world.points = [cc.v2(), cc.v2(), cc.v2(), cc.v2()];
}
else if (collider instanceof cc.PolygonCollider) {
world.position = null;
world.points = collider.points.slice(0, collider.points.length);
}
else if (collider instanceof cc.CircleCollider) {
world.position = cc.v2();
world.points = null;
}
}
},
updateCollider: function (collider) {
var offset = collider.offset;
var world = collider.world;
var aabb = world.aabb;
var t = world.transform = collider.node.getNodeToWorldTransformAR();
var preAabb = world.preAabb;
preAabb.x = aabb.x;
preAabb.y = aabb.y;
preAabb.width = aabb.width;
preAabb.height = aabb.height;
if (collider instanceof cc.BoxCollider) {
var size = collider.size;
var rect = cc.rect(offset.x - size.width/2, offset.y - size.height/2, size.width, size.height);
var wps = world.points;
var wp0 = wps[0];
var wp1 = wps[1];
var wp2 = wps[2];
var wp3 = wps[3];
cc.obbApplyAffineTransform(rect, t, wp0, wp1, wp2, wp3);
var minx = Math.min(wp0.x, wp1.x, wp2.x, wp3.x);
var miny = Math.min(wp0.y, wp1.y, wp2.y, wp3.y);
var maxx = Math.max(wp0.x, wp1.x, wp2.x, wp3.x);
var maxy = Math.max(wp0.y, wp1.y, wp2.y, wp3.y);
aabb.x = minx;
aabb.y = miny;
aabb.width = maxx - minx;
aabb.height = maxy - miny;
}
else if (collider instanceof cc.CircleCollider) {
var p = cc.pointApplyAffineTransform(collider.offset, t);
var tmpX = t.tx, tmpY = t.ty;
t.tx = t.ty = 0;
var tempP = cc.pointApplyAffineTransform(cc.v2(collider.radius, 0), t);
var d = cc.v2(tempP).mag();
world.radius = d;
world.position = cc.v2(p);
t.tx = tmpX;
t.ty = tmpY;
aabb.x = tmpX - d;
aabb.y = tmpY - d;
aabb.width = d * 2;
aabb.height = d * 2;
}
else if (collider instanceof cc.PolygonCollider) {
var points = collider.points;
var worldPoints = world.points;
var minx = 1e6, miny = 1e6, maxx = -1e6, maxy = -1e6;
for (var i = 0, l = points.length; i < l; i++) {
var p = points[i].add(offset);
p = cc.pointApplyAffineTransform(p, t);
worldPoints[i] = p;
if (p.x > maxx) maxx = p.x;
if (p.x < minx) minx = p.x;
if (p.y > maxy) maxy = p.y;
if (p.y < miny) miny = p.y;
}
aabb.x = minx;
aabb.y = miny;
aabb.width = maxx - minx;
aabb.height = maxy - miny;
}
},
addCollider: function (collider) {
var colliders = this._colliders;
var index = colliders.indexOf(collider);
if (index === -1) {
for (var i = 0, l = colliders.length; i < l; i++) {
var other = colliders[i];
if (this.shouldCollide(collider, other)) {
var contact = new Contact(collider, other);
this._contacts.push(contact);
}
}
colliders.push(collider);
this.initCollider(collider);
}
index = this._removeList.indexOf(collider);
if (index !== -1) {
this._removeList.splice(index, 1);
}
},
removeCollider: function (collider) {
var colliders = this._colliders;
var index = colliders.indexOf(collider);
if (index >= 0) {
if (this._updating) {
var removeList = this._removeList;
if (removeList.indexOf(collider) === -1) {
removeList.push(collider);
}
}
else {
colliders.splice(index, 1);
var contacts = this._contacts;
for (var i = contacts.length - 1; i >= 0; i--) {
var contact = contacts[i];
if (contact.collider1 === collider || contact.collider2 === collider) {
if (contact.touching) {
this._doCollide(CollisionType.CollisionExit, contact);
}
contacts.splice(i, 1);
}
}
}
}
else {
cc.error('collider not added or already removed');
}
},
drawColliders: function () {
if (!this._enabledDebugDraw || !this._debugDrawer) {
return;
}
this._debugDrawer.clear();
var colliders = this._colliders;
for (var i = 0, l = colliders.length; i < l; i++) {
var collider = colliders[i];
if (collider instanceof cc.BoxCollider || collider instanceof cc.PolygonCollider) {
this._debugDrawer.drawPoly(collider.world.points);
}
else if (collider instanceof cc.CircleCollider) {
this._debugDrawer.drawCircle(collider.world.position, collider.world.radius, 0, 30);
}
if (this.enabledDrawBoundingBox) {
var aabb = collider.world.aabb;
var points = [cc.v2(aabb.xMin, aabb.yMin), cc.v2(aabb.xMin, aabb.yMax), cc.v2(aabb.xMax, aabb.yMax), cc.v2(aabb.xMax, aabb.yMin)];
this._debugDrawer.drawPoly(points, null, 1, cc.Color.BLUE);
}
}
},
onSceneLaunched: function () {
if (this._enabledDebugDraw && this._debugDrawer) {
this._debugDrawer.removeFromParent();
cc.director.getScene()._sgNode.addChild(this._debugDrawer);
}
}
});
/**
* !#en
* !#zh
* 是否绘制碰撞组件的形状,默认为不绘制
* @property {Boolean} enabledDebugDraw
* @default false
*/
cc.js.getset(CollisionManager.prototype, 'enabledDebugDraw',
function () {
return this._enabledDebugDraw;
},
function (value) {
if (value && !this._enabledDebugDraw) {
if (!this._debugDrawer) {
this._debugDrawer = new cc.DrawNode();
this._debugDrawer.retain();
}
cc.director.getScene()._sgNode.addChild(this._debugDrawer);
cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLaunched, this);
}
else if (!value && this._enabledDebugDraw) {
cc.director.getScene()._sgNode.removeChild(this._debugDrawer);
cc.director.off(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLaunched, this);
}
this._enabledDebugDraw = value;
}
);
cc.CollisionManager = module.exports = CollisionManager;
+84
View File
@@ -0,0 +1,84 @@
var Intersection = require('./CCIntersection');
var CollisionType = cc.Enum({
None: 0,
CollisionEnter: 1,
CollisionStay: 2,
CollisionExit: 3
});
function Contact (collider1, collider2) {
this.collider1 = collider1;
this.collider2 = collider2;
this.touching = false;
var isCollider1Polygon = (collider1 instanceof cc.BoxCollider) || (collider1 instanceof cc.PolygonCollider);
var isCollider2Polygon = (collider2 instanceof cc.BoxCollider) || (collider2 instanceof cc.PolygonCollider);
var isCollider1Circle = collider1 instanceof cc.CircleCollider;
var isCollider2Circle = collider2 instanceof cc.CircleCollider;
if (isCollider1Polygon && isCollider2Polygon) {
this.testFunc = Intersection.polygonPolygon;
}
else if (isCollider1Circle && isCollider2Circle) {
this.testFunc = Intersection.circleCircle;
}
else if (isCollider1Polygon && isCollider2Circle) {
this.testFunc = Intersection.polygonCircle;
}
else if (isCollider1Circle && isCollider2Polygon) {
this.testFunc = Intersection.polygonCircle;
this.collider1 = collider2;
this.collider2 = collider1;
}
else {
cc.error('Can\'t find testFunc for (%s, $s).', cc.js.getClassName(collider1), cc.js.getClassName(collider2));
}
}
Contact.prototype.test = function () {
var world1 = this.collider1.world;
var world2 = this.collider2.world;
if (!world1.aabb.intersects(world2.aabb)) {
return false;
}
if (this.testFunc === Intersection.polygonPolygon) {
return this.testFunc(world1.points, world2.points);
}
else if (this.testFunc === Intersection.circleCircle) {
return this.testFunc(world1, world2);
}
else if (this.testFunc === Intersection.polygonCircle) {
return this.testFunc(world1.points, world2);
}
return false;
};
Contact.prototype.updateState = function () {
var result = this.test();
var type = CollisionType.None;
if (result && !this.touching) {
this.touching = true;
type = CollisionType.CollisionEnter;
}
else if (result && this.touching) {
type = CollisionType.CollisionStay;
}
else if (!result && this.touching) {
this.touching = false;
type = CollisionType.CollisionExit;
}
return type;
};
Contact.CollisionType = CollisionType;
module.exports = Contact;
+313
View File
@@ -0,0 +1,313 @@
/**
* !#en Intersection helper class
* !#zh 辅助类,用于测试形状与形状是否相交
* @class Intersection
* @static
*/
var Intersection = {};
/**
* @method lineLine
* @param {Vec2} a1
* @param {Vec2} a2
* @param {Vec2} b1
* @param {Vec2} b2
* @return {boolean}
*/
function lineLine ( a1, a2, b1, b2 ) {
// jshint camelcase:false
var ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x);
var ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x);
var u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
if ( u_b !== 0 ) {
var ua = ua_t / u_b;
var ub = ub_t / u_b;
if ( 0 <= ua && ua <= 1 && 0 <= ub && ub <= 1 ) {
return true;
}
}
return false;
}
Intersection.lineLine = lineLine;
/**
* @method lineRect
* @param {Vec2} a1
* @param {Vec2} a2
* @param {Vec2} b
* @return {boolean}
*/
function lineRect ( a1, a2, b ) {
var r0 = new cc.Vec2( b.x, b.y );
var r1 = new cc.Vec2( b.x, b.yMax );
var r2 = new cc.Vec2( b.xMax, b.yMax );
var r3 = new cc.Vec2( b.xMax, b.y );
if ( lineLine( a1, a2, r0, r1 ) )
return true;
if ( lineLine( a1, a2, r1, r2 ) )
return true;
if ( lineLine( a1, a2, r2, r3 ) )
return true;
if ( lineLine( a1, a2, r3, r0 ) )
return true;
return false;
}
Intersection.lineRect = lineRect;
/**
* @method linePolygon
* @param {Vec2} a1
* @param {Vec2} a2
* @param {[Vec2]} b
* @return {boolean}
*/
function linePolygon ( a1, a2, b ) {
var length = b.length;
for ( var i = 0; i < length; ++i ) {
var b1 = b[i];
var b2 = b[(i+1)%length];
if ( lineLine( a1, a2, b1, b2 ) )
return true;
}
return false;
}
Intersection.linePolygon = linePolygon;
/**
* @method rectRect
* @param {Rect} a
* @param {Rect} b
* @return {boolean}
*/
function rectRect ( a, b ) {
// jshint camelcase:false
var a_min_x = a.x;
var a_min_y = a.y;
var a_max_x = a.x + a.width;
var a_max_y = a.y + a.height;
var b_min_x = b.x;
var b_min_y = b.y;
var b_max_x = b.x + b.width;
var b_max_y = b.y + b.height;
return a_min_x <= b_max_x &&
a_max_x >= b_min_x &&
a_min_y <= b_max_y &&
a_max_y >= b_min_y
;
}
Intersection.rectRect = rectRect;
/**
* @method rectPolygon
* @param {Rect} a
* @param {[Vec2]} b
* @return {boolean}
*/
function rectPolygon ( a, b ) {
var i, l;
var r0 = new cc.Vec2( a.x, a.y );
var r1 = new cc.Vec2( a.x, a.yMax );
var r2 = new cc.Vec2( a.xMax, a.yMax );
var r3 = new cc.Vec2( a.xMax, a.y );
// intersection check
if ( linePolygon( r0, r1, b ) )
return true;
if ( linePolygon( r1, r2, b ) )
return true;
if ( linePolygon( r2, r3, b ) )
return true;
if ( linePolygon( r3, r0, b ) )
return true;
// check if a contains b
for ( i = 0, l = b.length; i < l; ++i ) {
if ( pointInPolygon(b[i], a) )
return true;
}
// check if b contains a
if ( pointInPolygon(r0, b) )
return true;
if ( pointInPolygon(r1, b) )
return true;
if ( pointInPolygon(r2, b) )
return true;
if ( pointInPolygon(r3, b) )
return true;
return false;
}
Intersection.rectPolygon = rectPolygon;
/**
* @method polygonPolygon
* @param {[Vec2]} a
* @param {[Vec2]} b
* @return {boolean}
*/
function polygonPolygon ( a, b ) {
var i, l;
// check if a intersects b
for ( i = 0, l = a.length; i < l; ++i ) {
var a1 = a[i];
var a2 = a[(i+1)%l];
if ( linePolygon( a1, a2, b ) )
return true;
}
// check if a contains b
for ( i = 0, l = b.length; i < l; ++i ) {
if ( pointInPolygon(b[i], a) )
return true;
}
// check if b contains a
for ( i = 0, l = a.length; i < l; ++i ) {
if ( pointInPolygon( a[i], b ) )
return true;
}
return false;
}
Intersection.polygonPolygon = polygonPolygon;
/**
* @method pointInPolygon
* @param {Vec2} point
* @param {[Vec2]} polygon
* @return {boolean}
*/
function pointInPolygon (point, polygon) {
var inside = false;
var x = point.x;
var y = point.y;
// use some raycasting to test hits
// https://github.com/substack/point-in-polygon/blob/master/index.js
var length = polygon.length;
for ( var i = 0, j = length-1; i < length; j = i++ ) {
var xi = polygon[i].x, yi = polygon[i].y,
xj = polygon[j].x, yj = polygon[j].y,
intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if ( intersect ) inside = !inside;
}
return inside;
}
Intersection.pointInPolygon = pointInPolygon;
/**
* @method circleCircle
* @param {Object} a - Object contains position and radius
* @param {Object} b - Object contains position and radius
* @return {boolean}
*/
function circleCircle (a, b) {
var distance = a.position.sub(b.position).mag();
return distance < (a.radius + b.radius);
}
Intersection.circleCircle = circleCircle;
/**
* @method polygonCircle
* @param {[Vec2]} polygon
* @param {Object} circle - Object contains position and radius
* @return {boolean}
*/
function polygonCircle (polygon, circle) {
var position = circle.position;
if (pointInPolygon(position, polygon)) {
return true;
}
for (var i = 0, l = polygon.length; i < l; i++) {
var start = i === 0 ? polygon[polygon.length - 1] : polygon[i- 1];
var end = polygon[i];
if (pointLineDistance(position, start, end, true) < circle.radius) {
return true;
}
}
return false;
}
Intersection.polygonCircle = polygonCircle;
/**
* !#en Calculate the distance of point to line.
* !#zh 计算点到直线的距离。如果这是一条线段并且垂足不在线段内,则会计算点到线段端点的距离。
* @method pointLineDistance
* @param {Vec2} point
* @param {Vec2} start - start point of line
* @param {Vec2} end - end point of line
* @param {boolean} isSegment - whether this line is a segment
* @return {boolean}
*/
function pointLineDistance(point, start, end, isSegment) {
var dx = end.x - start.x;
var dy = end.y - start.y;
var d = dx*dx + dy*dy;
var t = ((point.x - start.x) * dx + (point.y - start.y) * dy) / d;
var p;
if (!isSegment) {
p = cc.v2(start.x + t * dx, start.y + t * dy);
}
else {
if (d) {
if (t < 0) p = start;
else if (t > 1) p = end;
else p = cc.v2(start.x + t * dx, start.y + t * dy);
}
else {
p = start;
}
}
dx = point.x - p.x;
dy = point.y - p.y;
return Math.sqrt(dx*dx + dy*dy);
}
Intersection.pointLineDistance = pointLineDistance;
cc.Intersection = module.exports = Intersection;
@@ -0,0 +1,74 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Chukong Aipu reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* !#en Polygon Collider.
* !#zh 多边形碰撞组件
* @class PolygonCollider
* @extends Component
*/
var PolygonCollider = cc.Class({
name: 'cc.PolygonCollider',
extends: require('./CCCollider'),
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.collider/Polygon Collider',
},
properties: {
_offset: cc.v2(0, 0),
/**
* !#en Position offset
* !#zh 位置偏移量
* @property offset
* @type {Vec2}
*/
offset: {
get: function () {
return this._offset;
},
set: function (value) {
this._offset = value;
},
type: cc.Vec2
},
/**
* !#en Polygon points
* !#zh 多边形顶点数组
* @property points
* @type {[Vec2]}
*/
points: {
default: function () {
return [cc.v2(-50, -50), cc.v2(-50, 50), cc.v2(50, 50), cc.v2(50, -50)];
},
type: [cc.Vec2]
}
}
});
cc.PolygonCollider = module.exports = PolygonCollider;
+6
View File
@@ -0,0 +1,6 @@
require('./CCCollisionManager');
require('./CCCollider');
require('./CCBoxCollider');
require('./CCCircleCollider');
require('./CCPolygonCollider');
+1
View File
@@ -35,6 +35,7 @@ if (!CC_EDITOR || !Editor.isMainProcess) {
require('./CCScene');
require('./components');
require('./collider');
}
require('./base-ui/CCWidgetManager');
@@ -196,6 +196,40 @@ cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){
return rect;
};
/**
* !#en Apply the affine transformation on a rect, and truns to an Oriented Bounding Box.
* !#zh 应用 Rect 到仿射变换矩阵上, 并转换为有向包围盒
* @method obbApplyAffineTransform
* @param {Rect} rect
* @param {AffineTransform} anAffineTransform
* @param {Vec2} out_bl
* @param {Vec2} out_tl
* @param {Vec2} out_tr
* @param {Vec2} out_br
*/
cc.obbApplyAffineTransform = function (rect, anAffineTransform, out_bl, out_tl, out_tr, out_br) {
var x = rect.x;
var y = rect.y;
var width = rect.width;
var height = rect.height;
var tx = anAffineTransform.a * x + anAffineTransform.c * y + anAffineTransform.tx;
var ty = anAffineTransform.b * x + anAffineTransform.d * y + anAffineTransform.ty;
var xa = anAffineTransform.a * width;
var xb = anAffineTransform.b * width;
var yc = anAffineTransform.c * height;
var yd = anAffineTransform.d * height;
out_tl.x = tx;
out_tl.y = ty;
out_tr.x = xa + tx;
out_tr.y = xb + ty;
out_bl.x = yc + tx;
out_bl.y = yd + ty;
out_br.x = xa + yc + tx;
out_br.y = xb + yd + ty;
};
/**
* !#en Create a new affine transformation with a base transformation matrix and a translation based on it.
* !#zh 基于一个基础矩阵加上一个平移操作来创建一个新的矩阵。
+23
View File
@@ -41,6 +41,15 @@ cc.js.mixin(cc.director, {
this._animationManager = null;
}
// collider manager
if (cc.CollisionManager) {
this._collisionManager = new cc.CollisionManager();
this.getScheduler().scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false);
}
else {
this._collisionManager = null;
}
// WidgetManager
cc._widgetManager.init(this);
},
@@ -65,6 +74,11 @@ cc.js.mixin(cc.director, {
this.getScheduler().scheduleUpdate(this._animationManager, cc.Scheduler.PRIORITY_SYSTEM, false);
}
// Collision manager
if (this._collisionManager) {
this.getScheduler().scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false);
}
this.startAnimation();
},
@@ -77,6 +91,15 @@ cc.js.mixin(cc.director, {
return this._animationManager;
},
/**
* Returns the cc.CollisionManager associated with this director.
* @method getCollisionManager
* @return {CollisionManager}
*/
getCollisionManager: function () {
return this._collisionManager;
},
/**
* Returns current running Scene. Director can only run one Scene at the time.
* @method getScene
+117
View File
@@ -0,0 +1,117 @@
largeModule('collider');
test('collision manager', function() {
var manager = cc.director.getCollisionManager();
ok(manager);
manager.enabled = true;
var node1 = new cc.Node();
cc.director.getScene().addChild(node1);
var box1 = node1.addComponent(cc.BoxCollider);
strictEqual( manager._colliders.length, 1, 'collision manager should add 1 collider');
var box2 = node1.addComponent(cc.BoxCollider);
strictEqual( manager._colliders.length, 2, 'collision manager should add 2 colliders');
var node2 = new cc.Node();
cc.director.getScene().addChild(node2);
var box3 = node2.addComponent(cc.BoxCollider);
strictEqual( manager._colliders.length, 3, 'collision manager should add 3 colliders');
strictEqual( manager._contacts.length, 2, 'collision manager should add 2 contacts');
var box4 = node2.addComponent(cc.BoxCollider);
strictEqual( manager._colliders.length, 4, 'collision manager should add 4 colliders');
strictEqual( manager._contacts.length, 4, 'collision manager should add 4 contacts');
box4.mask = 0;
strictEqual( manager._colliders.length, 4, 'collision manager should add 4 colliders');
strictEqual( manager._contacts.length, 2, 'collision manager should add 2 contacts');
box4.enabled = false;
strictEqual( manager._colliders.length, 3, 'collision manager should add 3 colliders');
node1.parent = null;
node2.parent = null;
strictEqual( manager._colliders.length, 0, 'collision manager should add 0 colliders');
strictEqual( manager._contacts.length, 0, 'collision manager should add 0 contacts');
manager.enabled = false;
});
test('collider callback', function () {
var manager = cc.director.getCollisionManager();
manager.enabled = true;
var callbacks = [];
// my component
var MyComponent = cc.Class({
name: 'MyComponent',
extends: cc.Component,
onCollisionEnter: function () {
callbacks.push('enter');
},
onCollisionExit: function () {
callbacks.push('exit');
},
onCollisionStay: function () {
callbacks.push('stay');
}
});
var node1 = new cc.Node();
cc.director.getScene().addChild(node1);
var box1 = node1.addComponent(cc.BoxCollider);
node1.addComponent(MyComponent);
var node2 = new cc.Node();
cc.director.getScene().addChild(node2);
var box2 = node2.addComponent(cc.BoxCollider);
deepEqual(callbacks, [], 'should hove no callbacks');
manager.update();
deepEqual(callbacks, ['enter'], 'should call enter');
callbacks = [];
manager.update();
deepEqual(callbacks, ['stay'], 'should call stay');
callbacks = [];
manager.update();
deepEqual(callbacks, ['stay'], 'should call stay again');
node2.x = 1000;
callbacks = [];
manager.update();
deepEqual(callbacks, ['exit'], 'should call exit');
node2.x = 0;
callbacks = [];
manager.update();
deepEqual(callbacks, ['enter'], 'should call enter');
callbacks = [];
node1.parent = null;
node2.parent = null;
deepEqual(callbacks, ['exit'], 'should call exit');
cc.js.unregisterClass(MyComponent);
manager.enabled = false;
});