Search Unity

Endless - 2D Terrain Generator

Discussion in 'Assets and Asset Store' started by NeilMeredith, Oct 25, 2013.

  1. ImpossibleRobert

    ImpossibleRobert

    Joined:
    Oct 10, 2013
    Posts:
    531
    Currently the terrain will add random ups or downs. This can lead to e.g. constant upwards movements so that the camera has to adjust vertically. I have a setup where I'd prefer to move the camera only in X direction. This would mean that I somehow need to restrict how high/low a terrain can get. It would be great if terrain generation could be defined as a tunnel around a center line with min/max y amplitude. Could be a new terrain style rule.
     
  2. ImpossibleRobert

    ImpossibleRobert

    Joined:
    Oct 10, 2013
    Posts:
    531
    Currently the min detail height is 1. This is huge in my setup. Is there a reason for this restriction?

    Also, the detail has an adjusted z axis to avoid flickering. While this is good it means that if the camera is in a different angle the gap is visible. Wouldn't it be better to rotate the detail slightly around X instead if translating it? This way the seems would stay intact.
     
  3. ImpossibleRobert

    ImpossibleRobert

    Joined:
    Oct 10, 2013
    Posts:
    531
    It would be great if rules could overwrite the default materials so that segments with different "mood" can be created. A sunny rule with grass followed by a rainy rule for example with swamps followed by a scifi rule on a space ship etc.
     
  4. ImpossibleRobert

    ImpossibleRobert

    Joined:
    Oct 10, 2013
    Posts:
    531
    The comment in TerrainDisplayer.cs Start() states that Initialization should be done, but it is not doing so. I recommend to put in there a call to Update(). This solved some bootstrapping issues I had since I did not have to wait for the first frame to have the terrain generated.
     
  5. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    @10FingerArmy,

    Wow, that's a lot of suggestions! Let me repond to these:

    1. Support programatically moving terrain

    -Due to the way I have the code setup, this would not be a small change. I'd have to adjust all the code generation, scroll the terrain, and also track and update all the prefabs and move the existing ones. This is possible for a future enhancement, but I have no immediate plans to make this change.

    2. Allow selecting the camera

    -Yes, this is a good idea. It is on my list of things to do.

    3. Allow rotating the terrain

    -You can rotate the terrain by adjusting the angle parameter in the terrain rules, but it sounds like you want to rotate the top of the terrain towards the camera. I thought it would be easiest to just rotate the camera since tha way you can make sure your background and everything lines up with the camera properly.

    4. Support boundaries

    -I may be able to create this as a new terrain rule. I'll look into it

    5. Support detail height < 1

    -I just didn't want to get bug reports from people who put in negative heights. If you want to disable the check, comment out line 194 in the TerrainEditor class:
    Code (csharp):
    1.  
    2. if (DetailPlaneHeight.floatValue < 1) { DetailPlaneHeight.floatValue = 1; }
    6. Support different materials per rule

    - I can look into this, but the changes would be pretty abrupt. There would just be a line at which point the materials just changed and no real blending.

    7. Small initialization improvement

    -Sure, you can call that there. I don't think it will cause any issues
     
  6. ImpossibleRobert

    ImpossibleRobert

    Joined:
    Oct 10, 2013
    Posts:
    531
    Didn't want to spam you but give some inspiration for the future! I think your asset has huge potential since it can be reused in all kinds of scenarios. I found several workarounds already for the current limitations. Let me update the points with the newest findings:

    1. I now generate enough terrain preview manually so that I can move it and never have to regenerate. Works!

    2. Nice but with my new setup not that important anymore to me. I was going to blend the terrain in through a second camera before but I hope I will not need it anymore.

    3. Important! The angle currently rotates around z. What should also work is rotation around x. Quick test: adjust the rotation of the terrain around x to -15. Works. Change a parameter. Rotation is reset (still shown as -15 in the inspector but the generated terrain lost the rotation info). This should not happen. I have a workaround in place that re-rotates the terrain at game start but that is ugly and not deterministic. Here it would also be great to have an event thrown (e.g. OnTerrainGenerated) so that the app can react and do additional steps.

    4. Would be great!

    5. If the value should not become negative, why not check for < 0 instead of < 1? This would solve the height issue without any negative consequences.

    6. Single most important request I currently have since no real workaround is possible. I agree we need to come up with a nice way for transitions. How about generating two identical slightly Y-disaligned meshes at the boundaries that overlap for a while and blend their alphas so that gradually the new segments with the new material become visible?

    7. I suggest to include that in your code by default since otherwise the initialization is happening too late (at the first frame and not during start() phase.

    Love this asset and will spread the word. Hope we can get the points above in somehow. I volunteer for beta testing and brain storming if you need someone!
     
  7. ImpossibleRobert

    ImpossibleRobert

    Joined:
    Oct 10, 2013
    Posts:
    531
    Would it be possible to calculate the tangents for the mesh pieces? Currently Unity will complain if the material tries to use bump mapping:

    "Shader wants tangents, but the mesh doesn't have them"

    I have no idea how much effort this is but maybe there is a convenience method which simply needs to be called. This would allow much nicer terrain materials to be displayed.
     
  8. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    I'm glad you found some workarounds for some of the issues you were running into. I don't have much time to work on this during the week (because of my actual job), but I'll take a look at it this weekend and see if I can get through some of these.

    I will definitely send you a beta version of this once I get working on it before I push out these updates.
     
  9. Padonakkk

    Padonakkk

    Joined:
    Nov 10, 2013
    Posts:
    2
    Hi! Where can i find demo of last version of your great asset?
     
  10. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
  11. ImpossibleRobert

    ImpossibleRobert

    Joined:
    Oct 10, 2013
    Posts:
    531
    The demos include a Resources folder. Unity will always package resources folders into the final build. This means the demos will end up in the compiled asset which makes no sense and increases build size. Would be great if the folder name could be changed :)
     
  12. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    Sure, I can change that for the next release.
     
  13. DevMerlin

    DevMerlin

    Joined:
    Dec 21, 2011
    Posts:
    96
    I am loving this system, but I'm having trouble with object rotation. I'm placing buildings, and the rules do NOT keep the default rotation, instead forcing them to a 0,0, Angle. Is there any way to fix this so that objects stay in the rotation that the prefab is set to?
     
  14. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    I'm at work right now so I can't test this out, but the prefabs are actually instantiated in the Add method of the PrefabPool class.

    Code (csharp):
    1.                 GameObject prefab = (GameObject)GameObject.Instantiate(prefabToClone, position, new Quaternion());
    2.                 prefab.name = prefabToClone.name;
    3.                 if (angle != 0  matchGroundAngle){
    4.                      prefab.transform.localEulerAngles = new Vector3(0, 0, angle);
    5.                 }
    You might have to specifically set the rotation of the new prefab to match the rotation of the prefabToClone (the initial prefab). I'll have to look at this some more, but I think that will take care of it for you.
     
  15. Brutus2KK

    Brutus2KK

    Joined:
    Feb 3, 2014
    Posts:
    5
    Hi Neil, thanks for a great tool!

    I have a question for you:

    What would be the best way going about generating a new set of terrain with pre-defined rules and materials per "level". If you use only a gameScene?

    Basically I need the terrain to load different rules and materials on scene initialization based on an int or such. Is this doable today with a edit file or similar?

    Additional Question:

    Is it possible to assign a tag to the mesh collider automatically on creation in code?

    Thanks a bunch
     
    Last edited: Feb 3, 2014
  16. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    Brutus2KK,

    There is no built in way to load different rules and materials on scene initialization, but it shouldn't be too hard for you to do. There is a Setup() method in the TerrainDisplayer class where all rules, prefabs, materials, etc. are set. These are set from what you entered in the editor, but if you wanted to override these settings with something else this would be the place to do it.

    Code (csharp):
    1.  
    2.     public void Setup()
    3.     {
    4.         if (Rules != null)
    5.         {
    6.             Settings s = new Settings();
    7.             s.Rules = Rules;
    8.             s.PrefabRules = PrefabRules;
    9.  
    10.             s.MainMaterial = MainMaterial;
    11.             s.MainMaterialXTiling = MainMaterialXTiling;
    12.             s.MainMaterialYTiling = MainMaterialYTiling;
    13.             s.MainMaterialRotation = MainMaterialRotation;
    14.             //etc...
    15.        }
    16. }
    17.  
    18.  
    19.  
    As far as the MeshCollider, the colliders are setup in the AddCollider method of the MeshPiece class. You should be able to adjust the code to add any tags you need there.
     
  17. awardell

    awardell

    Joined:
    Feb 5, 2014
    Posts:
    71
    I'm having difficulty getting this into my project. I've purchased it from the asset store and downloaded it into the project. When I try following the quickstart guide, the first step is Component->Endless 2D Terrain->Create Terrain, but I don't see Endless 2D Terrain under Component. What might I be doing wrong?

    EDIT: I've added it in fine now by simply finding and dragging in the prefab. Wondering why it doesn't work from the Component panel though.

    New question: Is there a way to change the Layer of the generated mesh?
     
    Last edited: Feb 5, 2014
  18. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    I'm not sure why that wouldn't show up in the menu...maybe try saving the scene, closing and then re-opening Unity?

    All the meshes are grouped under the 'Endless 2D Terrain' game object, so changing the layer of the parent game object should do the trick.

    If that is not what you want, the mesh pieces are generated in the CreateMesh() method of the MeshPiece class, and you could programatically set the layer there.
     
  19. awardell

    awardell

    Joined:
    Feb 5, 2014
    Posts:
    71
    Speedy reply! Thanks! I've saved, closed, and reopened a number of times now and it hasn't shown... Fortunately it isn't blocking me.

    Changing the layer of the "Endless 2D Terrain" object was the first thing I tried. When I check in the running scene though, all of the child objects including the meshes are set to the Default layer. My hunch is it might have something to do with TerrainDisplayer.Cleanup(), but I haven't looked through all of the code much yet.

    After a bit of searching, I've found where I think I want to set the layer manually, and it's actually inside the InstantiateMeshObject() function rather than the CreateMesh() function, because I need a handle on the actual MeshPiece GameObject which is created in the game. Thanks so much for leading me in the right direction though!

    EDIT: So the end of my InstantiateMeshObject() function now has this:
    GameObject rootObj = GameObject.FindGameObjectWithTag("Terrain Generator");
    MeshObject.gameObject.layer = rootObj.layer;
    This works nicely after I set the tag and layer for the generator. I'll probably look into a more efficient way of doing it, but this works for now.
     
    Last edited: Feb 6, 2014
  20. Brutus2KK

    Brutus2KK

    Joined:
    Feb 3, 2014
    Posts:
    5
    Thanks for your previous answer Neil got it working just fine! However I am now having issues with prefab generation as the distance from the top, they are generated with varied hight from the platform depending on current curvature/altidude.

    I want them to always be lets say 100px above the surface regardless of current curvature/height,

    Thanks
    (if double post the damn forum killed it for me).

    Never mind!
    I re-created everything and zeroed out all, and now it works.
     
    Last edited: Feb 6, 2014
  21. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    @awardell and @Brutus2KK,

    Great, glad you both got this working how you needed it to!
     
  22. awardell

    awardell

    Joined:
    Feb 5, 2014
    Posts:
    71
    Is there a way to periodically alternate between terrain generation rules, rather than just going through them once sequentially?
     
  23. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    You can go through the rules sequentially and then start over at the beginning, if that's what you mean, but you can't randomly choose rules without modifying the code.
     
  24. niraj

    niraj

    Joined:
    Feb 14, 2013
    Posts:
    56
    Hello Neil,

    This asset is really awesome, Really. But i would like to achieve one thing that i am unable to do. Actually in your demo scene "KOALA" is generated a bit above of the ground, because ground is generated each time with different ups and down. But what in case i want to make KOALA start from the ground (not falling from above) i.e., KOALA position should be grounded when game starts. What should i do? Please help me.
     
  25. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    I would recommend adding a short beginning terrain rule that is completely flat (so it won't change y position from the random generation) , that way you should know where it will start and can position the koala accordingly.
     
  26. niraj

    niraj

    Joined:
    Feb 14, 2013
    Posts:
    56
    Thank you so much Mr. Neil for lightening response. Yes this will be the solution of my problem.

    Thanks again. Keep Great Work On.
     
  27. DevMerlin

    DevMerlin

    Joined:
    Dec 21, 2011
    Posts:
    96
    Thank you for the reply! I eventually solved it using a script to rotate. I've got a couple of questions for you though. I want to clean up the garbage collection a bit, noticing that it's 'jerking' a little in the editor but fine when played in an actual executable. Also.. I want to add two new rules - Distance to Appear from, and Chance to Appear - for prefabs, in order to randomize things a bit more. How would I go about doing this?
     
  28. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    Teonnyn,

    Sorry for the slow response, I am subscribed to this thread but didn't get an email about your new comment.

    Object management is handled in the PrefabPool and TerrainPool classes. The terrain is just destroyed after leaving the screen, but the prefabs are pooled and reused.

    It is a bit of work to add a new prefab rule. You will have to set the prefab values in the TerrainEditor class (lines 505-514). Ultimately this gets passed along to the PrefabManager class, where you have to define how you want the prefabs to act.
     
  29. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    So many questions...so little time.
    :)
    time for two more?
    Planning another release? if so...ideas when?
    Second...
    Any thoughts about having two endless terrains on the screen at same time?
    (I want to do a sort of flying through tunnels game....)
     
  30. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    CasperJeff,

    I do plan another release at some point in the future, but it will mostly be minor tweaks and fixes, I have no major new features planned, I just have too much else going on right now.

    I have experimented some with multiple endless terrains on the screen at once, but it complicated the code even more and didn't work as smoothly as I hoped, so I currently have no plans to offer this. Thanks for your interest though!
     
  31. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    Thanks for the quick response...
    I just purchased - and so far, does everything smoothly and as advertised!!!!
    yay!!

    Sometimes Unity goes brain-dead and doesn't show your terrain component in the menu - but I blame that on Unity.

    As to the multiple terrains at once (and some other tweaks I am thinking about), your code is very well written and commented...
    I'm pretty sure I can put something together.

    Kudos on a top-notch asset - will make my project go much much smoother!!
     
  32. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    Great, I hope it works out well for you!
     
  33. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    Took me a little time to figure out that most of your classes weren't derived from monobehavior...was stumped trying to figure out what all the ManagerName stuff and instantiation was.....thought it was some odd singleton implementation or something.
    ...now it's getting clearer.

    Weekend goal -
    .Inverted second endless terrain (to provide underground/tunnel effect)
    .ability to allow for flat (but random) areas - to represent man-made areas of my levels

    and then
    .random concave ability (will be tricky with the prefabs) but I want some less accessible nooks and crannies for some baddies.


    great asset!!
     
  34. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    Sounds like a great goal! You can already create flat sections of the terrain by adding a terrain rule with a height of zero. For the rest, sounds like a fun game, good luck!
     
  35. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    Anyone ever see an issue where eventually (not too long - maybe after 3 or 4 terrain generations) prefabs start getting created - but are disabled?
    I have 4 different prefab 'rules' and it appears that all but the first (I think) exhibit this behavior. eventually all prefabs will instantiate and be in the right place - but will be disabled in the scene. Very odd.
    I have not looked closely at the code yet to track this down....
     
  36. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    This happens in the PrefabPool class. A prefab is instantiated if needed, and when it is removed it is kept in the pool but set inactive. It is then reused (and set back to active) where needed.

    I haven't come across the case you are describing in my own testing, but to see if this is causing the issue you could basically disable the pooling. So in the Add method of the PrefabPool class, only leave the case where it is instantiating the prefab. In the Remove method, destroy the prefab instead of re-using it. If that fixes the problem for you, then something in that PrefabPool code is not working correctly for you.
     
  37. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    Yeah...I was just looking at this code...
    I'm going to try to find a stupid simple example to try to track it down further.
    I'm convinced it happens when you have more than one prefab set up....
    Will let you know if I spot anything
     
  38. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    hmmm..simple experiments yielded nothing of interest.

    I'm beginning to think it has something to do with the fact that I destroy my objects instead of just calling Pool.Remove like you do in your coinpickup.cs.
    Also - I have some prefabs that rocket off way in the Y direction...I wonder if possibly X as well (out of view) and it's not being picked up properly by your cleanup() code.

    hmmm....more experimentation.
    I really like your pool concept...so I'm going to try hard to figure out what's the happs...
     
  39. justlivinanotherday

    justlivinanotherday

    Joined:
    Feb 6, 2014
    Posts:
    1
    Hello! I wanted to ask if it was possible to create spikes inside the terrain as it's being generated. My idea is to have a player jump over obstacles, (in this case spikes) and if the player falls on them he dies and the game resets. Can this be done with this asset by simple means?

    Note - I'm not a programmer.

    Thanks!
     
  40. awardell

    awardell

    Joined:
    Feb 5, 2014
    Posts:
    71
    justlivinanotherday, what you want is going to require some knowledge of programming in Unity. This terrain generator can add spikes to your level if you make the spike a prefab and add it to the prefab generation rules. As for the player dying, you're going to need to code that yourself or find another asset in the store that can handle that for you.

    NeilMeredith - I'm a bit curious as to one of the constraints you have in the code for the editor. In TerrainEditor.cs, around line 380 or so, you have this:

    Code (csharp):
    1. //Make sure we have enough verts to make a mesh
    2. if (maximumKeyVertexSpacing.floatValue * 2f > meshLength.floatValue){
    3.         meshLength.floatValue = maximumKeyVertexSpacing.floatValue * 2f;                       
    4. }
    Why the * 2? Wouldn't a rule be able to function fine with only a single key vertex? I'm going to mess with this and see what happens, but I was wondering your thinking.

    EDIT:

    It seems to be fine as long as meshLength > maximumKeyVertexSpacing, but NOT if meshLength == maximumKeyVertexSpacing. Thus it could be:

    Code (csharp):
    1. //Make sure we have enough verts to make a mesh
    2. if (maximumKeyVertexSpacing.floatValue >= meshLength.floatValue){
    3.         meshLength.floatValue = maximumKeyVertexSpacing.floatValue + 1f;                       
    4. }
     
    Last edited: Mar 11, 2014
  41. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    I need to place some prefabs along the terrain that require a wide flat space - (like a building) - so I tweaked the code a bit to allow me to support it.
    Added 3 new variables to TerrainRules
    Code (csharp):
    1.    
    2. public bool FlatPlaces;
    3. public float FlatSpacing;
    4. public float FlatWidth;
    Added changes to TerrainEditor.cs to make them editable (line 242 and then 314
    Code (csharp):
    1.  
    2. SerializedProperty flatPlaces = terrainRule.FindPropertyRelative("FlatPlaces");
    3. SerializedProperty flatWidth = terrainRule.FindPropertyRelative("FlatWidth");
    4. SerializedProperty flatSpacing = terrainRule.FindPropertyRelative("FlatSpacing");
    5.  
    6. EditorGUILayout.PropertyField(flatPlaces, new GUIContent("Flat Places", "Will there be periodic flat places for prefabs"));
    7. if(flatPlaces.boolValue == true){
    8. EditorGUILayout.PropertyField(flatSpacing, new GUIContent("Flat Spacing (# key Vertices)", "Spacing between flat areas - as number of key vertices"));
    9. EditorGUILayout.PropertyField(flatWidth, new GUIContent("Flat Width (# of key vertices", "Width of flat areas - as number of key vertices"));
    10. }
    11.  
    12.  
    and finally some changes to VertexGenerator.cs around line 162 - (stopping just before it gets to the "repeated terrain generation" section.
    Code (csharp):
    1.  
    2.  
    3. //Loop until we've generated enough vertices to reach the desired mesh length (or we hit a new rule)
    4.             bool inFlat = false;
    5.             int flatVerts = 0;
    6.             while (CurrentLocation < endLocation  !MoveToNextTerrainRule())
    7.             {
    8.  
    9.                 float keyVertexStepSize = GetKeyVertexStepSize();
    10.  
    11.                 //Random terrain generation
    12.                 if (CurrentTerrainRule.SelectedTerrainStyle == TerrainRule.TerrainStyle.Random)
    13.                 {
    14.                     float y = GetKeyVertexRandomHeight();
    15.                     if(CurrentTerrainRule.FlatPlaces  !inFlat  verticies.Count > 0  (verticies.Count % CurrentTerrainRule.FlatSpacing==0)){
    16.                             inFlat = true;
    17.                             flatVerts = 0;
    18.                     }
    19.                     if(CurrentTerrainRule.FlatPlaces  inFlat){
    20.                         {
    21.                             y = verticies.Last().y;
    22.                             if(flatVerts >= CurrentTerrainRule.FlatWidth){
    23.                                 flatVerts = 0;
    24.                                 inFlat = false;
    25.                             }
    26.                             flatVerts++;
    27.                         }
    28.                     }
    29.                    
    30.                     float x = CurrentLocation + keyVertexStepSize;
    31.                     verticies.Add(new Vector3(x, y, settings.OriginalStartPoint.z));
    32.                 }
    33.  
    34.  
    $flat1.jpg
     
    Last edited: Mar 12, 2014
  42. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    I needed to have random Y offsets for my prefab creation so I made some changes
    (btw - this asset is SO well commented that it was easy peasy - thanks so much!!!)

    In PrefabRule.cs around line 21, I replaced the Vector3 offset with:
    Code (csharp):
    1.  
    2. public Vector3 MinOffset;
    3. public Vector3 MaxOffset;
    4.  
    then I replaced the InstantiatePrefab function int he same script (around line 49ish)

    Code (csharp):
    1.  
    2. public void InstantiatePrefab(Vector3 position, GameObject prefabManager, PrefabPool pool, float angle)
    3.         {
    4.             var prefab = pool.Add(PrefabToClone, position, angle, PrefabToClone.name, MatchGroundAngle);            
    5.             prefab.transform.parent = prefabManager.transform;
    6.             Vector3 Offset = new Vector3(UnityEngine.Random.Range (MinOffset.x,MaxOffset.x),UnityEngine.Random.Range (MinOffset.y,MaxOffset.y),UnityEngine.Random.Range (MinOffset.z,MaxOffset.z));
    7.             //If we have an offset (and we are placing prefabs at an angle), get the direction of that offset.
    8.             //In otherwords, if our offset says to move one up in the y direction, getting the transform direction means the
    9.             //prefab will move one up relative to the rotation it currently has
    10.             Vector3 transformDirection = prefab.transform.TransformDirection(Offset);
    11.             prefab.transform.position = transformDirection + prefab.transform.position;
    12.         }
    13.  
    14.  
    and finally - some tweaks so they were accessible in the editor

    Line 459 or so in TerrainEditor.cs
    Code (csharp):
    1.  
    2. SerializedProperty minOffset = prefabRule.FindPropertyRelative("MinOffset");
    3. SerializedProperty maxOffset = prefabRule.FindPropertyRelative("MaxOffset");
    4.  
    and
    line 516 or so
    Code (csharp):
    1.  
    2. EditorGUILayout.PropertyField(minOffset, new GUIContent("Min Offset", "The minimum amount the prefab will be offset fron the default placement (random between)."), true);
    3. EditorGUILayout.PropertyField(maxOffset, new GUIContent("Max Offset", "The maximum amount the prefab will be offset fron the default placement (random between)."), true);
    4.  
    $2.jpg $1.jpg
     
  43. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    @justlivinanotherday - Awardell answered your question correctly, the prefab generator can place the prefabs but you would have to script the player death yourself.

    @awardell - The new chunk of code you have looks fine to me, I think I was just trying to prevent invalid values from crashing the terrain generator, but what you have is probably more correct that what was initially there.

    @casperjeff - Way to dig into the code! The updates you made look great!
     
  44. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    I really wanted to use the prefab rule logic for spacing and slope...but wanted a random prefab (from a set of 3 or 4) - so I tweaked the code a bit. This (for me) solves the potential overlap problem (because otherwise I'd need separate prefab rules that could overlap resulting prefabs).
    I have near-zero ability to code Unity editor GUI stuff like our author - so I cobbled something horriffic just so it would show in his custom editor. Anyway - my code is horrific (normally would have used a new class with prefab and % weights and put in array)
    In doing it this way, I broke the ability to see what "prefabs allowed on this rule" - but that was just a little helper display thing.

    I don't dare post the code changes here - but I guess you could PM me if you need help making same change.

    $2.jpg $1.jpg
     
    diegoadrada likes this.
  45. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    Ah shoot - it wasn't just a helper...it actually was a feature to designate WHICH prefabs applied to that terrain rule...
    I was using only one terrain rule so I missed that.
    Grumble...back to drawing board on that one a bit....
     
  46. casperjeff

    casperjeff

    Joined:
    Apr 13, 2013
    Posts:
    333
    I think I finally figured this out -
    It only happened on prefabs where I had to put an empty parent gameobject in order to rotate my actual model properly - because the prefab instantiator here doesn't honor the rotation (sets it to 0/0/0?)
    I had code that was deactivating that child when collision occurred - and the pool manager was only reactivating the parent empty gameobject?
    Does that make sense?
    So this was my bug/lissue (although I did change the instantiate code to honor the original rotation of the prefab) .
    Yay!
     
  47. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    That does make sense, good to know. Thanks for the update!
     
  48. awardell

    awardell

    Joined:
    Feb 5, 2014
    Posts:
    71
    Hey I'm having a weird issue, or maybe I'm not understanding the generator perfectly. The terrain keeps dipping well below the point at which I've set the "Min Terrain Height" for a particular terrain generation rule. This causes issues for me because I have elements in the game which have a y-value that is absolute. Can you help me understand what is going on and what can be done to remedy this?
     
  49. NeilMeredith

    NeilMeredith

    Joined:
    Jul 15, 2013
    Posts:
    81
    The min terrain height is just relative to the last position. So if you vary terrain heights, you can get a relative height, but it is not an absolute setting. Unfortunately, to get it to work that way would require code changes on your part, it is not a configurable option.
     
  50. awardell

    awardell

    Joined:
    Feb 5, 2014
    Posts:
    71
    So I've been trying to fix the situation myself, but it's behaving very strangely. Let me post some code, and maybe you can show me what I'm doing wrong.

    In VertexGenerator.GetKeyVertexRandomHeight:

    Code (csharp):
    1.  
    2. public float GetKeyVertexRandomHeight()
    3.         {
    4.             //STUB: replace these
    5.             bool boolStub = true;
    6.             float minStub = -30f;
    7.             float maxStub = 30f;
    8.            
    9.             float min, max;
    10.             if (boolStub  NextOrigin.y + CurrentTerrainRule.MinimumKeyVertexHeight < minStub)
    11.             {
    12.                 Debug.Log("too low: " + NextOrigin.y + " + " + CurrentTerrainRule.MinimumKeyVertexHeight + " < " + minStub);
    13.                 min = -(NextOrigin.y - minStub);
    14.             }
    15.             else
    16.             {
    17.                 min = CurrentTerrainRule.MinimumKeyVertexHeight;
    18.             }
    19.            
    20.             if (boolStub  NextOrigin.y + CurrentTerrainRule.MaximumKeyVertexHeight > maxStub)
    21.             {
    22.                 Debug.Log("too high: " + NextOrigin.y + " + " + CurrentTerrainRule.MaximumKeyVertexHeight + " > " + maxStub);
    23.                 max = maxStub - NextOrigin.y;
    24.             }
    25.             else
    26.             {
    27.                 max = CurrentTerrainRule.MaximumKeyVertexHeight;
    28.             }
    29.            
    30.             float result = Random.Range(min, max);
    31.             Debug.Log(result + " = Random.Range(" + min + ", " + max + ")");
    32.            
    33.             return result;
    34.         }
    35.  
    NextOrigin is managed in GenerateKeyVertices...
    Code (csharp):
    1.  
    2. //Random terrain generation
    3.                 if (CurrentTerrainRule.SelectedTerrainStyle == TerrainRule.TerrainStyle.Random)
    4.                 {
    5.                     float y = GetKeyVertexRandomHeight();
    6.                     float x = CurrentLocation + keyVertexStepSize;
    7.                     Vector3 vertex = new Vector3(x, y, settings.OriginalStartPoint.z);
    8.                     NextOrigin = NextOrigin + vertex;
    9.                     verticies.Add(vertex);
    10.                 }
    11.  
    ... and in TerrainManager.GenerateTerrainPiece:
    Code (csharp):
    1.  
    2. public TerrainPiece GenerateTerrainPiece(TerrainPiece currentTerrain, Vector3 origin)
    3.         {
    4.        
    5.             //Don't keep generation if we have no rules left
    6.             if (VertexGen.CurrentTerrainRule == null){return null;}
    7.            
    8.             VertexGen.NextOrigin = origin;
    9.  
    From my debug logs, I can tell that GetKeyVertexRandomHeight is returning all negative numbers when it's too high, and all positive numbers when it's too low. Since vertices positions are relative to their predecessors, negative should always make it curve down and positive should make it curve up, right? But this doesn't happen. What is going on that I'm not catching?