utility

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package utility is the core of the engine.

It holds four kinds of things:

  • The game loop and its global state: PlayGame, SetLevel, SetAssetFS, SetScreenSize, GetTickIndex and the tunable values in game.go.
  • The level: Level keeps every actor and the lists of the roles they play, and gives the AI its pathfinding.
  • The roles an actor can play, as interfaces: Actor, Collider, MovableCollider, Player, Ticker, Drawer and the others in interfaces.go. The level sorts actors into its lists by the interfaces they implement, so an actor takes a new role just by implementing one.
  • The values a 2D game works with: Vector, Point, Size, RectangleF, CircleF, Transform, Set, Smap, Array2D and the collision helpers of trace.go.

The game loop and the current level are package level state, so a program runs one game at a time.

Index

Constants

View Source
const (
	// TickCount is how many times the game updates in a second.
	TickCount = 60
	// TickDuration is how long one update lasts in seconds.
	TickDuration = 1.0 / float64(TickCount)

	// The order the drawers are drawn in, from the ground up.
	// A drawer chooses its order by implementing ZSpecifiedDrawer.
	ZOrderDefault = 0
	ZOrderEffect  = 1
	ZOrderWidget  = 2
	ZOrderMax     = ZOrderWidget
)

Variables

View Source
var (
	TypeBool  = reflect.TypeOf(bool(false))
	TypeInt   = reflect.TypeOf(int(0))
	TypeFloat = reflect.TypeOf(float64(0))

	TypeEbitenImagePtr = reflect.TypeOf((*ebiten.Image)(nil))
	TypeRGB            = reflect.TypeOf(RGB{})
)
View Source
var (
	// MovementMaxReflectionCount is how many times a movement can slide along the
	// colliders it hits within one update.
	MovementMaxReflectionCount = 1

	// AIValidOffset shrinks a pathfinding cell when testing whether it is blocked,
	// so that a cell touching a wall only at its edge stays walkable.
	AIValidOffset = 0.5

	// AIMaxTaskCount is how many paths may be searched in the background at a time.
	AIMaxTaskCount = 1

	// GamepadDeadZone is the stick range around the center which is read as no input.
	GamepadDeadZone = 0.2

	// WidgetFloatUnit is the unit of the sizes in widget files: 100 means percent.
	WidgetFloatUnit = 100.0

	ColorRed         = RGB{0xff, 0x00, 0x00}
	ColorOrange      = RGB{0xff, 0x80, 0x00}
	ColorYellow      = RGB{0xff, 0xff, 0x00}
	ColorLightGreen  = RGB{0x80, 0xff, 0x00}
	ColorGreen       = RGB{0x00, 0xff, 0x00}
	ColorLightBlue   = RGB{0x00, 0x80, 0xff}
	ColorBlue        = RGB{0x00, 0x00, 0xff}
	ColorPurple      = RGB{0x80, 0x00, 0xff}
	ColorWhite       = RGB{0xff, 0xff, 0xff}
	ColorGray        = RGB{0x80, 0x80, 0x80}
	ColorBlack       = RGB{0x00, 0x00, 0x00}
	ColorTransparent = ColorBlack.ToNRGBA(0x00)

	// The capacity the lists of a level start with. They only avoid growing the
	// lists while a level fills up, so a wrong value costs nothing but a little memory.
	InitialActorCap                = 128
	InitialStaticColliderCap       = 128
	InitialMovableColliderCap      = 32
	InitialInputReceivableActorCap = 1
	InitialPlayerCap               = 1
	InitialBeginPlayerCap          = 1
	InitialEndPlayerCap            = 1
	InitialAITickerCap             = 32
	InitialTickerCap               = 32
	InitialDrawerCap               = 128
	InitialTrashCap                = 32
	InitialPFResultCap             = 128
	InitialWidgetFontCap           = 4
)

The settings of the engine. Change them before playing a game.

View Source
var (
	// DebugServerAddress is where the pprof profiler is served in debug mode.
	DebugServerAddress = ":6060"

	DebugInitialDrawsCap = 32

	DebugIsShowLocation     = false
	DebugLocationTextOffset = NewVector(3, -12)

	DebugIsShowTraceDistance = false
	DebugTraceDistanceColors = map[int]color.Color{
		0: ColorRed,
	}

	DebugIsShowTraceResult               = false
	DebugTraceResultLength               = 30.0
	DebugTraceResultOffsetColor          = ColorLightGreen
	DebugTraceResultRemainingOffsetColor = ColorWhite
	DebugTraceResultHitNormalColor       = ColorRed

	DebugIsShowAIPath = false
	DebugAIPathColor  = ColorGreen.ToNRGBA(0x30)
)

The settings of the debug mode. See IsDebugMode.

View Source
var DebugEnvNames = []string{"debug", "EBITENHELPER_DEBUG"}

