Documentation
¶
Overview ¶
Package rooms splits a 2D world into rooms with their own camera bounds and moves a tilemap.Camera between them with a cut, slide or fade transition, as metroidvania platformers do.
Room Maps ¶
A Map is a versioned YAML file listing rectangular rooms in world points and the transition each one plays when the player enters it. Parse decodes and validates a map, refusing unknown fields, unsupported versions, duplicate IDs, empty or non-finite rectangles, unknown transition kinds or curves and malformed colors. Encode writes deterministic 2-space YAML that Parse reads back to the same Map. FromLDtk and FromTiledLayer build rooms from an LDtk project's levels or a Tiled object layer's rectangles, so a map can be laid out in either editor.
Director ¶
A Director owns the camera's position. Each fixed step, Update finds the room holding the target (usually the player), keeping the current room while the target is still inside it so overlapping edges do not flicker. When the target enters another room, Update sets Camera.Bounds to that room and plays its transition:
- cut snaps the camera to the target, clamped to the new room.
- slide pans the camera from where it was to the target's clamped position in the new room over the transition's duration, along its curve.
- fade covers the view with a color over the first half, cuts the camera to the new room at the midpoint and uncovers the view over the second half; DrawFade paints the cover.
Outside transitions Update follows the target with tilemap.Camera.Follow, clamped to the current room. Transitioning reports when a transition is playing, so a game can pause its player until the camera lands.
Example ¶
Example reads a room map, finds the room holding a point and writes the map back unchanged.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/rooms"
"github.com/nsgo-dev/nsgo/core"
)
const exampleMap = `version: 1
transition:
kind: slide
duration: 300ms
rooms:
- id: entrance
x: 0
"y": 0
width: 320
height: 180
- id: hall
x: 320
"y": 0
width: 640
height: 180
transition:
kind: fade
color: '#102030'
`
func main() {
m, err := rooms.Parse([]byte(exampleMap))
if err != nil {
panic(err)
}
r := m.RoomAt(core.Point{X: 400, Y: 90})
fmt.Println(r.ID, r.Bounds())
fmt.Println(m.TransitionInto(m.Room("entrance")).Kind, m.TransitionInto(r).Length())
out, err := rooms.Encode(m)
if err != nil {
panic(err)
}
fmt.Println(string(out) == exampleMap)
}
Output: hall {{320 0} {640 180}} slide 600ms true
Index ¶
- Constants
- Variables
- func Encode(m *Map) ([]byte, error)
- func Validate(m *Map) error
- type Director
- func (d *Director) DrawFade(dr *core.Drawing)
- func (d *Director) FadeAlpha() float32
- func (d *Director) Previous() *Room
- func (d *Director) Progress() float64
- func (d *Director) Room() *Room
- func (d *Director) Start(target core.Point) bool
- func (d *Director) Transition() Transition
- func (d *Director) Transitioning() bool
- func (d *Director) Update(target core.Point, dt time.Duration) bool
- type Duration
- type Easing
- type Kind
- type Map
- type Room
- type Transition
Examples ¶
Constants ¶
const ( // DefaultSlideDuration is how long a slide lasts when its Duration is 0. DefaultSlideDuration = 400 * time.Millisecond // DefaultFadeDuration is how long a fade lasts, out and back in, when its Duration is 0. DefaultFadeDuration = 600 * time.Millisecond )
Default transition lengths, used when a slide or fade leaves Duration at 0.
const FormatVersion = 1
FormatVersion is the room map schema version this package reads and writes.
Variables ¶
var ErrInvalidMap = errors.New("rooms: invalid map")
ErrInvalidMap reports that a room map breaks the schema: a wrong version, no rooms, a missing or duplicate ID, an empty or non-finite rectangle, or a malformed transition.
Functions ¶
Types ¶
type Director ¶
type Director struct {
// Map is the room map the Director moves through.
Map *Map
// Camera is the camera the Director moves.
Camera *tilemap.Camera
// Smoothing is the Camera.Follow smoothing used outside transitions; <= 0 keeps the camera locked on the target.
Smoothing float32
// contains filtered or unexported fields
}
Director moves a tilemap.Camera between a Map's rooms, clamping it to the room the target is in and playing the room's transition on entry.
The Director owns Camera.X, Camera.Y and Camera.Bounds: a game calls Update once per fixed step instead of Camera.Follow or Camera.Clamp, and keeps calling Camera.Update for shake. Map must not change while the Director uses it; call Start again after replacing it.
Example ¶
ExampleDirector moves a camera from the entrance into the hall, which fades: the view is covered over the first half, the camera cuts at the midpoint and the view is uncovered over the second half.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/rooms"
"github.com/nsgo-dev/game/pkg/tilemap"
"github.com/nsgo-dev/nsgo/core"
)
const exampleMap = `version: 1
transition:
kind: slide
duration: 300ms
rooms:
- id: entrance
x: 0
"y": 0
width: 320
height: 180
- id: hall
x: 320
"y": 0
width: 640
height: 180
transition:
kind: fade
color: '#102030'
`
func main() {
m, err := rooms.Parse([]byte(exampleMap))
if err != nil {
panic(err)
}
cam := &tilemap.Camera{Width: 320, Height: 180}
dir := rooms.NewDirector(m, cam)
dir.Start(core.Point{X: 100, Y: 90})
fmt.Println(dir.Room().ID, cam.X, cam.Y)
player := core.Point{X: 400, Y: 90}
fmt.Println(dir.Update(player, 150*time.Millisecond), dir.Room().ID, dir.FadeAlpha(), cam.X)
dir.Update(player, 150*time.Millisecond)
fmt.Println(dir.FadeAlpha(), cam.X)
dir.Update(player, 300*time.Millisecond)
fmt.Println(dir.Transitioning(), dir.FadeAlpha(), cam.X, cam.Y)
}
Output: entrance 160 90 true hall 0.5 160 1 480 false 0 480 90
func NewDirector ¶
NewDirector returns a Director that moves cam through m's rooms.
func (*Director) DrawFade ¶
DrawFade covers the view with the fade's color at FadeAlpha, and draws nothing when no cover is showing. Call it in view space, after the world and outside Camera.Apply, so the cover fills the Camera.Width by Camera.Height view.
func (*Director) FadeAlpha ¶
FadeAlpha returns the opacity of the fade's cover, from 0 to 1, or 0 when no cover is showing. A fade interrupted by a room change keeps its cover's opacity: a new fade covers on from it, and a slide or cut lets it clear as the interrupted fade would have.
func (*Director) Previous ¶
Previous returns the room the camera last left, or nil before the first room change.
func (*Director) Progress ¶
Progress returns how far the playing transition has run, from 0 to 1 in linear time, or 1 when none is playing.
func (*Director) Room ¶
Room returns the room the camera is in or moving into, or nil before the target was first found in a room.
func (*Director) Start ¶
Start puts the camera in the room holding target, clamped to it, with no transition, and reports whether a room holds target. Use it to spawn the player or after loading a save; when no room holds target, or target has a non-finite coordinate, the Director keeps its state.
func (*Director) Transition ¶
func (d *Director) Transition() Transition
Transition returns the transition that is playing, or the last one played; its Kind is empty before the first room change.
func (*Director) Transitioning ¶
Transitioning reports whether a slide or fade is playing.
func (*Director) Update ¶
Update advances the Director by one fixed step of dt toward target, usually the player's position, and reports whether target entered a room on this step.
While target stays in the current room it stays there, even where rooms overlap. When target leaves it for another room, Update clamps the camera to that room and starts its transition. When target is in no room, the camera keeps to the current one. A target with a non-finite coordinate is ignored: the camera and any transition hold for that step. Before the first room is found, Update behaves as Start.
type Duration ¶
Duration is a time.Duration written in YAML as a Go duration string with a unit, such as "400ms" or "1.5s".
func (Duration) MarshalYAML ¶
MarshalYAML writes d as its time.Duration string.
type Easing ¶
type Easing string
Easing names one of NSGo's standard easing curves in a room map.
const ( // EasingLinear is core.Linear. EasingLinear Easing = "linear" // EasingEase is core.Ease. EasingEase Easing = "ease" // EasingEaseIn is core.EaseIn. EasingEaseIn Easing = "easeIn" // EasingEaseOut is core.EaseOut. EasingEaseOut Easing = "easeOut" // EasingEaseInOut is core.EaseInOut. EasingEaseInOut Easing = "easeInOut" )
type Kind ¶
type Kind string
Kind is how the camera moves into a room.
const ( // KindCut snaps the camera into the new room at once. KindCut Kind = "cut" // KindSlide pans the camera into the new room over the transition's duration. KindSlide Kind = "slide" // KindFade covers the view with a color, cuts to the new room at the midpoint and uncovers it. KindFade Kind = "fade" )
type Map ¶
type Map struct {
// Version is the schema version; it must equal FormatVersion.
Version int `yaml:"version"`
// Transition is played when entering a room that sets none; nil cuts.
Transition *Transition `yaml:"transition,omitempty"`
// Rooms lists the rooms. Where rooms overlap, a target entering the overlap from outside both belongs to the first one listed.
Rooms []Room `yaml:"rooms"`
}
Map is the root of a versioned YAML room map.
func Parse ¶
Parse decodes a YAML room map and validates it. Unknown fields and trailing YAML documents are refused.
Errors are *loaderr.Error values wrapping ErrInvalidMap with line, field and fix; callers that read from a file name it with loaderr.WithFile.
func (*Map) RoomAt ¶
RoomAt returns the first room in list order that contains p, or nil when none does.
func (*Map) TransitionInto ¶
func (m *Map) TransitionInto(r *Room) Transition
TransitionInto returns the transition played when entering r: r's own, else the map's, else a cut.
type Room ¶
type Room struct {
// ID uniquely identifies the room within the map and in saves.
ID string `yaml:"id"`
// Name is the room's display name or a localization key; the package does not interpret it.
Name string `yaml:"name,omitempty"`
// X is the room's left edge in world points.
X float32 `yaml:"x"`
// Y is the room's top edge in world points.
Y float32 `yaml:"y"`
// Width is the room's width in world points; it must be positive.
Width float32 `yaml:"width"`
// Height is the room's height in world points; it must be positive.
Height float32 `yaml:"height"`
// Transition is played when entering this room, overriding the map's.
Transition *Transition `yaml:"transition,omitempty"`
}
Room is one rectangle of the world with its own camera bounds.
func FromLDtk ¶
FromLDtk returns one room per level of an LDtk project (.ldtk JSON), with the level's identifier as the room's ID and its world position and pixel size as the room's rectangle.
An empty world reads the project's top-level levels; a project with LDtk's multi-worlds enabled names the world to read by its identifier. The world's layout must be Free or GridVania, since Linear layouts give levels no world positions. The rooms carry no transitions; put them in a Map, whose Transition applies to every room, and run Validate.
func FromTiledLayer ¶
func FromTiledLayer(layer *tilemap.ObjectLayer) ([]Room, error)
FromTiledLayer returns one room per object of a Tiled object layer, in layer order, with the object's name as the room's ID and its rectangle, moved by the layer's offset (which includes the offsets of the groups holding it), as the room's.
Every object must be an unrotated rectangle (not a tile, point, ellipse, polygon or polyline) with a name and a positive size, so a misdrawn room is reported instead of skipped. The rooms carry no transitions; put them in a Map, whose Transition applies to every room, and run Validate.
type Transition ¶
type Transition struct {
// Kind is cut, slide or fade.
Kind Kind `yaml:"kind"`
// Duration is how long a slide or fade lasts; 0 uses DefaultSlideDuration or DefaultFadeDuration. A cut must leave it 0.
Duration Duration `yaml:"duration,omitempty"`
// Easing eases a slide's pan or a fade's cover; empty uses easeInOut for a slide and linear for a fade. A cut must leave it empty.
Easing Easing `yaml:"easing,omitempty"`
// Color is a fade's cover color as a CSS color, such as "#000" or "rgb(20 10 40)"; empty is black. Only a fade may set it.
Color string `yaml:"color,omitempty"`
}
Transition is how the camera moves into a room.
func (Transition) Curve ¶
func (t Transition) Curve() core.Curve
Curve returns t's easing curve: the one Easing names, or core.EaseInOut for a slide and core.Linear otherwise.
func (Transition) FadeColor ¶
func (t Transition) FadeColor() core.Color
FadeColor returns the color a fade covers the view with: Color parsed as a CSS color, or opaque black when Color is empty or malformed.
func (Transition) Length ¶
func (t Transition) Length() time.Duration
Length returns how long t lasts: Duration, or the kind's default when Duration is 0. A cut lasts 0.