DX라이브러리2014. 12. 24. 12:35

3.2 나눗셈 나머지를 이용한 루프


게임 제작시에 루프처리를 매우 많이 사용한다. 예를 들어 0-1-2-3-0-1-2-3.......같은 흐름의 루프들이다. 다음과 같이 루프시키는 방법도 있지만,


int x = 0;

while( ... ){

  x++;

  if( x == 3 ){

    x = 0;

  }

}


나눗셈의 나머지를 사용하면 좀더 간단하게 구현이 가능하다.


int x = 0;

while( ... ){

  x = ( x + 1 ) % 4

}


x의 값은 다음과 같다.


0-1-2-3-4-5-6-7-8-9.....

0-1-2-3-0-1-2-3-0-1.....


이를 활용한 예제를 확인해보자.


#include <DxLib.h>


int Key[256];



int gpUpdateKey(){

char tmpKey[256];

GetHitKeyStateAll( tmpKey );

for( int i=0; i<256; i++ ){ 

if( tmpKey[i] != 0 ){

Key[i]++;

} else {

Key[i] = 0;

}

}

return 0;

}


int WINAPI WinMain(HINSTANCE,HINSTANCE,LPSTR,int){

        ChangeWindowMode(TRUE), DxLib_Init(), SetDrawScreen( DX_SCREEN_BACK );


        int Count = 0; // 카운트를 위한 변수 선언

        int Handle = LoadGraph("image/character_01.png");


        while( ScreenFlip()==0 && ProcessMessage()==0 && ClearDrawScreen()==0 && gpUpdateKey()==0 ){


                DrawGraph(   0, Count% 50, Handle, TRUE ); // 50을 주기로 루프

                DrawGraph( 100, Count%100, Handle, TRUE ); // 100을 주기로 루프

                DrawGraph( 200, Count%150, Handle, TRUE ); // 150을 주기로 루프


                Count++; // Count 1씩 증가


        }


        DxLib_End();

        return 0;

}


실행결과




Posted by 캡슐리어