resolv

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2024 License: MIT Imports: 7 Imported by: 63

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/solarlune/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 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

View Source
var WorldDown = WorldUp.Invert()

WorldDown represents a unit vector in the global direction of WorldDown on the right-handed OpenGL / Tetra3D's coordinate system (+Y).

View Source
var WorldLeft = WorldRight.Invert()

WorldLeft represents a unit vector in the global direction of WorldLeft on the right-handed OpenGL / Tetra3D's coordinate system (-X).

View Source
var WorldRight = NewVector(1, 0)

WorldRight represents a unit vector in the global direction of WorldRight on the right-handed OpenGL / Tetra3D's coordinate system (+X).

View Source
var WorldUp = NewVector(0, 1)

WorldUp represents a unit vector in the global direction of WorldUp on the right-handed OpenGL / Tetra3D's coordinate system (+Y).

Functions

func LineTest added in v0.8.0

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.

func ToDegrees added in v0.6.0

func ToDegrees(radians float64) float64

ToDegrees is a helper function to easily convert radians to degrees for human readability.

func ToRadians added in v0.6.0

func ToRadians(degrees float64) float64

ToRadians is a helper function to easily convert degrees to radians (which is what the rotation-oriented functions in Tetra3D use).

Types

type Bounds added in v0.8.0

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

Bounds represents the minimum and maximum bounds of a Shape.

func (Bounds) Center added in v0.8.0

func (b Bounds) Center() Vector

Center returns the center position of the Bounds.

func (Bounds) Height added in v0.8.0

func (b Bounds) Height() float64

Height returns the height of the bounds.

func (Bounds) Intersection added in v0.8.0

func (b Bounds) Intersection(other Bounds) Bounds

Intersection returns the intersection between the two Bounds objects.

func (Bounds) IsEmpty added in v0.8.0

func (b Bounds) IsEmpty() bool

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

func (Bounds) IsIntersecting added in v0.8.0

func (b Bounds) IsIntersecting(other Bounds) bool

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

func (Bounds) MaxAxis added in v0.8.1

func (b Bounds) MaxAxis() float64

MaxAxis returns the maximum value out of either the Bounds's width or height.

func (Bounds) MinAxis added in v0.8.1

func (b Bounds) MinAxis() float64

MinAxis returns the minimum value out of either the Bounds's width or height.

func (Bounds) Move added in v0.8.0

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 added in v0.8.0

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

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

func (Bounds) Width added in v0.8.0

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 added in v0.8.0

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 added in v0.8.0

func (cell *Cell) IsOccupied() bool

IsOccupied returns whether a Cell contains any Objects at all.

type CellSelection added in v0.8.0

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 added in v0.8.0

func (c CellSelection) FilterShapes() ShapeFilter

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

func (CellSelection) ForEach added in v0.8.0

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 added in v0.8.0

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

func (*Circle) Radius

func (c *Circle) Radius() float64

Radius returns the radius of the Circle.

func (*Circle) SetRadius added in v0.6.0

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 []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 vectors with ConvexPolygon.AddPointsVec().

func NewConvexPolygonVec added in v0.7.0

func NewConvexPolygonVec(position Vector, points []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 added in v0.8.0

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 added in v0.8.1

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 ...Vector)

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

func (*ConvexPolygon) Bounds

func (cp *ConvexPolygon) Bounds() Bounds

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

func (*ConvexPolygon) Center

func (cp *ConvexPolygon) Center() 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 added in v0.8.0

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 Vector) Projection

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

func (*ConvexPolygon) RecenterPoints added in v0.6.1

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 added in v0.6.0

func (p *ConvexPolygon) Rotate(radians float64)

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

func (*ConvexPolygon) Rotation added in v0.6.0

func (p *ConvexPolygon) Rotation() float64

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

func (*ConvexPolygon) SATAxes

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

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

func (*ConvexPolygon) Scale added in v0.6.0

func (p *ConvexPolygon) Scale() Vector

Scale returns the scale multipliers of the ConvexPolygon.

func (*ConvexPolygon) SetRotation added in v0.6.0

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 added in v0.6.0

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

SetScale sets the scale multipliers of the ConvexPolygon.

func (*ConvexPolygon) SetScaleVec added in v0.7.0

func (p *ConvexPolygon) SetScaleVec(vec Vector)

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

func (*ConvexPolygon) ShapeLineTest added in v0.8.0

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() []Vector

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

type IShape added in v0.6.0

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

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

	Move(x, y float64)
	MoveVec(vec 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) Vector
	DistanceTo(other IShape) float64
	DistanceSquaredTo(other IShape) float64
	// contains filtered or unexported methods
}

IShape represents an interface that all Shapes fulfill.

type Intersection added in v0.8.0

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

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

type IntersectionSet added in v0.8.0

type IntersectionSet struct {
	Intersections []Intersection // Slice of points indicating contact between the two Shapes.
	Center        Vector         // Center of the Contact set; this is the average of all Points contained within all contacts in the IntersectionSet.
	MTV           Vector         // Minimum Translation Vector; this is the 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 added in v0.8.0

func (is IntersectionSet) BottommostPoint() Vector

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

func (IntersectionSet) Distance added in v0.8.0

func (is IntersectionSet) Distance(alongAxis Vector) float64

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

func (IntersectionSet) IsEmpty added in v0.8.0

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 added in v0.8.0

func (is IntersectionSet) LeftmostPoint() Vector

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

func (IntersectionSet) RightmostPoint added in v0.8.0

func (is IntersectionSet) RightmostPoint() Vector

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

func (IntersectionSet) TopmostPoint added in v0.8.0

func (is IntersectionSet) TopmostPoint() Vector

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

type IntersectionTestSettings added in v0.8.0

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 added in v0.8.0

type LineTestSettings struct {
	Start       Vector        // The start of the line to test shapes against
	End         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 ModVector added in v0.7.0

type ModVector struct {
	*Vector
}

ModVector represents a reference to a Vector, made to facilitate easy method-chaining and modifications on that Vector (as you don't need to re-assign the results of a chain of operations to the original variable to "save" the results). Note that a ModVector is not meant to be used to chain methods on a vector to pass directly into a function; you can just use the normal vector functions for that purpose. ModVectors are pointers, which are allocated to the heap. This being the case, they should be slower relative to normal Vectors, so use them only in non-performance-critical parts of your application.

func (ModVector) Add added in v0.7.0

func (ip ModVector) Add(other Vector) ModVector

Add adds the other Vector provided to the ModVector. This function returns the calling ModVector for method chaining.

func (ModVector) AddMagnitude added in v0.8.0

func (ip ModVector) AddMagnitude(mag float64) ModVector

AddMagnitude adds magnitude to the Vector in the direction it's already pointing. This function returns the calling ModVector for method chaining.

func (ModVector) AddX added in v0.8.0

func (ip ModVector) AddX(x float64) ModVector

AddX adds a value to the X axis of the given Vector. This function returns the calling ModVector for method chaining.

func (ModVector) AddY added in v0.8.0

func (ip ModVector) AddY(y float64) ModVector

AddY adds a value to the Y axis of the given Vector. This function returns the calling ModVector for method chaining.

func (ModVector) ClampAngle added in v0.7.0

func (ip ModVector) ClampAngle(baselineVector Vector, maxAngle float64) ModVector

ClampAngle clamps the Vector such that it doesn't exceed the angle specified (in radians). This function returns the calling ModVector for method chaining.

func (ModVector) ClampMagnitude added in v0.7.0

func (ip ModVector) ClampMagnitude(maxMag float64) ModVector

ClampMagnitude clamps the overall magnitude of the Vector to the maximum magnitude specified. This function returns the calling ModVector for method chaining.

func (ModVector) Clone added in v0.7.0

func (ip ModVector) Clone() ModVector

Clone returns a ModVector of a clone of its backing Vector. This function returns the calling ModVector for method chaining.

func (ModVector) Distance added in v0.8.0

func (ip ModVector) Distance(other Vector) float64

Distance returns the distance from the calling ModVector to the other Vector provided.

func (ModVector) DistanceSquared added in v0.8.0

func (ip ModVector) DistanceSquared(other Vector) float64

DistanceSquared returns the distance from the calling ModVector to the other Vector provided.

func (ModVector) Divide added in v0.7.0

func (ip ModVector) Divide(scalar float64) ModVector

Divide divides a Vector by the given scalar (ignoring the W component). This function returns the calling ModVector for method chaining.

func (ModVector) Expand added in v0.7.0

func (ip ModVector) Expand(margin, min float64) ModVector

Expand expands the ModVector by the margin specified, in absolute units, if each component is over the minimum argument. To illustrate: Given a ModVector of {1, 0.1, -0.3}, ModVector.Expand(0.5, 0.2) would give you a ModVector of {1.5, 0.1, -0.8}. This function returns the calling ModVector for method chaining.

func (ModVector) Invert added in v0.7.0

func (ip ModVector) Invert() ModVector

Invert inverts all components of the calling Vector. This function returns the calling ModVector for method chaining.

func (ModVector) Lerp added in v0.7.0

func (ip ModVector) Lerp(other Vector, percentage float64) ModVector

Lerp performs a linear interpolation between the starting Vector and the provided other Vector, to the given percentage (ranging from 0 to 1). This function returns the calling ModVector for method chaining.

func (ModVector) Mult added in v0.7.0

func (ip ModVector) Mult(other Vector) ModVector

Mult performs Hadamard (component-wise) multiplication with the Vector on the other Vector provided. This function returns the calling ModVector for method chaining.

func (ModVector) Perp added in v0.8.0

func (ip ModVector) Perp() ModVector

Perp returns the right-handed perpendicular of the input vector (i.e. the Vector rotated 90 degrees to the right, clockwise). This function returns the calling ModVector for method chaining.

func (ModVector) Reflect added in v0.8.0

func (ip ModVector) Reflect(normal Vector) ModVector

Reflect reflects the vector against the given surface normal. This function returns the calling ModVector for method chaining.

func (ModVector) Rotate added in v0.7.0

func (ip ModVector) Rotate(angle float64) ModVector

Rotate rotates the calling Vector by the angle provided (in radians). This function returns the calling ModVector for method chaining.

func (ModVector) Round added in v0.7.0

func (ip ModVector) Round(snapToUnits float64) ModVector

Round snaps the Vector's components to the given space in world units, returning a clone (e.g. Vector{0.1, 1.27, 3.33}.Snap(0.25) will return Vector{0, 1.25, 3.25}). This function returns the calling ModVector for method chaining.

func (ModVector) Scale added in v0.7.0

func (ip ModVector) Scale(scalar float64) ModVector

Scale scales the Vector by the scalar provided. This function returns the calling ModVector for method chaining.

func (ModVector) SetX added in v0.8.0

func (ip ModVector) SetX(x float64) ModVector

SetX sets a value to the X axis of the given Vector. This function returns the calling ModVector for method chaining.

func (ModVector) SetY added in v0.8.0

func (ip ModVector) SetY(y float64) ModVector

SetY sets a value to the Y axis of the given Vector. This function returns the calling ModVector for method chaining.

func (ModVector) SetZero added in v0.7.0

func (ip ModVector) SetZero() ModVector

func (ModVector) Slerp added in v0.7.0

func (ip ModVector) Slerp(targetDirection Vector, percentage float64) ModVector

Slerp performs a linear interpolation between the starting Vector and the provided other Vector, to the given percentage (ranging from 0 to 1). This function returns the calling ModVector for method chaining.

func (ModVector) String added in v0.7.0

func (ip ModVector) String() string

String converts the ModVector to a string. Because it's a ModVector, it's represented with a *.

func (ModVector) Sub added in v0.7.0

func (ip ModVector) Sub(other Vector) ModVector

Sub subtracts the other Vector from the calling ModVector. This function returns the calling ModVector for method chaining.

func (ModVector) SubMagnitude added in v0.7.0

func (ip ModVector) SubMagnitude(mag float64) ModVector

SubMagnitude subtacts the given magnitude from the Vector's. If the vector's magnitude is less than the given magnitude to subtract, a zero-length Vector will be returned. This function returns the calling ModVector for method chaining.

func (ModVector) SubX added in v0.8.0

func (ip ModVector) SubX(x float64) ModVector

SubX subtracts a value from the X axis of the given Vector. This function returns the calling ModVector for method chaining.

func (ModVector) SubY added in v0.8.0

func (ip ModVector) SubY(y float64) ModVector

SubY subtracts a value from the Y axis of the given Vector. This function returns the calling ModVector for method chaining.

func (ModVector) ToVector added in v0.7.0

func (ip ModVector) ToVector() Vector

func (ModVector) Unit added in v0.7.0

func (ip ModVector) Unit() ModVector

Unit normalizes the ModVector (sets it to be of unit length). It does not alter the W component of the Vector. This function returns the calling ModVector for method chaining.

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 added in v0.8.0

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 added in v0.8.0

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

Set represents a Set of elements.

func (Set[E]) Add added in v0.8.0

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

Add adds the given elements to a set.

func (Set[E]) Clear added in v0.8.0

func (s Set[E]) Clear()

Clear clears the set.

func (Set[E]) Clone added in v0.8.0

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

Clone clones the Set.

func (Set[E]) Combine added in v0.8.0

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

Combine combines the given other elements to the set.

func (Set[E]) Contains added in v0.8.0

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

Contains returns if the set contains the given element.

func (Set[E]) ForEach added in v0.8.0

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 added in v0.8.0

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

Remove removes the given element from the set.

func (Set[E]) Set added in v0.8.0

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 added in v0.8.0

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 added in v0.8.0

func (s *ShapeBase) Data() any

Data returns any auxiliary data set on the shape.

func (*ShapeBase) DistanceSquaredTo added in v0.8.0

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 added in v0.8.0

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

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

func (*ShapeBase) ID added in v0.8.0

func (s *ShapeBase) ID() uint32

ID returns the unique ID of the Shape.

func (*ShapeBase) IntersectionTest added in v0.8.0

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 added in v0.8.0

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

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

func (*ShapeBase) IsBelow added in v0.8.0

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

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

func (*ShapeBase) IsIntersecting added in v0.8.0

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

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

func (*ShapeBase) IsLeftOf added in v0.8.0

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

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

func (*ShapeBase) IsRightOf added in v0.8.0

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

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

func (*ShapeBase) Move added in v0.8.0

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

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

func (*ShapeBase) MoveVec added in v0.8.0

func (s *ShapeBase) MoveVec(vec Vector)

MoveVec translates the ShapeBase by the designated Vector.

func (*ShapeBase) Position added in v0.8.0

func (s *ShapeBase) Position() Vector

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

func (*ShapeBase) SelectTouchingCells added in v0.8.0

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 added in v0.8.0

func (s *ShapeBase) SetData(data any)

SetData sets any auxiliary data on the shape.

func (*ShapeBase) SetPosition added in v0.8.0

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 added in v0.8.0

func (c *ShapeBase) SetPositionVec(vec Vector)

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

func (*ShapeBase) SetX added in v0.8.0

func (c *ShapeBase) SetX(x float64)

SetX sets the X position of the Shape.

func (*ShapeBase) SetY added in v0.8.0

func (c *ShapeBase) SetY(y float64)

SetY sets the Y position of the Shape.

func (*ShapeBase) Space added in v0.8.0

func (s *ShapeBase) Space() *Space

func (*ShapeBase) Tags added in v0.8.0

func (s *ShapeBase) Tags() *Tags

Tags returns the tags applied to the shape.

func (*ShapeBase) VecTo added in v0.8.0

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

VecTo returns a vector from the given shape to the other Shape.

type ShapeCollection added in v0.8.0

type ShapeCollection []IShape

ShapeCollection is a slice of Shapes.

func (ShapeCollection) First added in v0.8.1

func (s ShapeCollection) First() IShape

First returns the first shape in the ShapeCollection.

func (ShapeCollection) ForEach added in v0.8.0

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 added in v0.8.1

func (s ShapeCollection) Last() IShape

Last returns the last shape in the ShapeCollection.

func (ShapeCollection) SetTags added in v0.8.0

func (s ShapeCollection) SetTags(tags Tags)

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

func (ShapeCollection) SortByDistance added in v0.8.1

func (s ShapeCollection) SortByDistance(point Vector)

SortByDistance sorts the ShapeCollection by distance to the given point.

func (ShapeCollection) UnsetTags added in v0.8.0

func (s ShapeCollection) UnsetTags(tags Tags)

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

type ShapeFilter added in v0.8.0

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 added in v0.8.1

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 added in v0.8.0

func (s ShapeFilter) ByDistance(point 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 Vector. The function returns the ShapeFiler for easy method chaining.

func (ShapeFilter) ByFunc added in v0.8.0

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 added in v0.8.0

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 added in v0.8.1

func (s ShapeFilter) Count() int

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

func (ShapeFilter) First added in v0.8.1

func (s ShapeFilter) First() IShape

First returns the first shape that passes the ShapeFilter.

func (ShapeFilter) ForEach added in v0.8.0

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 added in v0.8.1

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 added in v0.8.0

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 added in v0.8.1

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 added in v0.8.0

func (s ShapeFilter) Shapes() ShapeCollection

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

type ShapeIterator added in v0.8.0

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 added in v0.8.0

type ShapeLineTestSettings struct {
	StartOffset Vector        // An offset to use for casting rays from each vertex of the Shape.
	Vector      Vector        // The direction and distance 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 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 added in v0.8.0

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

FilterCells selects a selection of cells.

func (*Space) FilterShapes added in v0.8.0

func (s *Space) FilterShapes() ShapeFilter

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

func (*Space) ForEachShape added in v0.8.0

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 added in v0.8.1

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 added in v0.8.0

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 added in v0.8.0

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 added in v0.8.1

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 added in v0.8.0

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 added in v0.8.0

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 added in v0.8.0

func (t *Tags) Clear()

Clear clears the Tags object.

func (Tags) Has added in v0.8.0

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 added in v0.8.0

func (t Tags) IsEmpty() bool

IsEmpty returns if the Tags object has no tags set.

func (*Tags) Set added in v0.8.0

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 added in v0.8.0

func (t Tags) String() string

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

func (*Tags) Unset added in v0.8.0

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`).

type Vector added in v0.7.0

type Vector struct {
	X float64 // The X (1st) component of the Vector
	Y float64 // The Y (2nd) component of the Vector
}

Vector represents a 2D Vector, which can be used for usual 2D applications (position, direction, velocity, etc). Any Vector functions that modify the calling Vector return copies of the modified Vector, meaning you can do method-chaining easily. Vectors seem to be most efficient when copied (so try not to store pointers to them if possible, as dereferencing pointers can be more inefficient than directly acting on data, and storing pointers moves variables to heap).

func NewVector added in v0.7.0

func NewVector(x, y float64) Vector

NewVector creates a new Vector with the specified x, y, and z components. The W component is generally ignored for most purposes.

func NewVectorZero added in v0.7.0

func NewVectorZero() Vector

NewVectorZero creates a new "zero-ed out" Vector, with the values of 0, 0, 0, and 0 (for W).

func (Vector) Add added in v0.7.0

func (vec Vector) Add(other Vector) Vector

Add returns a copy of the calling vector, added together with the other Vector provided (ignoring the W component).

func (Vector) AddMagnitude added in v0.8.0

func (vec Vector) AddMagnitude(mag float64) Vector

AddMagnitude adds magnitude to the Vector in the direction it's already pointing.

func (Vector) AddX added in v0.8.0

func (vec Vector) AddX(x float64) Vector

AddX returns a copy of the calling vector with an added value to the X axis.

func (Vector) AddY added in v0.8.0

func (vec Vector) AddY(y float64) Vector

AddY returns a copy of the calling vector with an added value to the Y axis.

func (Vector) Angle added in v0.7.0

func (vec Vector) Angle(other Vector) float64

Angle returns the signed angle in radians between the calling Vector and the provided other Vector (ignoring the W component).

func (Vector) AngleRotation added in v0.7.0

func (vec Vector) AngleRotation() float64

AngleRotation returns the angle in radians between this Vector and world right

func (Vector) ClampAngle added in v0.7.0

func (vec Vector) ClampAngle(baselineVec Vector, maxAngle float64) Vector

ClampAngle clamps the Vector such that it doesn't exceed the angle specified (in radians). This function returns a normalized (unit) Vector.

func (Vector) ClampMagnitude added in v0.7.0

func (vec Vector) ClampMagnitude(maxMag float64) Vector

ClampMagnitude clamps the overall magnitude of the Vector to the maximum magnitude specified, returning a copy with the result.

func (Vector) Distance added in v0.7.0

func (vec Vector) Distance(other Vector) float64

Distance returns the distance from the calling Vector to the other Vector provided.

func (Vector) DistanceSquared added in v0.7.0

func (vec Vector) DistanceSquared(other Vector) float64

Distance returns the squared distance from the calling Vector to the other Vector provided. This is faster than Distance(), as it avoids using math.Sqrt().

func (Vector) Divide added in v0.7.0

func (vec Vector) Divide(scalar float64) Vector

Divide divides a Vector by the given scalar (ignoring the W component), returning a copy with the result.

func (Vector) Dot added in v0.7.0

func (vec Vector) Dot(other Vector) float64

Dot returns the dot product of a Vector and another Vector (ignoring the W component).

func (Vector) Equals added in v0.7.0

func (vec Vector) Equals(other Vector) bool

Equals returns true if the two Vectors are close enough in all values (excluding W).

func (Vector) Expand added in v0.7.0

func (vec Vector) Expand(margin, min float64) Vector

Expand expands the Vector by the margin specified, in absolute units, if each component is over the minimum argument. To illustrate: Given a Vector of {1, 0.1, -0.3}, Vector.Expand(0.5, 0.2) would give you a Vector of {1.5, 0.1, -0.8}. This function returns a copy of the Vector with the result.

func (Vector) Floats added in v0.7.0

func (vec Vector) Floats() [2]float64

Floats returns a [2]float64 array consisting of the Vector's contents.

func (Vector) Invert added in v0.7.0

func (vec Vector) Invert() Vector

Invert returns a copy of the Vector with all components inverted.

func (Vector) IsInside added in v0.8.0

func (vec Vector) IsInside(shape IShape) bool

IsInside returns if the given Vector is inside of the given Shape.

func (Vector) IsZero added in v0.7.0

func (vec Vector) IsZero() bool

IsZero returns true if the values in the Vector are extremely close to 0 (excluding W).

func (Vector) Lerp added in v0.7.0

func (vec Vector) Lerp(other Vector, percentage float64) Vector

Lerp performs a linear interpolation between the starting Vector and the provided other Vector, to the given percentage (ranging from 0 to 1).

func (Vector) Magnitude added in v0.7.0

func (vec Vector) Magnitude() float64

Magnitude returns the length of the Vector.

func (Vector) MagnitudeSquared added in v0.7.0

func (vec Vector) MagnitudeSquared() float64

MagnitudeSquared returns the squared length of the Vector; this is faster than Length() as it avoids using math.Sqrt().

func (*Vector) Modify added in v0.7.0

func (vec *Vector) Modify() ModVector

Modify returns a ModVector object (a pointer to the original vector). Using a ModVector allows you to chain functions without having to reassign it to the original Vector object all of the time.

func (Vector) Mult added in v0.7.0

func (vec Vector) Mult(other Vector) Vector

Mult performs Hadamard (component-wise) multiplication on the calling Vector with the other Vector provided, returning a copy with the result (and ignoring the Vector's W component).

func (Vector) Perp added in v0.8.0

func (vec Vector) Perp() Vector

Perp returns the right-handed perpendicular of the vector (i.e. the vector rotated 90 degrees to the right, clockwise).

func (Vector) Reflect added in v0.8.0

func (vec Vector) Reflect(normal Vector) Vector

Reflect reflects the vector against the given surface normal.

func (Vector) Rotate added in v0.7.0

func (vec Vector) Rotate(angle float64) Vector

Rotate returns a copy of the Vector, rotated around an axis Vector with the x, y, and z components provided, by the angle provided (in radians), counter-clockwise. The function is most efficient if passed an orthogonal, normalized axis (i.e. the X, Y, or Z constants). Note that this function ignores the W component of both Vectors.

func (Vector) Round added in v0.7.0

func (vec Vector) Round(snapToUnits float64) Vector

Round rounds off the Vector's components to the given space in world unit increments, returning a clone (e.g. Vector{0.1, 1.27, 3.33}.Snap(0.25) will return Vector{0, 1.25, 3.25}).

func (Vector) Scale added in v0.7.0

func (vec Vector) Scale(scalar float64) Vector

Scale scales a Vector by the given scalar (ignoring the W component), returning a copy with the result.

func (Vector) Set added in v0.7.0

func (vec Vector) Set(x, y float64) Vector

Set sets the values in the Vector to the x, y, and z values provided.

func (Vector) SetX added in v0.7.0

func (vec Vector) SetX(x float64) Vector

SetX sets the X component in the vector to the value provided.

func (Vector) SetY added in v0.7.0

func (vec Vector) SetY(y float64) Vector

SetY sets the Y component in the vector to the value provided.

func (Vector) Slerp added in v0.7.0

func (vec Vector) Slerp(targetDirection Vector, percentage float64) Vector

Slerp performs a spherical linear interpolation between the starting Vector and the provided ending Vector, to the given percentage (ranging from 0 to 1). This should be done with directions, usually, rather than positions. This being the case, this normalizes both Vectors.

func (Vector) String added in v0.7.0

func (vec Vector) String() string

String returns a string representation of the Vector, excluding its W component (which is primarily used for internal purposes).

func (Vector) Sub added in v0.7.0

func (vec Vector) Sub(other Vector) Vector

Sub returns a copy of the calling Vector, with the other Vector subtracted from it (ignoring the W component).

func (Vector) SubMagnitude added in v0.7.0

func (vec Vector) SubMagnitude(mag float64) Vector

SubMagnitude subtracts the given magnitude from the Vector's existing magnitude. If the vector's magnitude is less than the given magnitude to subtract, a zero-length Vector will be returned.

func (Vector) SubX added in v0.8.0

func (vec Vector) SubX(x float64) Vector

SubX returns a copy of the calling vector with an added value to the X axis.

func (Vector) SubY added in v0.8.0

func (vec Vector) SubY(y float64) Vector

SubY returns a copy of the calling vector with an added value to the Y axis.

func (Vector) Unit added in v0.7.0

func (vec Vector) Unit() Vector

Unit returns a copy of the Vector, normalized (set to be of unit length). It does not alter the W component of the Vector.

Directories

Path Synopsis
examples module

Jump to

Keyboard shortcuts

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