Skip to content

Instantly share code, notes, and snippets.

@Demkeys
Last active October 24, 2018 11:33
Show Gist options
  • Save Demkeys/a8409824623f4681452361d01aaafcbb to your computer and use it in GitHub Desktop.
Save Demkeys/a8409824623f4681452361d01aaafcbb to your computer and use it in GitHub Desktop.
Simple Grid Snapper script to show how the Grid component can be used to align GameObjects along the cells of a Grid.
/// <summary>
/// - Make sure you have a Grid GameObject (any GameObject with a Grid component attached to it) in the scene.
/// - Attach this script to the GameObject you wanna snap to the Grid. Then drag and drop the Grid
/// GameObject into the AttachedGrid field to create a reference to the Grid component attached to it.
/// - Enter Play Mode, and then every time you hit the Space key, this GameObject will move 1 unit
/// down along the Y axis, while remaining snapped to the Grid.
/// </summary>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class GridSnapper : MonoBehaviour {
public Grid AttachedGrid;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
{
// Calculate the cell position on a Grid that is closest to this GameObjects world position.
Vector3Int TileCellPosition = AttachedGrid.WorldToCell(transform.position);
TileCellPosition.y -= 1; // Move 1 unit down on the Y axis.
// Convert the cell position into a position in World Space.
Vector3 TargetPosition = AttachedGrid.CellToWorld(TileCellPosition);
// Add (AttachedGrid.cellSize.x/2) and (AttachedGrid.cellSize.y/2) on the X and Y axes so
// that the GameObject is centered in the cell, regardless of cell size.
TargetPosition.x += (AttachedGrid.cellSize.x/2);
TargetPosition.y += (AttachedGrid.cellSize.y/2);
// Apply TargetPosition to this GameObject's position.
transform.position = TargetPosition;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment