관련 자료

|

http://www.raywenderlich.com

'잡다한것들전부 > 2D 관련 자료' 카테고리의 다른 글

유니티 2디 간단 사용영상  (0) 2014.01.22
관련 자료  (0) 2014.01.15
Trackback 0 And Comment 0

안드로이드 NDK 책

|

안드로이드 NDK 네이티브 프로그래밍(위키북스 임베디드 & 모바일 시리즈)
유일한 국내 번역 안드로이드 NDK 책?

'보고싶은책' 카테고리의 다른 글

c# 기본서 추천(c# IN DEPTH)  (0) 2014.01.19
열혈강의 cocos2d-x  (0) 2014.01.16
안드로이드 NDK 책  (0) 2014.01.15
“Game Programming Gems 1권 – 3.3 A* 길찾기 알고리즘의 기초”  (0) 2014.01.14
프로그래머를 위한 책  (0) 2014.01.13
Code Complete  (0) 2014.01.13
Trackback 0 And Comment 0

[Box2D] Box2D 기본 예제 디버그 모드 및 스프라이트 생성

|

RecipeCollection01.zip


전체소스




#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




Trackback 0 And Comment 0