GitHubCommencer

Cette page n’est pas encore traduite en français ; la version anglaise est affichée ci-dessous.

Venir d’un autre moteur

Coming from Ebitengine

A map from Ebitengine's game loop, images, input, audio and builds to this layer, and to the scenes, nodes, resources, signals, input maps, physics and export it adds on top, with the page that covers each one.

Both are Go, so most of your game logic moves over unchanged. What changes is the host: an Ebitengine game owns the whole window and draws everything on the GPU, while a game here is an NSGo component that draws into one core.Canvas, with its HUD and menus as native NSGo views on top. Ebitengine leaves scenes, entities, events and physics to you; this layer ships packages for each, which you can adopt one at a time.

At a glance

Ebitengine Here Guide
ebiten.Game.Update at ebiten.TPS() game.Loop.Update(dt) at Loop.Rate Loop
ebiten.Game.Draw(screen) core.Canvas.Draw(d, size), redrawn from Loop.Draw(alpha) Loop
Layout(outsideWidth, outsideHeight) screen.Viewport with ModeFit, ModeFill, ModeStretch or ModeExpand screen
*ebiten.Image, SubImage sprite.Atlas and its Frame values sprite
DrawImageOptions.GeoM, ColorScale alpha sprite.Sprite position, origin, rotation, scale, flip and Alpha sprite
DrawImageOptions.Blend, drawing with a mask sprite.Sprite.Blend and sprite.Sprite.Mask sprite
ebiten.NewShader and DrawRectShader Kage chains with postfx.Compile and postfx.View. Use sprite.EffectShader for built-in sprite effects. postfx
ebiten.SetFullscreen, SetWindowSize screen.Video.Apply and ApplyResolution screen
ebiten.SetTPS Loop.Rate for updates and Loop.DrawRate for the draw cap Loop
ebiten.SetCursorMode(ebiten.CursorModeCaptured) input.Actions.LockPointer input
ebiten.SetRunnableOnUnfocused(false) Set Loop.PauseOnLeave to game.LeaveInactive for a pause that stays in effect on return Loop
A hand-written scene switcher scene.Manager with transitions scene
A slice of structs you update yourself entities.World, components and systems Entities
//go:embed plus ebitenutil.NewImageFromFile "asset:" URIs in resources/ loaded via assets.Manager (optional assets.WithFS for //go:embed) assets
Channels or callbacks between systems flow.Bus; core.Signal for UI state flow
ebiten.IsKeyPressed, inpututil.IsKeyJustPressed Bind input.Key or input.KeyCode and query Actions.Pressed or JustPressed input
ebiten.IsStandardGamepadButtonPressed, StandardGamepadAxisValue input.GamepadButton and Actions.BindGamepadAxis, with WatchGamepads input
ebiten.AppendTouchIDs, TouchPosition Actions.Touches for a snapshot, or input.TouchRegion to bind a region to an action input
Your own AABB checks physics shapes, MoveAndSlide, RigidWorld physics
audio.Context, audio.Player sound.Mixer with sound.Effect for short sounds and sound.Music for streaming tracks sound
audio.Context.NewPlayer with procedural PCM NSGo’s audio.NewOutput with a sample callback NSGo audio
go build, GOOS=js GOARCH=wasm, ebitenmobile bind go tool nsgo build for every target Building and Shipping

The loop

Ebitengine calls Update 60 times a second by default and Draw once per display frame. game.Loop keeps the same split: Update gets a fixed dt of 1/Rate seconds (60 updates a second by default), and Draw runs once per display frame with alpha, how far the frame falls into the next update. Pass alpha to the canvas through a core.Signal and interpolate between the last two states, so motion stays smooth on 120 Hz displays without changing the update rate. Loop also pauses while the app is in the background and caps the updates one frame may run after a hitch. See Loop.

ebiten.ActualFPS becomes FPS on the gamedebug overlay's Stats(), the average frame rate over the frames it recorded (0 under -tags release); the overlay also draws a frame-time graph, and nsgo dev -fps shows NSGo's monitor. In place of ebiten.ActualTPS, Loop.Steps() counts the fixed updates run so far and Loop.Elapsed() is the simulated time they advanced. Use these values for diagnostics rather than changing the simulation rate.

