box2d.js


https://github.com/kripken/box2d.js/

Demo: http://kripken.github.io/box2d.js/webgl_demo/box2d.html

演示: http://kripken.github.io/box2d.js/webgl_demo/box2d.html

Example code to give you an idea of the API: https://github.com/kripken/box2d.js/blob/master/demo/webgl/box2d.html#L14

向您提供API的示例代碼: https://github.com/kripken/box2d.js/blob/master/demo/webgl/box2d.html#L14

box2d.js is a direct port of the Box2D 2D physics engine to JavaScript, using Emscripten. The source code is translated directly to JavaScript, without human rewriting, so functionality should be identical to the original Box2D.

box2d.js是Box2D 2D物理引擎到JavaScript的直接端口,使用Emscripten。 源代碼直接轉換為JavaScript,無需人工重寫,因此功能應與原始Box2D完全相同。

box2d.js is zlib licensed, just like Box2D.

box2d.js是zlib許可的,就像Box2D。

Discussion takes place on IRC at #emscripten on Mozilla's server (irc.mozilla.org)

討論發生在IRC的#emscripten在Mozilla的服務器(irc.mozilla.org)

Details

細節

The automatically generated bindings have been tested to the extent that can be found in the examples in the 'testbed'. For general notes on using the bindings, see the ammo.js project (a port of Bullet to JavaScript using Emscripten), many of the details of wrapping classes and so forth are identical.

自動生成的綁定已經測試到在“testbed”的示例中可以找到的程度。 有關使用綁定的一般注意事項,請參閱ammo.js項目(使用Emscripten的Bullet到JavaScript的端口),包裝類的許多細節等是相同的。

It seems to be running ok on at least the following:

它似乎運行確定至少以下:

  • Desktop PC (Linux) - Chrome22, Opera12, Firefox16
  • 台式機(Linux) - Chrome22,Opera12,Firefox16
  • Desktop PC (OSX) - Chrome22, Opera12, Firefox16
  • 台式機(OSX) - Chrome22,Opera12,Firefox16
  • Desktop PC (Win7) - Chrome22, Opera12, Firefox16
  • 台式機(Win7) - Chrome22,Opera12,Firefox16
  • iOS 5 - Safari, Chrome, Dolphin
  • Android ICS - Chrome18
  • Android JB - Chrome18, Dolphin9

Testbed

測試床

The demo/html5canvas folder contains an example web page and script files to reproduce the original Box2D testbed, with similar controls and features.

demo / html5畫布文件夾包含一個示例網頁和腳本文件,用於再現原始Box2D測試平台,具有類似的控件和功能。

Demo: http://www.iforce2d.net/embox2d/testbed.html

Like the original C++ version, the testbed is set up so that adding another test scene is easy. Look in the tests folder and find the template.js file....

像原來的C ++版本一樣,測試台被設置,以便添加另一個測試場景很容易。 查看測試文件夾並找到template.js文件....

  1. Copy template.js and rename it.復制template.js並重命名它。
  2. In the renamed file, replace all occurrences of 'embox2dTest_template' with your test name.在重命名的文件中,將所有出現的'embox2dTest_template'替換為測試名稱。
  3. Fill in the setup function.填寫設置功能。
  4. Optionally, fill in the other functions.或者,填寫其他功能。
  5. Include the new file at the beginning of testbed.html with the other tests.包括新文件在testbed.html的開始與其他測試。
  6. Add the new test option to the "testNumber" select box in test.html將新的測試選項添加到test.html中的“testNumber”選擇框

R.U.B.E testbed試驗台

The demo/rube_testbed folder contains the testbed with scenes which were exported from the R.U.B.E editordemo / rube_testbed文件夾包含從R.U.B.E編輯器導出的場景的測試台

Demo: http://argadnet.com/demo/rube_testbed/box2djs/index.php

Building

$ /PATH/TO/EMSCRIPTEN emmake make

To build latest (2.3.1) version:

$ /PATH/TO/EMSCRIPTEN emmake make VERSION=latest 

Also, You can build the debug version of javascript file (with source maps support):

$ /PATH/TO/EMSCRIPTEN emmake make VERSION=latest BUILD=debug

This runs emscripten and uses it to compile a version of the Box2D source code stored within the box2d.js git. This source code has been modified to add constructors to some objects to ensure that emscripten will generate bindings for them.

Currently, you need to use a very recent Emscripten to build, version 1.23.0 or later (master branch as of Aug 21 2014) to build box2d.js. See http://kripken.github.io/emscripten-site/docs/building_from_source/building_emscripten_from_source_using_the_sdk.html#building-emscripten-from-source-using-the-sdk

Usage (WebIDL bindings)用法(WebIDL綁定)

The current bindings are created with the WebIDL binder. Read Box2D_v2.2.1.idl to see the class, methods, and attributes that are bound.當前綁定是使用WebIDL綁定器創建的。 閱讀Box2D_v2.2.1.idl來查看綁定的類,方法和屬性。

