Making a RTS game #15: Adding a minimap and fog of war 3/3 (Unity/C#)

Today, let’s continue our RTS programming tutorial and finish up our minimap and fog of war features!

This article is also available on Medium.

These past few weeks, we’ve been working on the minimap and the fog of war systems for our RTS game. They allow us to get a bird’s-eye view of the terrain and to distinguish unexplored, already explored and in-sight areas. We have a little UI indicator to better materialise the part of the map currently in view of the main camera and some game parameters to easily change the settings of the fog of war.

In this final part, we’re going to wrap this up by adding some final touches:

  • a mechanism for direct camera “teleportation” when we click on the minimap
  • a small “fade-in” effect on units FOV so we transition a bit from dark to light when we place a building or create a character unit
  • conditional rendering for the scene objects depending on their type and on whether they are currently in an in-sight area or simply in an already discovered area

Moving the camera when we click on the minimap

Instant camera teleportation is neat because it allows the player to quickly go to the other edge of the map without having to continuously press some arrow key or stick your mouse on a screen border during dozens of seconds.

So like in most RTS games, we’ll implement this “minimap click”: whenever the player clicks somewhere on the minimap (in an explored zone or not), the camera will move instantly so the matching point in the 3D scene is in the middle of the main camera screen. We will even make it so we can click and drag the minimap indicator and automatically update the main camera accordingly (watch the mouse cursor on the minimap in the bottom-left corner):

The idea is roughly to:

  • add a script on the minimap UI object (the image that is fed the render texture and shoved in the bottom-left corner of the interface)
  • in this script, handle dragging events and, whenever a movement is detected, send an event to update the (main) camera position
  • in the CameraManager script, catch this event and re-place the camera accordingly

Let’s start with our minimap dragging logic. Create a new C# script named Minimap.cs and drag it on the minimap UI object in your scene hierarchy. Now, add the following content in it:

This script inherits from Unity’s built-in UI-event-handling classes (here IPointerDownHandler and IPointerUpHandler) just like the BuildingButton class did, several tutorials ago. Thanks to this inheritance, we can directly access two methods in our Minimap class: OnPointerDown() and OnPointerUp(). Those functions are called automatically by Unity when – you guessed it! – the mouse is on the object and the left button is pressed or released.

Note: because we want to be able to click and drag the indicator to continuously move the main camera, we can’t use a simple “click” event – we need to separate the down and up moments so we can track the potential dragging in the middle.

The class is basically watching those press/release events and setting a _dragging flag. _dragging is true if the user is currently click-and-dragging (and false if he/she is simply moving the cursor around and not pressing the left button). Then, if the player is dragging, we get the position of the cursor on the image. Finally, here’s the trick: we get the relative position on the image and re-apply it to the given terrain size. This way, we can compute easily the following:

  • my minimap has a 100 pixels width, and my terrain has a 700 units width
  • the player clicked 20 pixels from the left
  • so it is a 20% ratio on the horizontal axis
  • meaning 0.2 * 700 = 140 units to the right on the X-axis in the 3D world

Similarly, we can “transfer” the relative 2D Y-position to a corresponding 3D Z-position.

And in the end, we send this final computed 3D position as an event so our main camera can catch it.

Note: the Mathf.Epsilon constant is a predefined very small value that is a nice way to check for zero distances: because of floating point precision, requiring a distance of 0 is always “risky” – the approximation might create a super-small difference that will make the condition impossible to match. Instead, it’s better to require that the distance is below this tiny threshold – the human eye can’t see the difference but the computer will! 😉

On the camera side, we need to update our CameraManager script a bit. First off, we’ll extract the logic to fix the altitude of the camera compared to the ground beneath into its own private function, _FixAltitude():

Now, we can easily add the event listener and its callback function – this method receives the 3D position we computed earlier, adds the orthographic view offset to it and re-adjusts the altitude:

And that’s it! You can now click around on your minimap to instantly teleport your camera to this location!

Adding a “fade-in” on units FOV

In the first part of the minimap/fog of war tutorials, we added some logic in our unit-related classes to take care of the FOV object – the “hidden” mesh that is just seeable by the fog of war cameras. Basically, we told the unit to set the scale of the object when it is first created (but it’s still disabled) and to then enable the game object when the unit is actually “placed”.

The problem is that it makes for quite a harsh change of light. When we place a building, the shadow just “pops out” suddenly with no transition whatsoever:

It would be better to feel like the terrain is “discovered” gradually. To do that, we’re going to start with a scaled-down FOV object and use an IEnumerator (yes, again!) to scale it up over a little timespan. To get the right “final” scale (i.e. the actual field of view of the unit), we’ll simply store it in the Unit class and pass it on to the EnableFOV() method:

There are a couple of things to note in this simple coroutine:

  • we use a “do-while” loop: this statement is present in the programming languages of the C family and in C#; it’s similar to a while loop but it is guaranteed to run at least once, and the condition is evaluated at the end of each iteration
  • the step float variable sets how frequently the scale of the FOV object is updated – so it defines how smooth / precise our scale-up transition is, but also how heavy it is in terms of computation
  • we use lerping (aka linear interpolation) to automatically compute the scale of the FOV: the Vector3.Lerp() function allows us to parametrise the variation between two Vector3
  • you can of course play around with the scale-up time to have our coroutine reveal the terrain more or less quickly

We now have a way better effect when we place a building where we quickly (but not instantaneously!) scale up the FOV so we see how a new part of the map has been explored 🙂

Rendering units and doodads based on the map explored areas

The RTS “fog of war” is great for getting the player thrilled with excitement as he/she discovers the map. But it’s also useful for hiding away some info about the current state of the game in the places this player hasn’t got units – even if you’ve discovered a zone, you shouldn’t have the same amount of information if it’s in sight of one of your units or if you walked through it half an hour ago!

A very common choice for RTS designers is:

  • to hide everything in unexplored areas
  • to only show the terrain and doodads (i.e. scenery assets) in the already explored (but not in-sight) areas; in particular, you don’t show enemy/NPC units
  • to show everything in in-sight areas

We have taken care of the first and last points just by implementing our fog of war. But the second feature is not coded up yet – at the moment, we see everything in already explored areas, there’s no difference with the in-sight zones.

If you take a look at this Unity forum thread, you’ll see that JoshuaMcKenzie gave a very nice and very detailed answer to the question: “how to make a cool fog of war in Unity?”. It’s pretty similar to our current setup, and it has a script for toggling the renderers of game objects on and off based on their position on the map and the state of the fog of war at that position. The idea is to convert the object’s world position to a screen point for the fog of war camera; then, you can simply check what colour the matching pixel is on the “unexplored areas” render texture: if it’s white, then the unit is currently in-sight for the player, else it’s either completely in the dark or in an already explored area. So if the pixel is white, the renderer should be enabled, else it should be disabled.

The rest of the script is mostly about getting references to the proper assets in our scene (I’ve slightly adapted the script to get the camera automatically on Awake(), since the units using this component won’t exist before the game has started):

We can now add this component to all of our units. Remember to drag in the “MeshRenderer” of your prefab in the myRenderer field of the script — this renderer might be on different parts of your prefab depending on how it’s constructed. In our case, the prefabs have a subchild called “Mesh” with the “MeshRenderer component on it.

Note: we’ll see in a later episode that this script is not the most optimised and takes quite a toll on the CPU – but it’s ok for now, especially since we’re primarily focusing on PC builds 😉

So now any House, Tower or Soldier that is not owned by the player disappears as soon as it is not directly in-sight:

Note: we haven’t yet talked about unit ownership – this will come in a later episode! In the end, we’ll need to conditionally toggle the FOV on or off depending on whether we own the unit or not. But for now, I’ve just placed some buildings on the ground before running the scene and removed their FOV logic entirely 😉


This part of the RTS tutorial was complex and a bit long, but we now have two crucial features for our RTS game: a nice and readable (although basic) minimap, and a simple fog of war system that updates as the player’s units move around, differentiates between unexplored, already explored and in-sight areas, and even toggles the rendering of some objects in the scene based on the state of this fog.

This minimap can still be improved in many ways; for example, we could show the position of players’ units with colour spots (corresponding to each player colour), or we could add specific icons to denote particular structures on the map (such as a mysterious cave, a treasure chest, etc.).

In the next episode, we’ll continue building up an atmosphere and discuss the importance of sounds and music in video games…

4 thoughts on “Making a RTS game #15: Adding a minimap and fog of war 3/3 (Unity/C#)”

  1. I followed everything, but nothing works unfortunely, can’t move camera by clicking on minimap correctly and I am not able to hide enemy units in explored fog of war :/ Don’t know what I am doing wrong. About changing camera position my x.position is setting correctly, y.position is static and it’s good, but my z.position is always same wherever I click and it’s surprisingly high. About hiding units, it’s like when I set treshold higher than 0, then my enemy units are always invisible (meshRenders are always not enabled) and when I set treshold on 0 then units are always visible. And nothing changed wherever my units are. Could help me?

    1. Hi, I’m happy to know you’re following the series! 🙂
      But too bad you’re having some difficulties :/
      It’s a bit hard to debug just with this info, but if you want you can either check the Github repo (it’s a bit more “advanced” because I’ve continued the tutorials but I think the camera mechanics are pretty similar); or you can send me your Unity code via email and I can help you find out what’s wrong 🙂

  2. Unfortunately I have an error with the camera movement I don’t see…

    When clicking on the minimap the camera is moved correctly, but I’m getting this error:
    transform.position assign attempt for ‘Main Camera’ is not valid. Input position is { NaN, 100.000000, NaN }.
    UnityEngine.Transform:set_position (UnityEngine.Vector3)
    CameraManager:_OnMoveCamera (object) (at Assets/Scripts/Managers/CameraManager.cs:193)
    UnityEngine.Events.UnityEvent`1:Invoke (object)
    EventManager:TriggerEvent (string,object) (at Assets/Scripts/Managers/EventManager.cs:95)
    Minimap:Update () (at Assets/Scripts/UI/Minimap.cs:32)

    point towards the row containing the newPos (in your snippet above: row 30).
    Of course I can’t click again on the minimap, because the scripts broken right there, but I don’t see the error. Especially because of the camera have been moved correctly to the new position. *confused*

    Hope you can help me. =)

    And one small part that bothers me… If I deactivate the FogOfWar object in the hierarchy the GameManager seems not to be able to find the GameObject “FogOfWar” and thus is not able to activate or deactivate it. Looks like it has to be activated all the time, right? (Don’t like the black screen though :P)

    1. Hi!

      Hmm so the first issue comes from some errors in the “UI to world re-mapping”… to be honest, it’s a pretty complex feature, so I’ve refined it several times throughout the tutorial ^^
      I think you should check out the latest episode, episode #40: it’s quite standalone so you don’t really need to have covered all the previous tutorials, I think, and it focuses on fixing the minimap! 🙂

      For the fog problem: the idea is that it is controlled by the GameManager depending on your game parameters Scriptable Object. So the GameManager should always be able to access it, that’s why the GameObject in itself has to stay active.
      But then, if you turn off the enableFOV boolean in the game parameters, the GameManager should take care of toggling it off when the game starts 😉

      I hope it helps,

Leave a Reply to Chung-Tai Cancel reply

Your email address will not be published.