Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by snowangel912 · May 02, 2014 at 09:32 AM · gridsnap

Snap object to grid

hi guys.

i've made a grid by creating a plane and set grid texture on it,besides I had a script for drag-and-drop object.

Now, i trying to create a script that when i release the mouse, the object i've been dragging snaps to the line of grid (in the picture shown below, the red is object). Can anyone help me? thanks in advance !

alt text

 //Drag-and-Drop script
 
 using UnityEngine;
 
 using System.Collections;
 
 public class MovePoint2 : MonoBehaviour
 {
     private Vector3 screenPoint;
     private Vector3 offset;
 
     void OnMouseDown() 
     { 
         screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
         
         offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
         
         Screen.showCursor = false;
         

     }
     
     void OnMouseDrag() 
     { 
         Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
         
         Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
         
         transform.position = curPosition;
         
     }
     
     void OnMouseUp()
     {
         Screen.showCursor = true;
     }
 }
Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image GrahamReeves ♦♦ · May 02, 2014 at 11:01 AM 1
Share

The best approach is probably to first work out where on the plane curPosition is;

 Vector3 gridPosition = grid.InverseTransformPoint( transform.position );

Then you can move that x&y to the nearest line. Which should be

 gridPosition.x = $$anonymous$$athf.Floor( gridPosition.x * GridWidth ) / GridWidth;
 gridPosition.y = $$anonymous$$athf.Floor( gridPosition.y * GridHeight ) / GridHeight;

GridWidth and GridHeight are the number of lines you have. If you've done the grid texture by repeating the tiling you could get that straight from the grid's material. Then move it back into world space...

 transform.position = grid.TransformPoint( gridPosition );

There might be a few errors with this, (due to size of plane, center of your dragged object etc), I'll whip up a quick test project :)

avatar image snowangel912 · May 02, 2014 at 11:36 AM 0
Share

thank you :D. But i wonder that i created my grid by texture,not by script,so whether your script works?

avatar image GrahamReeves ♦♦ · May 02, 2014 at 03:46 PM 0
Share

yeah it'll be fine! Just need to fetch the gridwidth/height from your texture. I'll post an answer shortly which will do most of what you need!

1 Reply

· Add your reply
  • Sort: 
avatar image
12
Best Answer

Answer by GrahamReeves · May 02, 2014 at 03:55 PM

Here's a function you just need to call to snap to your grid object. The grid width/height is determined from the material's tiling, (my texture is just an edge, then repeated to make a grid)

Then we manipulate the position relative to the grid (a quad in my case) so it's irrelevant how much it's scaled, and even works when rotated!

alt text

 Vector3 SnapToGrid(Vector3 Position)
     {
         GameObject grid = GameObject.Find ("grid");
         if (! grid)
             return Position;
 
         //    get grid size from the texture tiling
         Vector2 GridSize = grid.renderer.material.mainTextureScale;
 
         //    get position on the quad from -0.5...0.5 (regardless of scale)
         Vector3 gridPosition = grid.transform.InverseTransformPoint( Position );
         //    scale up to a number on the grid, round the number to a whole number, then put back to local size
         gridPosition.x = Mathf.Round( gridPosition.x * GridSize.x ) / GridSize.x;
         gridPosition.y = Mathf.Round( gridPosition.y * GridSize.y ) / GridSize.y;
 
         //    don't go out of bounds
         gridPosition.x = Mathf.Min ( 0.5f, Mathf.Max (-0.5f, gridPosition.x) );
         gridPosition.y = Mathf.Min ( 0.5f, Mathf.Max (-0.5f, gridPosition.y) );
 
         Position = grid.transform.TransformPoint( gridPosition );
         return Position;
     }

Then change OnMouseDrag to include this to snap-as-you-drag

 transform.position = SnapToGrid(curPosition);

or when you let go, in OnMouseUp...

 transform.position = SnapToGrid(transform.position);

My example is just a square, but you just need to change the square so the center is the top of your line, or make a small adjustment to the final Postion = line

Here is the project I made you can play with :)


snaptogrid_rot.gif (230.4 kB)
snaptogrid699158.zip (330.6 kB)
Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image snowangel912 · May 02, 2014 at 04:03 PM 0
Share

you are genius :D. Thank you very much. I regret that i don't have enough 15 reputation to vote for you :D

avatar image GrahamReeves ♦♦ · May 02, 2014 at 05:23 PM 1
Share

no need! please accept the answer if that's everything you need though! :)

avatar image snowangel912 · May 03, 2014 at 12:52 PM 0
Share

@GrahamReeves the problem is, i want object snaps to the line of grid, ins$$anonymous$$d of intersection of lines of grid. Can you help me?

avatar image GrahamReeves ♦♦ · May 06, 2014 at 10:06 AM 0
Share

The snap is the center of the object (this). So what you need to do is adjust Position to accommodate this so that Position is offset by the distance from the center to the top of this (the line).

 // extents is half the size of the bounding box (in world space, so do this AFTER TransformPoint())
 // https://docs.unity3d.com/Documentation/ScriptReference/Bounds.html
 Position.y -= this.renderer.bounds.extents.y;
 return Position;

Obviously this isn't enough if your grid is rotated, but hopefully this is enough for your needs :)

avatar image snowangel912 · May 07, 2014 at 06:58 AM 0
Share

thank you :D. I will add this script to make it work :D

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

22 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Gameobject follow mouse on center 1 Answer

Snap object to grid with offset? 1 Answer

How can I snap to hex tile centers in world x,z coords? 1 Answer

RTS building snap to grid 2 Answers

Snap All Axes Hotkey? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges