레이블이 Unity인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Unity인 게시물을 표시합니다. 모든 게시물 표시

2019년 11월 18일 월요일

How to completely make 'Minecraft'(마인크래프트를 통째로 만드는 방법)을 따라해보며 유니티(Unity)를 연구하자 : 07-시점에 십자선(Crosshair)넣기, 08-(응용)UI..

유튜브(Youtube) Vagabond Developer(방랑개발자)님의 How to completely make 'Minecraft'(마인크래프트를 통째로 만드는 방법)을 따라하면서 유니티(Unity)를 알아가고 있습니다.  그 정리입니다.




07-시점에 십자선(Crosshair)넣기

십자선(Crosshair)이미지 준비

그림판에서 가로,세로 32픽셀의 검정색배경의 정사각형 이미지작성, 흰색 선으로 정중앙을 기준으로 십자선 작성
이미지를 Crosshair.png로 저장



임포트(Import) 후 투명이미지로 변경





Sprites폴더를 만들고 작성한 이미지(Crosshair.png)를 임포트(Import)





임포트 설정(Import Settings)을 변경해서 투명이미지 작성

Texture Type : Sprite (2D and UI)
Advanced>>Alpha Source : From Gray Scale
변경후 Apply(적용)



UI Image추가





Hierarchy >> Create >> UI >> Image 선택





추가된 Canvas>>Image의 Image >> Source Image를 Sprites>>Crosshair 로 설정
오른쪽의 설정버튼(톱니바퀴)를 클릭해서 선택하거나, Sprites>>Crosshair를 드래그 앤 드롭

Game화면에 십자선(Crosshair)가 표시됨

실행





십자선이 잘 표시됨

수정1. 십자선이 너무 크므로 조정





Canvas>>Image 의 Rect Transform>>Width : 20, Height:20으로 조정

수정2. 클릭위치 조정





블럭의 모서리를 클릭한 경우 블럭이 삭제되지 않음






Canvas>>Image 의 Rect Transform>>Pos Y:15으로 조정

블럭의 모서리를 클릭해도 잘 삭제됨

08-(응용)UI-Image, UI-Text 만져보기

이미지 준비해서 임포트, 좌측상단에 표시





샘플이미지를 임포트(Import)





임포트 설정(Import Settings)을 변경

Texture Type : Sprite (2D and UI)
변경후 Apply(적용)






좌측 상단에 표시위해 Game화면상태에서
Canvas>>Image 의 Rect Transform>>Width,Height를 조정
(Width, Height글자위에 마우스를 올린후 오른쪽클릭하면 스크롤로 직관적으로 조정가능)






잘 표시됨






Hierarchy >> Create >> UI >> Text 선택

Canvas>>Image 의 Text>>Text에 "Unity"입력
Text>>Font Style : Bold
Font Size>>27
로 설정

좌측 상단에 표시위해 Game화면상태에서
Canvas>>Image 의 Rect Transform>>Width,Height를 조정
(Width, Height글자위에 마우스를 올린후 오른쪽클릭하면 스크롤로 직관적으로 조정가능)






잘 표시됨

이로서 "How to completely make 'Minecraft' (Part 1): Terrain Generation" 은 완료입니다.
다음부터는 블록이 많아질수록 느려지는 현상을 해결하기 위한 오클루전 컬링(Occlusion Culling)를 다루는 "How to completely make 'Minecraft' (Part 2): Basic Runtime Occlusion Culling"의 정리예정입니다.

2019년 10월 31일 목요일

How to completely make 'Minecraft'(마인크래프트를 통째로 만드는 방법)을 따라해보며 유니티(Unity)를 연구하자 : 04-땅표면 아래를 흙블럭과 돌블럭로 채우기, 05-블럭을 스크립트(Script)로 제어

유튜브(Youtube) Vagabond Developer(방랑개발자)님의 How to completely make 'Minecraft'(마인크래프트를 통째로 만드는 방법)을 따라하면서 유니티(Unity)를 알아가고 있습니다.  그 정리입니다.





