resolv

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2025 License: MIT Imports: 7 Imported by: 0

README

Resolv v0.8.0

pkg.go.dev

What is Resolv?

Resolv is a 2D collision detection and resolution library, specifically created for simpler, arcade-y (non-realistic) video games. Resolv is written in pure Go, but the core concepts are fairly straightforward and could be easily adapted for use with other languages or game development frameworks.

Basically: It allows you to do simple physics easier, without actually doing the physics part - that's still on you and your game's use-case.

Why is it called that?

Because it's like... You know, collision resolution? To resolve a collision? So... That's the name. I juste seem to have misplaced the "e", so I couldn't include it in the name - how odd.

Why did you create Resolv?

Because I was making games in Go and found that existing frameworks tend to omit collision testing and resolution code. Collision testing isn't too hard, but it's done frequently enough, and most games need simple enough physics that it makes sense to make a library to handle collision testing and resolution for simple, "arcade-y" games; if you need realistic physics, you have other options like cp or Box2D.


As an aside, this actually used to be quite different; I decided to rework it a couple of times. This is now the second rework, and should be significantly easier to use and more accurate. (Thanks a lot to everyone who contributed their time to submit PRs and issues!)

It's still not totally complete, but it should be solid enough for usage in the field.

Dependencies?

Resolv has no external dependencies. It requires Go 1.20 or above.

How do I get it?

go get github.com/edwinsyarief/resolv

How do I use it?

There's a couple of ways to use Resolv. One way is to just create Shapes then use functions to check for intersections.

func main() {

    // Create a rectangle at 200, 100 with a width and height of 32x32
    rect := resolv.NewRectangle(200, 100, 32, 32)

    // Create a circle at 200, 120 with a radius of 8
    circle := resolv.NewCircle(200, 120, 8)

    // Check for intersection
    if intersection, ok := rect.Intersection(circle); ok {
        fmt.Println("They're touching! Here's the data:", intersection)
    }

}

You can also get the intersection with Shape.Intersection(other).

However, you'll probably want to check intersection with a larger group of objects, which you can do with Spaces and ShapeFilters. You create a Space, add Shapes to the space, and then call Shape.IntersectionTest() with more advanced settings:


type Game struct {
    Rect *resolv.ConvexPolygon
    Space *resolv.Space
}

func (g *Game) Init() {

    // Create a space that is 640x480 large and that has a cellular size of 16x16. The cell size is mainly used to
    // determine internally how close objects are together to qualify for intersection testing. Generally, this should
    // be the size of the maximum speed of your objects (i.e. objects shouldn't move faster than 1 cell in size each
    // frame).
    g.Space = resolv.NewSpace(640, 480, 16, 16)

    // Create a rectangle at 200, 100 with a width and height of 32x32
    g.Rect = resolv.NewRectangle(200, 100, 32, 32)

    // Create a circle at 200, 120 with a radius of 8
    circle := resolv.NewCircle(200, 120, 8)

    // Add the shapes to allow them to be detected by other Shapes.
    g.Space.Add(rect)
    g.Space.Add(circle)
}

func (g *Game) Update() {

    // Check for intersection and do something for each intersection
    g.Space.Rect.IntersectionTest(resolv.IntersectionTestSettings{
        TestAgainst: rect.SelectTouchingCells(1).FilterShapes(), // Check only shapes that are near the rectangle (within 1 cell's margin)
        OnIntersect: func(set resolv.IntersectionSet, index, max int) bool {
            fmt.Println("There was an intersection with some other object! Here's the data:", set)
            return true
        }
    })

}

You can also do line tests and shape-based line tests, to see if there would be a collision in a given direction - this is more-so useful for movement and space checking.


If you want to see more info, feel free to examine the examples in the examples folder; the platformer example is particularly in-depth when it comes to movement and collision response. You can run them and switch between them just by calling go run . from the examples folder and pressing Q or E to switch between the example worlds.

You can check out the documentation here, as well.

To-do List

  • Rewrite to be significantly easier and simpler
  • Allow for cells that are less than 1 unit large (and so Spaces can have cell sizes of, say, 0.1 units)
  • Custom ebimath.Vector struct for speed, consistency, and to reduce third-party imports
    • Implement Matrices as well for parenting?
  • Intersection MTV works properly for external normals, but not internal normals of a polygon
  • Properly implement moving around inside a circle (?)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LineTest

func LineTest(settings LineTestSettings) bool

LineTest instantly tests a selection of shapes against a ray / line. Note that there is no MTV for these results.

Types

type Bounds

type Bounds struct {
	Min, Max ebimath.Vector
	// contains filtered or unexported fields
}

Bounds represents the minimum and maximum bounds of a Shape.