Shaders, blend modes and masks

Shaders here are written in Kage, as in Ebitengine: postfx.Compile chains Kage effects, and sprite.EffectShader draws a sprite through the built-in Kage sprite effect (palette swap, tint, dissolve, flash and outline). DrawImageOptions.Blend becomes sprite.Sprite.Blend, and sprite.Sprite.Mask clips a sprite to a sprite.RectMask, CircleMask, EllipseMask or PolygonMask. The offscreen-image-plus-DrawRectShader post-processing pattern maps to postfx.Over for a canvas subtree and postfx.OverScreen for the whole surface; until NSGo's core shader effects accept Kage (they take WGSL today), both leave what they cover unchanged, and postfx.View, which runs the chain over a pixel buffer, is the path that draws. See postfx and sprite.

Window and cursor

Use screen.Video.Apply for fullscreen settings and Video.ApplyResolution for the windowed size. Set Loop.Rate to change the fixed simulation rate and Loop.DrawRate to cap rendering separately. To capture the mouse, call input.Actions.LockPointer from a press on the game view. See screen and pointer lock for platform limits.

Lifecycle and audio

Loop suspends updates while the app is backgrounded and normally continues when it returns. Set PauseOnLeave to game.LeaveInactive to pause on focus loss until the game explicitly resumes. Use Loop.OnLeave to save progress and actions.WatchLifecycle(cx) to release held input. sound.Mixer mutes in the background on its own. Wire Loop.OnPause to Mixer.SetPaused to keep gameplay audio paused with the game. See Loop, input and sound.

sound.Effect plays short decoded sounds. sound.Music.Play streams an audio.Source, such as a track identified by an asset URI. Use PlayWithIntro or PlaySections for music with a separate intro and loop. See sound.

Ebitengine’s audio.Context.NewPlayer can read raw PCM from an io.Reader. To port procedural PCM, use NSGo’s audio.NewOutput and supply samples in its pull callback. The output runs alongside sound.Mixer. For custom stateful bus effects, sound.NewSoftwareMixer processes interleaved float32 PCM blocks supplied by the game. See Ebitengine audio, NSGo audio, and the software mixer.

Offscreen drawing and text

Use postfx.View or a canvas subtree for offscreen image effects. pkg/text provides text layout and drawing for the role covered by Ebitengine's text/v2; native NSGo text remains appropriate for HUD and menus.

Drawing

An Ebitengine Draw receives the screen image; a canvas Draw receives a *core.Drawing and the view's size in points. A sprite sheet becomes a sprite.Atlas loaded from a TexturePacker or Aseprite export, or written by hand, and SubImage rectangles become its named frames and animations. Where you set GeoM translate, rotate and scale, set the fields on a sprite.Sprite; a sprite.Batch draws many sprites from one atlas in Z order. See sprite.

Layout becomes a screen.Viewport: give it the virtual resolution, choose how it fits the window, and draw inside vp.Draw. Integer scaling for pixel art and safe-area rectangles live in the same package. See screen. For maps, tilemap loads Tiled .tmj files and draws only the visible tiles through a 2D camera. See tilemap.

Scenes

Ebitengine has no scene type, so games usually keep a current Scene field and swap it. scene.Manager does that with a stack: Switch replaces the scene with a fade, crossfade or wipe, Push lays an overlay such as a pause menu over it, and Pop returns. Each scene gets its own *core.Scope, and everything made on it is disposed when the scene exits. A scene.Scene inside it orders layers in world space (under a camera) and screen space (for the HUD), and hit-tests taps against sprites. See scene.

A level's layout can live in a YAML scene file rather than in Go: sceneformat.Parse reads it and sceneformat.Build produces layers ready to draw. See Editor & Scene Format.

Nodes

Where an Ebitengine game keeps []*Enemy and loops over it, entities keeps components in typed sparse sets on a World and runs systems in a declared order on each fixed step, with no allocations in steady state. Prefab stamps a template's components onto new entities, and a world saves to JSON through save. See Entities.

