前回の記事「liquidfunをSpriteKit上で動かしてみる」の続きです。
今回は軽め記事として、ボールを追加できるようにしてみます。
ボックスとボールは共通部分があるのでコードをまとめて、せっかくのObjective-C++なので、ラムダ式を使ってみました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | auto createFixtureWithValues = [](b 2 Body* body, const b 2 Shape* shape, float density, float friction, float restitution) { b 2 FixtureDef def; def .shape = shape; def .density = density; def .friction = friction; def .restitution = restitution; body->CreateFixture(&def); }; auto createDynamicBody = [ self ]( const CGPoint& pos) -> b 2 Body* { b 2 BodyDef bodyDef; bodyDef .type = b 2 _dynamicBody; bodyDef .position .Set (pos .x / DISPLAY_SCALE , pos .y / DISPLAY_SCALE); return _world->CreateBody(&bodyDef); }; auto addBall = [ self ,createDynamicBody,createFixtureWithValues]( const CGPoint& pos, float radius) { const float r = radius * DISPLAY_SCALE ; SKShapeNode* node = SKShapeNode .alloc .init ; UIBezierPath* ovalPath = [ UIBezierPath bezierPathWithOvalInRect : CGRectMake(-r, -r, r* 2 , r* 2 )]; node .path = ovalPath .CGPath ; node .fillColor = UIColor .whiteColor ; node .lineWidth = 0 ; node .position = pos; [ self addChild :node]; b 2 Body* body = createDynamicBody(pos); b 2 CircleShape ballShape; ballShape .m_radius = radius; createFixtureWithValues(body, &ballShape, 1 .0f , 0 .8f , 0 .8f ); body->SetUserData((__bridge void *) node); }; auto addBall = [ self ,createBody,createFixtureWithValues]( const CGPoint& pos, float radius) { const float r = radius * DISPLAY_SCALE ; UIBezierPath* ovalPath = [ UIBezierPath bezierPathWithOvalInRect : CGRectMake(-r, -r, r* 2 , r* 2 )]; b 2 CircleShape ballShape; ballShape .m_radius = radius; SKShapeNode* node = SKShapeNode .alloc .init ; node .path = ovalPath .CGPath ; node .fillColor = UIColor .whiteColor ; node .lineWidth = 0 ; node .position = pos; [ self addChild :node]; b 2 Body* body = createBody(pos); createFixtureWithValues(body, &ballShape, 1 .0f , 0 .3f , 0 .4f ); body->SetUserData((__bridge void *) node); }; |
これで、次のようにすると、ボックスとボールとそれぞれ作成できます。
1 2 | addBox(location, 0 .5f , 0 .5f ); addBall(location, 0 .5 ); |
0 件のコメント:
コメントを投稿
注: コメントを投稿できるのは、このブログのメンバーだけです。