펄린 노이즈 관련 이미지

펄린 노이즈

PerlinNoise는 Ken Perlin이 1980년대 영화 “Tron”을 제작하는 동안 컴퓨터 효과를 위한 그라데이션 텍스처를 만들기 위해 만들었습니다. 개발한 노이즈 기능입니다. 노이즈 함수는 Minecraft 및 Terrari와 같은 많은 분야에서 사용됩니다. 설정된 규칙에 따라 게임 내 콘텐츠 자동 생성 “프로그램 콘텐츠 생성” 사용하는 게임에 적용할 수 있습니다. 이 노이즈 함수는 Unity에서 Mathf.PerlinNoise() 메서드로 제공됩니다. 그런 다음 텍스처에 노이즈를 칠하고 눈으로 노이즈를 검사해 보겠습니다.

노이즈 텍스처

using UnityEngine;

public class PerlinNoise : MonoBehaviour
{
    public int width = 256;
    public int height = 256;

    public float scale = 20f;

    public float offsetX;
    public float offsetY;

    private void Start()
    {
        offsetX = Random.Range(0f, 99999f);
        offsetY = Random.Range(0f, 99999f);       
    }

    private void Update()
    {
        Renderer renderer = GetComponent<Renderer>();
        renderer.material.mainTexture = GenerateTexture();
    }

    Texture2D GenerateTexture()
    {
        Texture2D texture = new Texture2D(width, height);

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                Color color = CalculateColor(x, y);

                texture.SetPixel(x, y, color);
            }
        }

        texture.Apply();

        return texture;
    }

    Color CalculateColor(int x, int y)
    {
        float xCoord = (float)x / width * scale + offsetX;  
        float yCoord = (float)y / height * scale + offsetY; 

        float sample = Mathf.PerlinNoise(xCoord, yCoord);

        return new Color(sample, sample, sample);
    }
}


펄린 노이즈 관련 대표 이미지

오브젝트를 생성하여 텍스처를 적용하면 위와 같이 노이즈를 확인할 수 있습니다. 이 노이즈 기능은 게임의 다양한 부분에 적용될 수 있습니다.

파도

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

public class Wave : MonoBehaviour
{
    float scale;
    float heightScale;

    int planeSize;
    public GameObject cube;

    void Start()
    {
        scale = 0.2f;
        heightScale = 2f;

        planeSize = 25;

        for (int x = 0; x < planeSize; x++)
        {
            for (int z = 0; z < planeSize; z++)
            {
                var c = Instantiate(cube, new Vector3(x, 0, z), Quaternion.identity);
                c.transform.parent = transform;
            }
        }
    }

    void Update()
    {
        foreach (Transform child in transform)
        {
            child.transform.position = new Vector3(child.transform.position.x,
            heightScale * Mathf.PerlinNoise(Time.time + (child.transform.position.x * scale),
            Time.time + (child.transform.position.z * scale)),
            child.transform.position.z);
        }
    }
}


펄린 노이즈 관련 이미지

높이 지도

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

public class PerlinColor : MonoBehaviour
{
    public int size;
    public GameObject cube;
    public float scale;
    public float m;
    bool move;
    float height;

    void Start()
    {
        move = true;

        for (int x = 0; x < size; x++)
        {
            for (int z = 0; z < size; z++)
            {
                var c = Instantiate(cube, new Vector3(x, 0, z), Quaternion.identity);

                c.transform.parent = transform;
            }
        }
    }

    void Update()
    {
        foreach (Transform child in transform)
        {
            height = Mathf.PerlinNoise(child.transform.position.x / scale, child.transform.position.z / scale);

            child.GetComponent<MeshRenderer>().material.color = new Color(height, height, height, height);
        }

        if (move)
        {
            foreach (Transform child in transform)
            {
                height = Mathf.PerlinNoise(child.transform.position.x / scale, child.transform.position.z / scale);
                child.transform.position = new Vector3(child.transform.position.x, Mathf.RoundToInt(height * m), child.transform.position.z);

                // Mathf.RoundToInt() : 매개변수로 받은 두 정수중 가까운 정수를 반환합니다.
            }
        }
    }
}


펄린 노이즈 관련 이미지

지역

using UnityEngine;

public class TerrainGenerator : MonoBehaviour
{
    public int depth = 20;

    public int width = 256;
    public int height = 256;

    public float scale = 20f;

    public float offsetX = 100f;
    public float offsetY = 100f;

    private void Start()
    {
        offsetX = Random.Range(0f, 99999f);
        offsetY = Random.Range(0f, 99999f);
    }

    private void Update()
    {
        Terrain terrain = GetComponent<Terrain>();
        terrain.terrainData = GenerateTerrain(terrain.terrainData);

        //offsetX += Time.deltaTime * 5f;
    }

    TerrainData GenerateTerrain(TerrainData terrainData)
    {
        terrainData.heightmapResolution = width + 1;

        terrainData.size = new Vector3(width, depth, height);
        terrainData.SetHeights(0, 0, GenerateHeights());

        return terrainData;
    }

    float(,) GenerateHeights()
    {
        float(,) heights = new float(width, height);

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                heights(x, y) = CalculateHeight(x, y);
            }
        }

        return heights;
    }

    float CalculateHeight(int x, int y)
    {
        float xCoord = (float)x / width * scale + offsetX;
        float yCoord = (float)y / height * scale + offsetY;

        return Mathf.PerlinNoise(xCoord, yCoord);
    }
}


펄린 노이즈 관련 이미지


펄린 노이즈 관련 이미지

Similar Posts

  • Arc’teryx Heliod 6 메신저백 일본에서 구매

    저번에 일본에서 맨티스 메신저백 살까 말까 고민했는데 품절이라 한국에 와서 눈물나게 고가에 사서 이번에 망설임 없이 사게 되었어요. 이번 오사카 여행에서 쇼핑 천국인 우메다역에 갔다가 쇼핑을 하다가 발견한 아크테릭스 매장. 최근 일본에 자주 가다보니 특별한 신제품이 없어서 눈 깜짝할 사이에 아크테릭스 헬리오드6 메신저백에 낚였습니다. 얼마전에 맨티스를 사서 아주 잘 사용하고 있지만 나 그거 봤었 어……

  • 트위터 공식 계정 신청 방법과 주의사항

    트위터는 전 세계에서 가장 인기 있는 소셜 미디어 플랫폼 중 하나로, 기업이나 개인이 공식 계정을 통해 브랜드 이미지를 구축하고 팬과 소통할 수 있는 기회를 제공합니다. 본 글에서는 트위터 공식 계정 신청 방법과 함께 알아두어야 할 중요한 팁들을 소개하겠습니다. 트위터 공식 계정 신청 절차 트위터 공식 계정 신청은 간단하지만 몇 가지 단계를 반드시 거쳐야 합니다. 아래…

  • 기능성 무기도료(재개발,재오염제거)

    새 아파트의 오염 물질 및 유해 미생물 제거 “친환경 기능성 코팅제” 올려 ㈜쎄믹스하우징은 친환경 기능성 무기질 건축마감재 “생태고급 녹색벽체”를 전문으로 생산하는 기업으로 창업이래 지속적인 친환경 건축마감재 개발을 통해 관련 특허 및 녹색기술인증을 획득하였습니다. 중소기업청과 환경부로부터 녹색기술제품으로 인증받았으며, 국가공인 인증기관인 환경보호청(KCL)으로부터 녹색환경상을 수상함과 동시에 무기 코팅에 대한 생태학적 인증 미국 식품의약국(FDA) 친화적 제품 등록(US Code Title21)의…

  • 유루 2023.03.09.

    매일 뉴스 내 말은 모두의 목소리 세상이 어떻게 판단하느냐에 맡기고 싶어 (내 말은 만인 명망의 세계 검토) 청일전쟁 때 ‘군사’로 중의원에서 쫓겨난 사이토 다카오(1870~1949)가 지은 한시이다. 그는 회고록에서 “앞으로 반드시 국민이 중의원을 축출하는 날이 올 것”이라고 회고했다. 대부분의 민주주의 국가에서 퇴거는 변칙 중의 변칙입니다. 의회 탄압의 역사적 교훈은 배후에 있다. 세 명의 의원이 남북 전쟁…

  • 개구리 종이 접기를 만드는 방법

    이번에는 아주 쉽게 만들 수 있는 개구리 종이접기 접는 방법을 천천히 소개하도록 하겠습니다. 자, 이번에는 종이접기 동물 중 가장 쉽고 쉬운 수준인 개구리를 만들어 볼게요. 이 작품은 위아래로 점프할 수 있는데, 바닥을 직접 손으로 누르면 아주 멀리 점프합니다. 개구리 만드는 과정 검토 초등학교 때 개구리 많이 접고 친구들과 따먹기 놀이를 많이 했어요. 토끼도 개구리도 쉽다고…

  • (밀키트 리뷰) 나만의 든든한 스팸 부대찌개 – 홈플러스 (2.0)

    (밀키트 리뷰) 나만의 든든한 스팸 부대찌개 – 홈플러스 (2.0) 기본정보 판매자: (주)홈플러스 제조사 : (주)참맛나라 정가 : 5,900원 / 할인구매가 2,990원 무게: 1인분당 525g 보관: 냉장(0~10°C) 홈플러스 방문시 할인폭이 커서 이 제품을 구매했습니다. 부대찌개 밀키트로 만족하기란 쉽지 않다. 할인글 올리고 나니 가격이 엄청 흑화되서 사버렸네요. 기본을 맛본 후 몇 가지를 추가하는 경향이 있습니다. 라면을 미루고…