How to Grid Snap Instantiated objects in Game

using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using UnityEngine;
using UnityEngine.UI;

public class JumpSpawn : MonoBehaviour
{
    public GameObject Jump;
    public Button jumpButton;
    private bool canSpawn = false;
    public LayerMask Ground;
    public float spawnRadius = 0.5f;
    public float snapFactor = 1f;
    void Start()
    {
        jumpButton.onClick.AddListener(OnJumpButtonClick);
    }
    public void OnJumpButtonClick()
    {
        canSpawn = true; 
    }
    void Update()
    {
        if (canSpawn && Input.GetMouseButtonDown(0))
        {
            UnityEngine.Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            //RaycastHit2D hit = Physics2D.Raycast(mousePos, UnityEngine.Vector2.zero, Mathf.Infinity, Ground);
            GameObject j = Instantiate(Jump, mousePos, UnityEngine.Quaternion.identity);
            //Instantiate(Jump, mousePos, UnityEngine.Quaternion.identity);
            canSpawn = false;
        }
    }
    UnityEngine.Vector2 SnapPosition2D(UnityEngine.Vector2 input, float factor = 1f)
    {
        if (factor <= 0f)
            throw new UnityException("factor argument must be above 0");

        float x = Mathf.Round(input.x / factor) * factor;
        float y = Mathf.Round(input.y / factor) * factor;

        return new UnityEngine.Vector2(x, y);
    }
}


So whenever I spawn the jump button, I wanted it to automatically snap to grid, I can’t seem to make it work in my code

So where do you actually use the SnapPosition2D method? Or what specifically isn’t working?

Maybe worth pointing out Unity already has a static class with a method with some overloads to snap positions: Unity - Scripting API: Snapping

1 Like

Yeah, it’s not being used, so I tried putting the x and y in the Update instead, Lo and behold, it worked : }

void Update()
    {
        if (canSpawn && Input.GetMouseButtonDown(0))
        {
            UnityEngine.Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.x = Mathf.Round(mousePos.x / snapFactor) * snapFactor;
            mousePos.y = Mathf.Round(mousePos.y / snapFactor) * snapFactor;
            mousePos.z = Mathf.Round(mousePos.z / snapFactor) * snapFactor;
            GameObject j = Instantiate(Jump, mousePos, UnityEngine.Quaternion.identity);
            canSpawn = false;
        }
    }
2 Likes

good i really appricated your work also good