DebugEnvNames are the environment variables which turn the debug mode on when any of them is set, whatever its value is.

Functions

func AddDebugDraw

func AddDebugDraw(event func(*ebiten.Image))

func AppendFontFamiliesFromFilePathsString

func AppendFontFamiliesFromFilePathsString(in []*text.GoTextFaceSource, pathsString string) []*text.GoTextFaceSource

func ClampFloat

func ClampFloat(value float64, min float64, max float64) float64

ClampFloat returns the value limited to the range.

func ClampRotation

func ClampRotation(rotation float64) float64

ClampRotation returns the rotation wrapped into the range (-Pi, Pi].

func ConvertFromString

func ConvertFromString(str string, typeTo reflect.Type) (any, error)

func DegreeToRadian

func DegreeToRadian(degree float64) float64

DegreeToRadian converts an angle in degrees to radians.

func DrawCircle

func DrawCircle(screen *ebiten.Image, center Vector, radius float32, borderWidth float32, borderColor color.Color, fillColor color.Color, antialias bool)

DrawCircle draws a circle. A nil color, or a zero border width, skips that part.

func DrawDebugAIPath

func DrawDebugAIPath(path []Point)

func DrawDebugCircle

func DrawDebugCircle(center Vector, radius float32, color color.Color)

func DrawDebugLine

func DrawDebugLine(start Vector, end Vector, color color.Color)

func DrawDebugLocation

func DrawDebugLocation(location Vector)

func DrawDebugRectangle

func DrawDebugRectangle(topleft Vector, size Vector, color color.Color)

func DrawDebugText

func DrawDebugText(topleft Vector, text string)

func DrawDebugTraceDistance

func DrawDebugTraceDistance(target Bounder, distance int)

func DrawDebugTraceResult

func DrawDebugTraceResult[T ColliderComparable](r *TraceResult[T], b Bounder)

func DrawImage

func DrawImage(dst *ebiten.Image, src *ebiten.Image, transform StaticTransformer)

DrawImage draws the image at the transform. In a looping level it also draws the eight copies around the screen, so that an image crossing an edge appears on the opposite edge as well.

func DrawLine

func DrawLine(screen *ebiten.Image, start Vector, end Vector, width float32, color color.Color, antialias bool)

DrawLine draws a line between the two locations.

func DrawRectangle

func DrawRectangle(screen *ebiten.Image, topLeft Vector, size Vector, borderWidth float32, borderColor color.Color, fillColor color.Color, antialias bool)

DrawRectangle draws a rectangle. A nil color, or a zero border width, skips that part.

func Exit

func Exit(code int)

Exit quits the game with the exit code. It does nothing on the web, where a program cannot exit by itself.

func GetActors

func GetActors[T Actor]() func(yield func(T) bool)

func GetActorsByName

func GetActorsByName[T Actor](name string) func(yield func(T) bool)

func GetAssetData

func GetAssetData(filename string) ([]byte, error)

func GetBoundsCollection

func GetBoundsCollection[T ColliderComparable](colliders []T, excepts Set[T]) func(yield func(T, Bounder) bool)

func GetFirstActor

func GetFirstActor[T Actor]() (actor T, ok bool)

func GetFirstActorByName

func GetFirstActorByName[T Actor](name string) (actor T, ok bool)

func GetFirstActorP

func GetFirstActorP[T Actor]() T

func GetFontFromFile

func GetFontFromFile(filename string) (*text.GoTextFaceSource, error)

func GetFontFromFileP

func GetFontFromFileP(filename string) *text.GoTextFaceSource

func GetGameInstance

func GetGameInstance[T GameInstancer]() T

func GetImageFromFile

func GetImageFromFile(filename string) (*ebiten.Image, error)

func GetImageFromFileP

func GetImageFromFileP(filename string) *ebiten.Image

func GetSubImage

func GetSubImage(parentimage *ebiten.Image, location Point, size Point) *ebiten.Image

GetSubImage returns the part of the image at the location of the size.

func GetTickIndex

func GetTickIndex() int

func GetWindowTitle

func GetWindowTitle() string

func HexStringToColor

func HexStringToColor(hex string, defColor color.Color) color.Color

func IsDebugMode

func IsDebugMode() bool

IsDebugMode returns whether the game runs in debug mode.

In debug mode the engine draws the debug shapes enabled in game.go, builds the missing pathfinding cache of a level instead of failing, and serves the profiler.

func OpenAssetFile

func OpenAssetFile(filename string) (fs.File, error)

func PanicIfError

func PanicIfError(err error)

PanicIfError panics when the error is not nil. It is used by the P variants of the functions which read assets, where an unreadable asset is not a recoverable state.

func PlayGame

func PlayGame(instance GameInstancer, firstlevel *Level) error

PlayGame opens the game window and runs the game loop until it is closed. Set the asset filesystem, the window title and the screen size before calling it.

Most games call ebitenhelper.Run instead, which does all of it in one call.

func RadianToDegree

func RadianToDegree(radian float64) float64

RadianToDegree converts an angle in radians to degrees.

func RemoveAllStrings

func RemoveAllStrings(src string, targets ...string) string

RemoveAllStrings returns the string without all occurrences of the targets.

func RemoveSliceItem

func RemoveSliceItem[T comparable](slice []T, item T) []T

RemoveSliceItem removes the first occurrence of the item from the slice.

func RunDebugServer

func RunDebugServer()

RunDebugServer starts serving the pprof profiler at DebugServerAddress in debug mode.

func RuneToInt

func RuneToInt(r rune) int

func SetAssetFS

func SetAssetFS(fsys fs.FS)

SetAssetFS sets the filesystem every asset is read from, usually an embed.FS. Call it before loading a level.

func SetLevel

func SetLevel(level *Level) error

SetLevel leaves the current level and starts the given one: it calls EndPlay on the actors of the old level, loads the pathfinding cache of the new one, and calls BeginPlay on its actors.

func SetScreenSize

func SetScreenSize(width int, height int)

func SetWindowTitle

func SetWindowTitle(title string)

func StringToFloatSlice

func StringToFloatSlice(strings []string) ([]float64, error)

Types

type AITicker

type AITicker interface {
	Actor
	AITick()
}

AITicker is an actor which decides its movement every update. Every AITick of a level runs before any Tick, so all of them decide on the same state of the level.

type AStar

type AStar struct {
	// contains filtered or unexported fields
}

AStar finds the paths on a grid of locations and caches them.

A cached path is reused by every start location on it, and the cache of a whole level can be built ahead of time and saved to a file, so that the game does not search during play.

func NewAStar

func NewAStar(isValid func(location Point) bool) *AStar

NewAStar creates a pathfinding on the locations which isValid accepts. isValid is called from several goroutines, so it must be safe to do so.

func (*AStar) GetCache

func (a *AStar) GetCache(start Point, goal Point) (result []Point, ok bool)

func (*AStar) GetResult

func (a *AStar) GetResult(start Point, goal Point) (result []Point, ok bool)

GetResult returns the cached path from the start to the goal.

When the path is not cached yet it returns false and searches it in the background, so that the caller keeps running at a stable frame rate. The next calls return the path once the search is done.

func (*AStar) GetResultForce

func (a *AStar) GetResultForce(start Point, goal Point) []Point

GetResultForce searches the path from the start to the goal at once, and caches it.

func (*AStar) LoadCache

func (a *AStar) LoadCache(filename string) error

func (*AStar) SaveCache

func (a *AStar) SaveCache(filename string) error

type AStarInstance

type AStarInstance struct {
	// contains filtered or unexported fields
}

AStarInstance is one run of the pathfinding.

func NewAStarInstance

func NewAStarInstance(isValid func(location Point) bool) *AStarInstance

NewAStarInstance creates a run of the pathfinding on the locations which isValid accepts. isValid is called from several goroutines, so it must be safe to do so.

func (*AStarInstance) GetCurrentPath

func (a *AStarInstance) GetCurrentPath() []Point

func (*AStarInstance) GetNextOpenNode

func (a *AStarInstance) GetNextOpenNode() *AStarNode

func (*AStarInstance) Run

func (a *AStarInstance) Run(start Point, goal Point) []Point

Run returns the path from the start to the goal, or an empty path when there is none.

func (*AStarInstance) UpdateNode

func (a *AStarInstance) UpdateNode(node *AStarNode, goal Point)

type AStarNode

type AStarNode struct {
	Location  Point
	IsAllInit bool
	GDistance int
	HDistance int
	Parent    *AStarNode
}

func NewAStarNode

func NewAStarNode(location Point) *AStarNode

func (*AStarNode) GetAroundLocations

func (n *AStarNode) GetAroundLocations() func(yield func(Point) bool)

type AStarResultKey

type AStarResultKey struct {
	Start Point
	Goal  Point
}

func NewAStarResultKey

func NewAStarResultKey(start Point, goal Point) AStarResultKey

type Actor

type Actor interface {
	GetName() string
}

Actor is anything a level holds. Everything else in this file is a role an actor can play, and a level sorts its actors into its lists by the roles they implement, so an actor takes a new role just by implementing one of these interfaces.

type Array2D

type Array2D[T any] struct {
	// contains filtered or unexported fields
}

func NewArray2D

func NewArray2D[T any](width int, height int) *Array2D[T]

func (*Array2D[T]) Get

func (a *Array2D[T]) Get(x, y int) T

func (*Array2D[T]) Height

func (a *Array2D[T]) Height() int

func (*Array2D[T]) Range

func (a *Array2D[T]) Range() func(yield func(Point, T) bool)

func (*Array2D[T]) Set

func (a *Array2D[T]) Set(x, y int, value T)