04-땅표면 아래를 흙블럭과 돌블럭로 채우기

01-기본설정 및 평평한 땅 만들기에서 GrassBlock의 프리팹(Prefab)을 작성한 것과 동일한 방식으로 DirtBlock, StoneBlock의 프리팹(Prefab)을 작성

이미지를 준비해 텍스처작성 / 큐브(Cube)를 추가하고 머티리얼(Material)입히기 / 프리팹(Prefab) 작성

구글(Google) 이미지검색에서 dirt,stone를 아이콘사이즈로 검색해서 Dirt, Stone으로 저장, 팝업메뉴의 (Import New Asset...)로 임포트(Import)하거나 드래그해서 Textures폴더에 넣음






WorldGenerator스크립트(Script) 코딩

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WorldGenerator : MonoBehaviour
{
    public GameObject player;  //플레이어 설정용

    public int sizeX;
    public int sizeZ;

    public int groundHeight; //땅의 깊이

    public float terDetail;  //Mathf.PerlinNoise적용
    public float terHeight;  //Mathf.PerlinNoise적용
    int seed;                //Mathf.PerlinNoise적용

    public GameObject[] blocks;

    // Start is called before the first frame update
    void Start()
    {
        seed = Random.Range(100000,999999);
        GenerateTerrain();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void GenerateTerrain()
    {
        for (int x = 0; x < sizeX; x++)
        {
            for (int z = 0; z < sizeZ; z++)
            {
                //maxY : 표면(GlassBlock)
                int maxY = (int)(Mathf.PerlinNoise((x / 2 + seed) / terDetail, (z / 2 + seed) / terDetail) * terHeight);
                maxY += groundHeight; // 표면(GlassBlock)을 땅의 깊이(groundHeight)만큼 올려줌
                
                GameObject grass = Instantiate(blocks[0], new Vector3(x, maxY, z), Quaternion.identity) as GameObject;
                grass.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform,false);

                for (int y = 0; y < maxY; y++) // 표면(GlassBlock)아래의 땅 생성
                {
                   GameObject stone = Instantiate(blocks[1], new Vector3(x, y, z), Quaternion.identity) as GameObject;
                   stone.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform, false);
                }
                
                if (x == (int)(sizeX / 2) && z == (int)(sizeZ / 2)) //표면(GlassBlock)의 정 중앙에 표시
                {
                    Instantiate(player, new Vector3(x, maxY + 3, z), Quaternion.identity);
                }

            }
        }
    }
}
public int groundHeight;
땅 깊이

int y = (int)(Mathf.PerlinNoise((x / 2 + seed) / terDetail, (z / 2 + seed) / terDetail) * terHeight);
기존의 처리를 변경(땅 깊이(groundHeight)만큼 표면(GrassBlock)을 올려줌)
int maxY = (int)(Mathf.PerlinNoise((x / 2 + seed) / terDetail, (z / 2 + seed) / terDetail) * terHeight); 
maxY += groundHeight;GameObject grass = Instantiate(blocks[0], new Vector3(x, maxY, z), Quaternion.identity) as GameObject; 
grass.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform,false);

for (int y = 0; y < maxY; y++)
{ 
   GameObject stone = Instantiate(blocks[1], new Vector3(x, y, z), Quaternion.identity) as GameObject;       
   stone.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform, false); 
}
표면(GrassBlock) 아래의 땅을 StoneBlock으로 채우기

if (x == (int)(sizeX / 2) && z == (int)(sizeZ / 2)) //표면(GlassBlock)의 정 중앙에 표시
{
   Instantiate(player, new Vector3(x, maxY + 3, z), Quaternion.identity);
}
플레이어의 위치도 표면(GlassBlock)보다 조금 높은 위치로 조정

Environment오브젝트(Object)의 Blocks에 StoneBlock프리팹(Prefab)설정