Note: To improve readability all code snippets below assume that everything in the 'Box2D' namespace has been made available! (Check the 'using' function in helpers/embox2d-helpers.js for details.)注意:為了提高可讀性,下面的所有代碼片段假定“Box2D”命名空間中的所有內容都已可用! (有關詳細信息,請參閱helpers / embox2d-helpers.js中的“使用”函數。)

Class member variable access類成員變量訪問

The values of public member variables of Box2D classes (mostly the definition classes) can be set and accessed using the generated functions, which will be the variable name prefixed with set_ or get_, eg.Box2D類(大多數是定義類)的公共成員變量的值可以使用生成的函數進行設置和訪問,這些變量名稱的前綴為set_或get_,例如。

//C++
circleShape.m_radius = 2;
//javascript
circleShape.set_m_radius( 2 );

Vector manipulation矢量操縱

b2Vec2 vectors can be created like:b2Vec2向量可以創建如下:

var myVec = new b2Vec2( 1.2, 3.4 );

As mentioned above, the individual components of vectors can be obtained with the get_x() and get_y() functions.如上所述,可以使用get_x()和get_y()函數獲取向量的各個分量。

Vectors can be assigned with the = operator but if you are coming from a C++ background, you may be caught out by the fact that this does not result in two independent variables. To get the same behavior as the original C++ assignment you can copy the components like:向量可以賦值為=運算符,但是如果你是來自C ++背景,你可能會被這個事實所困惑,這不會導致兩個獨立的變量。 要獲得與原始C ++作業相同的行為,您可以復制組件,如:

var anotherVec = new b2Vec2( vec.get_x(), vec.get_y() );

Alternatively the assignment, addition and subtraction operators can be replaced with the functions below (however, experience shows these to be somewhat dodgy...)或者,賦值,加法和減法運算符可以替換為下面的函數(然而,經驗表明這些有點詭異...)

operator       name in JS
--------       ----------
    =            op_set
    +            op_add
    -            op_sub

Creating a world創造一個世界

A typical world can be created like:一個典型的世界可以創建為:

var world = new b2World( new b2Vec2(0.0, -10.0) );

Creating bodies創建body

A static body can be created like:靜態體可以像下面這樣創建:

var groundBody = world.CreateBody( new b2BodyDef() );

... and dynamic/kinematic bodies like:...和動態/運動體如:

var bodyDef = new b2BodyDef();
bodyDef.set_type( b2_dynamicBody );
var dynamicBody = world.CreateBody( bodyDef );

Creating fixtures創建燈具

A circle fixture with density 1 and default values for everything else (friction, restitution etc):具有密度1和其他所有默認值(摩擦,恢復等)的圓形夾具:

var circleShape = new b2CircleShape();
circleShape.set_m_radius( 0.5 );
body.CreateFixture( circleShape, 1.0 );

A circle fixture with some more specific settings:有一些更具體的設置的圓夾具:

var fixtureDef = new b2FixtureDef();
fixtureDef.set_density( 2.5 );
fixtureDef.set_friction( 0.6 );
fixtureDef.set_shape( circleShape );
body.CreateFixture( fixtureDef );

An edge shape:邊緣形狀:

var edgeShape = new b2EdgeShape();
edgeShape.Set( new b2Vec2( -20, 3 ), new b2Vec2( 20, 7 ) );
fixtureDef.set_shape( edgeShape );
body.CreateFixture( fixtureDef );

Creating polygon shapes seems to be somewhat messy with the current bindings, so the recommended way is to use thecreatePolygonShape helper function in embox2d-helpers.js:創建多邊形形狀似乎有點凌亂的當前綁定,所以建議的方法是使用emlayer2d-helpers.js中的thecreatePolygonShape幫助函數:

var verts = [];
verts.push( new b2Vec2( 7,-1 ) );
verts.push( new b2Vec2( 8,-2 ) );
verts.push( new b2Vec2( 9, 3 ) );
verts.push( new b2Vec2( 7, 1 ) );
var polygonShape = createPolygonShape( verts );
fixtureDef.set_shape( polygonShape );
body.CreateFixture( fixtureDef );

Likewise for chain shapes: Edit: seems to be a problem with this, best to avoid chain shapes for now同樣對於鏈形狀:編輯:似乎是這個問題,最好避免鏈形狀現在

var chainShape = createChainShape( verts, true ); //true for closed loop, false for open chain
fixtureDef.set_shape( chainShape );
body.CreateFixture( fixtureDef );

Creating joints創建關節

Example revolute joint:旋轉接頭示例:

var jointDef = new b2RevoluteJointDef();
jointDef.set_bodyA( body1 );
jointDef.set_bodyB( body2 );
jointDef.set_localAnchorA( new b2Vec2( 1, 2 ) );
jointDef.set_localAnchorB( new b2Vec2( 3, 4 ) );
jointDef.set_collideConnected( true );
var revoluteJoint = Box2D.castObject( world.CreateJoint( jointDef ), b2WheelJoint );

Using debug draw使用調試繪圖

Create a JSDraw object, and supply implementations of the draw methods. (Note: All methods must be implemented even if unused.)創建一個JS Draw對象,並提供繪制方法的實現。 (注意:即使未使用,所有方法也必須實現。)

var debugDraw = new Box2D.JSDraw();

debugDraw.DrawSegment = function(vert1Ptr, vert2Ptr, colorPtr ) {
    setColorFromDebugDrawCallback( colorPtr );
    drawSegment( vert1Ptr, vert2Ptr );
}
// Empty implementations for unused methods.
debugDraw.DrawPolygon = function() {};
debugDraw.DrawSolidPolygon = function() {};
debugDraw.DrawCircle = function() {};
debugDraw.DrawSolidCircle = function() {};
debugDraw.DrawTransform = function() {};

world.SetDebugDraw( debugDraw );

The parameters of the draw methods will be pointers to data inside emscripten's innards, so you'll need to wrap them to get the data type you are looking for. Here are the two functions mentioned above, as an example of how you would wrap the passedb2Color and b2Vec2 parameters and use them in your drawing. This example is to draw on a HTML5 canvas:繪制方法的參數將是指向emscripten的內部數據的指針,因此您需要包裝它們以獲取您要查找的數據類型。 這里是上面提到的兩個函數,作為一個例子,你將如何包裝passedb2Color和b2Vec2參數,並在你的繪圖中使用它們。 這個例子是在一個HTML5畫布上繪制:

function setColorFromDebugDrawCallback( colorPtr ) {
    var color = Box2D.wrapPointer( colorPtr, b2Color );
    var red = (color.get_r() * 255) | 0;
    var green = (color.get_g() * 255) | 0;
    var blue = (color.get_b() * 255) | 0;

    var colorStr = red + "," + green + "," + blue;
    context.fillStyle = "rgba(" + colorStr + ",0.5)";
    context.strokeStyle = "rgb(" + colorStr + ")";
}

function drawSegment( vert1Ptr, vert2Ptr ) {
    var vert1 = Box2D.wrapPointer( vert1Ptr, b2Vec2 );
    var vert2 = Box2D.wrapPointer( vert2Ptr, b2Vec2 );

    context.beginPath();
    context.moveTo( vert1.get_x(), vert1.get_y() );
    context.lineTo( vert2.get_x(), vert2.get_y() );
    context.stroke();
}

Accessing the vertex arrays passed to other functions such as DrawPolygon are somewhat more tricky - please see the embox2d-html5canvas-debugDraw.js source for an example.訪問傳遞給其他函數(如DrawPolygon)的頂點數組有點更加棘手 - 請參閱embox2d-html5canvas-debugDraw.js源代碼示例。

Using collision events使用碰撞事件

Contact listener callbacks are also implemented with customizeVTable.聯系人偵聽器回調也使用customizeVTable實現。

listener = new JSContactListener();
listener.BeginContact = function (contactPtr) {
    var contact = Box2D.wrapPointer( contactPtr, b2Contact );
    var fixtureA = contact.GetFixtureA();
    var fixtureB = contact.GetFixtureB();

    // now do what you wish with the fixtures
}

// Empty implementations for unused methods.
listener.EndContact = function() {};
listener.PreSolve = function() {};
listener.PostSolve = function() {};

world.SetContactListener( listener );

Using world callbacks使用世界回調

Callbacks for other uses such as world querying and raycasting can also be implemented with customizeVTable. Here is the callback used in the 'testbed' to find the fixture that the mouse cursor is over when the left button is clicked:用於其他用途(例如世界查詢和raycasting)的回調也可以使用customizeVTable實現。 這里是在'testbed'中使用的回調找到鼠標光標在點擊左鍵時結束的夾具:

myQueryCallback = new JSQueryCallback();

myQueryCallback.ReportFixture = function(fixturePtr) {
    var fixture = Box2D.wrapPointer( fixturePtr, b2Fixture );
    if ( fixture.GetBody().GetType() != Box2D.b2_dynamicBody ) //mouse cannot drag static bodies around
        return true;
    if ( ! fixture.TestPoint( this.m_point ) )
        return true;
    this.m_fixture = fixture;
    return false;
};

The callback is used like:回調使用像:

myQueryCallback.m_fixture = null;
myQueryCallback.m_point = new b2Vec2( mouseX, mouseY );

world.QueryAABB( myQueryCallback, aabb ); // the AABB is a tiny square around the current mouse position

if ( myQueryCallback.m_fixture ) {
    //do something with the fixture that was clicked
}

Using a Destruction Listener使用銷毀監聽器

The standard b2DestructionListener class can't be used directly from javascript, as it has two methods that share the same name (SayGoodbye), and differ only by the type of their single parameter.標准b2DestructionListener類不能直接從javascript中使用,因為它有兩個方法共享同一個名稱(SayGoodbye),並且不同的是它們的單個參數的類型。

To listen for destruction events, do:要監聽銷毀事件,請執行:

var myDestructionListener = new JSDestructionListener()
myDestructionListener.SayGoodbyeJoint = function(joint) {
    var joint = Box2D.wrapPointer( joint, b2Joint );
}
myDestructionListener.SayGoodbyeFixture = function(fixture) {
    var fixture = Box2D.wrapPointer( fixture, b2Fixture );
}

 


免責聲明!

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



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