func (*Array2D[T]) Width

func (a *Array2D[T]) Width() int

type BeginPlayer

type BeginPlayer interface {
	Actor
	BeginPlay()
}

BeginPlayer is an actor which prepares itself when its level starts. It is not called for an actor added to a level which is already playing.

type Bounder

type Bounder interface {
	ToCircle() *CircleF
	CenterLocation() Vector
	Offset(x, y float64, output Bounder) Bounder
	IntersectTo(target Bounder) (result bool, normal *Vector)
	IntersectFromRectangle(src *RectangleF) (result bool, normal *Vector)
	IntersectFromCircle(src *CircleF) (result bool, normal *Vector)
}

type CallTimer

type CallTimer struct {
	// contains filtered or unexported fields
}

func NewCallTimer

func NewCallTimer() *CallTimer

func (*CallTimer) StartCallTimer

func (c *CallTimer) StartCallTimer(f func(), seconds float32)

func (*CallTimer) StopCallTimer

func (c *CallTimer) StopCallTimer()

func (*CallTimer) Tick

func (c *CallTimer) Tick()

type CircleF

type CircleF struct {
	OrgX   float64
	OrgY   float64
	Radius float64
}

func NewCircleF

func NewCircleF(orgX, orgY, radius float64) *CircleF

func (*CircleF) CenterLocation

func (c *CircleF) CenterLocation() Vector

func (*CircleF) Draw

func (c *CircleF) Draw(screen *ebiten.Image, borderWidth float32, borderColor color.Color, fillColor color.Color, antialias bool)

func (*CircleF) IntersectFromCircle

func (c *CircleF) IntersectFromCircle(src *CircleF) (result bool, normal *Vector)

func (*CircleF) IntersectFromRectangle

func (c *CircleF) IntersectFromRectangle(src *RectangleF) (result bool, normal *Vector)

func (*CircleF) IntersectTo

func (c *CircleF) IntersectTo(target Bounder) (result bool, normal *Vector)

func (*CircleF) Offset

func (c *CircleF) Offset(x, y float64, output Bounder) Bounder

func (*CircleF) ToCircle

func (c *CircleF) ToCircle() *CircleF

type Collider

type Collider interface {
	ColliderBase
	StaticTransformer
}

Collider is an actor which blocks or is hit by the others, such as a wall.

type ColliderBase

type ColliderBase interface {
	Actor
	UpdateBounds()
	EnableBounds()
	DisableBounds()
	GetRealFirstBounds() Bounder
	GetRealBounds() []Bounder
	GetFirstBounds() Bounder
	GetBounds() []Bounder
	ReceiveHit(result *TraceResult[Collider])
}

ColliderBase is an actor which has bounds, without saying whether it can move.

type ColliderComparable

type ColliderComparable interface {
	Collider
	comparable
}

ColliderComparable is a collider which can be compared, so that it can be put in a Set and be excluded from a collision test.

type DangerCircler

type DangerCircler interface {
	Actor
	// GetDangerCircle returns the circle area where this actor is dangerous for the others
	GetDangerCircle() (circle CircleF, isActive bool)
}

type Drawer

type Drawer interface {
	Actor
	GetVisibility() bool
	SetVisibility(isVisible bool)
	Draw(screen *ebiten.Image)
}

Drawer is an actor which draws itself every frame.

type Empty

type Empty struct{}

Empty is a value holding nothing, used as the value type of Set.

type EndPlayer

type EndPlayer interface {
	Actor
	EndPlay()
}

EndPlayer is an actor which cleans itself up when its level is left.

type Game

type Game struct {
	// contains filtered or unexported fields
}

func NewGame

func NewGame() *Game

func (*Game) Draw

func (g *Game) Draw(screen *ebiten.Image)

func (*Game) Layout

func (g *Game) Layout(width int, height int) (int, int)

func (*Game) Update

func (g *Game) Update() error

type GameInstanceBase

type GameInstanceBase struct{}

func (*GameInstanceBase) ReceiveGamepadAxisInput

func (g *GameInstanceBase) ReceiveGamepadAxisInput(id ebiten.GamepadID, axis ebiten.StandardGamepadAxis, value float64)

func (*GameInstanceBase) ReceiveGamepadButtonInput

func (g *GameInstanceBase) ReceiveGamepadButtonInput(id ebiten.GamepadID, button ebiten.StandardGamepadButton, state PressState)

func (*GameInstanceBase) ReceiveKeyInput

func (g *GameInstanceBase) ReceiveKeyInput(key ebiten.Key, state PressState)

func (*GameInstanceBase) ReceiveMouseButtonInput

func (g *GameInstanceBase) ReceiveMouseButtonInput(button ebiten.MouseButton, state PressState, pos Point)

type GameInstancer

type GameInstancer interface {
	InputReceiver
}

GameInstancer reads the player input which is not sent to a specific actor, such as a key toggling fullscreen. Embed GameInstanceBase to implement it in one line.