GroundHeight설정

Blocks의 사이즈를 2로 변경
추가로 표시되는 Element 1에 StoneBlock프리팹(Prefab)을 설정(드래그 앤 드롭 또는 선택)

실행



표면(GrassBlock)과 땅밑이 깊이만큼 StoneBlock으로 잘 채워짐

WorldGenerator스크립트(Script) 코딩


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WorldGenerator : MonoBehaviour
{
    public GameObject player;  //플레이어 설정용

    public int sizeX;
    public int sizeZ;

    public int groundHeight; //땅의 깊이

    public float terDetail;  //Mathf.PerlinNoise적용
    public float terHeight;  //Mathf.PerlinNoise적용
    int seed;                //Mathf.PerlinNoise적용

    public GameObject[] blocks;

    // Start is called before the first frame update
    void Start()
    {
        seed = Random.Range(100000,999999);
        GenerateTerrain();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void GenerateTerrain()
    {
        for (int x = 0; x < sizeX; x++)
        {
            for (int z = 0; z < sizeZ; z++)
            {
                //maxY : 표면(GlassBlock)
                int maxY = (int)(Mathf.PerlinNoise((x / 2 + seed) / terDetail, (z / 2 + seed) / terDetail) * terHeight);
                maxY += groundHeight; // 표면(GlassBlock)을 땅의 깊이(groundHeight)만큼 올려줌
                
                GameObject grass = Instantiate(blocks[0], new Vector3(x, maxY, z), Quaternion.identity) as GameObject;
                grass.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform,false);

                for (int y = 0; y < maxY; y++) // 표면(GlassBlock)아래의 땅 생성
                {
                   int dirtLayers = Random.Range(1, 5); //흙(DirtBlock)의 깊이를 랜덤하게
                   if (y >= maxY - dirtLayers)
                   {
                      //흙(DirtBlock)
                      GameObject dirt = Instantiate(blocks[2], new Vector3(x, y, z), Quaternion.identity) as GameObject;
                      dirt.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform, false);
                   }
                   else
                   {
                      //돌(StoneBlock)
                      GameObject stone = Instantiate(blocks[1], new Vector3(x, y, z), Quaternion.identity) as GameObject;
                      stone.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform, false);
                   }
                }
                
                if (x == (int)(sizeX / 2) && z == (int)(sizeZ / 2)) //표면(GlassBlock)의 정 중앙에 표시
                {
                    Instantiate(player, new Vector3(x, maxY + 3, z), Quaternion.identity);
                }

            }
        }
    }
}
int dirtLayers = Random.Range(1, 5); 흙(DirtBlock)의 깊이를 랜덤하게

GrassBlock
------------- maxY
DirtBlock
-------------  ( maxY - dirtLayers )
StoneBlock
------------- 0

if (y >= maxY - dirtLayers) 
{ 
   GameObject dirt = Instantiate(blocks[2], new Vector3(x, y, z), Quaternion.identity) as GameObject;       
   dirt.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform, false); 
} 
else 
{ 
   GameObject stone = Instantiate(blocks[1], new Vector3(x, y, z), Quaternion.identity) as GameObject;      
   stone.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform, false); 
}

Environment오브젝트(Object)의 Blocks에 DirtBlock프리팹(Prefab)설정



Blocks의 사이즈를 3로 변경

추가로 표시되는 Element 2에 DirtBlock프리팹(Prefab)을 설정(드래그 앤 드롭 또는 선택)

실행



표면(GrassBlock)과 땅밑이 깊이만큼 랜덤의 DirtBlock과 StoneBlock으로 잘 채워짐

05-블럭을 스크립트(Script)로 제어

BlockScript스크립트(Script)을 추가하고 코딩




using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BlockScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    //마우스눌렀을때
    private void OnMouseDown()
    {
        Destroy(this.gameObject);
    }
}
private void OnMouseDown() 
{ 
   Destroy(this.gameObject); 
}

