Description
The SnapToGrid
method in the Vector2
struct is used to adjust the vector's components to align with a specified grid. This is useful for snapping positions to a grid in 2D space, which can be particularly helpful in applications like game development or graphical editing where precision alignment is required.
Usage
To use the SnapToGrid
method, you need to specify the grid size and whether each component (x and y) should be snapped. The method returns a new Vector2
instance with the snapped values.
Parameters:
gridSize
(System.Single): The size of the grid to snap to. This determines the intervals at which the vector components will be aligned.
sx
(System.Boolean): A boolean indicating whether the x component should be snapped to the grid.
sy
(System.Boolean): A boolean indicating whether the y component should be snapped to the grid.
Returns: A new Vector2
instance with the components snapped to the specified grid size.
Example
// Example of using SnapToGrid
Vector2 position = new Vector2(3.7f, 5.2f);
float gridSize = 1.0f;
Vector2 snappedPosition = position.SnapToGrid(gridSize, true, true);
// snappedPosition will be (4.0, 5.0) if both components are snapped to the nearest grid point.