type GamepadAxisKey

type GamepadAxisKey struct {
	ID   ebiten.GamepadID
	Axis ebiten.StandardGamepadAxis
}

type InputReceivableActor

type InputReceivableActor interface {
	Actor
	InputReceiver
}

InputReceivableActor is an actor which reads the player input.

type InputReceiver

type InputReceiver interface {
	ReceiveKeyInput(key ebiten.Key, state PressState)
	ReceiveMouseButtonInput(button ebiten.MouseButton, state PressState, pos Point)
	ReceiveGamepadButtonInput(id ebiten.GamepadID, button ebiten.StandardGamepadButton, state PressState)
	ReceiveGamepadAxisInput(id ebiten.GamepadID, axis ebiten.StandardGamepadAxis, value float64)
}

InputReceiver is anything which reads the player input of this update.

type Inset

type Inset struct {
	Top, Right, Bottom, Left float64
}

func NewInset

func NewInset(values []float64) Inset

func NewInsetFromString

func NewInsetFromString(str string, unit float64) Inset

type Level

type Level struct {
	Name          string
	IsLooping     bool
	AIGridSize    Vector
	AIPathfinding *AStar

	Actors                []Actor
	Colliders             []Collider
	StaticColliders       []Collider
	MovableColliders      []MovableCollider
	InputReceivableActors []InputReceivableActor
	Players               []Player
	BeginPlayers          []BeginPlayer
	EndPlayers            []EndPlayer
	AITickers             []AITicker
	Tickers               []Ticker
	Drawers               [][]Drawer
	NamedActors           *Smap[string, []Actor]
	DebugDraws            []func(screen *ebiten.Image)
	Trashes               []Actor
	// contains filtered or unexported fields
}

Level is one stage of a game: it holds every actor of the stage, and the lists of the actors playing each role, so that the game loop walks only the actors it needs.

Add sorts an actor into those lists, and Remove takes it out at the end of the update. The AI methods of a level, such as AIMove, move an actor along the pathfinding grid of the stage.

func GetLevel

func GetLevel() *Level

GetLevel returns the level being played.

func NewLevel

func NewLevel(name string, isLooping bool) *Level

NewLevel creates an empty level. Add the actors to it before playing it.

func (*Level) AIGetAngleAround

func (l *Level) AIGetAngleAround(center Vector, location Vector) float64

AIGetAngleAround returns the angle of the location on the circle around the center

func (*Level) AIGetLocationAround

func (l *Level) AIGetLocationAround(center Vector, angle float64, radius float64) Vector

AIGetLocationAround returns the location on the circle around the center

func (*Level) AIGetReachableAnglesAround

func (l *Level) AIGetReachableAnglesAround(center Vector, radius float64, sampleCount int, output []float64) []float64

AIGetReachableAnglesAround appends the angles on the circle around the center where the location is reachable by pathfinding, sampling the circle by the specified count

func (*Level) AIGetReachableLocationAround

func (l *Level) AIGetReachableLocationAround(center Vector, direction Vector, radius float64, retryCount int) (location Vector, ok bool)

AIGetReachableLocationAround returns the location which is reachable by pathfinding, searching on the circle around the center, from the specified direction in order

func (*Level) AIIsPFLocationValid

func (l *Level) AIIsPFLocationValid(location Point) bool

AIIsPFLocationValid returns whether the pathfinding cell is inside the screen and not blocked by a static collider. The answer is cached per cell.

func (*Level) AIMove

func (l *Level) AIMove(self MovableCollider, target Collider)

AIMove moves the actor one step towards the target along the pathfinding grid.

func (*Level) AIMoveToLocation

func (l *Level) AIMoveToLocation(self MovableCollider, targetLocation Vector)

AIMoveToLocation moves the actor one step towards the location along the pathfinding grid. It does nothing while the path is still being searched.

func (*Level) Add

func (l *Level) Add(actor Actor)

Add puts the actor into the level and into the list of every role it implements.

func (*Level) AddDebugDraw

func (l *Level) AddDebugDraw(event func(*ebiten.Image))

func (*Level) BuildPFCache

func (l *Level) BuildPFCache() error

BuildPFCache searches the path between every pair of cells of the level and saves the result next to the map file, so that the game never searches while playing.

It takes minutes on a large map and needs a writable assets directory, so it runs in debug mode only, from LoadOrBuildPFCache.

func (*Level) ClearDebugDraw

func (l *Level) ClearDebugDraw()

func (*Level) EmptyTrashes

func (l *Level) EmptyTrashes()

EmptyTrashes drops the actors asked by Remove. The game loop calls it every update.

func (*Level) GetPFCacheFileName

func (l *Level) GetPFCacheFileName() string

func (*Level) LoadOrBuildPFCache

func (l *Level) LoadOrBuildPFCache() error

