2012-01-24 66 views
1

我與box2djs玩耍。我試圖找到一種方法來寫一個'onCollision()回調函數,但文檔是稀疏的,我無法找到一個明顯的方式做到這一點。在box2djs碰撞事件處理程序

謝謝!

+0

請看這個問題和我的答案。 http://stackoverflow.com/questions/8951392/collision-detection-using-box2dfor-android – Andrew

回答

1

打回電話詢問box2djs爲衝突實際上是引用「過濾器」。這裏是你如何實現它。我還會介紹我在做什麼,而不是這也許是慢一點,但因爲我的另一種方法是步驟()之外,我可以銷燬對象和東西:

// Called whenever a collision occurs in the world 
// 

var JellyCollisionCallback = function() 
    { 
    // Required function - this is the function the gets called when b2ContactManager registers a collision between two bodies 
    // 
    this.ShouldCollide = function(shape1, shape2) 
     { 
     // These are the two bodies… 
     // 
     var cBody1 = shape1.m_body; 
     var cBody2 = shape2.m_body; 

     // I'm setting userData when I create the body object 
     // 
     var jellyObject1 = cBody1.GetUserData(); 
     var jellyObject2 = cBody2.GetUserData(); 


     // This is the code from the default collision filter 
     // 
     if (shape1.m_groupIndex == shape2.m_groupIndex && shape1.m_groupIndex != 0) 
      { 
      return shape1.m_groupIndex > 0; 
      } 

     var collide = (shape1.m_maskBits & shape2.m_categoryBits) != 0 && (shape1.m_categoryBits & shape2.m_maskBits) != 0; 

     return collide; 
     } 

    return this; 
    } 


function createWorld() 
    { 
    var world = new b2World(worldAABB, gravity, doSleep); 

    myCollisionCallback = new JellyCollisionCallback(); 

    world.SetFilter(myCollisionCallback); 
    } 

可能不會像你一樣真正回調,但我原本試圖回調工作時遇到了問題,所以我編寫了這個方法,最終保留了它。我這樣做,我的主循環調用world.step()

// Find collisions between selected objects 
// 
// (world is the main b2World object) 
// 
var aContact; 
for (aContact = world.m_contactList; aContact != null; aContact = aContact.m_next) 
    { 
    var cBody1 = aContact.m_shape1.m_body; 
    var cBody2 = aContact.m_shape2.m_body; 

    // I'm setting userData when I create the body object 
    // 
    var jellyObject1 = cBody1.GetUserData(); 
    var jellyObject2 = cBody2.GetUserData(); 

    // Not one of my controlled Objects 
    // 
    if (typeof(jellyObject1) != "object" || jellyObject1 == null) 
     continue; 
    if (typeof(jellyObject2) != "object" || jellyObject2 == null) 
     continue; 

    // Call my collision event for the colliding objects 
    // 
    jellyObject1.dink(); 
    jellyObject2.dink(); 
    } 

文檔幾乎是從我發現不可用,但我真的很喜歡box2djs並終於想通了一切,我需要完成一些簡單的愛好項目。這裏有一些例子可以擴展原來的box2djs demo jellyrobotics box2djs project