func (Bounds) Center

func (b Bounds) Center() ebimath.Vector

Center returns the center position of the Bounds.

func (Bounds) Height

func (b Bounds) Height() float64

Height returns the height of the bounds.

func (Bounds) Intersection

func (b Bounds) Intersection(other Bounds) Bounds

Intersection returns the intersection between the two Bounds objects.

func (Bounds) IsEmpty

func (b Bounds) IsEmpty() bool

IsEmpty returns true if the Bounds's minimum and maximum corners are 0.

func (Bounds) IsIntersecting

func (b Bounds) IsIntersecting(other Bounds) bool

IsIntersecting returns if the Bounds is intersecting with the given other Bounds.

func (Bounds) Move

func (b Bounds) Move(x, y float64) Bounds

Move moves the Bounds, such that the center point is offset by {x, y}.

func (*Bounds) MoveVec

func (b *Bounds) MoveVec(vec ebimath.Vector) Bounds

MoveVec moves the Bounds by the vector provided, such that the center point is offset by {x, y}.

func (Bounds) Width

func (b Bounds) Width() float64

Width returns the width of the Bounds.

type Cell

type Cell struct {
	X, Y   int
	Shapes []IShape // The Objects that a Cell contains.
}

Cell is used to contain and organize Object information.

func (*Cell) Contains

func (cell *Cell) Contains(obj IShape) bool

Contains returns whether a Cell contains the specified Object at its position.

func (*Cell) HasTags

func (cell *Cell) HasTags(tags Tags) bool

ContainsTags returns whether a Cell contains an Object that has the specified tag at its position.

func (*Cell) IsOccupied

func (cell *Cell) IsOccupied() bool

IsOccupied returns whether a Cell contains any Objects at all.

type CellSelection

type CellSelection struct {
	StartX, StartY, EndX, EndY int // The start and end position of the Cell in cellular locations.
	// contains filtered or unexported fields
}

CellSelection is a selection of cells. It is primarily used to filter down Shapes.

func (CellSelection) FilterShapes

func (c CellSelection) FilterShapes() ShapeFilter

FilterShapes returns a ShapeFilter of the shapes within the cell selection.

func (CellSelection) ForEach

func (c CellSelection) ForEach(iterationFunction func(shape IShape) bool)

ForEach loops through each shape in the CellSelection.

type Circle

type Circle struct {
	ShapeBase
	// contains filtered or unexported fields
}

Circle represents a circle (naturally), and is essentially a point with a radius.

func NewCircle

func NewCircle(x, y, radius float64) *Circle

NewCircle returns a new Circle, with its center at the X and Y position given, and with the defined radius.

func (*Circle) Bounds

func (c *Circle) Bounds() Bounds

Bounds returns the top-left and bottom-right corners of the Circle.

func (*Circle) Clone

func (c *Circle) Clone() IShape

Clone clones the Circle.

func (*Circle) Intersection

func (c *Circle) Intersection(other IShape) IntersectionSet

Intersection returns an IntersectionSet for the other Shape provided. If no intersection is detected, the IntersectionSet returned is empty.

func (*Circle) Project

func (c *Circle) Project(axis ebimath.Vector) Projection

func (*Circle) Radius

func (c *Circle) Radius() float64

Radius returns the radius of the Circle.

func (*Circle) SetRadius

func (c *Circle) SetRadius(radius float64)

SetRadius sets the radius of the Circle, updating the scale multiplier to reflect this change.

type ConvexPolygon

type ConvexPolygon struct {
	ShapeBase

	Points []ebimath.Vector // Points represents the points constructing the ConvexPolygon.
	Closed bool             // Closed is whether the ConvexPolygon is closed or not; only takes effect if there are more than 2 points.
	// contains filtered or unexported fields
}

ConvexPolygon represents a series of points, connected by lines, constructing a convex shape. The polygon has a position, a scale, a rotation, and may or may not be closed.

func NewConvexPolygon

func NewConvexPolygon(x, y float64, points []float64) *ConvexPolygon

NewConvexPolygon creates a new convex polygon at the position given, from the provided set of X and Y positions of 2D points (or vertices). You don't need to pass any points at this stage, but if you do, you should pass whole pairs. The points should generally be ordered clockwise, from X and Y of the first, to X and Y of the last. For example: NewConvexPolygon(30, 20, 0, 0, 10, 0, 10, 10, 0, 10) would create a 10x10 convex polygon square, with the vertices at {0,0}, {10,0}, {10, 10}, and {0, 10}, with the polygon itself occupying a position of 30, 20. You can also pass the points using ebimath.Vectors with ConvexPolygon.AddPointsVec().

func NewConvexPolygonVec

func NewConvexPolygonVec(position ebimath.Vector, points []ebimath.Vector) *ConvexPolygon

func NewLine

func NewLine(x1, y1, x2, y2 float64) *ConvexPolygon

func NewRectangle

func NewRectangle(x, y, w, h float64) *ConvexPolygon

NewRectangle returns a rectangular ConvexPolygon at the position given with the vertices ordered in clockwise order. The Rectangle's origin will be the center of its shape (as is recommended for collision testing). The {x, y} is the center position of the Rectangle).

func NewRectangleFromCorners

func NewRectangleFromCorners(x1, y1, x2, y2 float64) *ConvexPolygon

NewRectangleFromCorners returns a rectangluar ConvexPolygon properly centered with its corners at the given { x1, y1 } and { x2, y2 } coordinates. The Rectangle's origin will be the center of its shape (as is recommended for collision testing).

func NewRectangleFromTopLeft

func NewRectangleFromTopLeft(x, y, w, h float64) *ConvexPolygon

NewRectangleFromTopLeft returns a rectangular ConvexPolygon at the position given with the vertices ordered in clockwise order. The Rectangle's origin will be the center of its shape (as is recommended for collision testing). Note that the rectangle will be positioned such that x, y is the top-left corner, though the center-point is still in the center of the ConvexPolygon shape.

func (*ConvexPolygon) AddPoints

func (cp *ConvexPolygon) AddPoints(vertexPositions ...float64) error

AddPoints allows you to add points to the ConvexPolygon with a slice or selection of float64s, with each pair indicating an X or Y value for a point / vertex (i.e. AddPoints(0, 1, 2, 3) would add two points - one at {0, 1}, and another at {2, 3}).

func (*ConvexPolygon) AddPointsVec

func (cp *ConvexPolygon) AddPointsVec(points ...ebimath.Vector)

AddPointsVec allows you to add points to the ConvexPolygon with a slice of ebimath.Vectors, each indicating a point / vertex.

func (*ConvexPolygon) Bounds

func (cp *ConvexPolygon) Bounds() Bounds

Bounds returns two ebimath.Vectors, comprising the top-left and bottom-right positions of the bounds of the ConvexPolygon, post-transformation.

func (*ConvexPolygon) Center

func (cp *ConvexPolygon) Center() ebimath.Vector

Center returns the transformed Center of the ConvexPolygon.

func (*ConvexPolygon) Clone

func (cp *ConvexPolygon) Clone() IShape

Clone returns a clone of the ConvexPolygon as an IShape.

func (*ConvexPolygon) FlipH

func (cp *ConvexPolygon) FlipH()

FlipH flips the ConvexPolygon's vertices horizontally, across the polygon's width, according to their initial offset when adding the points.

func (*ConvexPolygon) FlipV

func (cp *ConvexPolygon) FlipV()

FlipV flips the ConvexPolygon's vertices vertically according to their initial offset when adding the points.

func (*ConvexPolygon) Intersection

func (p *ConvexPolygon) Intersection(other IShape) IntersectionSet

Intersection returns an IntersectionSet for the other Shape provided. If no intersection is detected, the IntersectionSet returned is empty.

func (*ConvexPolygon) IsContainedBy

func (cp *ConvexPolygon) IsContainedBy(otherShape IShape) bool

IsContainedBy returns if the ConvexPolygon is wholly contained by the other shape provided. Note that only testing against ConvexPolygons is implemented currently.

func (*ConvexPolygon) Lines

func (cp *ConvexPolygon) Lines() []collidingLine

Lines returns a slice of transformed internalLines composing the ConvexPolygon.

func (*ConvexPolygon) Project

func (cp *ConvexPolygon) Project(axis ebimath.Vector) Projection

Project projects (i.e. flattens) the ConvexPolygon onto the provided axis.

func (*ConvexPolygon) RecenterPoints

func (cp *ConvexPolygon) RecenterPoints()

RecenterPoints recenters the vertices in the polygon, such that they are all equidistant from the center. For example, say you had a polygon with the following three points: {0, 0}, {10, 0}, {0, 16}. After calling cp.RecenterPoints(), the polygon's points would be at {-5, -8}, {5, -8}, {-5, 8}.

func (*ConvexPolygon) ReverseVertexOrder

func (cp *ConvexPolygon) ReverseVertexOrder()

ReverseVertexOrder reverses the vertex ordering of the ConvexPolygon.

func (*ConvexPolygon) Rotate

func (p *ConvexPolygon) Rotate(radians float64)

Rotate is a helper function to rotate a ConvexPolygon by the radians given.

func (*ConvexPolygon) Rotation

func (p *ConvexPolygon) Rotation() float64

Rotation returns the rotation (in radians) of the ConvexPolygon.

func (*ConvexPolygon) SATAxes

func (cp *ConvexPolygon) SATAxes() []ebimath.Vector

SATAxes returns the axes of the ConvexPolygon for SAT intersection testing.

func (*ConvexPolygon) Scale

func (p *ConvexPolygon) Scale() ebimath.Vector

Scale returns the scale multipliers of the ConvexPolygon.

func (*ConvexPolygon) SetRotation

func (p *ConvexPolygon) SetRotation(radians float64)

SetRotation sets the rotation for the ConvexPolygon; note that the rotation goes counter-clockwise from 0 to pi, and then from -pi at 180 down, back to 0. This rotation scheme follows the way math.Atan2() works.

func (*ConvexPolygon) SetScale

func (p *ConvexPolygon) SetScale(x, y float64)

SetScale sets the scale multipliers of the ConvexPolygon.

func (*ConvexPolygon) SetScaleVec

func (p *ConvexPolygon) SetScaleVec(vec ebimath.Vector)

SetScaleVec sets the scale multipliers of the ConvexPolygon using the provided ebimath.Vector.

func (*ConvexPolygon) ShapeLineTest

func (cp *ConvexPolygon) ShapeLineTest(settings ShapeLineTestSettings) bool

ShapeLineTest conducts a line test from each vertex of the ConvexPolygon using the settings passed. By default, lines are cast from each vertex of each leading edge in the ConvexPolygon.

func (*ConvexPolygon) Transformed

func (cp *ConvexPolygon) Transformed() []ebimath.Vector

Transformed returns the ConvexPolygon's points / vertices, transformed according to the ConvexPolygon's position.

type IShape

type IShape interface {
	ID() uint32 // The unique ID of the Shape
	Clone() IShape
	Tags() *Tags

	Position() ebimath.Vector
	SetPosition(x, y float64)
	SetPositionVec(vec ebimath.Vector)

	Move(x, y float64)
	MoveVec(vec ebimath.Vector)

	SetX(float64)
	SetY(float64)

	SelectTouchingCells(margin int) CellSelection

	SetData(data any)
	Data() any

	Space() *Space

	Bounds() Bounds

	IsLeftOf(other IShape) bool
	IsRightOf(other IShape) bool
	IsAbove(other IShape) bool
	IsBelow(other IShape) bool

	IntersectionTest(settings IntersectionTestSettings) bool
	IsIntersecting(other IShape) bool
	Intersection(other IShape) IntersectionSet

	VecTo(other IShape) ebimath.Vector
	DistanceTo(other IShape) float64
	DistanceSquaredTo(other IShape) float64
	// contains filtered or unexported methods
}

IShape represents an interface that all Shapes fulfill.

type Intersection

type Intersection struct {
	Point  ebimath.Vector // The point of contact.
	Normal ebimath.Vector // The normal of the surface contacted.
}

Intersection represents a single point of contact against a line or surface.

type IntersectionSet

type IntersectionSet struct {
	Intersections []Intersection // Slice of points indicating contact between the two Shapes.
	Center        ebimath.Vector // Center of the Contact set; this is the average of all Points contained within all contacts in the IntersectionSet.
	MTV           ebimath.Vector // Minimum Translation ebimath.Vector; this is the ebimath.Vector to move a Shape on to move it to contact with the other, intersecting / contacting Shape.
	OtherShape    IShape         // The other shape involved in the contact.
}

IntersectionSet represents a set of intersections between the calling object and one other intersecting Shape. A Shape's intersection test may iterate through multiple IntersectionSets - one for each pair of intersecting objects.

func (IntersectionSet) BottommostPoint

func (is IntersectionSet) BottommostPoint() ebimath.Vector

BottommostPoint returns the bottom-most point out of the IntersectionSet's Points slice. If the IntersectionSet is empty, this returns a zero ebimath.Vector.

func (IntersectionSet) Distance

func (is IntersectionSet) Distance(alongAxis ebimath.Vector) float64

Distance returns the distance between all of the intersection points when projected against an axis.

func (IntersectionSet) IsEmpty

func (is IntersectionSet) IsEmpty() bool

IsEmpty returns if the IntersectionSet is empty (and so contains no points of iontersection). This should never actually be true.

func (IntersectionSet) LeftmostPoint

func (is IntersectionSet) LeftmostPoint() ebimath.Vector

LeftmostPoint returns the left-most point out of the IntersectionSet's Points slice. If the IntersectionSet is empty, this returns a zero ebimath.Vector.

func (IntersectionSet) RightmostPoint

func (is IntersectionSet) RightmostPoint() ebimath.Vector

RightmostPoint returns the right-most point out of the IntersectionSet's Points slice. If the IntersectionSet is empty, this returns a zero ebimath.Vector.

