これは、ボールを作成して返す単純なヘルパー クラスです。同様のアプローチを使用してボックスを作成できます。
//
// Ball.h
// BouncingBall
//
// Created by Omar Hussain on 8/12/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "Box2D.h"
class Ball : public CCSprite {
public:
CCSprite *sprite;
b2BodyDef ballBodyDef;
b2Body *ballBody;
b2FixtureDef ballShapeDef;
b2Fixture *fixture;
Ball(b2World *world);
b2Vec2 disp;
CCSprite *shadowBall;
b2World *world;
bool isAnimating;
void SetBallOverlap(bool willOverlap, int scale);
void Destroy();
};
#import "Ball.h"
#define Density 1.0f
#define Friction 1.0f
#define Restitution 0.8f
#define PTM_RATIO 32
#define SpriteRadius 40.5
Ball::Ball(b2World *world){
this->world = world;
this->sprite = [CCSprite spriteWithFile:@"5.png"];
[sprite setPosition:ccp(160,460)];
this->isAnimating = false;
//Set up sprite
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(160/PTM_RATIO, 460/PTM_RATIO);
ballBodyDef.userData = sprite;
this->ballBody = world->CreateBody(&ballBodyDef);
b2CircleShape circle;
circle.m_radius = SpriteRadius/PTM_RATIO;
ballShapeDef.shape = &circle;
ballShapeDef.density = Density;
ballShapeDef.friction =Friction;
ballShapeDef.restitution = Restitution;
this->fixture = this->ballBody->CreateFixture(&ballShapeDef);
//this->shadowBall = [TSprite spriteWithFile:@"ball_shadow.png"];
}
void Ball::SetBallSize(int scale){
this->ballBody->DestroyFixture(fixture);
this->world->DestroyBody(ballBody);
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(160/PTM_RATIO, 460/PTM_RATIO);
ballBodyDef.userData = sprite;
this->ballBody = world->CreateBody(&ballBodyDef);
float correctedScale = scale/9.0;
b2CircleShape circle;
circle.m_radius = (correctedScale *SpriteRadius)/PTM_RATIO;
ballShapeDef.shape = &circle;
ballShapeDef.density = Density;
ballShapeDef.friction = Friction;
ballShapeDef.restitution = Restitution;
this->fixture = this->ballBody->CreateFixture(&ballShapeDef);
//this->shadowBall.scale = scale;
this->sprite.scale = correctedScale;
}
void Ball::SetBallOverlap(bool willOverlap, int scale){
this->world->DestroyBody(ballBody);
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(160/PTM_RATIO, 460/PTM_RATIO);
ballBodyDef.userData = sprite;
this->ballBody = world->CreateBody(&ballBodyDef);
float correctedScale = scale/9.0;
b2CircleShape circle;
circle.m_radius = (correctedScale *SpriteRadius)/PTM_RATIO;
ballShapeDef.shape = &circle;
ballShapeDef.density = Density;
ballShapeDef.friction = Friction;
ballShapeDef.restitution = Restitution;
if(willOverlap)
ballShapeDef.filter.groupIndex = 1;
else
ballShapeDef.filter.groupIndex = -1;
this->ballBody->CreateFixture(&ballShapeDef);
}
void Ball::Destroy(){
this->ballBody->DestroyFixture(fixture);
this->world->DestroyBody(ballBody);
}