OnMouseDown : 마우스 왼쪽 클릭만 작동

public static void Destroy (Object obj, float t= 0.0F) :  오브젝트(obj)를 t만큼의 딜레이후 삭제

this.gameObject: 자기 자신 (스크립트(Script)를 블럭에 설정할 예정이므로 클릭된 블럭의 의미)
참고) 마우스 왼쪽, 오른쪽, 중간버튼 클릭 체크

    private void OnMouseOver()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Debug.Log("Left");
        }
        if (Input.GetMouseButtonDown(1))
        {
            Debug.Log("RIGHT");
        }
        if (Input.GetMouseButtonDown(2))
        {
            Debug.Log("CENTER");
        }
    }

블럭프리팹(Prefab)에 BlockScript스크립트(Script)을 설정




프리팹(Prefab)폴더안의 각 블럭프리팹(Prefab)을 선택>>Inspector >> Add Component 후 BlockScript검색해서 추가
혹은 스크립트(Script)폴더의 BlockScript를 블럭프리팹(Prefab)으로 드래그 앤 드롭

실행



마우스를 클릭하면 화면의 정중앙의 블록이 잘 삭제됨

FPSController조정

발밑의 땅을 파도(삭제) FPSController의 크기가 커서 빠지지 않으므로 크기를 조정


FPSController선택>>Inspector >>Transform>>Scale 조정
x,y,z 1 -> 0.8

다음엔 정중앙을 직관적으로 표시하기위해 십자선(Crosshair)넣기를 진행

2019년 10월 28일 월요일

How to completely make 'Minecraft'(마인크래프트를 통째로 만드는 방법)을 따라해보며 유니티(Unity)를 연구하자 : 02-울퉁불퉁한 지형 만들기, 03-Standard Assets의FPSController로 1인칭시점 플레이어추가

유튜브(Youtube) Vagabond Developer(방랑개발자)님의 How to completely make 'Minecraft'(마인크래프트를 통째로 만드는 방법)을 따라하면서 유니티(Unity)를 알아가고 있습니다.  그 정리입니다.


번외-게임오브젝트(Game Object)정리

우선 지난 정리의 상태로 실행하면 Hierarchy에 GrassBlock(Clone)이 무수히 생성되어 보기 좋지 않으니 GrassBlock(Clone)을 Environment아래로 속하도록 스크립트(Script)를 조정실시

WorldGenerator.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WorldGenerator : MonoBehaviour
{
    public int sizeX; //땅의 좌우크기
    public int sizeZ; //땅의 상하크기

    public GameObject[] blocks; //블록 저장

    // Start is called before the first frame update
    void Start()
    {
        GenerateTerrain();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    //땅 만들기 함수
    void GenerateTerrain()
    {
        //땅의 좌우,상하 크기까지 반복하며 블록복사 배치 
        for (int x = 0; x < sizeX; x++)
        {
            for (int z = 0; z < sizeZ; z++)
            {
                //Instantiate(blocks[0], new Vector3(x,0,z), Quaternion.identity); //기존처리
                GameObject grass = Instantiate(blocks[0], new Vector3(x, 0, z), Quaternion.identity) as GameObject;
                grass.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform);
            }
        }
    }
}
GameObject grass = Instantiate(blocks[0], new Vector3(x, y, z), Quaternion.identity) as GameObject;
GrassBlock(Clone)를 GameObject grass작성

grass.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform);
grass의 부모를 Environment로 설정
Transform.SetParent를 찾아봅니다.
public void SetParent (Transform parent);
public void SetParent (Transform parent, bool worldPositionStays);

Transform의 부모를 설정합니다.
worldPositionStays : 기본값은 true, 자식의 position정보를 부모의 position을 기반으로 하는 localPosition으로 함
                           false: 자식의 position정보를 부모를 기본으로 기존의 worldPosition만큼 멀어진 좌표로 함
