본문 바로가기

IT/유니티

3. 유니티 교육 (구조체와 함수)

1. 구조체와 함수


오늘은 C언어의 꽃이라고 할수 있는? 포인터 아닌가? 아무튼 엄청 중요한 구조체와 함수에 대해서 공부해보았습니다.

게임을 만들때에 있어서도 구조체는 엄청 중요할거 같내요.

함수야 프로그래밍에서 절대 없어서는 안되는 개념이니까요. 당연히 숙지해야하구요!


우선 다음 소스를 보시죠~



#include<stdio.h>

#include<string.h>

#include<cstdlib>

#include<ctime>


struct Monster

{

//이름은 10자리 이하로

char name[10];

//hp에 마이너스는 없으므로 언사인드를 사용한다.

unsigned int health;

//몬스터의 무기. 메모리 절약을 위해 1바이트만 사용한다

char weapon;

//생성위치

int pos[2];

};



int getRandNum(int num) {

int returnValue;

returnValue = rand() % num;


return returnValue;

}


void main(void) {

//랜덤함수를 위한 설정

srand((unsigned)time(NULL));


int maxMonsterNum = getRandNum(20)+1;

int mapX = 70;

int mapY = 30;



Monster *mArray = new Monster[maxMonsterNum];

char weaponName[4][10] =

{ "axe", "sword" ,"gun" ,"rocket" };

char monsterName[10][20] =

{ "orc", "troll" ,"orge" ,"imp", "hell hound"

, "vampire", "imp", "warewolf", "slime", "dark elf" };


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

strcpy(mArray[i].name, monsterName[getRandNum(10)]);

mArray[i].health = getRandNum(50000) + 10000;

mArray[i].weapon = getRandNum(4);

mArray[i].pos[0] = getRandNum(mapX);

mArray[i].pos[1] = getRandNum(mapY);

}


//현재 괴물이 가지고 있는 무기의 종류를 화면에 출력해주는 코드를 추가하자

//switch나 if else를 사용하자

//무기의 종류는 아래와 같다

//1.도끼 2.칼 3.총 4.로켓포

//괴물의 정보를 출력할때 이름 무기 2가지만 출력해줌


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

Monster tempMonster = mArray[i];

printf("name:%s\nweapon:%s hp:%d location:%d/%d\n", 

tempMonster.name, weaponName[tempMonster.weapon], tempMonster.health

, tempMonster.pos[0], tempMonster.pos[1]);

}


for (int y = 0; y < mapY; y++) {

for (int x = 0; x < mapX; x++) {

int isMonsterOnMap = 0;

char monstNameHead;

//몬스터 위치를 검색해서 표시해준다.

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

Monster tempMonster = mArray[i];

if (tempMonster.pos[0] == x && tempMonster.pos[1] == y) {

monstNameHead = tempMonster.name[0];

isMonsterOnMap = 1;

}

}

if (isMonsterOnMap == 0) {

printf("*");

}

else {

printf("%c", monstNameHead);

}

}

printf("\n");

}



}



위의 소스를 보시면 몬스터라는 구조체를 만들어서 사용하고 있습니다.

이렇게 구조체를 만들면 필요한 정보들을 구조체라는 덩어리에 담아서 일괄 보관 처리하기 용이해집니다.

결국 이 구조체라고 하는 개념이 발전해서 객체가 되는거니까요. 엄청 중요요!!


몬스터를 구조체를 만들고 몇십개의 랜덤 몬스터를 생성하기 위해 필요한 랜덤값이 필요한데

이때 필요할때마다 랜덤 코드를 쓰면 보기도 안좋고 쓸대없이 코드만 길어지니까,

위의 소스와같이 getrandnum이라는 함수를 만들어서 보기좋게 하였습니다.

인자는 최대값을 받고 리턴값은 그 최대값안의 랜덤값을 출력하도록 만들었습니다.



**갑자기 포인터 연습!**


  char data[5] = {'A','B', 'C', 'D', 'E'};

//포인터

char *pData = 0;


//배열의 시작위치를 저장해둔다.

pData = &data[0];


//해당 메모리 주소에 접근한후, 데이터에 접근

printf("%c", *pData);


//포인터는 결국 주소를 의미하므로, 

//주소의 위치를 변경해서 배열의 다음 값을 얻어 올수 있다.

printf("%c", *pData + 1);

printf("%c", *pData + 2);

printf("%c", *pData + 3);

printf("%c", *pData + 4);



포인터는 결국 주소값을 의미한다. 그래서 이 주소값을 가지고 간접적으로 

데이터에 접근 및 변경을 할수 있는것이 c언어의 큰 장점이나 단점이라고 할수 있을것이다.





메인안의 함수가 조금 지저분해보여서 조금 정리해보았습니다.


#include<stdio.h>

#include<string.h>

#include<cstdlib>

#include<ctime>


struct Monster

{

//이름은 10자리 이하로

char name[10];

//hp에 마이너스는 없으므로 언사인드를 사용한다.

unsigned int health;

//몬스터의 무기. 메모리 절약을 위해 1바이트만 사용한다

char weapon;

//생성위치

int pos[2];

};



int getRandNum(int num) {

int returnValue;

returnValue = rand() % num;


return returnValue;

}


void spawnMonster(Monster* mArray, int maxNum, char mName[][20], int mapX, int mapY) {

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

strcpy(mArray[i].name, mName[getRandNum(10)]);

mArray[i].health = getRandNum(50000) + 10000;

mArray[i].weapon = getRandNum(4);

mArray[i].pos[0] = getRandNum(mapX);

mArray[i].pos[1] = getRandNum(mapY);

}

}


void main(void) {

//랜덤함수를 위한 설정

srand((unsigned)time(NULL));


//몬스터 최대 생성수

int maxMonsterNum = getRandNum(20)+1;


//지도의 범위 지정

int mapX = 70;

int mapY = 30;


//몬스터 정보가 들어가 배열

Monster *mArray = new Monster[maxMonsterNum];


//무기 이름 배열

char weaponName[4][10] =

{ "axe", "sword" ,"gun" ,"rocket" };


//몬스터 이름 배열

char monsterName[10][20] =

{ "orc", "troll" ,"orge" ,"imp", "hell hound"

, "vampire", "imp", "warewolf", "slime", "dark elf" };



//몬스터를 생성한다.

spawnMonster(mArray, maxMonsterNum, monsterName, mapX, mapY);



//현재 괴물이 가지고 있는 무기의 종류를 화면에 출력해주는 코드를 추가하자

//switch나 if else를 사용하자

//무기의 종류는 아래와 같다

//1.도끼 2.칼 3.총 4.로켓포

//괴물의 정보를 출력할때 이름 무기 2가지만 출력해줌


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

Monster tempMonster = mArray[i];

printf("name:%s\nweapon:%s hp:%d location:%d/%d\n", 

tempMonster.name, weaponName[tempMonster.weapon], tempMonster.health

, tempMonster.pos[0], tempMonster.pos[1]);

}


for (int y = 0; y < mapY; y++) {

for (int x = 0; x < mapX; x++) {

int isMonsterOnMap = 0;

char monstNameHead;

//몬스터 위치를 검색해서 표시해준다.

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

Monster tempMonster = mArray[i];

if (tempMonster.pos[0] == x && tempMonster.pos[1] == y) {

monstNameHead = tempMonster.name[0];

isMonsterOnMap = 1;

}

}

if (isMonsterOnMap == 0) {

printf("*");

}

else {

printf("%c", monstNameHead);

}

}

printf("\n");

}

}