The SnapToGrid
method in the Vector2Int
struct is used to adjust the vector's components to align with a specified grid size. This method is useful for snapping positions to a grid, which is often required in grid-based games or applications.
The SnapToGrid
method in the Vector2Int
struct is used to adjust the vector's components to align with a specified grid size. This method is useful for snapping positions to a grid, which is often required in grid-based games or applications.
To use the SnapToGrid
method, you need to provide the grid size and specify whether each component (x and y) should be snapped. The method returns a new Vector2Int
instance with the snapped values.
Parameters:
gridSize
(System.Int32): The size of the grid to snap to. This determines the intervals at which the vector components will be adjusted.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 Vector2Int
with the components adjusted to the nearest grid points based on the specified grid size and snapping options.
// Example usage of SnapToGrid method Vector2Int position = new Vector2Int(13, 27); int gridSize = 10; bool snapX = true; bool snapY = true; Vector2Int snappedPosition = position.SnapToGrid(gridSize, snapX, snapY); // snappedPosition will be (10, 30) if both components are snapped to the nearest grid points.