Three.js와 Cannon.js를 연동해 마우스 클릭 시 충격량이 전달되는 3D 물리 샌드박스를 개발합니다.
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 로직을 출력하고 충격량 벡터 계산의 수학적 구현을 설명해주세요.
출처 · 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 obje원문과 같은 언어로 보완한 프롬프트입니다. 점수는 명확성 · 구체성 · 출력 형식 · 재사용성 기준의 AI 평가입니다.
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.