func (*Level) LoadPFCache

func (l *Level) LoadPFCache() error

LoadPFCache reads the pathfinding cache of the level from the assets.

func (*Level) PFToRealLocation

func (l *Level) PFToRealLocation(pfLocation Point, isCenter bool) Vector

func (*Level) RealToPFLocation

func (l *Level) RealToPFLocation(realLocation Vector) Point

func (*Level) Remove

func (l *Level) Remove(actor Actor)

Remove asks the level to drop the actor. It is dropped by EmptyTrashes at the end of the update, so that the running update still sees a consistent level.

type Location

type Location struct {
	StaticLocation
}

func NewLocation

func NewLocation(value Vector) Location

func (*Location) SetLocation

func (l *Location) SetLocation(value Vector)

type Locator

type Locator interface {
	StaticLocator
	SetLocation(value Vector)
}

type MaxSpeeder

type MaxSpeeder interface {
	GetMaxSpeed() float64
}

type MovableCollider

type MovableCollider interface {
	ColliderBase
	Transformer
	AddInput(normal Vector, scale float64)
	AddLocation(offset Vector) *TraceResult[Collider]
}

MovableCollider is a collider which moves, such as a character.

AddInput asks it to accelerate towards a direction in this update, and AddLocation moves it right away, stopping it at the first collider on the way.

type Player

type Player interface {
	InputReceivableActor
	MovableCollider
}

Player is the character the player moves. The AI chases the first one of a level.

type Point

type Point struct {
	X int
	Y int
}

func GetCursorPosition

func GetCursorPosition() Point

GetCursorPosition returns the location of the mouse cursor on the screen.

func GetScreenSize

func GetScreenSize() Point

func NewPoint

func NewPoint(x int, y int) Point

func ZeroPoint

func ZeroPoint() Point

func (Point) Add

func (p Point) Add(value Point) Point

func (Point) AddXY

func (p Point) AddXY(x int, y int) Point

func (Point) Distance

func (p Point) Distance(value Point) float64

func (Point) Distance2

func (p Point) Distance2(value Point) int

func (Point) Div

func (p Point) Div(value Point) Point

func (Point) DivXY

func (p Point) DivXY(x int, y int) Point

func (Point) Length

func (p Point) Length() float64

func (Point) Length2

func (p Point) Length2() int

func (Point) Mul

func (p Point) Mul(value Point) Point

func (Point) MulXY

func (p Point) MulXY(x int, y int) Point

func (Point) String

func (p Point) String() string

func (Point) Sub

func (p Point) Sub(value Point) Point

func (Point) SubXY

func (p Point) SubXY(x int, y int) Point

func (Point) ToVector

func (p Point) ToVector() Vector

type PressState

type PressState int

PressState is how a key, a button or a mouse button is pressed in this tick.

const (
	PressStatePressed PressState = iota
	PressStateReleased
	PressStatePressing
)

type RGB

type RGB struct {
	R, G, B uint8
}

func (RGB) RGBA

func (c RGB) RGBA() (r, g, b, a uint32)

func (RGB) ToNRGBA

func (c RGB) ToNRGBA(alpha uint8) color.NRGBA

func (RGB) ToRGBA

func (c RGB) ToRGBA(alpha uint8) color.RGBA

type Rectangle

type Rectangle struct {
	MinX int
	MinY int
	MaxX int
	MaxY int
}

func NewRectangle

func NewRectangle(minX, minY, maxX, maxY int) *Rectangle

func NewRectangleFromGoRect

func NewRectangleFromGoRect(rect image.Rectangle) *Rectangle

func (*Rectangle) Size

func (r *Rectangle) Size() Point

func (*Rectangle) TopLeft

func (r *Rectangle) TopLeft() Point

type RectangleF

type RectangleF struct {
	MinX float64
	MinY float64
	MaxX float64
	MaxY float64
}

func NewRectangleF

func NewRectangleF(minX, minY, maxX, maxY float64) *RectangleF

func NewRectangleFFromGoRect

func NewRectangleFFromGoRect(rect image.Rectangle) *RectangleF

func (*RectangleF) CenterLocation

func (r *RectangleF) CenterLocation() Vector

func (*RectangleF) IntersectFromCircle

func (r *RectangleF) IntersectFromCircle(src *CircleF) (result bool, normal *Vector)

func (*RectangleF) IntersectFromRectangle

func (r *RectangleF) IntersectFromRectangle(src *RectangleF) (result bool, normal *Vector)

func (*RectangleF) IntersectTo

func (r *RectangleF) IntersectTo(target Bounder) (result bool, normal *Vector)

func (*RectangleF) Offset

func (r *RectangleF) Offset(x, y float64, output Bounder) Bounder

func (*RectangleF) Size

func (r *RectangleF) Size() Vector

func (*RectangleF) ToCircle

func (r *RectangleF) ToCircle() *CircleF

