본문으로 건너뛰기
Skillpedia
일반 코딩6.4k · #14204

melonjs-input

하는 일

키를 이름이 있는 동작에 연결하고, 마우스와 터치에 반응하며, 게임패드를 처리하는 방법을 설명합니다. 조작 방식을 만드는 게임 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓개발자가 이동 키를 게임패드와 같은 방식으로 작동하게 하고 싶을 때.
  • ✓개발자가 점프나 발사 키를 누를 때마다 한 번만 실행되게 해야 할 때.
  • ✓개발자의 클릭 가능한 오브젝트가 포인터 입력에 반응하지 않을 때.

스킬 링크

https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-input/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-input/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“방향키로 캐릭터를 움직이게 하고, 스페이스바는 한 번 누를 때마다 한 번만 점프하게 해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

스킬은 AI에게 키를 동작 이름에 연결한 다음 업데이트 루프에서 그 동작을 확인하라고 안내합니다. 한 번만 실행되는 동작은 잠가서 누를 때마다 한 번만 실행되게 합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Input: keyboard, pointer and gamepad

Keyboard goes through named actions

Do not poll key codes. Bind a key to an action string, then poll the action — this is what lets gamepad and virtual controls map onto the same handling.

import { input } from "melonjs";

input.bindKey(input.KEY.LEFT,  "left");
input.bindKey(input.KEY.RIGHT, "right");
input.bindKey(input.KEY.X,     "jump", true);   // true = locked: one press per keydown

// in update()
if (input.isKeyPressed("left"))  { /* … */ }
if (input.isKeyPressed("jump"))  { /* fires once per press, not per frame */ }

The third argument to bindKey is lock (default false). Without it, isKeyPressed stays true for as long as the key is held — correct for movement, wrong for jump or fire. A locked action stays consumed until the key is released or you call input.unlockKey("jump"). Use input.keyStatus(action) when you want the raw held/not-held state regardless of locking.

A poll can miss a press entirely

isKeyPressed is sampled once per frame, and keyup decrements the key's counter the moment it arrives — locked or not. A press that goes down and up between two frames therefore leaves the counter back at zero and is never seen. At 60fps that is anything under ~16ms: rare from a human finger, routine from a synthetic event, and more likely the slower the frame rate.

For a screen where a missed press is a dead end — a splash, a "press any key", a notice to acknowledge — listen for the event instead, which cannot be missed:

import { event } from "melonjs";

// action is the bound action name, or undefined for an unbound key
const onKey = (action) => { if (action === "menuSelect") continue(); };
event.on(event.KEYDOWN, onKey);      // in onResetEvent
event.off(event.KEYDOWN, onKey);     // in onDestroyEvent — it does not self-remove

KEYDOWN fires for every key, bound or not, so matching on action is what narrows it; it also repeats while the key is held, so guard anything that must happen once. Keep polling for movement and for a menu cursor, where one step per press and a key held across a state change are the things that matter.

The full signature is bindKey(keyCode, action, lock?, preventDefault?); preventDefault defaults to input.preventDefault (itself true). Pass the fourth argument per binding, or change the global default with input.setPreventDefault(false) — assigning input.preventDefault = false does not work, it is a read-only module binding.

Pointer events need isKinematic = false

This is the trap. Renderable.isKinematic defaults to true, and both the broadphase and the pointer dispatcher skip any candidate whose isKinematic is still true. The handler registers successfully and simply never fires.

class Button extends Renderable {
    constructor(x, y, w, h) {
        super(x, y, w, h);
        this.isKinematic = false;               // ← required
    }
    onActivateEvent() {
        input.registerPointerEvent("pointerdown", this, this.onDown.bind(this));
    }
    onDeactivateEvent() {
        input.releasePointerEvent("pointerdown", this);
    }
}

Container, Camera2d, Draggable, DropTarget and the UI* elements set it to false for you, and so does attaching a physics body (Body's constructor sets ancestor.isKinematic = false) — so plain Renderable and Sprite subclasses with no body are the ones that catch people.

Register in onActivateEvent and release in onDeactivateEvent, not in the constructor — pooled objects are reused and would otherwise accumulate handlers.

app.viewport works as a whole-screen region when you want global clicks. Note it is asked before everything else, not as a fallback after nothing matched: the dispatcher appends it to the candidate list and walks that list from the end. So a viewport handler must not return false unless it really means to swallow every pointer event in the game.

The accepted event names are exactly "pointerdown", "pointerup", "pointermove", "pointercancel", "pointerenter", "pointerover", "pointerleave" and "wheel". Anything else — "click", "mousedown", "touchstart" — makes both registerPointerEvent and releasePointerEvent throw invalid event type. melonJS maps the canonical name onto whichever mouse/touch events the device actually supports, so you always register the pointer name.

Which object gets the event

The dispatcher collects the regions nea

자주 묻는 질문

점프가 여러 번 실행되는 이유는 무엇인가요?

잠금 처리가 없으면 누르고 있는 키가 프레임마다 눌린 것으로 계산되므로, 스킬은 한 번만 실행되는 동작을 잠그라고 권장합니다.

포인터 이벤트가 오브젝트에 전달되지 않는 이유는 무엇인가요?

스킬은 kinematic 설정이 포인터 이벤트를 조용히 막을 수 있다고 언급합니다.

게임패드에서도 작동하나요?

네. 스킬은 게임패드를 같은 동작 이름에 연결할 수 있다고 말합니다.

상세 정보

작성자의 원본 설명

Use this skill for keyboard, pointer, mouse, touch and gamepad input in melonJS. Covers the bindKey action indirection, registerPointerEvent on regions, the isKinematic requirement that silently blocks pointer events, which of several overlapping objects receives an event and how to consume it, world vs screen pointer coordinates, and gamepad mapping onto the same actions. Triggers on: input, bindKey, isKeyPressed, KEY, registerPointerEvent, releasePointerEvent, pointerdown, pointerup, pointermove, POINTERMOVE, gamepad, bindGamepad, triggerKeyEvent, virtual gamepad, touch controls, joystick, g

repo: melonjs/melonJS

인기도

GitHub 스타
6.4k
순위
#14204
라이선스
MIT
업데이트
2026. 11. 2.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