Search Unity

Grid Framework [scripting and editor plugins]

Discussion in 'Assets and Asset Store' started by hiphish, Jul 24, 2012.

  1. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    I don't use Playmaker myself, I only support it because it was in popular demand. The movement with walls example is somewhat tricky to realise using a state machine, you need two steps:
    1. When the game starts you need a globally visible array of tiles and every obstacle registers its tile as occupied. To that end every obstacle converts its world position to grid coordinates, then converts the X- and Y coordinate of that vector to integers and uses those to find its tile in the array.
    2. Every time the player want to move get grid position of the destination and use the above method to find the tile in the array. If the tile is free, then move, otherwise do something else.
    The Playmaker team can help you better with the general stuff; you should first try to set up an array and make an object move along a vector. I don't know how capable Playmaker is, they don't support every type that .NET does, so I have no idea if you can even make an array or convert the coordinates of a vector to integers. Once you have that down the rest is simple: using a grid object use the WorldToGrid action to convert a world position to grid coordinates.
     
  2. Krunchisoft

    Krunchisoft

    Joined:
    Jul 14, 2014
    Posts:
    22
    Ok Then.I'll give it a try.
    Thx man :)
     
  3. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Grid Framework version 1.8.0 released

    Version 1.8.0 of Grid Framework has been approved by the Asset Store team. This release introduces a new rendering shape for hex grid: the circle. Of course, like with polar grids, just because it's called a circle that does not mean you are limited to just circles, you can decide on the start and end "angle" or have a hole in the centre to create a ring.



    The shape can be drawn around any hex, not just the origin. Here is the full changelog:
     
  4. Krunchisoft

    Krunchisoft

    Joined:
    Jul 14, 2014
    Posts:
    22
    Hi again,
    Just upgrade to 1.8. and same like before i still cannot toggle playmaker action so i did the uncomment thing.
    Then this happen :

    Assets/Plugins/Grid Framework/PlayMaker Actions/FsmGFStateActionGetSet.cs(562,30): error CS1061: Type `GFGrid' does not contain a definition for `renderAround' and no extension method `renderAround' of type `GFGrid' could be found (are you missing a using directive or an assembly reference?)
     
  5. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Yes, I'm an idiot who did not double-check. I have already submitted an update and was hoping no one would have noticed by the time it got approved. You can open the script and delete the offending lines for now, that action is for the new hex grid rendering shape, so if you don't want to use it you will not miss anything.
     
  6. Tinimini

    Tinimini

    Joined:
    Mar 3, 2015
    Posts:
    8
    Hi hiphish,
    I've just started fooling around with Unity and one of the first things I did, was purchase your framework. Great job!
    I've been rendering the grid with Vectrosity and I ran into something that I don't quite understand. Namely the points that I get from the grid when calling GetVectrosityPoints. If I get just the points of the first hex (I have a 2 dimensional hex grid, with y = 0) with grid.GetVectrosityPoints(Vector3.zero, Vector3.zero) and it returns 24 points. I was wondering why is that? Shouldn't it only require 6 or 7 points to get one hex drawn?

    I hope this isn't a totally stupid question and I've just overlooked something blatantly obvious :)
     
  7. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Every line needs two points and since they are from different sets they cannot share points, so that's twelve points for six lines. Where are the other twelve points coming from? When you have more than one layer there are lines drawn through the vertices connecting the layers (blue by default). You have six vertices, that's six lines with two points each, so twelve more points. The total is 24 points. You just don't see the connecting lines because their start- and end points are the same.
     
  8. Tinimini

    Tinimini

    Joined:
    Mar 3, 2015
    Posts:
    8
    Ah yes, that's what I figured (now that I played around with it some more). Thanks for the quick answer. I will see if I can figure out a way to draw what I need by calculating the points by hand and not using GetVectrosityLines.
     
  9. Tinimini

    Tinimini

    Joined:
    Mar 3, 2015
    Posts:
    8
    Hmm. Okay, managed to get the lines drawn by calculating the points myself. But why does the lines look all wrong in the editor? They're fine in game view, but in the editor scene view they look all wonky. See screenshots.

    Editor:


    Game View:
     
  10. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    I don't know, how do you compute the line? I have seven vectors, one vector for the centre of the hex and six vectors for the vertices:
    Code (csharp):
    1. Vector3 vertices[] = {
    2.     new Vector3( Mathf.Sqrt(3) * radius / 2.0f,  radius / 2.0f, 0),
    3.     new Vector3( 0                            ,  radius       , 0),
    4.     new Vector3(-Mathf.Sqrt(3) * radius / 2.0f,  radius / 2.0f, 0),
    5.     new Vector3(-Mathf.Sqrt(3) * radius / 2.0f, -radius / 2.0f, 0),
    6.     new Vector3( 0                            , -radius       , 0),
    7.     new Vector3( Mathf.Sqrt(3) * radius / 2.0f, -radius / 2.0f, 0)
    8. };
    9. Vector3 points[] = new Vector3[6];
    10. for (int i = 0; i < 6; ++i) {points[i] = hex + vertices[i];}
     
    Last edited: Mar 12, 2015
  11. Tinimini

    Tinimini

    Joined:
    Mar 3, 2015
    Posts:
    8
    This is the way I have it calculated:
    Code (CSharp):
    1.  
    2. highlightedHex = grid.NearestFaceW(hit.point);
    3. highlightedHexPoints = new Vector3[7] {
    4.   highlightedHex + 0.5f * grid.width * Vector3.right + 0.5f * grid.radius * Vector3.forward,
    5.   highlightedHex + grid.radius * Vector3.forward,
    6.   highlightedHex - 0.5f * grid.width * Vector3.right + 0.5f * grid.radius * Vector3.forward,
    7.   highlightedHex - 0.5f * grid.width * Vector3.right - 0.5f * grid.radius * Vector3.forward,
    8.   highlightedHex - grid.radius * Vector3.forward,
    9.   highlightedHex + 0.5f * grid.width * Vector3.right - 0.5f * grid.radius * Vector3.forward,
    10.   highlightedHex + 0.5f * grid.width * Vector3.right + 0.5f * grid.radius * Vector3.forward
    11. };
    So I use vectors in my calculation, but I will try your way and see if it works better.
     
  12. Tinimini

    Tinimini

    Joined:
    Mar 3, 2015
    Posts:
    8
    Oh, and my plane is on the XZ axis, that's why we're moving forward instead of up & down.
     
  13. Tinimini

    Tinimini

    Joined:
    Mar 3, 2015
    Posts:
    8
    Looks like your code also makes the vectors crooked in the editor. Maybe it's got something to do with the way vectrosity draws them. I need to see if it works better when using GetVectrosityPoints.
     
  14. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Yes, it must be Vectrosity then, there is no way that our codes could produce different vectors. The width and radius of a grid are just float values and the vectors are fixed. GetVectrosityPoints will probably do the same, it's just a wrapper that calls the regular methods for computing the points and then packages them up in a format ready for Vectrosity.
     
  15. Tinimini

    Tinimini

    Joined:
    Mar 3, 2015
    Posts:
    8
    Yup, must be. But as long as things look peachy in the game view, I'm fine with it. Thanks for your help!
     
  16. DragonPrinces

    DragonPrinces

    Joined:
    Jan 19, 2015
    Posts:
    3
    Hello Hiphish

    I Love your GF. it has saved us so much time in our dev.
    I was hoping you could help us out here. Im sorry if this has been asked in this tread already. I couldn't figure out how to search just this thread for something.

    We are developing a bubble shooter game using almost exclusively playmaker as we have very little C# experience.
    I have been trying to figure out how to use the coordinate system for the hex grid with the playmaker actions.
    More specifically i want to be able to identify a gameobject (bubble) grid coordinate and use that coordinate to then determine if that bubble is the lowest bubble on the grid as we want the lowest bubble to be at a specific spacing above the bubble launcher.

    Any advice?

    Thanks
     
  17. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Can you at least read C# code? The Playmaker actions mirror the API exactly, so if you cannot read my API documentation you will have a hard time.

    Getting the grid coordinates of an object requires two steps: first get the world coordinates of your object, then run the WorldToXXX method on the result. XXX stands for the coordinate system you want to use, so for herringbone coordinates it would be Herring.

    Once you have the coordinates you can do the rest of what you want. I don't know what you mean by "lowest on the grid", but I assume you mean the one with the lowest Y-coordinate. In that case you wouldn't even need to convert world- to grid coordinates, you could just do the comparison in world coordinates and save the extra step.
     
  18. Johanna Stephen

    Johanna Stephen

    Joined:
    Feb 18, 2014
    Posts:
    5
    Hi hiPish, i looked your sliding puzzle example. how can i remove bounds rules? everthing linked each other. i simply wanna make drag an object, snap it to grid, and if it intersecting another then object must go first position. how can i do that with your framework? Thank you.
     
  19. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Hi, the sliding puzzle is too complicated for something that simple. You should take a look at the runtime snapping example, it does what you are looking for. Here is the basic idea:
    1. move the object via drag & drop the usual way, don't do any snappings
    2. use Unity's colliders as triggers to find out if two objects are intersecting
    3. if they are return the dragged object to the last snapped position
    4. else run AlignTransform on the object to snap it to the grid
    That's essentially how the example works, most of the code in the script is to implement the drag & drop input.
     
  20. Johanna Stephen

    Johanna Stephen

    Joined:
    Feb 18, 2014
    Posts:
    5
    Wow, thank you hiPish.I will try it.
     
  21. SandJosieph

    SandJosieph

    Joined:
    Feb 17, 2015
    Posts:
    8
    How can I make a grid expand dynamically during runtime? Like if I have two parts for a vehicle and wanted to connect them together how could I make the parent grid expand to incorporate the new part's grid? I tried simply having each part retain its own grid but the game didn't know which parts were connected to which grid. My setup currently has the grid as its own gameObject that gets applied to new parts as they are added to the world.
     
  22. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    I don't really understand your setup. If you want to change the size of a grid, the properties you want to change are the renderFrom and renderTo vectors (default), or the size vector if you don't use a customer rendering range. All of them are regular Vector3 types, so you can treat them at runtime like any Vector3:
    Code (csharp):
    1. GFGrid myGrid;
    2. // expand one unit to the left
    3. myGrid.renderFrom.x -= 1.0f;
    4. // move one unit upwards
    5. myGrid.renderFrom.y += 1.0f; myGrid.renderTo.y += 1.0f;
     
  23. yuewahchan

    yuewahchan

    Joined:
    Jul 2, 2012
    Posts:
    309
    any recommendation for fill color or texture for the grid cell ?
     
  24. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    You can place a mesh in the cell and colour it using a material. In the lights out example that's what I did for the polar grid, all the yellow lights are meshes that got generated at runtime using grid coordinates. When you look at the scene in the editor there is nothing besides the grid. Once you run the scene you will see a number of new objects spawned, those are the light objects, and each one has its own mesh.
     
  25. OlavoXXX

    OlavoXXX

    Joined:
    Mar 17, 2014
    Posts:
    6
    Hi Hiphish, just a simple question: I need a tridimensional grid with objects snaping at runtime, something similar to your Runtime Snapping example but with the ability of Stacking grids on top of each other (Y Axis). One good example of what i need is a 3D tic Tac Toe :

    or


    The question is, can I use your Framework to do this "Out of the Box"? If I duplicate the Grid on your Runtime Snapping Demo will it still work and the pieces would snap to the nearest slot not only in X/Z but also Y axis?
    Thanks
     
  26. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Yes, all grids are three-dimensional, so no need to stack or duplicate any grids, unless you want to. It's just in the examples when I want it to be 2D I simply ignore the third coordinate of every result.

    Rendering is a different thing though. Grid Framework can render lines, but not surfaces. The simple solution is to generate meshes at runtime, two triangles per "layer" to make a square are enough. In the lights-out example I use grid coordinates to generate the meshes of the yellow lights, so it's quite simple.
     
  27. OlavoXXX

    OlavoXXX

    Joined:
    Mar 17, 2014
    Posts:
    6
    Thanks for the quick reply, just one more thing, do I have an option to determine how many "layers" /stacks I want for a particular scene, and also change it at runtime?
    I'm not a programmer but I'm using Playmaker to do my projects so to me C# is very hard. For thsi particular project I'm working on I just need a simple way to switch the number of Y axis Layers/Stacks and also the number of rows/columns in the X/Z axis... If I buy the Framework you can help me with that or there's a way to customize it in the editor or via Playmaker FSM?
    By the way, I don't need the Grid to be rendered.
     
    Last edited: Apr 8, 2015
  28. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    You cannot determine how many layers you have, there are always infinitely many layers because all grids are infinitely large by design. What you can do is limit the range of the values you get. For example if you want to restrict a vector to a 5x5x5 box you would do this:
    Code (csharp):
    1. Vector3 vec, lower = new Vector3(0,0,0), upper = new Vector3(5, 5, 5);
    2. vec = Vector3.Min( upper, Vector3.Max(lower, vec));
    This effectively clamps your vector to always be less or equal to the upper limit and greater or qual than the lower limit. You can replicate this in Playmaker, it's just the two instructions.

    So if you are for example handling user input to position an object you get the position raw, clamp it and then snap it to the grid. Changing the number of "layers" is then just a matter of changing your bounds.
     
  29. OlavoXXX

    OlavoXXX

    Joined:
    Mar 17, 2014
    Posts:
    6
    Alright, thanks! I'll do some testing.
     
  30. Voronoi

    Voronoi

    Joined:
    Jul 2, 2012
    Posts:
    589
    Great Asset! I thought I would share a quick script I wrote up to enable pixel-drawing of level designs. I like how you store the grid as a text file, and plan to do the same. However, it's a pain designing in ASCII, so I thought why not draw the level as pixel art and then translate it to ASCII? This allows for easy reference for moving scripts, checking, etc.

    First, I create a 16 X 32 pixel image: LevelDesign3.png

    Then, using this script attached to a GameObject, I check that colors are 'close to' selected colors in the Editor:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ColorAnalysis : MonoBehaviour
    5. {
    6.  
    7.     public Texture2D m_texture;
    8.     public Color    m_land = Color.grey;
    9.     public Color    m_water = Color.blue;
    10.     public Color    m_road = Color.white;
    11.     public Color    m_grass = Color.green;
    12.  
    13.     void Start ()
    14.     {
    15.    
    16.         Vector3 threshold = new Vector3 (.1f, .1f, .1f);
    17.        
    18.         string output = "";
    19.    
    20.         for (int i = m_texture.height; i >= 0; i--) {                    //Analyse the color, order matters, first match will stop looking
    21.             for (int j = 0; j < m_texture.width; j++) {
    22.                 Color c = m_texture.GetPixel (j, i);
    23.                 if (IsCloseTo (c, m_land, threshold)) {
    24.                     output += "L";
    25.                 } else if (IsCloseTo (c, m_water, threshold)) {
    26.                     output += "W";
    27.                 } else if (IsCloseTo (c, m_road, threshold)) {
    28.                     output += "R";
    29.                 } else if (IsCloseTo (c, m_grass, threshold)) {
    30.                     output += "G";
    31.                 } else {
    32.                     output += "0";
    33.                 }
    34.    
    35.             }
    36.            
    37.             output += "\n";                                                //Output the string as a series of letters
    38.         }
    39.        
    40.         Debug.Log (output);
    41.     }
    42.    
    43.    
    44.     bool IsCloseTo (Color colorToCheck, Color colorToCheckAgainst, Vector3 thresholdAmount)
    45.     {
    46.         Color threshold = new Color (thresholdAmount.x, thresholdAmount.y, thresholdAmount.z);
    47.        
    48.         Color min = colorToCheckAgainst - threshold;
    49.    
    50.         Color max = colorToCheckAgainst + threshold;
    51.        
    52.         bool isRedGood = colorToCheck.r >= min.r && colorToCheck.r <= max.r;
    53.        
    54.         bool isGreenGood = colorToCheck.g >= min.g && colorToCheck.g <= max.g;
    55.        
    56.         bool isBlueGood = colorToCheck.b >= min.b && colorToCheck.b <= max.b;
    57.        
    58.         return isRedGood && isGreenGood && isBlueGood;
    59.     }
    60. }
    61.  
    The output returns a neatly formatted text object that can be used to generate a level design. Final level looks like this:

    LevelDesign3.png Screen Shot 2015-04-12 at 1.26.55 PM.png

    To Do: It would be awesome to allow for a larger image file that loads in 'tiles' as the camera nears the area. Similar to your Endless Grid example. This would allow for a nice large scale world, that uses object pooling to generate visible levels.
     
    Last edited: Apr 12, 2015
  31. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    That's an awesome idea! But if you are already using image files, why do you need a text file? Why not just skip that step and build the level from the image directly?
     
  32. Voronoi

    Voronoi

    Joined:
    Jul 2, 2012
    Posts:
    589
    Well I haven't finished building the level design system, but I wanted to store the results in an easy-to-access way for when a player moves. Basically, keeping track of what kind of thing is in which grid cell. I haven't looked closely at your wall/obstacle script yet, but was thinking that having a text list would be helpful.
     
  33. Lachie9383

    Lachie9383

    Joined:
    Aug 13, 2014
    Posts:
    3
    Hi hiphis, I haven't been able to get the Playmaker actions for your Grid Framework to work because the menu bar item to toggle them on is always greyed out. I've tried do it from a fresh new project as well and still had no luck. Any ideas on what the problem is?
     

    Attached Files:

  34. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    You need PlayMaker to be installed:
    Code (csharp):
    1. [MenuItem("Component/Grid Framework/Toggle Playmaker actions", true, 0)]
    2. public static bool ValidatePlaymakerActions() {
    3.     return System.IO.File.Exists (Application.dataPath + "/PlayMaker/PlayMaker.dll");
    4. }
    This checks to see whether the Playmaker DLL is present under Assets/PlayMaker/PlayMaker.dll. I did it to not confuse users who don't have Playmaker installed.
     
  35. Lachie9383

    Lachie9383

    Joined:
    Aug 13, 2014
    Posts:
    3
    Thanks for the quick reply.

    I do have playmaker installed.
     
  36. Lachie9383

    Lachie9383

    Joined:
    Aug 13, 2014
    Posts:
    3
    Oh I see, its under plugins not assets
     
  37. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Weird, maybe Playmaker changed the location in an update. We can make it both locations work, edit the file Editor/Grid Framework/GFMenuItems.cs, line 125 to read:
    Code (csharp):
    1.  
    2. [MenuItem("Component/Grid Framework/Toggle Playmaker actions", true, 0)]
    3. public static bool ValidatePlaymakerActions() {
    4.     bool exists = false;
    5.     exists |= System.IO.File.Exists (Application.dataPath + "/PlayMaker/PlayMaker.dll");
    6.     exists |= System.IO.File.Exists (Application.dataPath + "/Plugins/PlayMaker/PlayMaker.dll");
    7.     return exists;
    8. }
    Is that the right path?
     
  38. SimStm

    SimStm

    Joined:
    May 24, 2013
    Posts:
    44
    Hi.

    I'm working on a little project (just for study) and I can't find a nice Grid-based system for build things (like a Tycoon/RTS game like Rollercoaster Tycoon, SimCity, Age of Empires, etc). I've already done some scripts to instantiate the objects, not allowing to the player put an object in the same place as another object, but I need a grid-based system to define where the player is allowed to put this buildings in an entirely-flat map (so I will not need to deal with ramps or things like that).

    My question is: Grid Framework is capable of easily help me to manage this building construction thing? Do you have any kind of example demo with something like I said?

    Thanks!
     
  39. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Hi,

    is this example what you are looking for?
    http://hiphish.github.io/grid-framework/examples/snapping/

    I just use Unity's collision detection to find out if objects are intersecting. If you don't want to use collision detection you can have a matrix and register entries as free or occupied. That's what I did in this example:
    http://hiphish.github.io/grid-framework/examples/obstacles/

    All the examples are included, there is an overview of them on this page:
    http://hiphish.github.io/grid-framework/examples/

    Is that what you were looking for?
     
  40. SimStm

    SimStm

    Joined:
    May 24, 2013
    Posts:
    44
    Wow, it's exactly what I'm looking for. And I lost some weeks searching for a nice snapping/grid system script, without success... hahaha

    Just one more question, just curiosity (before I purchase): In the "square grid" from Snapping Demo, can I "paint" the grid squares where the object is (like some tycoon games who paint in red where isn't allowed and green when it's allowed)?
     
  41. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Just to clarify, Grid Framework is a programming library, not an out-of-the-box complete game solution. The goal is to make working with grids as easy as possible, but you still have to decide what you will do with those grids. That means there is no built-in drawing solution, because that would be too project-specific, what works great for you might be completely backwards for someone else.

    With that said, rolling your own painting solution is very easy: cast a ray from the mouse cursor into a collider plane that matches up with the grid. The hit point is where the player is pointing at. You can then use the built-in alignment function to snap that point to the nearest face:
    Code (csharp):
    1. GFGrid myGrid;
    2. Vector3 hitPoint;
    3. Vector3 face = myGrid.NearestFaceW(hitPoint, GridPlane.XY);
    This will return you the world coordinates of where you want to place the tile, so you can "paint" terrain into the level. This approach is used in all the examples that involve click-dragging. There might be other possibilities as well, but that's the most common approach. The nice thing about a framework is that it does not lock you into only a fixed set of solutions.
     
  42. SimStm

    SimStm

    Joined:
    May 24, 2013
    Posts:
    44
    Awesome. I will gonna get that today and read the doc/samples for more info, but what you've said already helped me to know if your asset is what I really need in my project.

    Thanks.
     
  43. SimStm

    SimStm

    Joined:
    May 24, 2013
    Posts:
    44
    Sorry, but I have one more question.

    I've looked at Grid Framework documentation and I haven't found what I need (I got some ideas how deal with it but nothing concrete yet). I have used the Runtime Snapping demo as a base to understand how Rectangle Grid works, and applied some things in my own scene, and everything is working as expected (like in demo example). I even made a "copy" from the original snapping script and modified with my specific needs.

    But like the Runtime Snapping example description says, the object positioning inside the grid's limits is based on where the mouse is pointing at, using raycast, but this allows that "large models" (2x2 models, for example) gets half of them positioned out of the grid limits, and "gets worse" if the model size is 3x3, 4x4, or even 2x3, 3x5, etc.

    I'm still trying some codes to fix that but I still haven't any success. Do you have used or helped someone who've tried to achieve the same effect as I'm trying to?

    2015-05-09_23-03-58.png 2015-05-09_23-02-12.png
     
  44. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    Yes, that is a consequence of the approach used with raycasting. I'll first explain what's happening and then how to solve the problem.

    A raycast needs a collider to hit, which is the collides attached to the plane. If the cast misses no point is reported and in our case nothing happens. The raycast can happen anywhere on the collider, even on the bare edge. In that case the script will position the centre of the box on top of an edge face and you box will hang over the edge. We must clamp the position of the hit point.

    Here is how to solve it: get the bounds of the grid in world coordinates. Add half the box's scale to the bounds. Clamp the hit point inside those bounds.
    Code (csharp):
    1. GFRectGrid grid;
    2. Vector3 hitPoint;
    3. Vector3 boxScale;
    4.  
    5. Vector3 lower = grid.GridToWorld(grid.renderFrom)) + 0.5f * boxScale;
    6. Vector3 upper = grid.GridToWorld(grid.renderTo  )) - 0.5f * boxScale;
    7.  
    8. hitPoint = Vector3.Max(Vector3.Min(hitPoint, upper), lower);
    First we have tightened the legal area for the mouse pointer from the original size of the grid to that size minus half of the object's scale. Then we clamp the hit point to that tightened area. You need to re-tighten the are for every new box the player clicks.
     
  45. Der_Kevin

    Der_Kevin

    Joined:
    Jan 2, 2013
    Posts:
    517
    Hey! I just bought your asset and its pretty cool to work with, i just got a question about the Snapping Units example:
    how would you handle Instantiated cubes/units like in a RTS? because when i drag the SnappingUnits.cs Script on a prefab, I have to select a Grid (GFGrid) put i can not select my ingame grid from a prefab which is not yet placed in the Game World.
     
  46. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    During gameplay some script will be instantiating the units. If that script knows the grid it can assign it to the units immediately after they have been instantiated. I would do it like this: there is a GameObject that carries your unit spawning script, so that object could be the same as the one carrying the grid component. When the game starts the script will find the grid using a simple GetComponent:
    Code (csharp):
    1. // inside the object spawning script
    2. GFGrid grid;
    3. void Awake() {
    4.     grid = GetComponent<GFGrid>();
    5. }
    Now whenever a unit has been spawned add a reference to the grid
    Code (csharp):
    1. // in the spawning routine
    2. GameObject spawnedUnit;
    3. spawnedUnit.GetComponent<SnappingUnits>.grid = grid;
     
    Der_Kevin likes this.
  47. SimStm

    SimStm

    Joined:
    May 24, 2013
    Posts:
    44
    Thanks for the tip hiphish.

    I understand the logic of what you've explained to me, but I just don't get it where to apply the code example you typed. I mean, considering that I'm using the SnappingUnits.cs script (untouched), where do I need to apply this code to get to work?

    Sorry for being a little slow to understand.
    Thanks!
     
  48. hiphish

    hiphish

    Joined:
    Nov 13, 2010
    Posts:
    626
    In the SnappingUnits script there is the function DragObject. Line 76 declares the variable cursorWorldPoint, that's the vector you need to clamp, so you must insert the code below that line. Instead of grid you use the variable _grid and the boxScale is transform.scale.
    Code (csharp):
    1. var cursorWorldPoint = ShootRay();
    2.  
    3. Vector3 lower = _grid.GridToWorld(_grid.renderFrom)) + 0.5f * transform.scale;
    4. Vector3 upper = _grid.GridToWorld(_grid.renderTo  )) - 0.5f * transform.scale;
    5.  
    6. cursorWorldPoint = Vector3.Max(Vector3.Min(cursorWorldPoint, upper), lower)
    If the size of a box and the grid do not change you can compute the values upper and lower when the game starts once and avoid the extra overhead from coordinate conversion during every frame.
     
  49. SimStm

    SimStm

    Joined:
    May 24, 2013
    Posts:
    44
    Awesome! I've looked every single part of the code but missed the DragObject method part, my bad.
    I'll test later to see how it works.

    And yeah, the grid will not change his size but the objects can vary (depending from what object the player will instantiate), so I can define the size when instantiating, to get a better performance.

    Thanks.
     
  50. SimStm

    SimStm

    Joined:
    May 24, 2013
    Posts:
    44
    Well, I've tried to do what you've recommended above but without success. The object positioning now is limited to 1/4 of the grid size, but getting from the center to one of the sides (images attached below).

    I've tried to use this code with some tweaks but doesn't solve the problem yet.

    In the first pic, I show where the object is now limited (ignore the red object, he's just intersecting with another object there)
    In the second pic, we can see that the object still works like before, getting a part of him out of the grid plane.
     

    Attached Files: