box2d-wasm常用函数

目前唯一不足就是不能动态修改shader。。。

1创建地面

   const gravity = new b2Vec2(0, 10);
    world = new b2World(gravity);

    const bd_ground = new b2BodyDef();
    
    const ground = world.CreateBody(bd_ground);
    const shape = new b2EdgeShape();
    shape.SetTwoSided(new b2Vec2(3, 4), new b2Vec2(6, 7));
    ground.CreateFixture(shape, 0);

2  创建方形

  const square = new b2PolygonShape();
    square.SetAsBox(sideLengthMetres / 2, sideLengthMetres / 2);

3 创建圆形

  const circle = new b2CircleShape();
    circle.set_m_radius(sideLengthMetres / 2);

 4 创建完刚体动态移动位置

   body.SetTransform(new b2Vec2(1, 0), 0);

5 修改userdata

function setuserdata(body, key, value) {
    if(iskong(key)){
        alert('key不能为空1');
    }else if(iskong(value)){
        alert('value不能为空');
    }
    let getdata = metadata[getPointer(body)];
    if (iskong(getdata)) {
    
        var data1 = {};
        data1[key]=value;
    } else {
        getdata[key] = value;
       
        var data1 = getdata;
    }
 
    metadata[getPointer(body)] = data1
}
function getuserdata(body, key) {
    if(iskong(key)){
        alert('key不能为空2');
    }
    let getdata=metadata[getPointer(body)];

    return getdata[key];

}

6监听碰撞 碰到就计算了

    var listener = new JSContactListener();
    listener.BeginContact = function (contactPtr) {

        var contact = wrapPointer(contactPtr, b2Contact);
        var bodyAY = contact.GetFixtureA().GetBody().GetPosition().get_y();
        var bodyBY = contact.GetFixtureB().GetBody().GetPosition().get_y();


    }

 7 设置睡眠

body.SetAwake(1);

8 设置刚体属性

      bd.set_type(b2_dynamicBody);
        bd.set_position(ZERO);

 9 获取xy坐标

GetPosition().get_y()

 10 获取AABB吧包围框bounds

 const gravity = new b2Vec2(0, 10);
    
    world = new b2World(gravity);

    const bd_ground = new b2BodyDef();
    
    const ground = world.CreateBody(bd_ground);
    const shape = new b2EdgeShape();
    var xx=new b2Vec2(3, 4)
    shape.SetTwoSided(xx, new b2Vec2(6, 7));
    ground.CreateFixture(shape, 0);
    console.log("getShape()",ground.GetFixtureList().GetAABB().get_lowerBound());
    console.log("getShape()",ground.GetFixtureList().GetAABB().get_upperBound());

 11获取中心点

function getbodycenter(body){
    let lowerBound=body.GetFixtureList().GetAABB().get_lowerBound();
    let lowerBoundX=lowerBound.get_x();
    let lowerBoundY=lowerBound.get_Y();

    let upperBound=body.GetFixtureList().GetAABB().get_upperBound();
    let upperBoundX=upperBound.get_x();
    let upperBoundY=upperBound.get_Y();

    let centerX=Math.abs(upperBoundX-lowerBoundX)/2;
    let centerY=Math.abs(upperBoundY-lowerBoundY)/2;
    let centerinfo={};
    centerinfo['x']=centerX;
    centerinfo['y']=centerY;
    return centerinfo;
}
function setbodypositionbycenter(body,x,y){
    let centerinfo=getbodycenter(body)
    body.SetTransform(new b2Vec2(x-centerinfo['x'], y-centerinfo['y']), 0);
}

 

posted @ 2022-05-23 09:12  newmiracle宇宙  阅读(90)  评论(0编辑  收藏  举报