ラベル Box2D の投稿を表示しています。 すべての投稿を表示
ラベル Box2D の投稿を表示しています。 すべての投稿を表示

2012年9月27日木曜日

[iOS,Box2D]衝突検知


1,Listenerを使う方法
class ContactListener:public b2ContactListener{
private:
    void BeginContact(b2Contact* contact){
        printf("#BeginContact ");
    }
    void PreSolve(b2Contact* contact, const b2Manifold* oldManifold){
    }
    void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse){
    }
    void EndContact(b2Contact* contact){
    }
};

これを、Worldにセットしてあげればいい。

    b2Vec2 gravity(0.0f, 10.0f);
    world=new b2World(gravity);
    world->SetContactListener(&contactListener);

2,Setpをすすめるときに、直接「contactList」をチェックする
for(b2Contact *contact=world->GetContactList();contact!=nil;contact = contact->GetNext(),i++){
        
        b2Vec2 v= contact->GetFixtureB()->GetBody()->GetLinearVelocity();
        b2Contact *contact2=contact->GetNext();
        
        printf("nomal: %x,%x \n", contact,contact2);
        
        b2Manifold* m= contact->GetManifold();
        int cc=m->pointCount;
        if(v.Length()>0.1){
            printf("v.Length(): %f \n", v.Length());
            printf("cc: %d x:%f y:%f \n", cc,v.x,v.y);
            printf("%d #1-%s \n",i,[((UserData*)(contact->GetFixtureA()->GetBody()->GetUserData())).str UTF8String]);
            printf("%d #2-%s \n",i,[((UserData*)(contact->GetFixtureB()->GetBody()->GetUserData())).str UTF8String]);
        }
        
    }

1,2の方法の違い
通常は1の場合が便利、
2の場合は、接触している間、contactListに入っているので、初回のインパクトかどうかを判断する必要がある。
2はworldだけでなくbodyで取得できるので、対象をしぼったリストを取得することもできる。

2012年8月1日水曜日

[iOS]UIKitでBox2Dを使おう

xCode4.4で作業しました。
プロジェクトはとりあえず、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倍してとりあえず動いているのを確認。あと回転とかかな。