cocos creator基礎-(二十)物理引擎碰撞檢測


1: 理解物體類型和分類,配置碰撞矩陣;
2: 編寫碰撞響應函數,監聽碰撞事件;
3: 學會了解Sensor來做觸發器,只觸發碰撞不改變運動;

物體類型與碰撞矩陣

1: 添加物體類型: Add Layer, 每個類型對應一個名字group與groupIndex
2: 創建物體的時候要選擇一個類型;
3: 配置碰撞矩陣,決定哪些物體類型碰撞;

 

碰撞事件監聽

1: 剛體組件開啟碰撞監聽;
2: 當有碰撞發生的時候,遍歷剛體所在的節點所掛的所有的組件,看組件是否實現了碰撞檢測函數,如果是,那么調用;
3: 在需要檢測碰撞的組件代碼里面編寫碰撞響應函數:
  onBeginContact ( contact, selfCollider, otherCollider): 碰撞開始
  onEndContact (contact, selfCollider, otherCollider): 碰撞結束
  onPreSolve(contact, selfCollider, otherCollider); 碰撞持續,接觸時被調用;
  onPostSolve (contact, selfCollider, otherCollider); 碰撞接觸更新完后調用,可以獲得沖量信息

4: 如果把碰撞器設置成了sensor,那么只會做碰撞檢測,而不會改變物體碰撞后的運動狀態;
  sensor: 用於觸發器: 道具, 關卡的出口,入口等;

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //    default: null,      // The default value will be used only when the component attaching
        //                           to a node for the first time
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
    },

    // use this for initialization
    onLoad: function () {

    },

    // contact 是碰撞對象,本次碰撞的信息
    // selfCollider: 是自己的碰撞器組件
    // otherCollider: 碰撞到的碰撞器組件;
    // 我們可以有碰撞器組件,來獲取我們的碰撞的節點對象
    // 碰撞開始
    onBeginContact: function ( contact, selfCollider, otherCollider) {
        console.log("onBeginContact:", otherCollider.node.name, " ", selfCollider.node.name);
        console.log("onBeginContact", selfCollider.node.group, otherCollider.node.group);
        console.log("onBeginContact", selfCollider.node.groupIndex, otherCollider.node.groupIndex);
    },

    // 碰撞結束
    onEndContact: function(contact, selfCollider, otherCollider) {
        console.log("onEndContact");
    },

    // 碰撞持續
    onPreSolve: function(contact, selfCollider, otherCollider) {
        console.log("onPreSolve function");
    },

    // 計算完本次碰撞持續后,調用這個
    onPostSolve: function (contact, selfCollider, otherCollider) {
        console.log("onPostSolve");
    }
    // called every frame, uncomment this function to activate update callback
    // update: function (dt) {

    // },
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM