今天來通過一個簡單的例子學(xué)習(xí)碰撞系統(tǒng)。
首先來看碰撞組件。CocosCreator提供了三種碰撞組件:Box Collider,Circle Collider,Polygon Collider。增添十分簡單,只需要選中節(jié)點在屬性檢查器中選擇添加組件。?
function boxAddBound(box, offset, size) {
? ? let bound = box.addComponent(cc.PhysicsBoxCollider);
? ? bound.offset = offset;
? ? bound.size.width = size.x; bound.size.height = size.y;
}
cc.Class({
? ? extends: cc.Component,
? ? properties: {
? ? ? ? box_width: 0,
? ? ? ? box_heigth: 0,
? ? },
? ? onLoad () {
? ? ? ? // append a bound box
? ? ? ? let boundbox = new cc.Node("boundbox");
? ? ? ? // boundbox.group = "map";
? ? ? ? boundbox.addComponent(cc.RigidBody).type = cc.RigidBodyType.Static; // attach a rigid body to the new node.
? ? ? ? boundbox.enabledContactListener = true;
? ? ? ? // size of box
? ? ? ? let width = this.box_width || this.node.width;
? ? ? ? let height = this.box_height || this.node.height;
? ? ? ? // add right bound
? ? ? ? let offset = cc.p(width/2, 0);
? ? ? ? let size = cc.p(20, height);
? ? ? ? boxAddBound(boundbox, offset, size);
? ? ? ? //add left bound
? ? ? ? offset = cc.p(-width/2, 0);
? ? ? ? boxAddBound(boundbox, offset, size);
? ? ? ? // add top bound
? ? ? ? offset = cc.p(0, height/2);
? ? ? ? size = cc.p(width, 20);
? ? ? ? boxAddBound(boundbox, offset, size);
? ? ? ? //add bottom bound
? ? ? ? offset = cc.p(0, -height/2);
? ? ? ? boxAddBound(boundbox, offset, size);
? ? ? ? //
? ? ? ? boundbox.addComponent(cc.Graphics);
? ? ? ? // attach this node to the scene tree after physics things attached to the node.
? ? ? ? this.node.addChild(boundbox); //attach it to the script related node
? ? },
? ? update() {
? ? ? ? var graphics = this.node.getChildByName("boundbox").getComponent(cc.Graphics);
? ? ? ? graphics.clear();
? ? ? ? graphics.circle(100, 200, 10);
? ? ? ? graphics.stroke();
? ? },
});
// let collider = this.node.addComponent(cc.PhysicsCircleCollider);
? ? ? ? // collider.radius = this.node.width / 2;
// // 開啟碰撞檢測
//? ? ? ? var mngr = cc.director.getCollisionManager();
//? ? ? ? mngr.enabled = true;
//? ? ? ? mngr.enabledDebugDraw = true;
//? ? ? ? // 開啟物理系統(tǒng)
//? ? ? ? var physics = cc.director.getPhysicsManager();
//? ? ? ? physics.enabled = true;
//? ? ? ? physics.debugDrawFlags = cc.PhysicsManager.DrawBits.e_aabbBit || cc.PhysicsManager.DrawBits.e_pairBit;
//? ? ? ? physics.enabledDebugDraw = true;