worldPositionStays은 정확히 이해를 하지못했으나 테스트결과를 정리
둘다 작동상 차이점은 확인 못했으나 true, false에 따라 position값이 달라짐을 확인

worldPositionStays(true)worldPositionStays(false)
Environmentposition.x=10position.x=10
GrassBlock(Clone)position.x=-10position.x=0
변경하고 실행하면 루트에서 표시되던 GrassBlock(Clone)이 Environment의 아래로 속함

02-울퉁불퉁한 땅 만들기

땅을 만드는 GrassBlock(Clone)의 position의 x,z값만 지정했기에 평평한 땅이 만들어짐
position의 y값도 지정해 울퉁불퉁하게 만듦

WorldGenerator스크립트(Script) 코딩

y의 값을 랜덤하게 넣어줘봄
    void GenerateTerrain()
    {
        for (int x = 0; x < sizeX; x++)
        {
            for (int z = 0; z < sizeZ; z++)
            {

                int y = Random.Range(0, 10);  //0~10사이의 랜덤값으로 y를 설정

                GameObject grass = Instantiate(blocks[0], new Vector3(x, y, z), Quaternion.identity) as GameObject;
                grass.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform,false);

            }
        }
    }

울퉁불퉁한 지형이 아닌 서로 떨어진 우주공간에 떠 있는 형태의 모양이됨

부드럽게 이어줘야 함
여기에서 유용한 것이 Mathf.PerlinNoise 함수
입력 값(x,y)의 변화에 따라 서서히 변화하는 난수를 생성
얻을 수 있는 값은 0~1
x와 y의 값이 같으면 항상 같은 값을 반환

Mathf.PerlinNoise 함수이용
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WorldGenerator : MonoBehaviour
{
    public int sizeX;
    public int sizeZ;

    public float terDetail;  //Mathf.PerlinNoise적용
    public float terHeight;  //Mathf.PerlinNoise적용
    int seed;                //Mathf.PerlinNoise적용

    public GameObject[] blocks;

    // Start is called before the first frame update
    void Start()
    {
        seed = Random.Range(100000,999999);
        GenerateTerrain();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void GenerateTerrain()
    {
        for (int x = 0; x < sizeX; x++)
        {
            for (int z = 0; z < sizeZ; z++)
            {
                int y = (int)(Mathf.PerlinNoise((x / 2 + seed) / terDetail, (z / 2 + seed) / terDetail) * terHeight);
                GameObject grass = Instantiate(blocks[0], new Vector3(x, y, z), Quaternion.identity) as GameObject;
                grass.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform,false);

            }
        }
    }
}
public float terDetail; 
public float terHeight; 
int seed;

seed = Random.Range(100000,999999);
seed값을 100000과 999999의 사이츼 수로 랜덤하게 설정

int y = (int)(Mathf.PerlinNoise((x / 2 + seed) / terDetail, (z / 2 + seed) / terDetail) * terHeight);
랜덤값이지만 이어지는 y값을 출력

TerDetail=20, TerHeight=20정도의 설정으로 생성된 지형

강좌에서 사용한 알고리즘이 아닌 스스로 여러가지 변경해봄

TerDetail=20, TerHeight=20
int y = (int)(Mathf.PerlinNoise( (x + seed) / terDetail, (z+seed) / terDetail) * terHeight));



TerDetail=20, TerHeight=40
int y = (int)(Mathf.PerlinNoise((x / 2 + seed) / terDetail, (z / 2 + seed) / terDetail) * terHeight);



TerDetail=40, TerHeight=20
int y = (int)(Mathf.PerlinNoise((x / 2 + seed) / terDetail, (z / 2 + seed) / terDetail) * terHeight);

강좌에서 사용된 알고리즘이 좋은 알고리즘이겠지만 자유롭게 변경해도 문제없을 것 같음

03-Standard Assets의FPSController로 1인칭시점 플레이어추가

