プロジェクトはとりあえず、SimpleView
Box2d
http://box2d.org/
をダウンロードしてBox2DフォルダをプロジェクトにDrop.
projectのbuild setting
Always User Search paths :YES
Header serach paths に上記ディレクトリをフルパスで追加
Library search pathsに上記ディレクトリをフルパスで追加
とりあえず、サンプルHelloWorld.cppにあるソースをほぼコピーで動作確認。
ViewController.mmに拡張子を変更して、見た目ようにUiviewを用意しました。
#import "ViewController.h"
#import
@interface ViewController (){
b2World* w;
b2Body* body;
}
@end
@implementation ViewController
//@synchronized obj;
- (void)viewDidLoad
{
[super viewDidLoad];
b2Vec2 gravity(0.0f, -10.0f);
w=new b2World(gravity);
// Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0.0f, -10.0f);
// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
b2Body* groundBody = w->CreateBody(&groundBodyDef);
// Define the ground box shape.
b2PolygonShape groundBox;
// The extents are the half-widths of the box.
groundBox.SetAsBox(50.0f, 10.0f);
// Add the ground fixture to the ground body.
groundBody->CreateFixture(&groundBox, 0.0f);
// Define the dynamic body. We set its position and call the body factory.
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(0.0f, 4.0f);
body = w->CreateBody(&bodyDef);
// Define another box shape for our dynamic body.
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(1.0f, 1.0f);
// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
// Set the box density to be non-zero, so it will be dynamic.
fixtureDef.density = 1.0f;
// Override the default friction.
fixtureDef.friction = 0.3f;
// Add the shape to the body.
body->CreateFixture(&fixtureDef);
//世界はタイマーですすみます。
float32 timeStep = 1.0f / 60.0f;
NSTimer *timer = [NSTimer
scheduledTimerWithTimeInterval:timeStep
target:self
selector:@selector(updateWorld:)
userInfo:nil
repeats:YES
];
}
-(void)updateWorld:(NSTimer *)timer{
int32 velocityIterations = 6;
int32 positionIterations = 2;
w->Step([timer timeInterval], velocityIterations, positionIterations);
// Now print the position and angle of the body.
b2Vec2 position = body->GetPosition();
float32 angle = body->GetAngle();
CGRect rect=self.obj.frame;
rect.origin.x=position.x*32;
rect.origin.y=position.y*32;
self.obj.frame=rect;
//printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end
動作確認はできたけど、座標系がUIKitのままだと、逆なのと、スケールもあってないので、調整が必要、32倍してとりあえず動いているのを確認。あと回転とかかな。