Description
The SnapToGrid
method in the Vector2
struct is used to adjust the vector's components to the nearest grid points based on a specified grid size. This method allows for snapping the vector's x and/or y components to the nearest multiple of the grid size, which is useful in scenarios like aligning objects to a grid in a 2D space.
Usage
To use the SnapToGrid
method, call it on an instance of Vector2
and provide the grid size along with boolean flags indicating whether to snap the x and/or y components.
Parameters:
gridSize
(System.Single): The size of the grid to snap to. This value determines the spacing between grid lines.
sx
(System.Boolean): A flag indicating whether the x component should be snapped to the grid.
sy
(System.Boolean): A flag indicating whether the y component should be snapped to the grid.
Returns: A new Vector2
instance with the components snapped to the nearest grid points as specified.
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 grid.