Asset Store에 연결해서 Standard Assets 다운로드(Download) 및 임포트(Import)

유니티(Unity)의 메뉴에서 Window >> Asset Store 선택 ( 혹은 Ctrl+9) 해서 Asset Store에 연결
유니티(Unity) 어카운트로 로그인 필요

Asset Store에서 'Standard'키워드로 검색
'Standard Assets'를 다운로드(Download) , 임포트(Import)

필요한 요소 선택
위의 그림은 이미 임포트(Import)된 상태에서 다시 임포트(Import)를 했을 경우임
반대(체크->비체크, 비체크->체크)로 해서 임포트(Import), 혹은 전체 임포트(Import)해도 무방

임포트(Import) 한 것들

Standard Assets
--Characters
----FirstPersonCharacter
------Prefabs
--------FPSController  <-이것을 이용함
--CrossPlatformInput
--Editor
--Environment
--PhysicsMeterials
--Utility

플레이어(Player)를 추가하기 위해 WorldGenerator스크립트(Script) 코딩

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WorldGenerator : MonoBehaviour
{
    public GameObject player;  //플레이어 설정용

    public int sizeX;
    public int sizeZ;

    public float terDetail;  //Mathf.PerlinNoise적용
    public float terHeight;  //Mathf.PerlinNoise적용
    int seed;                //Mathf.PerlinNoise적용

    public GameObject[] blocks;

    // Start is called before the first frame update
    void Start()
    {
        seed = Random.Range(100000,999999);
        GenerateTerrain();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void GenerateTerrain()
    {
        for (int x = 0; x < sizeX; x++)
        {
            for (int z = 0; z < sizeZ; z++)
            {
                int y = (int)(Mathf.PerlinNoise((x / 2 + seed) / terDetail, (z / 2 + seed) / terDetail) * terHeight);
                GameObject grass = Instantiate(blocks[0], new Vector3(x, y, z), Quaternion.identity) as GameObject;
                grass.transform.SetParent(GameObject.FindGameObjectWithTag("Environment").transform,false);

                if (x == (int)(sizeX / 2) && z == (int)(sizeZ / 2)) //땅의 정 중앙에 표시
                {
                    Instantiate(player, new Vector3(x, y + 3, z), Quaternion.identity);
                }

            }
        }
    }
}
public GameObject player;
유니티(Unity)에서 임포트(Import)한 FPSController를 설정할 예정

if (x == (int)(sizeX / 2) && z == (int)(sizeZ / 2)) 
{ 
  Instantiate(player, new Vector3(x, y + 3, z), Quaternion.identity); 
}
플레이어를 땅의 정 중앙에 땅보다 조금 높은 위치에 캐릭터를 위치시킴

Environment의 Player에 FPSController 설정

FPSController를 Environment의 Player에 드래그 앤 드롭
(혹은 Player 입력폼 옆의 동그래미를 클릭해 FPSController를 선택)

실행

1인칭 시점으로 출력됨
WASD키로 이동,  스페이스로 점프, 마우스로 좌우 시점 변경가능
그러나 마우스로 상하 시점변경이 불가능
이유는 FPSController에 포함된 카메라가 아닌 기본의 Main Camera로 표시되기 때문
Hierarchy >> Main Camera 의 팝업메뉴 >> Delete
Main Camera 삭제

재실행

마우스로 상하좌우 모든 시점변경가능

현재는 울툴불퉁한 땅의 표면만 GrassBlock(Clone)으로 표현상 상태로 다음엔 표면의 아래를 흙과 돌의 블럭으로 채우기진행

1、2、QWER! in OSAKA (大阪 2025/4/10(木) Yogibo META VALLEY)

https://www.creativeman.co.jp/event/qwer-osaka/ QWER - CREATIVEMAN PRODUCTIONS 主催:LIVET 企画:ソニー・ミュージックソリューションズ 招聘:クリエイティブマンプロダクション 制作協力:クリエイテ...