5. 밤하늘의 펄~

훈나무·2022년 7월 6일
0

https://github.com/hi6724/three.js-project/commit/fe33fb0b449304582cb056811e3ed4ab7d398265

이번에는 react 를 이용해서 밤하늘에 별을 만들어 보겠습니다!

1. Points


지금 까지는 mesh 만 사용해서 만들었다면, 이번에는 points 라는 것을 사용해 보겠습니다.

기본적으로 mesh 와 똑같이 geometry 와 material 이 필요합니다 (단 pointsMaterial)

points 는 mesh 와 비슷하나, 오직 점만으로 이루어졌다고 생각하면 이해하기 쉬울 것입니다.

예시

이제 points 를 이용해서 밤하늘에 별이 떠있는 모습을 만들어 보겠습니다

랜덤한 위치에 point 를 배치


  useEffect(() => {
    const count = 1000;
    const positions = new Float32Array(count * 32);
    const colors = new Float32Array(count * 32);

    for (let i = 0; i < positions.length; i++) {
      positions[i] = (Math.random() - 0.5) * 10;
      colors[i] = Math.random();
    }
    ref.current.setAttribute("position", new THREE.BufferAttribute(positions, 3));
    ref.current.setAttribute("color", new THREE.BufferAttribute(colors, 3));
  }, []);

for 문 안에서 랜덤한 배열을 생성해 줍니다.

그 다음으로는 bufferGeometry 에 setAttribute 함수를 이용해서 정점들을 생성해주고 그 정점들의 색또한 랜덤한 값으로 생성해 주었습니다

완성 코드


import { Environment, OrbitControls, useTexture } from "@react-three/drei";
import React, { useEffect, useRef } from "react";
import * as THREE from "three";
import star from "../images/star.png";

export default function ThreePoints() {
  const ref = useRef(null);
  const texture = useTexture(star);

  useEffect(() => {
    const count = 1000;
    const positions = new Float32Array(count * 32);
    const colors = new Float32Array(count * 32);

    for (let i = 0; i < positions.length; i++) {
      positions[i] = (Math.random() - 0.5) * 10;
      colors[i] = Math.random();
    }
    ref.current.setAttribute("position", new THREE.BufferAttribute(positions, 3));
    ref.current.setAttribute("color", new THREE.BufferAttribute(colors, 3));
  }, []);

  return (
    <>
      <OrbitControls />
      <points>
        <bufferGeometry ref={ref} />
        <pointsMaterial
          size={0.1}
          vertexColors
          color={"yellow"}
          map={texture}
          transparent
          alphaMap={texture}
          depthWrite={false}
        />
      </points>
    </>
  );
}
profile
프론트엔드 개발자 입니다

0개의 댓글

관련 채용 정보