Jump to content
  • Advertisement
Sign in to follow this  

Unity How to update tiles based on their neighbours

This topic is 2666 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello community i hope you can help me on this one.
I have a large hexagonal tile-map (150k tiles now might be more in future). I am working on an ecosystem simulation. Every hex has information about it's current state, and associated variables (like fertility). Tiles should be updated according to their neighboring tiles. I am facing some design and implementation problems here.
First problem is how to handle updating of two neighboring tiles. Let's say we have a tile. It's type is grass and it's fertility is 0.8, one neighbor is river, other is sand. River should rise grasses fertility, and sand should lower it, gradually until this system is balanced. If grasses fertility should drop under a certain threshold, that tile should change to sand (for example). How to design this situation in spirit of good oop.
Problem is I don't know what type is my neighbor, and so i don't know how to react to it. I could use something like double dispatch (but would two polymorphic calls incur too much overhead when world gets large?), or i could use some kind of ID system, and a switch statement. That way code could get pretty messy, as there will be more than 10 different types of tiles, and it would be nice to be able to add more later on.
Second problem is how to update a large system. Updating so much tiles could drop my frame-rate so I figured that it should be done asynchronously in a different thread. This is a big issue for me because i am a total threading noob. My idea is that worker thread updates once everything, then signals the main thread, main thread detects changes and accordingly displays results (if grass is no longer grass make it a dirt).
Also is there a way to organize my data to lower cache misses. I at first used bfs algorithm to traverse entire map, but that was about 20% slower than traversing them the way they are stored in memory. Problem with updating is that i need to access neighbors data that might bee "too far" in memory.

Any kind of help is mucho appreciato. Ideas, good design principles and code are all welcome.

Share this post

Link to post
Share on other sites
If you can generalize the type of tiles interactions, you may get away by not creating a class per type. You could have your tiles provide a modification factor to various properties and make an average and then update your tile. For example, sand could reduce fertility by 0.01 every update and river increase it by 0.01, balancing themselves. You then wouldn't need to know if your neighbor is a river or sand, just how it affects your fertility.

As for your threading problem, you could simply split your tiles in chunks and split them among your worker threads instead of doing your current loop through all tiles. I wouldn't have the update be done in parallel or you will have all sorts of fun problems to deal with later on.

Share this post

Link to post
Share on other sites
As for my threading problem what kind of problems could i get into? Also could you give me a word or two about worker thread method?

About tiles, you are right we could take some time to define our abstractions better, but lets say just hypotheticaly that i have to leave some room for adding new tile types that would break current hierarchy. What would be my approach in this case. (number of tiles and fast interaction still stand)

Sorry for the lack of comment but im on my mobile :/.

Share this post

Link to post
Share on other sites
You would lose determinism when compared to single-threaded code if you use a fixed timestep approach. For example, if your update loop is :
- updateEcosystem()
- doOtherStuff()

If you take out updateEcosystem() and place it in a concurrent thread, doOtherStuff() is no longer guaranteed to work with the up to date data. It may or may not be up to date and may become up to date in the middle of the function. That means you can no longer rely on the ecosystem being up to date in your algorithms. This is where bugs come from.

What you can do instead in the updateEcosystem() function is split all the tiles into chunks. Then you send the chunks to your worker threads and wait until they complete before exiting the function. That way, you retain the same determinism than with single threaded code.

For your tiles, I'm not sure I understand the problem. It seems to me the tiles can be abstracted with a set of values from 0 to 1 and each type affects its neighbors' value in some way, probably by trying to create uniformity. If you must have more complex logic, why not keep the type as a variable and centralize all processing in some common function? You can compare the types directly without calling polymorphic functions and all that. It's not really OOP, but if that's really your bottleneck, you may have to break some rules. It's too vague to properly answer.

Share this post

Link to post
Share on other sites
What you're implementing is essentially a cellular automata. Each cell will transition to a new state, based on its current state and that of its neighbors. Automata get a little more complex when you introduce supplementary data such as the "fertility" value you mention, but it's still possible. Let's assume you have a single integer value "F" for each cell in addition to its state "S". The F-value can have different interpretations depending on its state; say, for city tiles F would be population, and for farmland tiles F would be fertility.

In these terms, you need to define the transition function that takes as input current S, current F, and current S of each adjacent tile, and outputs a new S and new F value. Now, in whatever ways you like, you need to work out your rules and define the transition functions. Keep them simple, and have them generate a large lookup table.

