Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Grid with snapping objects

Discussion in 'Scripting' started by Vexos, Sep 15, 2015.

  1. Vexos

    Vexos

    Joined:
    Jun 1, 2015
    Posts:
    19
    So, I got a gameobject called "Grid" and I made a spawner which spawns the "Grid" in a grid pattern, im trying to achieve a instantiated object (which follows the mouse) to snap to one of the grids and spawn.

    I cant seem to figure out how to instantiate the objects right and how to make them react to the gridsystem. Any help is appreciated.
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    You can use a raycast to determine where the mouse is pointing. Take the position of the raycast's hit and adjust it properly.
    For the following example i assume your objects always occupy one cell and the cells are 1x1 units, the pivot of your objects are always centered, i.e. (0.5, 0, 0.5).

    Raycast hits P1(2.33, 0, 5.83) and thus you need to place the object at P1'(2.5, 0, 5.5).
    One way to find the final position is float to integer conversion, which results in (2, 0, 5). Place your object at this position with the desired offset (0.5 in this example).

    This is a basic approach and will surely need some adjustments to fit your needs.
     
  3. Vexos

    Vexos

    Joined:
    Jun 1, 2015
    Posts:
    19
    Thank you for clearing this up for me, I will give it a shot.