Box2D Cocos2d JS

601 Views Asked by At

enter image description hereI want to create a slope like in attached image in Box2D Cocos2d JS. However, I am unable to create it properly when attached sprites to it. My code is:

new b2Vec2(0, 0),
new b2Vec2(100 / worldScale, -50 / worldScale),
new b2Vec2(200 / worldScale, 0 / worldScale)

The image dimensions is 200 * 50, and worldScale = 30.

1

There are 1 best solutions below

0
On BEST ANSWER

First of all I see you're using negative coordinates (-50). Everything in Cocos2d-JS (the default viewport) is positive ({0,0} is bottom left point).

To debug slope positioning I suggest you to use Box2d DebugDraw first, to see the actual slope you've described and then to place your sprite based on those wireframes. Cocos2d-JS will clear it's own canvas in the update function, so you'll need to put another debug canvas on top of it, for DebugDraw.

This example helped me to add debug draw to my box2d sandbox successfully

add this code to update function

var debugDraw = new Box2D.Dynamics.b2DebugDraw();
debugDraw.SetSprite(document.getElementById("test").getContext("2d"));
// test is the id of another canvas which debugdraw works on
debugDraw.SetDrawScale(30.0); 
debugDraw.SetFillAlpha(0.3);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit |
Box2D.Dynamics.b2DebugDraw.e_jointBit);
this.world.SetDebugDraw(debugDraw); this.world.DrawDebugData();

box2d use a different coordinate frame than cocos, so you need to do transform 180 degrees. add this to the style of debug canvas

-webkit-transform:rotate(180deg); //and some other browsers' style