2014년 2월 28일 금요일

[일기]box2D. 내가 원하는 렌더링 구현하기.

이 기능을 전담할 클래스를 만들어본다.

공을 렌더링할 클래스다.

class Ball {
public:
b2Body* m_body;
float m_radius;

        //생성자에서는 이미지를 매칭시킬 강체와 고정체를 정의한다.
        //여기서 계의 포인터를 얻어오는 이유는 이 계가 여기서 생성된 강체를 관리하게 하기 위함이다.
Ball(b2World* world, float radius) {
m_body = NULL;
m_radius = radius;

b2BodyDef myBodyDef;
myBodyDef.type = b2_dynamicBody;
myBodyDef.position.Set(0, 20);
m_body = world->CreateBody(&myBodyDef);

b2CircleShape circleShape;
circleShape.m_p.Set(0, 0);
circleShape.m_radius = m_radius;

b2FixtureDef myFixtureDef;
myFixtureDef.shape = &circleShape;
myFixtureDef.density = 1;

m_body->CreateFixture(&myFixtureDef);
}
~Ball(){
                 //여기서는 해제 작업을 해야하는데 당장은 필요가 없었다.
}

        //웃는 얼굴 그리기
void render(){

                //속도에 따라 색이 변한다.
b2Vec2 vel = m_body->GetLinearVelocity();
float red = vel.Length() / 20.0;
red = b2Min( 1.0f, red );
glColor3f(red,0.5,0.5);


glColor3f(red,1-red,1);

//nose and eyes
glPointSize(4);
glBegin(GL_POINTS);
glVertex2f( 0, 0 );
glVertex2f(-0.5, 0.5 );
glVertex2f( 0.5, 0.5 );
glEnd();

//mouth
glBegin(GL_LINES);
glVertex2f(-0.5,  -0.5 );
glVertex2f(-0.16, -0.6 );
glVertex2f( 0.16, -0.6 );
glVertex2f( 0.5,  -0.5 );
glEnd();

//circle outline
glBegin(GL_LINE_LOOP);
for (float a = 0; a < 360 * DEGTORAD; a += 30 * DEGTORAD)
glVertex2f( sinf(a), cosf(a) );
glEnd();
}

        //강체의 위치에 렌더링 위치를 맞추기 위한 작업
void renderAtBodyPosition() {
b2Vec2 pos = m_body->GetPosition();
float angle = m_body->GetAngle();

glPushMatrix();
glTranslatef( pos.x, pos.y, 0 );
glRotatef( angle * RADTODEG, 0, 0, 1 );
glScalef( m_radius, m_radius, 1 );
render();
glPopMatrix();
}
};

이와 같이 하고 전역으로 벡터를 선언했다.

#include <vector>
std::vector<Ball*> balls;


Step 메서드에 다음을 추가했다.

for( int i = 0; i < balls.size(); i++)
balls[i]->renderAtBodyPosition();

생성자에는 다음을 추가했다.

for(int i = 0; i < 20; i++){
float radius = 1 + 2 * (rand()/(float)RAND_MAX); //random between 1 - 3
Ball* ball = new Ball(m_world, radius);
balls.push_back(ball);
}

결과는 이렇다.


거 신기하군.

댓글 없음:

댓글 쓰기