hopkit

Find your next move

Search the guide, API, and recipes.

    Pocket Trail / Chapter 02 of 08

    Make a move

    Turn keyboard actions into movement.

    Download checkpoint
    Make it move · chapter excerpt
    const game = await createGame({
      canvas,
      signal: options.signal,
      background: "#c9e5d8",
      assets: { hero: { image: `${options.art}character_green_idle.png` } },
    })
    const hero = game.sprite("hero", { x: 320, y: 180, anchor: "center", width: 96, height: 96 })
    game.update((dt) => {
      hero.x = Math.max(32, Math.min(608, hero.x + game.input.direction().x * options.speed * dt))
    })
    Live gameOpen game ↗
    Play, change a setting, and play again.How it works ↓
    Read the complete chapter module Imports, setup, and preview controls
    src/chapters/02.ts
    import { createGame } from "@hopkit/game"
    import type { LessonOptions } from "../types.js"
    
    export async function mount(canvas: HTMLCanvasElement, options: LessonOptions) {
      // lesson:start
      const game = await createGame({
        canvas,
        signal: options.signal,
        background: "#c9e5d8",
        assets: { hero: { image: `${options.art}character_green_idle.png` } },
      })
      const hero = game.sprite("hero", { x: 320, y: 180, anchor: "center", width: 96, height: 96 })
      game.update((dt) => {
        hero.x = Math.max(32, Math.min(608, hero.x + game.input.direction().x * options.speed * dt))
      })
      // lesson:end
      options.status("A / D or arrow keys move. Change the speed beside the game.")
      options.ready(game.current!)
      return {
        game,
        restart: () => {
          hero.position.set(320, 180)
          game.invalidate()
        },
      }
    }

    A character is much more interesting when you can nudge it around.

    Try it

    Click Play, then hold A / D or the arrow keys. Touch buttons inside the game send the same input. Drag Movement speed and try stopping near an edge. Press Tab to leave the game and reach the lesson controls.

    Actions describe intent

    The default actions map WASD and arrow keys to directions. You can provide your own named actions when a game needs jump, dash, or something stranger. Each action can have several keys.

    game.input.direction().x gives horizontal input between -1 and 1. game.update receives elapsed seconds for one simulation step, so direction * speed * dt moves at the chosen logical units per second. Hopkit commits input once per simulation step.

    The clamp keeps the character inside this first room. You will replace it with world bounds and collision in the next chapters.

    Make one change

    Change speed to 100. Then 300. Which one leaves you enough time to react?