func (IntersectionSet) TopmostPoint

func (is IntersectionSet) TopmostPoint() ebimath.Vector

TopmostPoint returns the top-most point out of the IntersectionSet's Points slice. I f the IntersectionSet is empty, this returns a zero ebimath.Vector.

type IntersectionTestSettings

type IntersectionTestSettings struct {
	TestAgainst ShapeIterator // The collection of shapes to test against
	// OnIntersect is a callback to be called for each intersection found between the calling Shape and any of the other shapes given in TestAgainst.
	// The callback should be called in order of distance to the testing object.
	// Moving the object can influence whether it intersects with future surrounding objects.
	// set is the intersection set that contains information about the intersection.
	// The boolean the callback returns indicates whether the LineTest function should continue testing or stop at the currently found intersection.
	OnIntersect func(set IntersectionSet) bool
}

IntersectionTestSettings is a struct that contains settings to control intersection tests.

type LineTestSettings

type LineTestSettings struct {
	Start       ebimath.Vector // The start of the line to test shapes against
	End         ebimath.Vector // The end of the line to test chapes against
	TestAgainst ShapeIterator  // The collection of shapes to test against
	// The callback to be called for each intersection between the given line, ranging from start to end, and each shape given in TestAgainst.
	// set is the intersection set that contains information about the intersection, index is the index of the current index
	// and count is the total number of intersections detected from the intersection test.
	// The boolean the callback returns indicates whether the LineTest function should continue testing or stop at the currently found intersection.
	OnIntersect func(set IntersectionSet, index, max int) bool
	// contains filtered or unexported fields
}

LineTestSettings is a struct of settings to be used when performing line tests (the equivalent of 3D hitscan ray tests for 2D)

type Projection

type Projection struct {
	Min, Max float64
}

Projection represents the projection of a shape (usually a ConvexPolygon) onto an axis for intersection testing. Normally, you wouldn't need to get this information, but it could be useful in some circumstances, I'm sure.

func (Projection) IsInside

func (projection Projection) IsInside(other Projection) bool

IsInside returns whether the Projection is wholly inside of the other, provided Projection.

func (Projection) IsOverlapping

func (projection Projection) IsOverlapping(other Projection) bool

IsOverlapping returns whether a Projection is overlapping with the other, provided Projection. Credit to https://www.sevenson.com.au/programming/sat/

func (Projection) Overlap

func (projection Projection) Overlap(other Projection) float64

Overlap returns the amount that a Projection is overlapping with the other, provided Projection. Credit to https://dyn4j.org/2010/01/sat/#sat-nointer

type Set

type Set[E comparable] map[E]struct{}

Set represents a Set of elements.

func (Set[E]) Add

func (s Set[E]) Add(elements ...E)

Add adds the given elements to a set.

func (Set[E]) Clear

func (s Set[E]) Clear()

Clear clears the set.

func (Set[E]) Clone

func (s Set[E]) Clone() Set[E]

Clone clones the Set.

func (Set[E]) Combine

func (s Set[E]) Combine(otherSet Set[E])

Combine combines the given other elements to the set.

func (Set[E]) Contains

func (s Set[E]) Contains(element E) bool

Contains returns if the set contains the given element.

func (Set[E]) ForEach

func (s Set[E]) ForEach(f func(element E) bool)

ForEach runs the provided function for each element in the set.

func (Set[E]) Remove

func (s Set[E]) Remove(elements ...E)

Remove removes the given element from the set.

func (Set[E]) Set

func (s Set[E]) Set(other Set[E])

Set sets the Set to have the same values as in the given other Set.

type ShapeBase

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

ShapeBase implements many of the common methods that Shapes need to implement to fulfill IShape (but not the Shape-specific ones, like rotating for ConvexPolygons or setting the radius for Circles).

func (*ShapeBase) Data

func (s *ShapeBase) Data() any

Data returns any auxiliary data set on the shape.

func (*ShapeBase) DistanceSquaredTo

func (s *ShapeBase) DistanceSquaredTo(other IShape) float64

DistanceSquaredTo returns the squared distance from the given shape's center to the other Shape.

func (*ShapeBase) DistanceTo

func (s *ShapeBase) DistanceTo(other IShape) float64

DistanceSquaredTo returns the distance from the given shape's center to the other Shape.

func (*ShapeBase) ID

func (s *ShapeBase) ID() uint32

ID returns the unique ID of the Shape.

func (*ShapeBase) IntersectionTest

func (s *ShapeBase) IntersectionTest(settings IntersectionTestSettings) bool

IntersectionTest tests to see if the calling shape intersects with shapes specified in the given settings struct, checked in order of distance to the calling shape's center point. Internally, the function checks to see what Shapes are nearby, and tests against them in order of distance. If the testing Shape moves, then that will influence the result of testing future Shapes in the current game frame. If the test succeeds in finding at least one intersection, it returns true.

func (*ShapeBase) IsAbove

func (s *ShapeBase) IsAbove(other IShape) bool

IsAbove returns true if the Shape is above the other shape.

func (*ShapeBase) IsBelow

func (s *ShapeBase) IsBelow(other IShape) bool

IsBelow returns true if the Shape is below the other shape.

func (*ShapeBase) IsIntersecting

func (s *ShapeBase) IsIntersecting(other IShape) bool

IsIntersecting returns if the shape is intersecting with the other given Shape.

func (*ShapeBase) IsLeftOf

func (s *ShapeBase) IsLeftOf(other IShape) bool

IsLeftOf returns true if the Shape is to the left of the other shape.

func (*ShapeBase) IsRightOf

func (s *ShapeBase) IsRightOf(other IShape) bool

IsRightOf returns true if the Shape is to the right of the other shape.

func (*ShapeBase) Move

func (s *ShapeBase) Move(x, y float64)

Move translates the Shape by the designated X and Y values.

func (*ShapeBase) MoveVec

func (s *ShapeBase) MoveVec(vec ebimath.Vector)

MoveVec translates the ShapeBase by the designated ebimath.Vector.

func (*ShapeBase) Position

func (s *ShapeBase) Position() ebimath.Vector

Position() returns the X and Y position of the ShapeBase.

func (*ShapeBase) SelectTouchingCells

func (s *ShapeBase) SelectTouchingCells(margin int) CellSelection

SelectTouchingCells returns a CellSelection of the cells in the Space that the Shape is touching. margin sets the cellular margin - the higher the margin, the further away candidate Shapes can be to be considered for collision. A margin of 1 is a good default. To help visualize which cells contain Shapes, it would be good to implement some kind of debug drawing in your game, like can be seen in resolv's examples.

func (*ShapeBase) SetData

func (s *ShapeBase) SetData(data any)

SetData sets any auxiliary data on the shape.

func (*ShapeBase) SetPosition

func (s *ShapeBase) SetPosition(x, y float64)

SetPosition sets the center position of the ShapeBase using the X and Y values given.

func (*ShapeBase) SetPositionVec

func (c *ShapeBase) SetPositionVec(vec ebimath.Vector)

SetPosition sets the center position of the ShapeBase using the ebimath.Vector given.

func (*ShapeBase) SetX

func (c *ShapeBase) SetX(x float64)

SetX sets the X position of the Shape.

func (*ShapeBase) SetY

func (c *ShapeBase) SetY(y float64)

SetY sets the Y position of the Shape.

func (*ShapeBase) Space

func (s *ShapeBase) Space() *Space

func (*ShapeBase) Tags

func (s *ShapeBase) Tags() *Tags

Tags returns the tags applied to the shape.

func (*ShapeBase) VecTo

func (s *ShapeBase) VecTo(other IShape) ebimath.Vector

VecTo returns a ebimath.Vector from the given shape to the other Shape.

type ShapeCollection

type ShapeCollection []IShape

ShapeCollection is a slice of Shapes.

func (ShapeCollection) First

func (s ShapeCollection) First() IShape

First returns the first shape in the ShapeCollection.

func (ShapeCollection) ForEach

func (s ShapeCollection) ForEach(forEachFunc func(shape IShape) bool)

ForEach allows you to iterate through each shape in the ShapeCollection; if the function returns false, the iteration ends.

func (ShapeCollection) Last

func (s ShapeCollection) Last() IShape

Last returns the last shape in the ShapeCollection.

func (ShapeCollection) SetTags

func (s ShapeCollection) SetTags(tags Tags)

SetTags sets the tag(s) on all Shapes present in the Shapecollection.

func (ShapeCollection) SortByDistance

func (s ShapeCollection) SortByDistance(point ebimath.Vector)

SortByDistance sorts the ShapeCollection by distance to the given point.

func (ShapeCollection) UnsetTags

func (s ShapeCollection) UnsetTags(tags Tags)

UnsetTags unsets the tag(s) on all Shapes present in the Shapecollection.

type ShapeFilter

type ShapeFilter struct {
	Filters []func(s IShape) bool
	// contains filtered or unexported fields
}

ShapeFilter is a selection of Shapes, primarily used to filter them out to select only some (i.e. Shapes with specific tags or placement). Usually one would use a ShapeFilter to select Shapes that are near a moving Shape (e.g. the player character).

func (ShapeFilter) ByDataType

func (s ShapeFilter) ByDataType(dataType reflect.Type) ShapeFilter

ByDataType allows you to filter Shapes by their Data pointer's type. You could use this to, for example, filter out Shapes that have Data objects that are Updatable, where `Updatable` is an interface that has an `Update()` function call. To do this, you would call `s.ByDataType(reflect.TypeFor[Updatable]())`

func (ShapeFilter) ByDistance

func (s ShapeFilter) ByDistance(point ebimath.Vector, min, max float64) ShapeFilter

ByDistance adds a filter to the ShapeFilter that filters out Shapes distance to a given point. The shapes have to be at least min and at most max distance from the given point ebimath.Vector. The function returns the ShapeFiler for easy method chaining.

func (ShapeFilter) ByFunc

func (s ShapeFilter) ByFunc(filterFunc func(s IShape) bool) ShapeFilter

ByFunc adds a filter to the ShapeFilter that filters out Shapes using a function if it returns true, the Shape passes the ShapeFilter. The function returns the ShapeFiler for easy method chaining.

func (ShapeFilter) ByTags

func (s ShapeFilter) ByTags(tags Tags) ShapeFilter

ByTags adds a filter to the ShapeFilter that filters out Shapes by tags (so only Shapes that have the specified Tag(s) pass the filter). The function returns the ShapeFiler for easy method chaining.

func (ShapeFilter) Count

func (s ShapeFilter) Count() int

Count returns the number of shapes that pass the filters as a ShapeCollection.

func (ShapeFilter) First

func (s ShapeFilter) First() IShape

First returns the first shape that passes the ShapeFilter.

func (ShapeFilter) ForEach

func (s ShapeFilter) ForEach(forEachFunc func(shape IShape) bool)

ForEach is a function that can run a customizeable function on each Shape contained within the filter. If the shape passes the filters, the forEachFunc will run with the shape as an argument. If the function returns true, the iteration will continue; if it doesn't, the iteration will end.

func (ShapeFilter) Last

func (s ShapeFilter) Last() IShape

Last returns the last shape that passes the ShapeFilter (which means it has to step through all possible options before returning the last one).

func (ShapeFilter) Not

func (s ShapeFilter) Not(shapes ...IShape) ShapeFilter

Not adds a filter to the ShapeFilter that specifcally does not allow specified Shapes in. The function returns the ShapeFiler for easy method chaining.

func (ShapeFilter) NotByTags

func (s ShapeFilter) NotByTags(tags Tags) ShapeFilter

NotByTags adds a filter to the ShapeFilter that filters out Shapes by tags (so only Shapes that DO NOT have the specified Tag(s) pass the filter). The function returns the ShapeFiler for easy method chaining.

func (ShapeFilter) Shapes

func (s ShapeFilter) Shapes() ShapeCollection

Shapes returns all shapes that pass the filters as a ShapeCollection.

type ShapeIterator

type ShapeIterator interface {
	// ForEach is a function that can iterate through a collection of Shapes, controlled by a function's return value.
	// If the function returns true, the iteration continues to the end. If it returns false, the iteration ends.
	ForEach(iterationFunction func(shape IShape) bool)
}

ShapeIterator is an interface that defines a method to iterate through Shapes. Any object that has such a function (e.g. a ShapeFilter or a ShapeCollection (which is essentially just a slice of Shapes)) fulfills the ShapeIterator interface.

type ShapeLineTestSettings

type ShapeLineTestSettings struct {
	StartOffset ebimath.Vector // An offset to use for casting rays from each vertex of the Shape.
	Vector      ebimath.Vector // The direction and distance ebimath.Vector to use for casting the lines.
	TestAgainst ShapeIterator  // The shapes to test against.
	// OnIntersect is the callback to be called for each intersection between a line from the given Shape, ranging from its origin off towards the given ebimath.Vector against each shape given in TestAgainst.
	// set is the intersection set that contains information about the intersection, index is the index of the current intersection out of the max number of intersections,
	// and count is the total number of intersections detected from the intersection test.
	// The boolean the callback returns indicates whether the line test should continue iterating through results or stop at the currently found intersection.
	OnIntersect      func(set IntersectionSet, index, count int) bool
	IncludeAllPoints bool  // Whether to cast lines from all points in the Shape (true), or just points from the leading edges (false, and the default). Only takes effect for ConvexPolygons.
	Lines            []int // Which line indices to cast from. If unset (which is the default), then all vertices from all lines will be used.
}

ShapeLineTestSettings is a struct of settings to be used when performing shape line tests (the equivalent of 3D hitscan ray tests for 2D, but emitted from each vertex of the Shape).

type Space

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

Space represents a collision space. Internally, each Space contains a 2D array of Cells, with each Cell being the same size. Cells contain information on which Shapes occupy those spaces and are used to speed up intersection testing across multiple Shapes that could be in dynamic locations.

func NewSpace

func NewSpace(spaceWidth, spaceHeight, cellWidth, cellHeight int) *Space

NewSpace creates a new Space. spaceWidth and spaceHeight is the width and height of the Space (usually in pixels), which is then populated with cells of size cellWidth by cellHeight. Generally, you want cells to be the size of a "normal object". You want to move Objects at a maximum speed of one cell size per collision check to avoid missing any possible collisions.

func (*Space) Add

func (s *Space) Add(shapes ...IShape)

Add adds the specified Objects to the Space, updating the Space's cells to refer to the Object.

func (*Space) Cell

func (s *Space) Cell(cx, cy int) *Cell

Cell returns the Cell at the given cellular / spatial (not world) X and Y position in the Space. If the X and Y position are out of bounds, Cell() will return nil. This does not flush shape vicinities beforehand.

func (*Space) CellHeight

func (s *Space) CellHeight() int

CellHeight returns the height of each cell in the Space.

func (*Space) CellWidth

func (s *Space) CellWidth() int

CellWidth returns the width of each cell in the Space.

func (*Space) FilterCells

func (s *Space) FilterCells(bounds Bounds) CellSelection

FilterCells selects a selection of cells.

func (*Space) FilterShapes

func (s *Space) FilterShapes() ShapeFilter

FilterShapes returns a ShapeFilter consisting of all shapes present in the Space.

func (*Space) ForEachShape

func (s *Space) ForEachShape(forEach func(shape IShape, index, maxCount int) bool)

ForEachShape iterates through each shape in the Space and runs the provided function on them, passing the Shape, its index in the Space's shapes slice, and the maximum number of shapes in the space. If the function returns false, the iteration ends. If it returns true, it continues.

func (*Space) Height

func (s *Space) Height() int

Height returns the spacial height of the Space grid in world coordinates.

func (*Space) HeightInCells

func (s *Space) HeightInCells() int

HeightInCells returns the height of the Space grid in Cells (so a 320x240 Space with 16x16 cells would have a HeightInCells() of 15).

func (*Space) Remove

func (s *Space) Remove(shapes ...IShape)

Remove removes the specified Shapes from the Space. This should be done whenever a game object (and its Shape) is removed from the game.

func (*Space) RemoveAll

func (s *Space) RemoveAll()

RemoveAll removes all Shapes from the Space (and from its internal Cells).

func (*Space) Resize

func (s *Space) Resize(width, height int)

Resize resizes the internal Cells array.

func (*Space) Shapes

func (s *Space) Shapes() ShapeCollection

Shapes returns a new slice consisting of all of the shapes present in the Space.

func (*Space) Width

func (s *Space) Width() int

Width returns the spacial width of the Space grid in world coordinates.

func (*Space) WidthInCells

func (s *Space) WidthInCells() int

WidthInCells returns the width of the Space grid in Cells (so a 320x240 Space with 16x16 cells would have a WidthInCells() of 20).

type Tags

type Tags uint64

Tags represents one or more bitwise tags contained within a single uint64. You can use a tag to easily identify a type of object (e.g. player, solid, ramp, platform, etc). The maximum number of tags one can define is 64 (to match the uint size).

func NewTag

func NewTag(tagName string) Tags

Creates a new tag with the given human-readable name associated with it. You can also create tags using bitwise representation directly (`const myTag = resolv.Tags << 1`). Be sure to use either method, rather than both; if you do use both, NewTag()'s internal tag index would be mismatched. The maximum number of tags one can define is 64.

func (*Tags) Clear

func (t *Tags) Clear()

Clear clears the Tags object.

func (Tags) Has

func (t Tags) Has(tagValue Tags) bool

Has returns if the Tags object has the tags indicated by tagValue set. Note that you can combine tags using the bitwise operator `|` (e.g. `TagSolidWall | TagPlatform`).

func (Tags) IsEmpty

func (t Tags) IsEmpty() bool

IsEmpty returns if the Tags object has no tags set.

func (*Tags) Set

func (t *Tags) Set(tagValue Tags)

Set sets the tag value indicated to the Tags object. Note that you can combine tags using the bitwise operator `|` (e.g. `TagSolidWall | TagPlatform`).

func (Tags) String

func (t Tags) String() string

String prints out the tags set in the Tags object as a human-readable string.

func (*Tags) Unset

func (t *Tags) Unset(tagValue Tags)

Unset clears the tag value indicated in the Tags object. Note that you can combine tags using the bitwise operator `|` (e.g. `TagSolidWall | TagPlatform`).

Jump to

Keyboard shortcuts

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