Description
The SnapToGrid
method in the Vector2
struct is used to adjust the components of a vector to align with a specified grid. This is particularly useful in scenarios where you need to ensure that a vector's position is aligned to a grid, such as in grid-based games or applications.
Usage
To use the SnapToGrid
method, you need to provide the size of the grid and specify whether each component (x and y) should be snapped. The method returns a new Vector2
instance with the snapped values.
gridSize
: A float
representing the size of the grid to snap to.
sx
: A bool
indicating whether the x component should be snapped.
sy
: A bool
indicating whether the y component should be snapped.
Example
// Example usage of SnapToGrid
Vector2 position = new Vector2(3.7f, 4.2f);
float gridSize = 1.0f;
Vector2 snappedPosition = position.SnapToGrid(gridSize, true, true);
// snappedPosition will be (4.0f, 4.0f) if both components are snapped to the nearest grid point.