For 3D, scene3d.Node is a transform hierarchy with sockets, tags and picking. See scene3d.

Resources

Put images, sounds, atlas JSON, tilemaps, models and other runtime files under resources/; NSGo packages them for every target, and "asset:..." URIs open them everywhere — including the web, fetched on demand through core.Scope.ReadAsset without embedding them in the binary. assets.Manager reads "asset:" bytes from the app's resources by default (pass assets.WithFS(fsys) to override with //go:embed or os.DirFS, or WithReadAsset for custom storage), loads atlases, sounds, images and your own parsed files in named groups off the engine goroutine, exposes progress for a loading screen and releases a group when its scene ends. See assets.

Signals

Systems that call each other or share channels can publish typed events on a flow.Bus instead: flow.Subscribe takes a function of the event's type, flow.Publish delivers at once and flow.Enqueue with Bus.Flush delivers once per step. flow.Timers, flow.Machine and flow.Seq replace frame counters, state switch statements and cutscene goroutines, and all of them advance only on the loop's dt, so they pause and replay with the game. See flow.

State the HUD shows, such as a score, is a core.Signal that an NSGo view reads and re-renders on.

Input maps

Ebitengine asks about devices directly (ebiten.IsKeyPressed, inpututil.IsMouseButtonJustPressed, ebiten.AppendTouchIDs). input.Actions names actions instead and binds inputs to them, so the game code asks about "jump", not a key:

Ebitengine Here
ebiten.IsKeyPressed(ebiten.KeySpace) actions.Bind("jump", input.Key("space")), then actions.Pressed("jump")
ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) actions.Bind("fire", input.MouseButton(core.MouseButtonLeft)), then actions.Pressed("fire")
ebiten.IsStandardGamepadButtonPressed actions.Bind("jump", input.GamepadButton(gamepad.ButtonSouth)), then actions.Pressed("jump")
ebiten.StandardGamepadAxisValue actions.BindGamepadAxis("move_x", gamepad.AxisLeftX, input.GamepadAxisOptions{}), then actions.Axis("move_x")
inpututil.IsKeyJustPressed(ebiten.KeySpace) actions.JustPressed("jump") on a Key or KeyCode binding
inpututil.IsMouseButtonJustPressed actions.JustPressed
inpututil.IsMouseButtonJustReleased actions.JustReleased
Checking touch positions against a button's rectangle input.TouchRegion(rect), or input.TouchControls with a YAML TouchLayout
Two opposing inputs combined into a direction actions.BindAxis("move_x", "left", "right") and actions.Axis

Call actions.Step() at the start of each Update. A tap that starts and ends between two updates still registers for one. actions.WatchKeys(cx) reads keys anywhere on the window, and KeyCode binds a physical key position instead of the layout-dependent name used by Key. Call actions.WatchGamepads(cx) to feed controller buttons and axes into the map. TouchControls.BindActions(actions) connects an on-screen layout to the same actions and axes. actions.Save and Load keep remapped bindings in core.Storage. See input.

Physics

Ebitengine has no physics, so this is new rather than a port. physics holds box and circle overlap tests, MoveAndSlide for platformer bodies against a tile grid with one-way platforms, trigger areas, and raycasts. 2D Rigid Bodies adds a deterministic rigid-body solver with distance, spring and revolute joints, and physics3d covers 3D bodies and a capsule character controller. All of them step on the loop's fixed dt. The 2D packages work in the same Y-down screen space the drawing uses, while physics3d works in the 3D space: right-handed, Y up, units in metres.

Export

Ebitengine Here
go run . go tool nsgo dev, which also reloads on save
GOOS=js GOARCH=wasm go build and a wasm_exec.js page go tool nsgo build -target web
ebitenmobile bind and an Xcode or Android Studio project go tool nsgo build -target ios or android
Bundling a .app or installer yourself go tool nsgo build, which writes .dmg, NSIS installers, .deb, .AppImage, .apk and .ipa

App name, identifier, version, icons and targets live in nsgo.yaml, and -channel store builds store packages. See Building and Shipping, and Getting Started for a first project.

Modifier cette page