Skip to content

Instantly share code, notes, and snippets.

@tks2shimizu
Last active December 16, 2015 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tks2shimizu/e69d420bc53675d982c3 to your computer and use it in GitHub Desktop.
Save tks2shimizu/e69d420bc53675d982c3 to your computer and use it in GitHub Desktop.
Pinball (3) 背景画像に物理構造を与える
#include "HelloWorldScene.h"
#include "GB2ShapeCache-x.h"
USING_NS_CC;
#define PTM_RATIO 1024
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
// シェイプデータの読込み
gbox2d::GB2ShapeCache::sharedGB2ShapeCache()->addShapesWithFile("pinball.plist");
// 物理空間の生成
initPhysics();
// 背景を追加
createBackground();
// 毎フレーム処理の開始
scheduleUpdate();
return true;
}
void HelloWorld::createBackground()
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSprite* background = CCSprite::create("background.png");
background->setPosition(ccp(winSize.width / 2, winSize.height / 2));
this->addChild(background);
// 背景の物理構造
b2BodyDef bgBodyDef;
bgBodyDef.type = b2_staticBody;
bgBodyDef.position.Set(background->getPositionX() / PTM_RATIO, background->getPositionY() / PTM_RATIO);
bgBodyDef.userData = background;
bgBody = world->CreateBody(&bgBodyDef);
gbox2d::GB2ShapeCache* sc = gbox2d::GB2ShapeCache::sharedGB2ShapeCache();
sc->addFixturesToBody(bgBody, "background");
background->setAnchorPoint(sc->anchorPointForShape("background"));
}
void HelloWorld::initPhysics()
{
b2Vec2 gravity;
gravity.Set(0.0f, -0.8f);
world = new b2World(gravity);
}
void HelloWorld::update(float dt)
{
int velocityIterations = 8;
int positionIterations = 1;
world->Step(dt, velocityIterations, positionIterations);
}
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "Box2D.h"
class HelloWorld : public cocos2d::CCLayer
{
protected:
void createBackground();
b2World* world;
void initPhysics();
b2Body* bgBody;
public:
virtual bool init();
static cocos2d::CCScene* scene();
CREATE_FUNC(HelloWorld);
void update(float dt);
};
#endif // __HELLOWORLD_SCENE_H__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment