Documentation index for AI agents (llms.txt) A Markdown version of every page is available: request the page's source under /docs/, follow the "alternate" link in this page's head, or start from /llms.txt.
Visual Script logo Manual

Snap to Grid#

Math / Snap to Grid

  • Can Read

  • Cannot Write

Description#

Moves a vector to the closest point of an imaginary grid of the specified size

Parameters#

Name Description
Vector The vector that is snapped
Grid Size The distance between two consecutive points of the grid on each axis

Code#

using System;
using UnityEngine;
using VisualScript.Icons;

namespace VisualScript.Runtime
{
    [Get]

    [Title("Snap to Grid")]
    [Category("Math/Snap to Grid")]

    [Description("Moves a vector to the closest point of an imaginary grid of the specified size")]
    [Image(typeof(IconGrid), ColorTheme.Type.Yellow, typeof(Badge2D))]

    [Parameter("Vector", "The vector that is snapped")]
    [Parameter("Grid Size", "The distance between two consecutive points of the grid on each axis")]

    [Keywords("Vector", "Grid", "Cell", "Tile", "Align", "Round", "Step")]

    [Serializable]
    public class TypeVector2MathSnap : TypeVector2
    {
        [SerializeField] private GetVector2 m_Vector = new GetVector2();
        [SerializeField] private GetVector2 m_GridSize = new GetVector2(Vector2.one);

        public override Vector2 GetPreview(GameObject source) => Snap(
            this.m_Vector.GetPreview(source),
            this.m_GridSize.GetPreview(source)
        );

        public override Vector2 Get(Args args) => Snap(this.m_Vector.Get(args), this.m_GridSize.Get(args));

        private static Vector2 Snap(Vector2 vector, Vector2 gridSize)
        {
            return new Vector2(
                Mathf.Approximately(gridSize.x, 0f) ? vector.x : Mathf.Round(vector.x / gridSize.x) * gridSize.x,
                Mathf.Approximately(gridSize.y, 0f) ? vector.y : Mathf.Round(vector.y / gridSize.y) * gridSize.y
            );
        }

        public override string ToString()
        {
            return $"Snap {this.m_Vector} to {this.m_GridSize}";
        }

        protected override SubscriptionMode Subscription => SubscriptionMode.OnChange;
    }
}
Visual Script logoVisual Script © Catsoft Works 2026. All rights reserved.