Vector2Int SnapToGrid( int gridSize, bool sx, bool sy )

book_4_sparkGenerated
code_blocksInput

Description

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.

Usage

To use the SnapToGrid method, you need to provide the grid size and two boolean values indicating whether to snap the x and y components respectively. The method returns a new Vector2Int instance with the snapped values.

Parameters:

  • gridSize (Int32): The size of the grid to snap to. This value determines the intervals at which the vector components will be snapped.
  • sx (Boolean): A flag indicating whether the x component should be snapped to the grid.
  • sy (Boolean): A flag indicating whether the y component should be snapped to the grid.

Returns: A Vector2Int with its components adjusted to the nearest grid points based on the specified grid size and snapping flags.

Example

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