'잡다한것들전부/cookbook관련'에 해당되는 글 2건
- 2014.01.14 [Box2D] Box2D 기본 예제 디버그 모드 및 스프라이트 생성
- 2014.01.14 Box2d 사용시(처음에 시작시 체크하지 않았을시)
전체소스
#ifndef __CH4_BASICSETUP__
#define __CH4_BASICSETUP__
#include "cocos2d.h"
#include "Recipe.h"
#include "Box2D/Box2D.h"
#include <GLES-Render.h>
//32 픽셀 = 1미터
#define PTM_RATIO 32
class Ch4_BasicSetup : public Recipe
{
private:
b2World* world;
GLESDebugDraw *m_debugDraw;
public:
virtual CCLayer* runRecipe();
void addLevelBoundaries();
void step(float dt);
virtual void draw();
void addNewSpriteWithCoords(CCPoint p);
void ccTouchesEnded(CCSet * touches, CCEvent * event);
};
CCLayer* Ch4_BasicSetup::runRecipe()
{
Recipe::runRecipe();
this->setTouchEnabled(true);
/* Box2D 초기화 */
// 중력의 방향을 결정한다.
b2Vec2 gravity = b2Vec2(0.0f, -30.0f);
// 월드를 생성한다.
world = new b2World(gravity);
world->SetAllowSleeping(true);
world->SetContinuousPhysics(true);
//디버그 드로잉 초기화
m_debugDraw = new GLESDebugDraw( PTM_RATIO );
world->SetDebugDraw(m_debugDraw);
uint32 flags = 0;
flags += b2Draw::e_shapeBit;
m_debugDraw->SetFlags(flags);
//레벨 경계 생성
this->addLevelBoundaries();
//블록생성을 위한 배치 노드 생성
CCSpriteBatchNode *batch = CCSpriteBatchNode::create("blocks.png", 150);
this->addChild(batch, 0, 0);
//새로운 블록 추가
CCSize screenSize = CCDirector::sharedDirector()->getWinSize();
this->addNewSpriteWithCoords(ccp(screenSize.width/2, screenSize.height/2));
//스텝 메서드 스케줄링
this->schedule(schedule_selector(Ch4_BasicSetup::step));
return this;
}
//양쪽 사각형 영역 설정
void Ch4_BasicSetup::addLevelBoundaries()
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
// 가장자리(테두리)를 지정해 공간(Ground Box)을 만든다.
// 바디데프에 좌표를 설정한다.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0);
// 월드에 바디데프의 정보(좌표)로 바디를 만든다.
b2Body *groundBody = world->CreateBody(&groundBodyDef);
// 가장자리(테두리) 경계선을 그릴 수 있는 모양의 객체를 만든다.
b2EdgeShape groundEdge;
b2FixtureDef boxShapeDef;
boxShapeDef.shape = &groundEdge;
// 에지 모양의 객체에 Set(점1 , 점2)으로 선을 만든다.
// 그리고 바디(groundBody)에 쉐이프(groundEdge)를 고정시킨다.
// 아래쪽
groundEdge.Set(b2Vec2(0,0), b2Vec2(winSize.width/PTM_RATIO, 0));
groundBody->CreateFixture(&boxShapeDef);
// 왼쪽
groundEdge.Set(b2Vec2(0,0), b2Vec2(0, winSize.height/PTM_RATIO));
groundBody->CreateFixture(&boxShapeDef);
// 위쪽
groundEdge.Set(b2Vec2(0, winSize.height/PTM_RATIO),
b2Vec2(winSize.width/PTM_RATIO, winSize.height/PTM_RATIO));
groundBody->CreateFixture(&boxShapeDef);
// 오른쪽
groundEdge.Set(b2Vec2(winSize.width/PTM_RATIO, winSize.height/PTM_RATIO),
b2Vec2(winSize.width/PTM_RATIO, 0));
groundBody->CreateFixture(&boxShapeDef);
}
//물리적 위치를 이용해서 그래픽 위치를 갱신
void Ch4_BasicSetup::step( float dt )
{
int32 velocityIterations = 8;
int32 positionIterations = 3;
world->Step(dt, velocityIterations, positionIterations);
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() != NULL) {
CCSprite *obj = (CCSprite*)b->GetUserData();
obj->setPosition( CCPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO) );
obj->setRotation( -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()) );
}
}
}
/* 디버그 그리기 데이터 */
void Ch4_BasicSetup::draw()
{
//텍스쳐 비활성화
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
world->DrawDebugData();
//텍스쳐 재활성화
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
/* 텍스처 입힌 블록을 추가합니다. */
void Ch4_BasicSetup::addNewSpriteWithCoords( CCPoint p )
{
CCSpriteBatchNode *batch = (CCSpriteBatchNode*) this->getChildByTag(0);
//랜덤하게 텍스쳐 처리된 블록을 생성
int idx = (CCRANDOM_0_1() > .5 ? 0:1);
int idy = (CCRANDOM_0_1() > .5 ? 0:1);
CCSprite *sprite = CCSprite::createWithTexture(batch->getTexture(), CCRectMake(32 * idx,32 * idy,32,32));
batch->addChild(sprite);
sprite->setPosition(ccp( p.x, p.y));
//물체 정의 및 생성
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
bodyDef.userData = sprite;
b2Body *body = world->CreateBody(&bodyDef);
//동적 본체를 위한 또다른 상자 모양 정의
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f, .5f);//1m 상자의 중간 지점
//동적 물체 픽스쳐 정의.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body->CreateFixture(&fixtureDef);
}
//클릭시 물체 추가 생성
void Ch4_BasicSetup::ccTouchesEnded( CCSet * touches, CCEvent * event )
{
//멀티터치 처리
CCSetIterator it = touches->begin();
CCTouch* touch;
for( int iTouchCount = 0; iTouchCount < touches->count(); iTouchCount++ )
{
touch = (CCTouch*)(*it);
CCPoint location = touch->getLocationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
this->addNewSpriteWithCoords(location);
it++;
}
}
#endif
'잡다한것들전부 > cookbook관련' 카테고리의 다른 글
| [Box2D] Box2D 기본 예제 디버그 모드 및 스프라이트 생성 (0) | 2014.01.14 |
|---|---|
| Box2d 사용시(처음에 시작시 체크하지 않았을시) (0) | 2014.01.14 |
처음 프로젝트를 생성할때 Box2d 를 선택하지 않고 프로젝트를 만들면
각종 오류들이뜸
속성-링커-입력-추가종속성- libBox2d.lib추가
속성-c/c++-추가포함디렉터리 - $(SolutionDir)external 추가
하면 대강 오류는 없어짐
'잡다한것들전부 > cookbook관련' 카테고리의 다른 글
| [Box2D] Box2D 기본 예제 디버그 모드 및 스프라이트 생성 (0) | 2014.01.14 |
|---|---|
| Box2d 사용시(처음에 시작시 체크하지 않았을시) (0) | 2014.01.14 |
RecipeCollection01.zip