func (*RectangleF) TopLeft

func (r *RectangleF) TopLeft() Vector

type Rectangler

type Rectangler interface {
	Locator
	Sizer
}

type Rotation

type Rotation struct {
	StaticRotation
}

func NewRotation

func NewRotation(value float64) Rotation

func (*Rotation) SetRotation

func (r *Rotation) SetRotation(value float64)

type Rotator

type Rotator interface {
	StaticRotator
	SetRotation(value float64)
}

type Scale

type Scale struct {
	StaticScale
}

func NewScale

func NewScale(value Vector) Scale

func (*Scale) SetScale

func (s *Scale) SetScale(value Vector)

type Scaler

type Scaler interface {
	StaticScaler
	SetScale(value Vector)
}

type Set

type Set[T comparable] map[T]Empty

func (Set[T]) Add

func (s Set[T]) Add(value T)

func (Set[T]) Contains

func (s Set[T]) Contains(value T) bool

func (Set[T]) IntersectRange

func (s Set[T]) IntersectRange(s2 Set[T]) func(yield func(T) bool)

func (Set[T]) Remove

func (s Set[T]) Remove(value T)

func (Set[T]) SubRange

func (s Set[T]) SubRange(s2 Set[T]) func(yield func(T) bool)

func (Set[T]) UnionRange

func (s Set[T]) UnionRange(s2 Set[T]) func(yield func(T) bool)

type Size

type Size struct {
	StaticSize
}

func NewSize

func NewSize(value Vector) Size

func (*Size) SetSize

func (s *Size) SetSize(value Vector)

type Sizer

type Sizer interface {
	StaticSizer
	SetSize() Vector
}

type Smap

type Smap[K, V any] struct {
	// contains filtered or unexported fields
}

func NewSmap

func NewSmap[K, V any]() *Smap[K, V]

func (*Smap[K, V]) Clear

func (s *Smap[K, V]) Clear()

func (*Smap[K, V]) Delete

func (s *Smap[K, V]) Delete(key K)

func (*Smap[K, V]) Len

func (s *Smap[K, V]) Len() int

func (*Smap[K, V]) Load

func (s *Smap[K, V]) Load(key K) (value V, ok bool)

func (*Smap[K, V]) Range

func (s *Smap[K, V]) Range() func(yield func(K, V) bool)

func (*Smap[K, V]) Store

func (s *Smap[K, V]) Store(key K, value V)

func (*Smap[K, V]) Swap

func (s *Smap[K, V]) Swap(key K, value V) (previous V, loaded bool)

type StaticLocation

type StaticLocation struct {
	// contains filtered or unexported fields
}

func NewStaticLocation

func NewStaticLocation(value Vector) StaticLocation

func (*StaticLocation) GetLocation

func (l *StaticLocation) GetLocation() Vector

type StaticLocator

type StaticLocator interface {
	GetLocation() Vector
}

type StaticRectangler

type StaticRectangler interface {
	StaticLocator
	StaticSizer
}

type StaticRotation

type StaticRotation struct {
	// contains filtered or unexported fields
}

func NewStaticRotation

func NewStaticRotation(value float64) StaticRotation

func (*StaticRotation) GetRotation

func (r *StaticRotation) GetRotation() float64

type StaticRotator

type StaticRotator interface {
	GetRotation() float64
}

type StaticScale

type StaticScale struct {
	// contains filtered or unexported fields
}

func NewStaticScale

func NewStaticScale(value Vector) StaticScale

func (*StaticScale) GetScale

func (s *StaticScale) GetScale() Vector

type StaticScaler

type StaticScaler interface {
	GetScale() Vector
}

type StaticSize

type StaticSize struct {
	// contains filtered or unexported fields
}

func NewStaticSize

func NewStaticSize(value Vector) StaticSize

func (*StaticSize) GetSize

func (s *StaticSize) GetSize() Vector

type StaticSizer

type StaticSizer interface {
	GetSize() Vector
}

type StaticTransform

type StaticTransform struct {
	StaticLocation
	StaticRotation
	StaticScale
}

func NewStaticTransform

func NewStaticTransform(location Vector, rotation float64, scale Vector) *StaticTransform

type StaticTransformer

type StaticTransformer interface {
	StaticLocator
	StaticRotator
	StaticScaler
}

type Ticker

type Ticker interface {
	Actor
	Tick()
}

Ticker is an actor which updates itself every update.

type TraceResult

type TraceResult[T ColliderComparable] struct {
	InputOffset  Vector
	InputOffsetD float64
	InputOffsetN Vector

	IsHit        bool
	IsFirstHit   bool
	HitCollider  T
	HitNormal    *Vector
	TraceOffset  Vector
	TraceOffsetD int
}

TraceResult is the result of moving a bounds by an offset through the colliders.

InputOffset is the requested movement, and TraceOffset is how far the bounds could move before it hit something. IsFirstHit means the bounds was already hitting a collider before it moved.

