美文网首页
cocos creator 刚体与碰撞

cocos creator 刚体与碰撞

作者: Float_Alex | 来源:发表于2018-06-27 12:52 被阅读0次

    今天来通过一个简单的例子学习碰撞系统。

    碰撞组件

    首先来看碰撞组件。CocosCreator提供了三种碰撞组件:Box Collider,Circle Collider,Polygon Collider。增添十分简单,只需要选中节点在属性检查器中选择添加组件。 

    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;

    //        // 开启物理系统

    //        var physics = cc.director.getPhysicsManager();

    //        physics.enabled = true;

    //        physics.debugDrawFlags = cc.PhysicsManager.DrawBits.e_aabbBit || cc.PhysicsManager.DrawBits.e_pairBit;

    //        physics.enabledDebugDraw = true;

    相关文章

      网友评论

          本文标题:cocos creator 刚体与碰撞

          本文链接:https://www.haomeiwen.com/subject/nkybyftx.html