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

인기 글

태그

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

최근 글

관리자

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

w__am 개발노트

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

카메라 컨트롤, Minecraft Controls

2024. 9. 5. 19:31

 

Minecraft Controls

 

플레이어가 게임 세계와 상호작용하고 탐색할 수 있도록 도와주는 다양한 입력 장치의 설정이다.

 

 

PointerLockControls에 키보드 컨트롤 추가

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

/* 주제: Minecraft Controls :  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 = 4;
  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!");
  });

  /* 키보드 컨트롤 만들기 */
  const keyController = new KeyController();

  function walk() {
    const UP = keyController.keys["KeyW"] || keyController.keys["ArrowUp"];
    const DOWN = keyController.keys["KeyS"] || keyController.keys["ArrowDown"];
    const LEFT = keyController.keys["KeyA"] || keyController.keys["ArrowLeft"];
    const RIGHT =
      keyController.keys["KeyD"] || keyController.keys["ArrowRight"];

    const moveAmount = 0.02; // 이동량을 상수로 정의
    
    if (UP) {
      controls.moveForward(moveAmount);
    }
    if (DOWN) {
      controls.moveForward(-moveAmount);
    }
    if (LEFT) {
      controls.moveRight(-moveAmount);
    }
    if (RIGHT) {
      controls.moveRight(moveAmount);
    }
  }

  /* 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();

    walk();

    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();
}

 

 

export class KeyController {
	constructor() {
		// 생성자
		this.keys = [];

		window.addEventListener('keydown', e => {
			console.log(e.code + ' 누름'); // [KeyW: true]
			this.keys[e.code] = true;
		});

		window.addEventListener('keyup', e => {
			console.log(e.code + ' 뗌');
			delete this.keys[e.code];
		});
	}
}

 

this.keys

  • this.keys는 객체로, 각 키 코드에 대해 true 또는 false 값을 가진다.
  • 이 객체는 현재 어떤 키가 눌려 있는지 추적하는 데 사용된다.

 

 

e.code

  • 키의 코드값을 나타낸다.
  • 예를 들어, 'KeyW', 'ArrowUp' 등이 있다.

 

 

저작자표시 변경금지

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

재질, MeshLambertMaterial, MeshPhongMaterial  (0) 2024.09.30
재질, MeshBasicMaterial  (0) 2024.09.30
카메라 컨트롤, DragControls  (0) 2024.09.05
카메라 컨트롤, PointerLockControls  (0) 2024.09.05
카메라 컨트롤, FirstPersonControls  (0) 2024.09.05
    'Frontend/Three.js' 카테고리의 다른 글
    • 재질, MeshLambertMaterial, MeshPhongMaterial
    • 재질, MeshBasicMaterial
    • 카메라 컨트롤, DragControls
    • 카메라 컨트롤, PointerLockControls
    wam
    wam

    티스토리툴바