func NewTraceResult

func NewTraceResult[T ColliderComparable](offset Vector) *TraceResult[T]

func Trace

func Trace[T ColliderComparable](colliders []T, target Bounder, offset Vector, excepts Set[T]) *TraceResult[T]

type Transform

type Transform struct {
	Location
	Rotation
	Scale
}

func NewTransform

func NewTransform(location Vector, rotation float64, scale Vector) *Transform

type Transformer

type Transformer interface {
	Locator
	Rotator
	Scaler
}

type Vector

type Vector struct {
	X float64
	Y float64
}

func ClampLocation

func ClampLocation(location Vector) Vector

ClampLocation returns the location wrapped into the screen when the current level is looping, so that an actor leaving an edge comes back from the opposite edge. It returns the location as it is in a level which is not looping.

func DefaultScale

func DefaultScale() Vector

func DefaultScalePtr

func DefaultScalePtr() *Vector

func DownVector

func DownVector() Vector

func DownVectorPtr

func DownVectorPtr() *Vector

func Intersect

func Intersect[T ColliderComparable](colliders []T, target Bounder, excepts Set[T]) (result bool, collider T, normal *Vector)

func IntersectAll

func IntersectAll[T ColliderComparable](colliders []T, target Bounder, excepts Set[T]) (result bool, iColliders []T, normal Vector)

func LeftVector

func LeftVector() Vector

func LeftVectorPtr

func LeftVectorPtr() *Vector

func NewVector

func NewVector(x float64, y float64) Vector

func NewVectorFromString

func NewVectorFromString(str string, unit float64) Vector

func NewVectorPtr

func NewVectorPtr(x float64, y float64) *Vector

func RandomVector

func RandomVector() Vector

func RandomVectorPtr

func RandomVectorPtr() *Vector

func RightVector

func RightVector() Vector

func RightVectorPtr

func RightVectorPtr() *Vector

func UpVector

func UpVector() Vector

func UpVectorPtr

func UpVectorPtr() *Vector

func ZeroVector

func ZeroVector() Vector

func ZeroVectorPtr

func ZeroVectorPtr() *Vector

func (Vector) Abs

func (v Vector) Abs() Vector

func (Vector) Add

func (v Vector) Add(value Vector) Vector

func (Vector) AddF

func (v Vector) AddF(value float64) Vector

func (Vector) AddXY

func (v Vector) AddXY(x, y float64) Vector

func (Vector) Clamp

func (v Vector) Clamp(min float64, max float64) Vector

func (Vector) ClampMax

func (v Vector) ClampMax(max float64) Vector

func (Vector) ClampMin

func (v Vector) ClampMin(min float64) Vector

func (Vector) CrossZ

func (v Vector) CrossZ(value Vector) float64

func (Vector) CrossingAngle

func (v Vector) CrossingAngle(value Vector) float64

func (Vector) Decompose

func (v Vector) Decompose() (length float64, normal Vector)

func (Vector) Div

func (v Vector) Div(value Vector) Vector

func (Vector) DivF

func (v Vector) DivF(value float64) Vector

func (Vector) DivXY

func (v Vector) DivXY(x, y float64) Vector

func (Vector) Dot

func (v Vector) Dot(value Vector) float64

func (Vector) IsZero

func (v Vector) IsZero() bool

func (Vector) Length

func (v Vector) Length() float64

func (Vector) Length2

func (v Vector) Length2() float64

func (Vector) Mod

func (v Vector) Mod(value Vector) Vector

func (Vector) ModF

func (v Vector) ModF(value float64) Vector

func (Vector) ModXY

func (v Vector) ModXY(x, y float64) Vector

func (Vector) Mul

func (v Vector) Mul(value Vector) Vector

func (Vector) MulF

func (v Vector) MulF(value float64) Vector

func (Vector) MulXY

func (v Vector) MulXY(x, y float64) Vector

func (Vector) Negate

func (v Vector) Negate() Vector

func (Vector) Normalize

func (v Vector) Normalize() Vector

func (Vector) Reflect

func (v Vector) Reflect(normal Vector, factor float64) Vector

func (Vector) Rotate

func (v Vector) Rotate(angle float64) Vector

func (Vector) String

func (v Vector) String() string

func (Vector) Sub

func (v Vector) Sub(value Vector) Vector

func (Vector) SubF

func (v Vector) SubF(value float64) Vector

func (Vector) SubXY

func (v Vector) SubXY(x, y float64) Vector

func (Vector) Trunc

func (v Vector) Trunc() Point

type Velocitier

type Velocitier interface {
	GetVelocity() Vector
}

type ZSpecifiedDrawer

type ZSpecifiedDrawer interface {
	Drawer
	ZOrder() int
}

ZSpecifiedDrawer is a drawer which is drawn at its own order instead of ZOrderDefault.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL