Three.js 3D 물리 샌드박스 구현
Three.js와 Cannon.js를 연동해 마우스 클릭 시 충격량이 전달되는 3D 물리 샌드박스를 개발합니다.
- 추천 툴
- CursorAI 분류
- 쓰인 기법
- 역할 부여 · 물리 엔진 요구사항 정의 · 수학적 알고리즘 명시
프롬프트 원문
I want you to act as a Senior WebGL Game Architect specializing in Three.js and Cannon.js. Your goal is to design a high-performance 3D physics sandbox logic. Core Mechanics: Implement a momentum-based collision system within a bounded 3D container. Requirements: Initialize a Three.js scene with a physics world using Cannon.js. Enable a "Force Interaction" system where clicking or touching the screen applies an instantaneous impulse to 3D objects based on the vector between the camera and the click point. Implement friction, restitution (bounciness), and linear/angular damping to simulate realistic energy loss. Use an efficient animation loop to synchronize the physics body positions with Three.js meshes. Ensure the code is modular so different geometries (Spheres, Boxes, Convex Hulls) can be added easily. Please output the core JavaScript logic and explain the mathematical implementation of the impulse vector calculation.
한국어 풀이 보기(참고용)
Three.js 및 Cannon.js를 전문으로 하는 수석 WebGL 게임 아키텍트 역할을 수행하세요. 당신의 목표는 고성능 3D 물리 샌드박스 로직을 설계하는 것입니다. 핵심 메커니즘: 경계가 있는 3D 컨테이너 내에서 운동량 기반 충돌 시스템을 구현합니다. 요구사항: - Cannon.js를 사용한 물리 세계로 Three.js 씬을 초기화합니다. - 화면을 클릭하거나 터치하면 카메라와 클릭 지점 사이의 벡터를 기반으로 3D 물체에 순간적인 충격량(Impulse)을 적용하는 '포스 인터랙션' 시스템을 활성화합니다. - 마찰, 반발계수(탄성), 선형/회전 감쇠를 구현하여 현실적인 에너지 손실을 시뮬레이션합니다. - 효율적인 애니메이션 루프를 사용하여 물리 바디 위치를 Three.js 메시와 동기화합니다. - 다양한 형상(구, 상자, 다대체)을 쉽게 추가할 수 있도록 코드를 모듈화합니다. 핵심 JavaScript 로직을 출력하고 충격량 벡터 계산의 수학적 구현을 설명해주세요.
- 활용웹 기반 3D 인터랙티브 랜딩페이지나 시각화 프로젝트의 기초 프레임워크로 바로 활용할 수 있습니다.
- 활용기본 렌더링 루프와 물리 엔진 동기화 코드를 한 번에 모듈식으로 제공받을 수 있습니다.
출처 · prompts.chat · 3D Physics Sandbox Architect — 원문은 출처에 게시된 그대로이며, 권리는 원작자에게 있습니다.
텍스트 결과
Gemini로 실행한 결과입니다. 입력 항목에는 국내 환경의 예시값을 적용했습니다(AI 생성 — 사실 확인 필요).
실행 입력값 보기
I want you to act as a Senior WebGL Game Architect specializing in Three.js and Cannon.js. Your goal is to design a high-performance 3D physics sandbox logic. Core Mechanics: Implement a momentum-based collision system within a bounded 3D container. Requirements: Initialize a Three.js scene with a physics world using Cannon.js. Enable a "Force Interaction" system where clicking or touching the screen applies an instantaneous impulse to 3D objects based on the vector between the camera and the click point. Implement friction, restitution (bounciness), and linear/angular damping to simulate realistic energy loss. Use an efficient animation loop to synchronize the physics body positions with Three.js meshes. Ensure the code is modular so different geometries (Spheres, Boxes, Convex Hulls) can be added easily. Please output the core JavaScript logic and explain the mathematical implementation of the impulse vector calculation.
Senior WebGL Game Architect 관점에서 작성한 Three.js 및 Cannon.js 물리 엔진 연동 핵심 로직과 수학적 설명입니다.
1. 핵심 JavaScript 로직
import * as THREE from 'three';
import * as CANNON from 'cannon-es';
// 1. 물리 및 시각 씬 초기화
const scene = new THREE.Scene();
const world = new CANNON.World({ gravity: new CANNON.Vec3(0, -9.82, 0) });
const defaultMat = new CANNON.Material({ friction: 0.3, restitution: 0.7 });
world.addContactMaterial(new CANNON.ContactMaterial(defaultMat, defaultMat, { friction: 0.3, restitution: 0.7 }));
const objects = [];
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// 2. 모듈식 객체 생성 함수 (Sphere, Box 등 커스텀 가능)
export function createPhysicsObject(mesh, shape, mass, position) {
const body = new CANNON.Body({ mass, shape, material: defaultMat });
body.linearDamping = 0.1; // 공기 저항 (선형 댐핑)
body.angularDamping = 0.1; // 회전 저항 (각 댐핑)
body.position.copy(position);
scene.add(mesh);
world.addBody(body);
objects.push({ mesh, body });
}
// 3. Force Interaction (클릭 시 충격량 부여)
window.addEventListener('pointerdown', (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(objects.map(o => o.mesh));
if (intersects.length > 0) {
const hit = intersects[0];
const target = objects.find(o => o.mesh === hit.object);
// 레이캐스팅 타격 지점으로의 단위 방향 벡터 계산
const dir = hit.point.clone().sub(camera.position).normalize();
const forceMagnitude = 25;
const impulse = new CANNON.Vec3(dir.x * forceMagnitude, dir.y * forceMagnitude, dir.z * forceMagnitude);
const hitPoint = new CANNON.Vec3(hit.point.x, hit.point.y, hit.point.z);
// 해당 타격 위치에 찰나의 충격량(Impulse) 적용
target.body.applyImpulse(impulse, hitPoint);
}
});
// 4. 물리-메시 동기화 애니메이션 루프
function animate() {
requestAnimationFrame(animate);
world.step(1 / 60);
for (const obj of objemopick 개선안
원문을 더 잘 동작하게 고쳐 쓴 프롬프트
원문을 그대로 넣으면 AI 가 매번 다르게 답하거나 중요한 부분을 빠뜨릴 수 있습니다. 개선안은 원문의 뜻과 언어는 그대로 두고 역할 · 바꿔 넣을 입력 칸 · 결과 형식 · 지킬 조건을 보완해 다시 쓴 버전입니다. 원문과 같은 곳(ChatGPT · Claude 등)에 그대로 붙여 넣어 쓰면 됩니다.
AI 자체 평가 — 개선안을 쓴 AI 가 명확성 · 구체성 · 결과 형식 · 재사용성 기준(100점)으로 직접 매긴 점수 · 결과를 돌려 검증한 값은 아님
원문의 문제 → 개선안에서 고친 점
AI 역할레슨 01 배우기 ›
원문 · 없음AI 에게 맡길 역할이 정해져 있지 않아 답의 관점 · 수준이 그때그때 달라질 수 있었습니다.
개선 · 역할을 정함Act as a Senior WebGL Game Architect specializing in Three.js and Cannon.js (or cannon-es)
입력 칸레슨 05 배우기 ›
원문 · 없음바꿔 넣을 자리가 표시돼 있지 않아 쓸 때마다 원문을 직접 고쳐야 했습니다.
개선 · 3개[Container Size, e.g., 20x20x20] · [Gravity Vector, e.g., (0, -9.81, 0)] · [Geometries, e.g., Spheres, Boxes]
작업 순서레슨 07 배우기 ›
원문 · 없음작업 순서가 정해져 있지 않아 AI 가 순서를 스스로 정해야 했습니다.
개선 · 5단계
고친 이유 (개선안을 만든 AI 의 설명)
- 1Raycaster 기반 광선 투사 및 구현 단계를 구체화함.
- 2컨테이너 크기, 중력 값 등을 [대괄호] 변수화하여 재사용성 강화.
- 3코드 출력 구조(ES6+, 예외 처리)와 수학적 설명 섹션을 규격화함.
이 개선안에 쓰인 기법 — 프롬프트 클래스에서 배우기
01역할 정하기03결과 모양 정하기04지킬 조건 걸기05입력 칸으로 템플릿 만들기07작업을 단계로 나누기09구역을 나눠 쓰기
원문
I want you to act as a Senior WebGL Game Architect specializing in Three.js and Cannon.js. Your goal is to design a high-performance 3D physics sandbox logic. Core Mechanics: Implement a momentum-based collision system within a bounded 3D container. Requirements: Initialize a Three.js scene with a physics world using Cannon.js. Enable a "Force Interaction" system where clicking or touching the screen applies an instantaneous impulse to 3D objects based on the vector between the camera and the click point. Implement friction, restitution (bounciness), and linear/angular damping to simulate realistic energy loss. Use an efficient animation loop to synchronize the physics body positions with Three.js meshes. Ensure the code is modular so different geometries (Spheres, Boxes, Convex Hulls) can be added easily. Please output the core JavaScript logic and explain the mathematical implementation of the impulse vector calculation.
개선안 · 색칠한 [칸]에 내 내용을 넣어 쓰세요
Act as a Senior WebGL Game Architect specializing in Three.js and Cannon.js (or cannon-es). Design a modular, high-performance 3D physics sandbox. Core Objective: Implement a momentum-based collision system within a bounded container of size [Container Size, e.g., 20x20x20]. Requirements: 1. Scene Setup: Initialize Three.js scene, camera, renderer, and Cannon.js physics world with gravity [Gravity Vector, e.g., (0, -9.81, 0)]. 2. Force Interaction: Use Three.js Raycaster to detect clicks/touches. Compute an impulse vector from camera position through the hit point, and apply an instantaneous impulse using `body.applyImpulse()`. 3. Physics Tuning: Set realistic friction, restitution (bounciness), and linear/angular damping. 4. Render Loop: Synchronize Cannon.js bodies with Three.js meshes using a fixed time-step loop. 5. Modular Geometry: Provide an extensible factory to spawn shapes like [Geometries, e.g., Spheres, Boxes]. Output Format: - Section 1: Well-commented ES6+ JavaScript code (including raycast error handling). - Section 2: Mathematical breakdown of the camera-to-click impulse vector calculation.
같은 분야 프롬프트 코딩 · 개발
더 보기 ›- 텍스트 결과
코딩 · 개발 · Claude Code
전체 코드 버그 종합 분석
프로젝트 코드 전체의 보안 취약점과 로직 오류를 체계적으로 분석하고 수정 보고서를 만듭니다.
기법 · 역할 부여 · 단계별 사고 · 출력 형식 지정
- 텍스트 결과
코딩 · 개발 · Claude Code
레트로 게임 AI 코딩 연출
AI로 웹 게임 개발 시 불필요한 텍스트 연출을 막고 레트로 사운드와 UI를 깔끔하게 구현합니다.
기법 · 네가티브 제약
- 웹 화면(HTML)텍스트 결과
코딩 · 개발 · 공통
공장 AI HMI 시뮬레이터 제작
공장 작업자의 AI 시스템 대응 교육용 단일 HTML 웹 HMI 시뮬레이터를 즉시 구축할 때 활용합니다.
기법 · 역할 부여 · 단계별 지시 · 출력 형식 지정

