前回の記事「liquidfunをSpriteKit上で動かしてみる」の続きです。
今回は軽め記事として、ボールを追加できるようにしてみます。
ボックスとボールは共通部分があるのでコードをまとめて、せっかくのObjective-C++なので、ラムダ式を使ってみました。
auto createFixtureWithValues = [](b2Body* body, const b2Shape* shape, float density, float friction, float restitution) {
b2FixtureDef def;
def.shape = shape;
def.density = density;
def.friction = friction;
def.restitution = restitution;
body->CreateFixture(&def);
};
auto createDynamicBody = [self](const CGPoint& pos) -> b2Body* {
b2BodyDef bodyDef;
bodyDef.type = b2_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];
b2Body* body = createDynamicBody(pos);
b2CircleShape 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)];
b2CircleShape 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];
b2Body* body = createBody(pos);
createFixtureWithValues(body, &ballShape, 1.0f, 0.3f, 0.4f);
body->SetUserData((__bridge void*) node);
};
これで、次のようにすると、ボックスとボールとそれぞれ作成できます。
addBox(location, 0.5f, 0.5f); addBall(location, 0.5);




0 件のコメント:
コメントを投稿
注: コメントを投稿できるのは、このブログのメンバーだけです。