Communitygithub.com

melonjs/melonjs-physics (물리 엔진)

melonJS의 내장 SAT 물리 세계와 planck/matter 어댑터를 사용한 충돌 감지, 물리 바디, 이동 및 공간 질의를 위한 스킬입니다.

melonjs-physics (물리 엔진)란 무엇인가요?

이 스킬은 melonJS 게임 엔진에서 물리 시스템을 구현할 때 필요한 모든 요소를 다룹니다. 기본 SAT(분리 축 정리) 세계와 강력한 물리 엔진인 planck.js 및 matter.js 어댑터를 지원하여 개발자가 게임 내 오브젝트의 충돌, 중력, 속도, 힘 적용 등을 제어할 수 있도록 돕습니다. `bodyDef`와 `Body`의 차이점, 충돌 유형과 마스크 설정, `onCollision`, `onCollisionStart`, `onCollisionActive` 등 다양한 충돌 콜백의 발동 규칙을 상세히 설명합니다. 또한 `raycast`, `queryAABB`, `querySphere` 같은 공간 질의 함수를 통해 특정 영역 내 오브젝트를 감지하는 방법도 포함되어 있습니다. 각 물리 어댑터(PlanckAdapter, MatterAdapter) 간의 동작 차이를 명확히 비교하여 개발자가 자신의 프로젝트에 가장 적합한 물리 엔진을 선택하고 사용할 수 있도록 안내합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/melonjs/melonJS/tree/master/packages/melonjs/skills/melonjs-physics

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

melonjs-physics (물리 엔진)은(는) 무엇을 하나요?

이 스킬은 melonJS의 내장 SAT(분리 축 정리) 물리 세계와 planck.js / matter.js 어댑터를 사용한 충돌 감지, 물리 바디, 이동 및 공간 질의를 다룹니다. 다음 주제를 포함합니다: bodyDef vs Body, 충돌 유형과 마스크, 충돌 콜백 패밀리 및 발동 규칙, raycast / queryAABB / querySphere, 그리고 각 어댑터 간의 동작 차이. 트리거 키워드: Body, bodyDef, collision, collisionType, collisionMask, onCollision, onCollisionStart, onCollisionActive, raycast, queryAABB, querySphere, PlanckAdapter, MatterAdapter, gravity, velocity, applyForce, isGrounded, SAT.


주요 개념

bodyDef vs Body

  • bodyDef: 물리 바디를 생성할 때 사용하는 설정 객체로, 질량, 위치, 고정 여부 등 초기 속성을 정의합니다.
  • Body: 생성된 물리 바디 인스턴스로, 실제 충돌 및 힘 시뮬레이션에 사용됩니다.

충돌 유형과 마스크

  • collisionType: 충돌 그룹을 정의하는 비트마스크 값입니다.
  • collisionMask: 충돌할 대상의 collisionType을 지정합니다. 두 객체의 마스크가 서로 일치해야 충돌이 발생합니다.

충돌 콜백

  • onCollision: 충돌이 시작될 때 호출됩니다.
  • onCollisionStart: 충돌이 첫 프레임에 발생할 때 호출됩니다.
  • onCollisionActive: 충돌이 지속되는 동안 매 프레임 호출됩니다.

공간 질의

  • raycast: 광선을 발사하여 첫 번째 충돌 객체를 찾습니다.
  • queryAABB: 축 정렬 경계 상자(AABB) 영역 내의 모든 물리 바디를 반환합니다.
  • querySphere: 구형 영역 내의 모든 물리 바디를 반환합니다.

어댑터 동작 차이

기능SAT (기본)PlanckAdapterMatterAdapter
물리 엔진내장 SATplanck.jsmatter.js
충돌 유형비트마스크비트마스크비트마스크
중력(gravity)설정 가능설정 가능설정 가능
힘 적용(applyForce)지원지원지원
지면 감지(isGrounded)직접 구현 필요기본 지원기본 지원
고정 바디(static)isStatic 속성type: 'static'isStatic: true

사용 예시

// 기본 물리 바디 생성
let playerBody = new me.Body({
    pos: new me.Vector2d(100, 200),
    width: 32,
    height: 48
});

// 충돌 유형 및 마스크 설정
playerBody.collisionType = me.game.COLLISION_TYPE.PLAYER;
playerBody.collisionMask = me.game.COLLISION_TYPE.ENEMY | me.game.COLLISION_TYPE.WALL;

// 충돌 콜백 등록
playerBody.onCollision = function(response, other) {
    console.log("Player collided with:", other.body.collisionType);
    return false; // 충돌 처리를 기본 동작으로 전달하지 않음
};

// 중력 적용 (프레임 업데이트에서)
playerBody.force.y += 9.8 * playerBody.mass;

// planck 어댑터 사용 예시 (PlanckAdapter 적용 후)
let physicsWorld = new me.PlanckAdapter();
physicsWorld.gravity = new me.Vector2d(0, 9.8);

참고 사항

  • SAT 어댑터는 melonJS에 내장되어 추가 설치가 필요 없지만, planck/matter 어댑터는 별도 패키지로 제공됩니다.
  • isGrounded는 planck와 matter 어댑터에서 기본적으로 지원되지만, SAT에서는 직접 충돌 검사를 구현해야 합니다.
  • 모든 공간 질의 함수는 물리 세계가 활성화된 상태에서만 작동합니다.

이 스킬은 melonJS의 물리 시스템을 정확히 이해하고 활용하는 데 도움을 줍니다.

Individual skills in this repo

This repo contains 10 individual skills — each has its own dedicated page.

melonjs/melonjs-3d

Use this skill for anything 3D or 2.5D in melonJS — Camera3d, Mesh, InstancedMesh, Sprite3d billboards, Light3d, ground shadows, glTF/GLB scenes, and depth sorting. Covers the Y-down/+Z-forward convention that is the inverse of OpenGL, the cameraClass opt-in, clip planes, and what does not work on the Canvas fallback. Triggers on: Camera3d, Mesh, InstancedMesh, Sprite3d, Light3d, billboard, glTF, glb, 3D, 2.5D, depth, cameraClass, fov, setClipPlanes, setFog, fog, distance fog, height fog, heightFalloff, transparent, transparency, alpha, blendMode, fade, castGroundShadow, lit.

melonjs/melonjs-3d-assets

Use this skill when loading 3D models into melonJS — glTF and GLB scenes, OBJ/MTL models, materials, imported lights, node animation, ground shadows and GPU instancing. Covers level.load options including the async flag, the rightHanded conversion, and exactly what the loader does and does not support. Triggers on: glTF, gltf, glb, OBJ, MTL, 3D model, getGLTF, getOBJ, getMTL, GLTFModel, GLTFScene, level.load glb, rightHanded, lightIntensityScale, castGroundShadow, shadowGroundY, EXT_mesh_gpu_instancing, KHR_lights_punctual, skinning, Blender export, 3D asset.

melonjs/melonjs-camera-and-drawing

Use this skill for camera control and immediate-mode drawing in melonJS — following a target, viewport bounds, shake and fade, secondary cameras, and drawing shapes, lines and gradients inside a custom draw(). Covers world versus screen coordinate conversion, clipping and masking, and baking with CanvasRenderTarget. Triggers on: Camera2d, viewport, follow, setBounds, shake, fadeIn, fadeOut, worldToLocal, localToWorld, colorMatrix, renderer.fill, renderer.stroke, Rect, Ellipse, Polygon, Line, Gradient, clipRect, mask, CanvasRenderTarget, NoiseTexture2d.

melonjs/melonjs-effects-and-shaders

Use this skill for post-processing effects, custom shaders, blend modes and colour grading in melonJS. Covers the built-in ShaderEffect presets, addPostEffect on renderables and cameras, writing a custom dual-language GLSL/WGSL effect, the screen_texture builtins, and why effects silently do nothing on the Canvas fallback. Triggers on: ShaderEffect, addPostEffect, removePostEffect, getPostEffect, VignetteEffect, GlowEffect, BlurEffect, PixelateEffect, ScanlineEffect, shader, GLSL, WGSL, uniform, setUniform, setTexture, setTime, blendMode, colorMatrix, screen_texture, toFrameTexture, post effect, filter.

melonjs/melonjs-loading-assets

Use this skill for loading and managing game assets in melonJS — the resource descriptor format, the full asset type list, preload versus load, retrieving loaded assets, base URLs and cross-origin settings, and the loading screen. Triggers on: loader, loader.preload, loader.load, resources, getImage, getJSON, getTMX, getGLTF, getVideo, getFont, setBaseURL, setOptions, crossOrigin, withCredentials, credentials, cookies, authenticated assets, CORS, asset, preload, LOADER_COMPLETE, loading screen, unload.

melonjs/melonjs-performance

Use this skill when a melonJS game drops frames, allocates heavily, or needs to scale to many objects. Covers object pooling, draw-call batching, atlases, baking with CanvasRenderTarget, instancing, culling and alwaysUpdate, the debug plugin, and where the real costs are. Triggers on: performance, slow, frame rate, fps, lag, pool, pool.register, pool.pull, batching, draw calls, InstancedMesh, culling, alwaysUpdate, inViewport, CanvasRenderTarget, optimise, profiling, debug plugin, memory.

melonjs/melonjs-renderables

Use this skill when subclassing Renderable, writing a custom draw() method, handling pointer or click events on game objects, applying post effects and shaders, or controlling draw order. Covers the pos-relative draw contract, isKinematic and input, addPostEffect vs the deprecated shader property, and z-ordering. Triggers on: Renderable, extends Renderable, draw(, update(, isKinematic, pointerEvent, registerPointerEvent, onClick, addPostEffect, removePostEffect, ShaderEffect, addChild, z-order, anchorPoint, floating.

melonjs/melonjs-renderer-backends

Use this skill when a feature works on one machine and not another, when choosing or pinning a renderer, or when writing code that must degrade gracefully. Covers the WebGPU to WebGL 2 to Canvas fallback ladder, what each backend supports, capability detection, and the subsystems that warn once and then stop working on Canvas. Triggers on: video.AUTO, video.WEBGPU, video.WEBGL, video.CANVAS, renderer.type, supportsDepthBuffer, shaderLanguage, WebGPU, WebGL2, Canvas fallback, context loss, backen

melonjs/melonjs-scenes-and-state

Use this skill for scene structure and game flow in melonJS — Stage subclasses, the state manager, transitions, pausing, the update loop, timers and tweens. Covers onResetEvent versus the constructor, state.set before state.change, the camera and world lifecycle per stage, and pause-aware timing. Triggers on: Stage, state, state.set, state.change, state.transition, state.pause, onResetEvent, onDestroyEvent, onActivateEvent, onDeactivateEvent, PLAY, MENU, LOADING, update loop, GAME_UPDATE, timer, setTimeout, setInterval, Tween, freeze.

melonjs/melonjs-ui-and-text

Use this skill for HUDs, buttons, menus, dialogue panels and on-screen text in melonJS. Covers UIBaseElement/UISpriteElement/UITextButton, Draggable and DropTarget, the floating screen-space container pattern, Text and BitmapText, web font loading, and NineSliceSprite panels. Triggers on: UI, HUD, button, UIBaseElement, UISpriteElement, UITextButton, Draggable, DropTarget, menu, dialogue, Text, BitmapText, font, fontface, wordWrapWidth, NineSliceSprite, score display, floating.

관련 스킬