Finally, because a cellular automata updates atomically from one step to another, you need to keep two copies of your grid; one "current", and one "updated". After updating, swap them, making the "updated" into "current" and vice-versa. Now you can have any number of worker threads running on your grid, in whatever order ends up being best optimized; they cannot interfere with eachother, because they all read from one grid and write to non-overlapping portions of another grid.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Similar Content

    • By RoKabium Games
      Been a bit quiet recently, but we've been busy bug fixing and tweaking things... Now we have lots more 'Particle effects' in the game, specifically here the Flamethrower and Enemy attacks!
    • By Alexander_Vovk
      Hello Guys!
      Please share your experience, where is it better to find sales manager  specialists for indie team of 6 + people(remotely)?
      Maybe someone has a good experience of cooperation with finding projects through sale managers(USA and Canada)?
      In our team more than 6 developers. We are working since 2014 now we are looking for projects mainly on upWork and Unity Connect.
      But that's not enough 
      This is the site of our team https://www.sixteensq.com/             
      Thank you
      Best Regards
      Alex Vovk
      Co-Founder of Sixteen Squares
    • By JoshuaFraser
      Hi and thanks for reading, I have an issue with this reactive crosshair script, everything works fine until I start changing the offset. Give the script a go and you will see what I mean, when I do SetOffset(0f); it doesnt always set back to the origional state, if anyone can spot a fix I'd be super appreciative!
      using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReactiveCrosshair : MonoBehaviour { [SerializeField] GameObject c_limb_prefab; private float center_offset = 0f; private float current_offset = 0f; private float max_offset = .5f; private int number_of_limbs = 4; private float limb_length = .05f; private float limb_width = .005f; private List<GameObject> c_limbs = new List<GameObject>(); public void SetupCrosshair(){ for (int i = 0; i < number_of_limbs; i++) { GameObject line_go = (GameObject)Instantiate (c_limb_prefab); line_go.transform.SetParent (this.transform); Vector3 limb_pos = new Vector3 (0f,0f,0f); //line_go.transform.position = limb_pos; line_go.transform.localPosition = limb_pos; LineRenderer line = line_go.GetComponent<LineRenderer>(); line.startWidth = limb_width; line.positionCount = 2; line.SetPosition (0, line_go.transform.localPosition + new Vector3(center_offset, 0f, 0f)); line.SetPosition (1, line_go.transform.localPosition + new Vector3(center_offset + limb_length, 0f, 0f)); line.useWorldSpace = false; c_limbs.Add(line_go.gameObject); } if (c_limbs != null) { OrientLimbs (); SetOffset (0f); } } public void OrientLimbs(){ for (int i = 0; i < c_limbs.Count; i++) { float rotation_step = 360f / (float)c_limbs.Count; c_limbs [i].transform.RotateAround (c_limbs[i].transform.position, c_limbs[i].transform.forward, 90f + (rotation_step * (float)i)); } } public void SetOffset(float _current_spread){ float offset = Mathf.Lerp (0f, max_offset, _current_spread); for (int i = 0; i < number_of_limbs; i++) { if (offset > current_offset) { Vector3 pos = c_limbs [i].transform.position + (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } if (offset < current_offset) { Vector3 pos = c_limbs [i].transform.position - (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } } Debug.Log ("SetOffset() offset: " + offset.ToString () + " _current_spread: " + _current_spread.ToString() + " localPos: " + c_limbs[1].transform.localPosition); current_offset = offset; } }  
    • By Erik Nivala
      So, as the title says i am trying to figure out a good way sync all that information with other players in Unity. My problem is that i can't come up with a good solution since i am used to creating classes for everything e.g. attachments are its own class and then the weapon would save a reference to that attachment. But since you can't send custom classes over [Command] & [ClientRPC] i am a little stuck. A solution for this would be giving each attachment for a slot a unique ID and then passing the ID to other player but i feel like that is very error prone if other ppl add a new attachment or the IDs get mixed up.
      Is there a "standard" way that this is usually done that i am missing?
      I am fairly new to programming so any help is appreciated!
    • By MintyLyton
      I'm looking for any team / people that need a programmer for their project. I'm looking to expand my portfolio which you can see Here. I'm more experienced with Unity but I can spend the time to learn new Engines if that's your preference. I have worked on Unreal Engine 4 before but I might take some time to re-learn it, if the project requires it. Feel free to DM here or use the contact info on my website. 
    • By ethancodes
      I'm working on a system for my game that will allow the player to stack pick ups in a queue. As one pick up expires, the next automatically activates. I'm having an issue though where if I pick up the first one, it activates fine, but if i pick up a second directly after it, it overrides the first one, activates the second one, and then once it has run it's course, everything goes back to normal gameplay, no first pick up. I'm not sure why this is happening. Hopefully someone can spot what I'm doing wrong in my code.
      Here is the code for the pick up manager:
      // Update is called once per frame void Update () { if (pickUpQueue.Count != 0 && !pickUpActive) { pickUpActive = true; pickUpQueue[0].ActivatePickUp(); } DeactivatePickUp(); } void DeactivatePickUp () { if (pickUpQueue.Count != 0 && pickUpActive) { Destroy (pickUpQueue [0]); pickUpQueue.RemoveAt (0); pickUpActive = false; } } And here is the PickUp:
      public override void ActivatePickUp () { ball.GetComponent<Ball>().Speed = 2.0f; //increase ball speed... ball.GetComponent<Ball>().StartCoroutine(timer); //...set time that power up is active }  
      There is also a Base Pick Up:
      public void OnCollisionEnter2D (Collision2D collision) { Vector2 tweak = new Vector2 (Random.Range(0f, 0.2f),Random.Range(0f, 0.2f)); this.gameObject.GetComponent<Rigidbody2D>().velocity += tweak; //if the pickup makes contact with the paddle or ball.... if (collision.gameObject.tag == "Paddle" || collision.gameObject.tag == "Ball") { GameObject.FindObjectOfType<GameManager>().GetComponent<PickUpManager>().pickUpQueue.Add(this); Destroy(gameObject); //...and finally destroy power up object } } As a side note, I am trying to find a solution to this that will work for all of my pickups. Some pickups are ammo based, some are timed. 
    • By D34DPOOL
      Edit Your Profile D34DPOOL 0 Threads 0 Updates 0 Messages Network Mod DB GameFront Sign Out Add jobEdit jobDeleteC# Programmer for a Unity FPS at Anywhere   Programmers located Anywhere.
      Posted by D34DPOOL on May 20th, 2018
      Hello, my name is Mason, and I've been working on a Quake style arena shooter about destroying boxes on and off for about a year now. I have a proof of concept with all of the basic features, but as an artist with little programming skill I've reached the end of my abilities as a programmer haha. I need someone to help fix bugs, optomize code, and to implent new features into the game. As a programmer you will have creative freedom to suggest new features and modes to add into the game if you choose to, I'm usually very open to suggestions :).
      What is required:
      Skill using C#
      Experience with Unity
      Experience using UNET (since it is a multiplayer game), or the effort and ability to learn it
      Since the game currently has no funding, we can split whatever revenue the game makes in the future. However if you would perfer I can create 2D and/or 3D assets for whatever you need in return for your time and work.
      It's a very open and chill enviornment, where you'll have relative creative freedom. I hope you are interested in joining the team, and have a good day!
      To apply email me at mangemason@yahoo.com
    • By davejones
      Is there a way to automatically change the start position of an animation? I have a bunch of animations set up on 3D models in unity. The issue is that I need to move the 3D models, however when I do so the animation start positions are not updated and I have to do it manually.

      Changing the transform of key frames is time consuming with the amount of animations I have, so I was wondering if there was a way to do it automatically?
    • By MoreLion
      hey all! We are looking for members for our Unity horror game! 
      Here’s the story:
      After a deadly virus plunges the world into chaos killing 85% of the human population there are now what they call “zones” these zones are watched very closely by the surviving government, people are checked every day for the virus, even if you touch the spit or any human waste or fluids of the victim who is infected, you will die. But one day, people in the west zone start to go missing, 1 woman goes outside the walls to uncover the mystery, is there more to the virus than meets the eye?, That is where your story starts.
      This game is not a long development game, I have loads other game ideas,
      I will also allow you to have a bit of creative freedom if you wish to add or share a idea!
      And no, it’s not a zombie game lol I feel like zombie games are too generic, in this game you will encounter terrifying beasts!
      There is some concept art one of our concept artists have made
      If interested email liondude12@gmail.com
    • By Canadian Map Makers
      GOVERNOR is a modernized version of the highly popular series of “Caesar” games. Our small team has already developed maps, written specifications, acquired music and performed the historical research needed to create a good base for the programming part of the project.

      Our ultimate goal is to create a world class multi-level strategic city building game, but to start with we would like to create some of the simpler modules to demonstrate proof of concept and graphical elegance.


      We would like programmers and graphical artists to come onboard to (initially) create:

      A module where Province wide infrastructure can be built on an interactive 3D map of one of the ancient Roman Provinces.
      A module where city infrastructure can be built on a real 3D interactive landscape.
      For both parts, geographically and historically accurate base maps will be prepared by our team cartographer. Graphics development will be using Blender. The game engine will be Unity.


      More information, and examples of the work carried out so far can be found at http://playgovernor.com/ (most of the interesting content is under the Encyclopedia tab).


      This project represents a good opportunity for upcoming programmers and 3D modeling artists to develop something for their portfolios in a relatively short time span, working closely with one of Canada’s leading cartographers. There is also the possibility of being involved in this project to the point of a finished game and commercial success! Above all, this is a fun project to work on.


      Best regards,

      Steve Chapman (Canadian Map Makers)

  • Advertisement
  • Popular Now

  • Forum Statistics

    • Total Topics
    • Total Posts

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!