wam
w__am 개발노트
wam
  • 분류 전체보기 (165)
    • CS 지식 (10)
      • 자료구조 (0)
      • 알고리즘 (0)
      • 컴퓨터 구조 (0)
      • 운영체제 (0)
      • 네트워크 (7)
      • 데이터베이스 (0)
      • 디자인 패턴 (3)
    • Frontend (131)
      • Three.js (64)
      • NPM (1)
      • Nest.js (19)
      • React (10)
      • Apollo (7)
      • TypeScript (2)
      • JavaScript (12)
      • HTML, CSS (1)
      • Jest (3)
      • E2E (5)
      • Cypress (7)
    • Database (12)
      • TypeORM (12)
    • IT 지식 (8)
      • 클라우드 서비스 (3)
      • 네트워크 (1)
      • 데이터 포맷 (2)
      • 기타 (2)
    • IT Book (2)
    • 유용한 사이트 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 🐱 Github

인기 글

태그

  • mapped types
  • math.sin()
  • 함수 리터럴
  • 데이터 포맷
  • 삼각함수
  • 함수 표현식
  • getdelta()
  • type-graphql
  • math.cos()
  • API
  • 원형적인 움직임
  • Interface
  • 렌더링 성능 최적화
  • 디자인 패턴
  • e.preventdefault()
  • 함수의 범위
  • 오프-프레미스(off-premise) 방식
  • 초기 환경설정
  • react 성능 최적화
  • 스코프
  • 함수 선언문
  • isabstract
  • joi 에러
  • gridhelper
  • reactive variables
  • axeshelper
  • threejs 개발 할 때 도움을 줄 수 있는 유틸리티
  • three.js 구성 요소
  • getelapsedtime()
  • Decorators

최근 글

관리자

글쓰기 / 스킨편집 / 관리자페이지
hELLO · Designed By 정상우.
wam

w__am 개발노트

카메라 컨트롤, PointerLockControls
Frontend/Three.js

카메라 컨트롤, PointerLockControls

2024. 9. 5. 16:48

 

PointerLockControls

 

마우스 커서를 숨기고 사용자가 마우스를 움직이는 방향에 따라 카메라의 시점을 변경해주는 컨트롤러이다. 이 컨트롤러는 주로 1인칭 시점 게임이나 3D 시뮬레이션에서 자유롭게 시점을 변경하고, 사용자가 화면을 넘어서도 마우스를 계속 움직일 수 있도록 해준다.

 

 

MDN문서_Pointer Lock API

PointerLock API를 사용하여 마우스 커서를 화면에서 숨기고, 커서의 위치 대신 움직임 변화를 추적하는 방식이다. 이는 Three.js와 같은 3D 라이브러리에서 1인칭 시점 제어를 구현할 때 매우 유용하다.

 

 

import * as THREE from "three";
import { PointerLockControls } from "three/examples/jsm/controls/PointerLockControls";

/* 주제: PointerLockControls */

export default function example() {
  /* Renderer 만들기 : html에 캔버스 미리 만들기 */
  const canvas = document.querySelector("#three-canvas");
  const renderer = new THREE.WebGLRenderer({
    canvas,
    antialias: true
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);

  /* Scene 만들기 */
  const scene = new THREE.Scene();

  /* Camera 만들기 */
  const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  camera.position.y = 1.5;
  camera.position.z = 7;
  scene.add(camera);

  /* Light 만들기 */
  const ambientLight = new THREE.AmbientLight("white", 0.5);
  scene.add(ambientLight);

  const directionalLight = new THREE.DirectionalLight("white", 1);
  directionalLight.position.x = 1;
  directionalLight.position.z = 2;
  scene.add(directionalLight);

  /* Controls 만들기 */
  const controls = new PointerLockControls(camera, renderer.domElement);

  // 클릭 시 포인터 잠금 활성화
  controls.domElement.addEventListener("click", () => {
    controls.lock();
  });

  // 잠금 설정 시 호출
  controls.addEventListener("lock", () => {
    console.log("lock!");
  });

  // 잠금 해제 시 호출 (Esc 키 누를 시 잠금 해제 됨)
  controls.addEventListener("unlock", () => {
    console.log("unlock!");
  });

  /* Messh 만들기 */
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  let mesh;
  let material;

  const minColorValue = 50; // RGB 값의 최소값
  const colorRange = 255 - minColorValue; // RGB 값의 범위 (최대값 - 최소값)
  for (let i = 0; i < 20; i++) {
    material = new THREE.MeshStandardMaterial({
      color: `rgb(
				${minColorValue + Math.floor(Math.random() * colorRange)},
				${minColorValue + Math.floor(Math.random() * colorRange)},
				${minColorValue + Math.floor(Math.random() * colorRange)}
			)`
    });

    // Mesh 무작위 위치 조정
    const range = 0.5;
    const positionRange = 5;
    mesh = new THREE.Mesh(geometry, material);
    mesh.position.x = (Math.random() - range) * positionRange;
    mesh.position.y = (Math.random() - range) * positionRange;
    mesh.position.z = (Math.random() - range) * positionRange;
    scene.add(mesh);
  }

  /* 그리기 */
  const clock = new THREE.Clock();

  function draw() {
    const delta = clock.getDelta();

    // PointerLockControls에서는 업데이트 메소드가 없다.

    renderer.render(scene, camera);
    renderer.setAnimationLoop(draw);
  }

  function setSize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.render(scene, camera);
  }

  /* 이벤트 */
  window.addEventListener("resize", setSize);

  draw();
}

  • controls가 동작하기 위해서는 Lock이라는 메소드를 실행해야 한다.
  • 사용자의 제스처가 필요하다. (예. 마우스 클릭)
  • PointerLockControls에서는 업데이트 메소드가 없다.

 

 

주요 기능

  1. 마우스 제어
    • 마우스를 움직이면 커서는 보이지 않지만, 사용자의 움직임이 카메라 회전에 반영된다.
  2. 커서 잠금
    • 마우스가 화면을 넘어가도 계속 움직임이 반영되며, 사용자는 화면 경계를 신경 쓸 필요가 없다.
  3. 키보드 조작:
    • W, A, S, D 키를 사용하여 전진, 후진, 좌우 이동을 할 수 있다.

 

 

저작자표시 변경금지

'Frontend > Three.js' 카테고리의 다른 글

카메라 컨트롤, Minecraft Controls  (0) 2024.09.05
카메라 컨트롤, DragControls  (0) 2024.09.05
카메라 컨트롤, FirstPersonControls  (0) 2024.09.05
카메라 컨트롤, FlyControls  (0) 2024.09.04
카메라 컨트롤, OrbitControls와 TrackballControls 차이  (0) 2024.09.04
    'Frontend/Three.js' 카테고리의 다른 글
    • 카메라 컨트롤, Minecraft Controls
    • 카메라 컨트롤, DragControls
    • 카메라 컨트롤, FirstPersonControls
    • 카메라 컨트롤, FlyControls
    wam
    wam

    티스토리툴바