title: swipe control can't destroy gameobject

text:
# Question
Title: swipe control can't destroy gameobject
I tried to make a game where you can destroy something when you swipe or tap. However, it says `NullReferenceException` & while the swipe control actually works, the `gameobject` can't be destroyed.

```
public class checkUp : MonoBehaviour {
private Swipe swipe;
private UIManager uiManager;

private void Awake()
{
    swipe = GetComponent<Swipe>();
    uiManager = GetComponent<UIManager>();
}

// Update is called once per frame
void Update()
{
    if (swipe.SwipeUp ) //NullReferenceException: Object reference not set to an instance of an object
    {
        Debug.Log("Passed!");
        uiManager.destroyed = true;
        Destroy(gameObject);
    }

```

Here's the partial code from swipe:

```
    if (swipeDelta.magnitude > 125)
    {
        //which direction?
        float x = swipeDelta.x;
        float y = swipeDelta.y;
        if (Mathf.Abs(x) > Mathf.Abs(y))
        {
            //left or right
            if (x < 0)
                swipeLeft = true;
            else
                swipeRight = true;
        }
        else
        {
            // Up or down?
            if (y < 0)
                swipeDown = true;
            else
                swipeUp = true;
        }
    }

```

# Answer
It is probable that your GameObject does not have a `Swipe` component. Try adding it and it should work.
> 0 votes

---
Tags: unity
---


# Question
Title: Comparing meshes and reducing duplication of data
I'm writing a class that reads an obj file, indexes each mesh and creates a VAO and GameObject of the appropriate type. I've stumbled on a design issue. Objects of the same name (Tree\_A001, Tree\_A002) are currently skipped over, and their min and max extents are used to calculate their centre, and therefore where to position the a copy of that mesh. Not only does this mean I've read in the mesh twice, just to ignore all the data as soon as I've got the min and max, but in my case I have 230 trees. It works but takes 12-15 seconds to read in the file itself, and I've not been able to gleam the rotation or scale of said object. I understand that comparing the min and max extents of the duplicate mesh to the original could let me get the scale, but as soon as the mesh is rotated in the scene file then it breaks. I'd like to do something more efficient than this however, and I'm stuck on what do to. What is the done thing in professional games, that allows multiple objects to be placed in a 3d modelling software, and their individual position rotation and scale to be kept? I've experimented with using single triangles to represent the position and scale etc but it makes designing the scene much harder as you can't see what you're placing. Thanks for any advice

# Answer
> 1 votes
There are a couple of issues here, but it looks like they are all solvable for you.

A good starting point is to distinguish between a Scene and a Mesh. A Scene might contain many Meshes. The Mesh here is the obj file and the Scene is a list including, for example,

> "meshname.obj", position(x,y,z), scale(x,y,z), rotation, ...

and so on for each object in the scene.

From here, you can identify the mesh object by it's filename, load it once, and place instances of it at each location as specified by the scene file.

Also, while you load it you can check the data in place to calculate the extents of the bounding box. That is, load the model from disk into a buffer, use the buffer to calculate extents, use the same buffer to build the VBOs.

Calculating the center point may or may not be necessary anymore. What I would do in this situation is export each obj file individually from the modelling package, with the pivot point at the origin of the model. That way it doesn't need to be calculated at run-time, the zero point for each model is already where I want it. It sounds like you tried to export a whole scene as an obj, but you really want to split up the scene and just the individual elements are obj.

Finally, you can do this kind of thing in Blender using scene export plugins. This will depend on your engine and your modelling program, but it can be done. Many games develop a custom editor to handle this kind of thing.

---
Tags: opengl, 3dsmax, obj
---


# Question
Title: How to make a person walk within a Unity scene?
I have a person in my Unity scene. My person follows waypoints and move. However, the movement is very unrealistic, the person seems to be floating through the scene rather than walking. How to make a person walk in unity?

# Answer
It's not an easy answer. First you need to decide how do you want to handle your character walk. For what you said you will handle it like a point&click game so you will of course need a navmesh (try to take also a look to the new navmesh component: https://github.com/Unity-Technologies/NavMeshComponents ). After that you will need to create an animator controller, your character will move based on your animations. Blend multiple animations to get a natural result (from idle to walk and from walk to run... by using the animator controller you will just need idle walk and run animations and the controller will blend them. just make sure your change of state of the animator controller is based of a float variable).

That's the basic idea.

You should try to understand how animator controller work first. Read doc and tutorial of animator controller if you want to start to solve your problem.
> 1 votes

---
Tags: unity, art, graphics-design
---


# Question
Title: Why my charchter fluctuate instead go down stairs?
My player is a capsule with:

* First person controller
* Charchter controller

When my player go up stairs, it works well. When my player go down stairs, it fluctuate in air.

What am i wrong ?

Thanks

# Answer
You have **Gravity Multiplier** set to 0, which is stopping gravity from applying to your character.
> 2 votes

---
Tags: unity
---


title: Struggle with resetting coroutine

text:
# Question
Title: Struggle with resetting coroutine
A little bit of context; I'm still not experienced at this, I'm creating a 2D platformer and this is my enemies script (some part of it). This is supposed to be a minatour, which charges towards the player on sight. When rays hit the player I call the Charge coroutine from update. As you can see below rays are not casted during the coroutine. Everything works according to plan, but after this coroutine ends if rays hit the player in two seconds, coroutine never stops again, rays are always casted and the minatour always keep charging. But if rays hit the player after 2 seconds it's perfectly fine. What am I doing wrong?

```
void FixedUpdate()
{
    if (!canChargeRight && !canChargeLeft)
    {
        rightRay = Physics2D.Raycast(transform.position, Vector2.right, rayDistance, layerMask);
        leftRay = Physics2D.Raycast(transform.position, Vector2.left, rayDistance, layerMask);

        if (rightRay.collider != null)
        {
            canChargeLeft = true;
        }
        else if (leftRay.collider != null)
        {
            canChargeRight = true;
        }
    }
}

void Update()
{
    if (canChargeRight)
    {
        StartCoroutine(Charge(-1));
    } else if (canChargeLeft)
    {
        StartCoroutine(Charge(1));
    }
}

private IEnumerator Charge(int chargeDirection)
{
    myRigidBody.velocity = Vector2.right * chargeDirection * chargeSpeed;

    yield return new WaitForSeconds(2);
    canChargeLeft = false;
    canChargeRight = false;
    myRigidBody.velocity = Vector2.zero;
}

```

# Answer
> 1 votes
As @DMGregory mentioned, I guess the main issue was calling the coroutine in update function. Here is the final version if anyone is interested

```
 void Update()
{
    if(!chargingLeft && !chargingRight)
    {
        if ((player.position.x - transform.position.x) < 0)
        {
            transform.localScale = new Vector2(1, 1);           //this is where we flip enemy
        }
        else
        {
            transform.localScale = new Vector2(-1, 1);
        }
    }
}

void FixedUpdate()
{
    if (canCharge)
    {
        rightRay = Physics2D.Raycast(transform.position, Vector2.right, rayDistance, layerMask);
        leftRay = Physics2D.Raycast(transform.position, Vector2.left, rayDistance, layerMask);

        Debug.DrawRay(transform.position, rayDistance * Vector2.right, Color.green);
        Debug.DrawRay(transform.position, rayDistance * Vector2.left, Color.red);

        if (rightRay.collider != null)
        {
            chargingRight = true;
            StartCoroutine(Charge());
            canCharge = false;
        }
        else if (leftRay.collider != null)
        {
            chargingLeft = true;
            StartCoroutine(Charge());
            canCharge = false;
        }
    }

    if (chargingLeft)
    {
        myRigidBody.velocity = Vector2.left * chargeSpeed;
    } else if (chargingRight)
    {
        myRigidBody.velocity = Vector2.right * chargeSpeed;
    }
}

private IEnumerator Charge()
{
    myAnimator.SetBool("Charge", true);

    yield return new WaitForSeconds(2);
    myAnimator.SetBool("Charge", false);
    myRigidBody.velocity = Vector2.zero;
    chargingRight = false;
    chargingLeft = false;
    StartCoroutine(Recovery());
}

private IEnumerator Recovery()
{
    StopCoroutine(charge);
    //recovery
    yield return new WaitForSeconds(2);
    canCharge = true;
}

```

---
Tags: unity, c#
---


title: Z rotation matrix inverting object

text:
# Question
Title: Z rotation matrix inverting object
I'm currently creating a 3d game where I need to rotate shapes. To do se, I created a rotation matrix for each axis, X, Y and Z. X and Y are giving me expected results, but not Z who kind of "inverts the shape". I need it to rotate like it would rotate a 2d shape.

Here is the Z matrix :

```
zRotation.matrix[0][0] = cosf(rotationAngles.z);
zRotation.matrix[1][0] = -sinf(rotationAngles.z);
zRotation.matrix[0][1] = sinf(rotationAngles.z);
zRotation.matrix[1][1] = cosf(rotationAngles.z);
zRotation.matrix[2][2] = 1;

```

Here is what it looks like : https://i.stack.imgur.com/W14C7.jpg

PS : The game have an isometric perspective.

EDIT : Here is how I do matrix * vector

```
vec3 operator *(vec3 operand){
    //multiply vector by matrix

    vec3 result = vec3((operand.x * matrix[0][0]) + (operand.x * matrix[1][0]) + (operand.x * matrix[2][0]) + (operand.x * matrix[3][0]), (operand.y * matrix[0][1]) + (operand.y * matrix[1][1]) + (operand.y * matrix[2][1]) + (operand.y * matrix[3][1]), (operand.z * matrix[0][2]) + (operand.z * matrix[1][2]) + (operand.z * matrix[2][2]) + (operand.z * matrix[3][2]));
    return result;
}

```

(Fourth element is always 0)

# Answer
> 0 votes
Something's not quite right here. If you take the matrix and multiply it with the vector by hand, you'll get

$$\vec v(x\cdot cos(\theta)-x\cdot sin(\theta), y\cdot sin(\theta)+y\cdot cos(\theta), 0)$$

When it should be

$$\vec v(x\cdot cos(\theta)-y\cdot sin(\theta), x\cdot sin(\theta)+y\cdot cos(\theta), 0)$$

(notice the \\$x\\$ and \\$y\\$)

The problem actually lies in your vector multiplication function. When we multiply a matrix by a vector, we are basically taking the dot products of the vector and every row of the matrix. What you are doing is multiplying every element of a row by the same coordinate. So your code should be something like this instead:

```
vec3 result = vec3(operand.x * matrix[0][0] + operand.y * matrix[1][0] + operand.z * matrix[2][0], operand.x * matrix[0][1] + operand.y * matrix[1][1] + operand.z * matrix[2][1], operand.x * matrix[0][2] + operand.y * matrix[1][2] + operand.z * matrix[2][2]);

```

---
Tags: c++, 3d, rotation, matrix, projection
---


title: Calculating surface normal numerically

text:
# Question
Title: Calculating surface normal numerically
Say I have a 2D surface defined with the use of bitmap.

I want to use this bitmap for collision detection (white color is where object can move freely, with black I mark the walls).

How can I numerically calculate the surface normal vector at given point?

For example, in the attached picture, how can I calculate the surface normal vector for the red point?

# Answer
You should use the Sobel opererator, which is a type of convolution filter.

A 3x3 pixel convolution would work fine, but you need to do it twice: once for horizontal edges, then once for vertical edges.

Your normal will be (x,y) where x is the output from the horizontal edge detect, and y is the output from the vertical edge detect.

You need to normalize the result though, and use 'undefined' values where both convolution filters return zero.

If you want to have more gradual normals, then a 5x5 filter will generate a more diverse set of angles for the normals.
> 2 votes

---
Tags: geometry, normals, numerical-methods
---


# Question
Title: When should you use a baseclass and a class as a datatype?
Im following a C# rpg game development tutorial atm and what confuses me is that I cant figure out when to use what.

The author writes different classes where 1 class derives from another so the derived class has all the properties of the bass class. With other classes when all the properties are needed from another class he just makes them a datatype

Example: both the monster and player class have currentHealth and and maximumHealth as properties from the LivingCreature baseclass. But then the author writes Item class as a public data type property in the InventoryItem class. Can someone explain to me when I should make a datatype and when I should I derive a class?

```
public class Monster : LivingCreature {
 public int ID { get; set; }
    public string Name { get; set; }
    public int MaximumDamage { get; set; }
    public int RewardExperiencePoints { get; set; }
    public int RewardGold { get; set; }
    public List<LootItem> LootTable { get; set; }

    public Monster(int id, string name, int maximumDamage, int rewardExperiencePoints, int rewardGold, int currentHitPoints, int maximumHitPoints)
        :base  (currentHitPoints, maximumHitPoints) {

        ID = id;
        Name = name;
        MaximumDamage = maximumDamage;
        RewardExperiencePoints = rewardExperiencePoints;
        RewardGold = rewardGold;
        LootTable = new List<LootItem>();
}

}
public class InventoryItem
{
 public Item Details { get; set; }
 public int Quantity { get; set; }

    public InventoryItem(Item details,int quantity)
    {
        Details = details;
        Quantity = quantity;
    }
}

```

# Answer
Your terminology is a little unusual. A "data type" is a name for a *kind of value*, just like a class is a name for a *kind of value*. They're the same thing. It sounds like what you're calling a "datatype" is actually an *instance of a value*.

The difference between when you'd use the two is the difference between an "is a" relationship and a "has a" relationship (also known as inheritance versus composition).

You derive from a class, generally, when you want to express functionality with an "is a" relationship: "A monster is-a kind of living creature."

You create instances of types as properties, generally, when you want to express functionality with a "has a" relationship: "A living creature has-a current health value."

When the "is a" or "has a" phrasing makes sense, use that. When they both could make sense, that's more of a judgement call. The typical suggestion *today* is to prefer composition ("has a") over inheritance ("is a"). This was not always the case, though. In recent history it was far more prevalent to see a lot of "is a" relationships used to express functionality.

When you want to use which is, thus, to some extent up to you, and I would encourage you to experiment with both to discover the pros and cons for yourself (as they are many and varied, depending on your use case).

In your inventory example, `InventoryItem` sounds like it represents an item within a player's inventory, and so it has an `Item` property referring to what general kind of item is in the inventory, and maybe a "stack count" property to indicate how many there are.
> 1 votes

---
Tags: c#
---


# Question
Title: How to use textures in 2D games in WebGL
I have been trying to figure out how to structure the VBOs in WebGL, and think that keeping them all together in one if at all possible sounds like the best approach. Right now I'm thinking of having color buffer, position buffer, and index buffer, just those 3. But my question is what about a texture buffer (maybe it's called a UV buffer, but I'm not sure if that's 3D only).

I would like to have a game with basically flat colors and alpha/opacity and some drop shadows perhaps, maybe some glows, but nothing too complex. Mainly it would be like traditional vector graphics look but in WebGL. As such, I'm wondering how to solve the texture problem. If I *need* a texture, or I don't at all need one.

Part of figuring this out is knowing what you should really be using textures for. I get that they are useful for mapping *images* to geometry, but I don't know of any other use case. Wondering if one could explain some use cases of textures as it applies to my situation. The main goal is figuring out if I need a texture buffer at all, or I can/should just stick with color/position/index.

A look I like is like this:

# Answer
> 1 votes
You probably will want to use textures. Looking at the image you posted, I would probably make the door one texture, have another one for the lights, the wreath another, the pumpkins another, etc. That way the door can be a single quad, instead of the 9 or more it would take to draw that door using only geometry.

In addition to simply mapping images to geometry, textures can be used for a variety of other things. They can be used as a gradient. You'll likely still apply that to geometry, but not necessarily in a straightforward way. (You might make a radial gradient display on some geometry using a 1D gradient texture, for example.) They can also store things like velocities. For example, you can use a texture as a "flow field" for animating particles or other objects. They can even be used to control geometry. You can sample a texture in a vertex shader, for example, and use the result to determine how to transform the vertex.

---
Tags: opengl, textures, webgl, vertex-buffer
---


# Question
Title: What game mechanic can I use to show that the player character is bored?
I'm designing a part in my game where the player must notice that *his character feels bored* about a certain mundane task he is doing, *without being boring for the player*.

By observing the game mechanic, the player should understand that his character is bored or fatigued. To keep the player interested in playing though, the mechanic has to gamify that mundane process into something interesting or challenging.

How could this be done?

# Answer
> 8 votes
Just a whistle and blow bubble animation would do well.

Because people don't wear wrist watches anymore, you could have the player take out a phone device and start flipping through that.

The classic Sonic waiting animations are good too.

Though this isn't a *game mechanic*, it's just a visual animation.

# Answer
> 4 votes
If you're wanting the design to be central to the game, or at least to the section of the game in which the boredom occurs, you could desaturate the screen.

Since you're wanting to express boredom in a visual/mechanical medium, yet wanting to avoid mechanical boredom, the logical conclusion is to implement visual boredom. Remove a large amount of color saturation while the character is bored, so the mechanics can remain fun while still showing the negative effect on the character. Conversely, when the character starts having more fun, the saturation can be brought back, maybe even enhanced beyond the normal for the game to express the relief/distraction.

Audio could be similarly used, but would be much more subtle and likely to be missed entirely unless the sound of the game is fundamental to the emotional feel throughout the game.

# Answer
> 0 votes
They can get distracted and disobey and you'll have to make them work by making them concentrate(mashing a button?). Not sure if this is fun, though.

# Answer
> 0 votes
I suppose a lot depends on how you want that boredom to affect the player character. Are they just zoning out at a basic work task, like folding laundry or assembling packets? Maybe the gameplay becomes simpler and simpler, starting with multiple inputs to do the first few iterations, then maybe just one click or press per iteration, to maybe even just hold button to continuously complete the task. This makes the gameplay becoming less interesting a metaphor for the lowered interest of the character.

If you want to emphasize how the boredom makes their will to continue working on the task suffer, then perhaps have the character start to look away, sigh audibly, or change the ui text that refers to the text to editorialize its plainness. For example going from "wash plate" to "clean the stupid plate" or "waste more of my life". Or each time the character looks away you have to manually "refocus" the character to get them to continue the task.

# Answer
> 0 votes
I have never tried this before. But maybe you could have your characters head and the camera turn off to the side every now and then. Like when you are handing in a quest or something have the sound go fuzzy and the camera turn off requiring the player to shake the camera a bit to get the character back on task.

# Answer
> 0 votes
* Have the character react with a slight (random but increasing, within limits, short but noticeable) delay.
* Have the character occasionally turn it's back to the object he should process.
* Have jump on one leg instead of walking.
* Occasionally measure wind direction with wet finger?
* After T of inactivity, let feet innaturally, slowly sink 10 cm into the ground. Corrects upon any action. Or... oh well, maybe make it a constant state?
* During inactivity, let the character slowly elevate innaturally (balance erratically against physics laws). Or sway.
* Re-sale characters head a little. Goes towards flat. Any user action suddenly corrects.

I guess i'm proposing to do unexpected, slightly erratic, innatural, comical if possible, small adjustments that are minor enough to just about give a hunch, fetch the users curiosity for "what next"?. Like the big artsts say: Give a small seed and let the audience imagine the rest themselves. Or, well - extensive exaggeration might produce some laughs too :-).

# Answer
> 0 votes
# Atelier Shallie: Alchemists of the Dusk Sea

In Atelier Shallie, a mechanic is implemented to keep the player connected to the plot of the game in a relatively open sandbox though the "Life task system". The player may lead the player character (PC) to do whatever they like, but if the PC is preoccupied with a certain central task or problem, then the performance of the PC on unrelated tasks is lessened. As you can see here: https://www.siliconera.com/2014/04/14/atelier-shallie-changes-world-depending-play/ there are on-screen pop ups that give regular reminders of what the PC would like to do, and there is a special screen to see what tasks they would like to focus on.

You can implement a similar mechanic that keeps track of the PC's boredom, and lessens their performance if they are chronically bored. Show some on screen popups that gently guide the player towards the what the PC considers as "fun" and reward the player for doing these things by improving the character's performance. Like that you still give the player freedom to do what they want, but push them gently towards doing what the PC wants, and, indirectly through the PC, to doing what you want them to do.

---
Tags: game-design, game-mechanics
---


# Question
Title: Spine + MonoGame > viewMatrix / camera offset
we switched from frame by frame animations to Spine (this animation software).

The issue I am facing now, that it am unable to fit it in our coordinate system. (simple 2D game) I guess there is an issue with the projection or some other matrix-related stuff that I am not really good in. (It works perfectly in an empty project, Example provided here: https://github.com/EsotericSoftware/spine-runtimes/tree/3.7/spine-monogame It's probably a one-liner, but I cant figure it out. Target in this case I want to draw the tree at world position 100,100 - so the top left corner.

This is my sample class for spine objects:

```
public class SpineObject
    {
        private SkeletonRenderer skeletonRenderer;
        private Skeleton skeleton;
        private AnimationState state;
        private SkeletonBounds bounds = new SkeletonBounds();
        private string assetsFolder = "Content/Animations/";

        public SpineObject()
        {
            skeletonRenderer = new SkeletonRenderer(Orbs.graphics.GraphicsDevice);
            skeletonRenderer.PremultipliedAlpha = false;

            String name = "Objects/tree1/tree1";
            String atlasName = "Objects/tree1/tree1";

            Atlas atlas = new Atlas(assetsFolder + atlasName + ".atlas", new XnaTextureLoader(Orbs.graphics.GraphicsDevice));

            SkeletonJson json = new SkeletonJson(atlas);
            json.Scale = 1;
            SkeletonData skeletonData = json.ReadSkeletonData(assetsFolder + name + ".json");
            skeleton = new Skeleton(skeletonData);
            AnimationStateData stateData = new AnimationStateData(skeleton.Data);
            state = new AnimationState(stateData);
            state.SetAnimation(0, "animation", true);

            skeleton.X = 100;
            skeleton.Y = 100;
        }

        public void Update(GameTime gameTime)
        {
            state.Update(gameTime.ElapsedGameTime.Milliseconds / 1000f);
            skeleton.UpdateWorldTransform();
            state.Apply(skeleton);
        }

        public void Draw(Matrix viewMatrix)
        {
            ((BasicEffect)skeletonRenderer.Effect).Projection = Matrix.CreateOrthographicOffCenter(0, Orbs.graphics.GraphicsDevice.Viewport.Width, 0, Orbs.graphics.GraphicsDevice.Viewport.Height, 1, 0);
           ((BasicEffect)skeletonRenderer.Effect).View = Orbs.camera.GetViewMatrix();

            skeletonRenderer.Begin();
            skeletonRenderer.Draw(skeleton);
            skeletonRenderer.End();
        }
    }

```

The Draw-Call looks like this:

```
[...]
Animations.SpineObject tree1 = new Animations.SpineObject();
Camera2D camera = new Camera2D(GraphicsDevice.Viewport);
Matrix viewMatrix  = camera.GetViewMatrix();
[...]

protected override void Draw(GameTime gameTime)
{
    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, null, null, null, viewMatrix);
    //Draw Map Layers and Stuff
    tree1.Draw(viewMatrix);
    spriteBatch.End();
}

```

I guess the tree is beeing drawn somwhere far off, so how do I get the trees X/Y value to be on par with the worlds coordinates?

# Answer
Just in case someone runs into the same issue, I've found a simple workaround: I moved the Draw()-call of the tree out of the current spriteBatch-call. Means after spriteBatch.End(). It works perfectly now, also drawing it on the correct world position. I did not get an answer yet from Spine if it is some kind of restriction that it needs to be drawn outside of the current spriteBatch or if I did something wrong.

SpineObject Draw call:

```
    public void Draw()
    {
        ((BasicEffect)skeletonRenderer.Effect).Projection = Matrix.CreateOrthographicOffCenter(0, Orbs.graphics.PreferredBackBufferWidth, Orbs.graphics.PreferredBackBufferHeight, 0, 1, 0);
        ((BasicEffect)skeletonRenderer.Effect).World = Orbs.camera.GetViewMatrix();

        skeletonRenderer.Begin();
        skeletonRenderer.Draw(skeleton);
        skeletonRenderer.End();
    }

```
> 0 votes

---
Tags: camera, monogame, coordinates, spine
---


# Question
Title: In Unity , How to clear instantiated object when I call the function?
Here is a function I call out am UI element:

```
public void LoadCurrentItem(ItemType t)
{
    List<Item> itemList = SessionManager.singleton.GetItemAsList(t);

    if (itemList == null)
        return;
    if (itemList.Count == 0)
        return;
    GameObject prefab = (t == ItemType.consumable) ? eq_left.inventory.slotTemplateUD : eq_left.inventory.slotTemplateLR;
    Transform p = eq_left.inventory.slotGrid;

    int dif = iconSlotCreated.Count - itemList.Count;
    int extra = (dif > 0)?dif: 0;

    for (int i = 0; i < itemList.Count + extra; i++)
    {
        if (i > itemList.Count -1)
        {
            iconSlotCreated[i].gameObject.SetActive(false);
            continue;
        }

        IconBase icon = null;
        if(iconSlotCreated.Count -1 < i)
        {
            GameObject g = Instantiate(prefab) as GameObject;
            g.SetActive(true);
            g.transform.SetParent(p);
            icon = g.GetComponent<IconBase>();
            iconSlotCreated.Add(icon);
        }
        else
        {
            icon = iconSlotCreated[i];
        }

        icon.gameObject.SetActive(true);
        icon.icon.enabled = true;
        icon.icon.sprite = itemList[i].icon;
        icon.id = itemList[i].item_id;
    }

}

```

It might seem less informative, but my question is simple and stupid: I want to destroy my `GameObject g` that instantiates prefab before it instantiates prefab so that I can refresh `GameObject g` to create `eq_left.inventory.slotTemplateUD` or `eq_left.inventory.slotTemplateLR`

How can I achieve this goal?

# Answer
Just store a reference to your instantiated object and check if it is `!= null` when you want to create a new one. Then destroy the old one. Try something like this:

```
private GameObject someObject;

private void SpawnObject()
{
    if(someObject != null)
    {
        Destroy(someObject);
    }
    someObject = Instantiate(yourPrefab);
}

```

Of course to minimize perfomace losses by instantiating on runtime I would suggest you implement some sort of `ObjectPool` for that.
> 3 votes

---
Tags: unity, c#
---


# Question
Title: Defining tileset for Tiled Terrain Brush — incorrect tiles selected at transitions
I'm using TilEd (https://mapeditor.org) to make maps, and so far have used the programs Terrain feature to create water/paths etc no problem.

I'm trying to create trees now, and I've been at it a whole day and cannot figure out what I'm doing wrong. Have tried countless variations of sizes but here's what i'm currently using:

Tileset:

Now here's the terrain setup, types TREES and GRASS

Here's what it looks like in the map editor, close, but issues:

Any tips on how to define the terrain in TilEd? Or maybe a link to a working trees terrain pattern so I can compare?

# Answer
Tiled's Terrain system appears to use what are called corner tiles.

That means it uses the following rule to identify what tile to place in each slot:

1. Identify the type of terrain present at each of the four corners of the tile to be placed
2. Find a tile in the tileset that has exactly this pattern of four corner types.

These rules are sufficient to handle tilesets like this one (from this guide):

Notice here that each pattern of corners appears exactly once. Reading across the rows, and listing the corner values clockwise from the top-left of the tile:

1. empty empty dirt empty
2. empty empty dirt dirt
3. empty empty empty dirt
4. dirt dirt empty dirt
5. dirt dirt dirt empty
6. empty dirt dirt empty
7. dirt dirt dirt dirt
8. dirt empty empty dirt
9. dirt empty dirt dirt
10. empty dirt dirt dirt
11. empty dirt empty empty
12. dirt dirt empty empty 13 dirt empty empty empty

(You'll notice this forms a binary code we can use to uniquely look up a tile by an integer bitmask - which is how many of these autotiling systems work under the hood)

But that's not the case for the terrain tileset you've authored:

Note that from the perspective of the Tiled program, both these marked tiles have exactly the same corner pattern: grass trees grass grass.

So wherever Tiled sees a tile that needs "grass trees grass grass" it uses one of these, picked arbitrarily (maybe the first or last one it found in its internal ordering), without further deliberation about which tile might fit better.

In this case, you want it to pick the right-hand tile when the tile above it is "trees trees trees grass" and choose the left-hand tile otherwise - but Tiled's terrain system doesn't look further than the current tile's corners to make that selection.

If you want a more global rule to be used in selecting these corners, that will be left up to you.
> 0 votes

# Answer
You're using the wrong tiles. This here  (the corner) is taken from the "grass" tileset at coordinates (1; 1). Replace it with (4; 3) from the tree tileset.

Same thing with this edge

Don't mix the tilesets up. Use the tree tileset when you're creating a forest and the grass tileset, when you're creating an opening in it.
> 0 votes

---
Tags: tiles, tiled
---


# Question
Title: How to use 2D textures in OpenGL / WebGL for physics
Following along the answer here, it was mentioned about textures:

> They can also store things like velocities. For example, you can use a texture as a "flow field" for animating particles or other objects. They can even be used to control geometry. You can sample a texture in a vertex shader, for example, and use the result to determine how to transform the vertex.

That is a new idea to me, using it for physics stuff! That is pretty cool.

I am implementing a 2D game where there will be basic physics like gravity, light shining, things rotating and orbiting like planets, things moving fast and slow, plants blowing in the wind, things flying and flapping wings, things cracking like rocks, water flowing (simple 2D water, nothing fancy), smoke billowing, etc.

I'm wondering some specific ways I can apply textures and shaders to these physics problems, rather than implementing them on the CPU like you typically see. My understanding of shaders so far is that they are purely for mapping position and color into the graphics renderer, so that's all I'm using them for currently. But I have tried to imagine how I could use shaders (and now textures) for velocity so I could optimize the calculations for how everything is moving around, and I don't see how it's possible. Same with calculating the geometries. It seems you need that hierarchical calculation (iterative computation) which you can't do in the GPU, for calculating relative positions of all the stuff relative to everything else (or just their parent). But if you could somehow batch GPU calculate that, that would be super cool.

Other physics things that might benefit from the texture system are raycasting. I can imagine having a 2D light like the sun, and it shines and creates shadows on the 2D objects from the side. Wondering what some pseudocode of OpenGL/WebGL might look like for that perhaps (if it is using shaders and textures only). Wondering if it's even possible to get it to work if it's only using shaders and textures, not completely implemented in JavaScript or the main CPU.

Another physics thing is just the motion of things (smoke billowing, wings flapping, water moving or splashing, leaves blowing in wind force, etc.). The sub question is if I can calculate these velocities (and hence, positions) directly using WebGL/OpenGL/the GPU, not simply calculating them on the CPU. Wondering if you could direct me to any resources/examples demonstrating how to do this in greater detail.

But the main question is simply if one could explain how you would go about generally implementing raycasting, velocity calculations, or other force calculations, using only shaders and textures, and/or perhaps some resources that describe how to do this. I would like to implement these in my game and there is a big architectural difference implementing them in shaders/textures vs. on the CPU, so it would be helpful to figure this out first.

# Answer
> 3 votes
I can't possibly cover everything, nor do I know every technique... in fact, I am unfamiliar with OpenGL 4.0 and newer. yet, I think I know enough to expand the way you think about this. However, have it clear thet there is much more to say about every technique, I am not going into technical detail, no code (it would be a lot) and very little math.

*I suggest to make narrower questions, then answers can be deeper and less broad.*

Before I go into shaders and what not, I want to mention that iterative algorithms in GPU are possible, and very useful. However I would recomend against walking an object hierarchy in GPU.

---

## Vertex types

There are multiple types of shaders. The two more common are: vertex shaders and fragment shaders, which I will go into in more detail. I also want to mention geometry shaders and compute shaders.

As far as I can tell common GPU models out there has poor performance on geometry shaders, reason why I avoid using these.

About compute shaders, I am not the right person to ask. Although, you should probably look into them.

---

**Inputs**

Know that you can send data to the GPU in at least these ways:

* Textures that you will be able to query on the GPU
* Vertex data, such as position, color, normal, etc...
* Uniform values that are not attached to a given vertex or texture

Also know that the shader program could be manipulated as a string before uploading to the GPU. Doing this to inline values that are not meant to change during the lifetime of the application - for example user settings - can improve performance. In fact, you could trim out entire portions of the shader program if the user has disabled visual effects.

Aside from that uniform values are useful to pass information that does not change during the frame and could affect all of it. The best use is passing time, allowing the GPU to know the time allows the GPU to do animations.

For instance, if I want to do morph target animations in GPU, I pass as vertex data the last position, the last time, the future position and the future time, and then as uniform I pass the current time and have code in the shader program to interpolate. Similar techniques can be used to animate a day/night cycle and stuff like that.

---

**Output**

As per getting data out of the GPU to the CPU, that would require to draw to a texture. And of course the output texture can be the input for another GPU call.

*Note: in some cases you can also do multi pass renders for a single frame (by not cleaning buffers between them), that is not what I mean by using a texture as input. We will see below.*

---

## Vertex Shaders

You have send some vertex data to the GPU, and the vertex shader will run on each vertex and allow you to manipulate it. If you want to change the position of something in GPU, here is where you do it.

---

**Wind**

Let us say we want to have a tree swing in the wind. But... updating the position of each vertex in CPU is time consuming. No problem, we can offset each position in the vertex shader.

How much to offset the vertex by? Well, for a simple model, we can use the vertical position of the tree (so that the higher the more swing), which we would multiply with a sort of wave changing in time... that can be done with a 1D perlin noise and the time uniform as input, and perhaps a third parameter to tweak how stiff the tree is.

Alright, but... computing perlin noise on the GPU? We can do better. Generate a 1D texture (it is an array, ok?) with 1D perlin noise in CPU and upload it to the GPU.

A similar approach can be used for water. In 3D you can animate the high of water to make waves. That would also work in 2D... but, I will come back to that.

---

**Gravity and particles**

Things fall, right? We can pass starting position, starting velocity and starting time as vertex data, and gravitational acceleration and time as uniforms. Then the GPU can compute the displacement for the current time and offset the vertex by that amount. Simple.

In fact, if you want particle effect this a way to do it. You would have some buffer space dedicated to particles, then when you need to an explosion you write on vertex on the buffer the starting position and some velocities (which you can have pre computed, just copy them to the buffer) and have the GPU animate them.

You can do similarly for rain and snow. In fact, that wind effect will probably look good if you apply it to snow too. Or similarly for falling leaves.

Note: Since you will have some dedicated buffer space for particles, there will be a maximum number of particles on the game at any given moment (a particles budget if you like). And this will have a performance impact. Thus, I would like to encourage to let the user change it via configuration.

---

**Orbit and pendulums**

You got the idea by this point. You will be moving the vertex coordinates according to a circular path (you can also do elliptic path or similar), using the polar equation for the orbit you want.

To do it, you pass the start angle (or you compute it on GPU) and time as vertex data. If you need to, you can pass rotation speed as a uniform (or inline it as a literal in the shader program) and have the GPU compute the current position.

The same idea will work for pendulums, and thus for flapping things.

---

**Others**

Go back to the idea of morph target animation. You can have multiple kinds of interpolations to do all sort of things. For example, if you need an object to fall to the ground and bounce lower and lower until it stops... well, guess what, that is a valid interpolation curve between the starting point and the ground※.

※: Which will be valid as long as the ground does not move and no obstacle gets in the way. You could check for obstacles, which will require the involment of the CPU, and update the animation if needed. That means that your CPU code changes from computing the position each frame to deciding a trajectory and checking if it is still valid... for which the code is basically continuous collision detection.

---

**Addemdum: Flow fields**

To make your flow field create a texture where each texel represents a vector (each color channel for a coordinate). You also need a position where the flow field is and a its size.

If you want to animate particles to follow the flow field you need to find where on the flow field the particle is. Apply the appropiate transformation to the position of the particle according to the size and position of the flow field and query it texture. Now you have a vector that tells you how to move the particle.

Remember, you are passing time as a uniform, so you can animate the movement. However, within the realm of my knowledge, getting the updated position of the particle to feedback in would be a hassle.

Addendum: Apparently Transform Feedback helps with this.

---

## Fragment Shader

The fragment shader will run per output pixel. You will pass information from the vertex shader to the fragment shader, and - usually - these gets interpolated between the shaders.

This allows you to have - for example - the position of the pixel in 3D (it is the interpolation of the positions of the vertex of the primitive - triangle or squad - that define it), also interpolated normals, texture coordinates, etc.

Note: you also have access to uniforms here.

A common task in fragment shaders is to take these values and use them to look up in textures.

---

## Fragment Shader 3D effects

**Directional light**

Very simple: compute how close the normal matches the direction of the source of the light and use it to change the color of the pixel, for example by blending with the color of the light.

---

**Fog**

Also straight forward: compute the distance from the origin (the camera) and use it to blend the pixel color with the fog color.

---

**Spotlights and shadows**

*We are getting somewhere...*

I will describe an old school technique: we are going to make a source of light with a viewing volume. So, build a viewing volume you want, such that everyting in view is what will be light. For example, it can be a street lamp looking down.

Once you have your viewing volume, use it as camera and render the scene to a texture. However, only the depth buffer.

Place the camera where you need it, upload the depth buffer you extracted as a texture to the GPU, and pass the information of the light viewing volume as uniforms. In the fragment buffer, compute where it falls in the view from the source of light, with that position query the depth buffer texture you uploaded, and if the pixel position is futher away than what the depth buffer says... it means something else is closer to the light source, thus that pixel is in shadow. Otherwise it is in light. Adjust the color of the pixel accordingly.

Of course you could also change the position of the source of light from one frame to the other. And of course you could also have multiple sources of light. Note that with this approach each light is a render pass to extract the depth buffer, and you can only have a finite number of uniforms... so, you will be forced to pick what lights are relevant to the scene (which usually means the sun and whatever is close to player).

In fact, you can tell if the player is in light or in shadow by checking in the depth buffer for the sun the position of the camera. If you check this between frames, you can find the moment where the player steps to the light or to the shadow, allowing you to, for example, animate a gamma correction to mimic the eyes adjusting to light or dark, or you could add a light source near the camera to mimic a headlamp.

---

**Ray-casting**

*I'm not a hero, I'm not a savior, forget what you know.*

We will only place a geometry that covers the view (a single quad can do), and then in the fragment shader we will be running once per pixel on this quad. Start by computing a ray director vector with the position of the vertex and the origin. That will be the ray. We will advance with it...

We will need the geometry of the environment, but not in vertex data (as I said, we are only covering the view with vertex), instead we want the geometry in textures.

First we need to find what is closer in the general direction of the ray. Using a cube skybox instead of a single quad can help, because then we can use the vertex data to save us some time. We have six general directions. We can then partition our geometry data accordingly and that will make the query easier. There are other approaches, of course.

Note: some medical imaging software use a similar approach to present a 3D view of volumetric scans of body parts (MRI and similar). They use a point cloud data loaded as a 3D texture to represent the object to render.

How do we represent the geometry? You have a lot of freedom for this. We are no longer constrained to triangles and quads. For example, we can describe actual curve surfaces.

One approach is to inch your way with the ray. You make a loop and each iteration you advance the ray, then you need to find the nearest object (you may for example use a 3D texture where each voxel tells you the nearest object to that coordinate with some resolution) and try to collide with it.

I want to suggest an alternative… I confess I haven't fully figured out the data-structures for 3D, however the following will work: start with an oct-tree, and dump it three times to a texture, one per axis. So that in the GPU we can traverse it in any of these axis. Knowing the position of the camera and the general direction of the ray we can pick on what axis to traverse the data, from where and in what direction.

You could have a colliding volume (I suggest a sphere) for each object described in a texture that we query in the fragment shader. Then we can intercept the ray with the colliding volume to find if it can collide with a given object, that is a potential hit.

*Yes, this whole thing is a loop until we find a hit. Yes, iterative computation.*

For each potential hit we would then check against the geometry of that object, described however you want to describe it (as long as we can check collision with our ray director vector). You would then go on to query the texture for the object, compute normals and apply lights.

---

Ray-casting will be bound by the number of pixels on screen instead of by the number of polygons, that can make performance better or worse depending on the scene you are rendering. It is great for indoor scenes where rays do not have to travel too far.

You can combine it with the traditional approach too. For example, you can render all the static stuff (floors, walls, stairs, etc...) with ray-casting, and then do another render pass to put in entities and particle effects. *There are a few gotchas when trying to use this approach, such as transparency and shadows.*

---

## Fragment Shader 2D effects

**Water (simple)**

I said I would go back to that 2D water. If you have a side view (as in most 2D platformers, at least the good ones) and you want to animate the edge of water... with polygons you need a lot and it can be a mess.

Do not fret. All you need to do is decide what fragments to drop. If you can describe the wave on the edge of the body of water with a math formula (with a time parameter to animate it, of course), it is trivial to check if a given pixel is above or below the curve and use this to decide if you will drop the fragment. By dropping all the fragments above the curve you are giving a curve edge to your triangle or quad.

We can go futher... let us say that you want to update the animation so that when an object falls into the water it changes the waves. Well, no problem. What you need is to have multiple parametric wave functions that you can combine. One will be the motion of water when nothing has dropped in (say for example ocean waves). The others you will have a center position, an intensity and a start time as parameters, such that changing the time will also make them fade out. Then combine them in GPU.

There will be a fixed number of these waves and you set them one by one each time something falls in water, when you get to the end, simply go back to the first and continue. Assuming there are enough waves and they fade out quickly enough, people should not notice.

---

**Fire**

One way to do them is with particles effects. Here is another way that works for 2D...

We can do fire with a very old school feedback loop.

You will be rendering to a texture that you will then use to represent the fire or smoke. This texture will be initialized empty, but with a seed texel (texture pixel) of another color. Each frame, you will apply a kind of kernel (think convolution) that will update the texture.

The rules for the update are basically that fire moves up, and fire cools down. You can add noise to make it more realistic.

However, the player will not see this texture, instead you will combine it with another texture to give it color.

I'll refer you to Playing with fire – WebGL fire simulation for more information.

---

**Terrain**

If we are doing a 2d top view (as in most 2D RPGs, at least the good ones) you will want to render a lot of terrain, usually in the form of tiles.

Pass a quad for each tile? Nope. Pass a single quad for the whole thing, you can place it at the far plane. Then pass a texture where each texel represent a type of tile, and another texture that serve as atlas for all the tile textures, and the position of the camera as uniform.

In the GPU you will compute for each pixel of this quad, on what tile it is (by using the position of the camera), then query the first texture to get the kind of tile, and then query the second texture to get the color.

You can go a step further and pick a texture based not only on the texture of the current tile, but also consider the textures of the neighbor tiles.

---

**Water (complex)**

A 2D fluid simulation for side view is possible. They are a cellular automata. Use similar ideas as the ones above: have a texture tell how much water is in each tile, and we will update this texture each frame.

Initialize the water texture with a pixel of water for each tile that has water and obstacle pixels to make the tank and floors.

The rules to update the texture are basically that water falls, has a maximum density, flows to the sides when it can't fall and does not go through obstacles.

And again, it is not this texture what you render. This texture has a resolution of tiles, and you will be deciding how to render it considering neighbor tiles...

For instance, if the current tile is 50% water and the pixel below is an obstacle, then it is a tile with the bottom half full. If it is 50% water, nothing on the sides or below, but water on top, then it is the tip of a stream of water falling down. If it is 50% water, nothing below, but there is water at the sides then it is part of a wide stream. Etc.

---

**Light**

Again in a 2D top view, there are have lamps and we want to cast shadows. You can do this as line of side checks. However we want to do it on the GPU...

You can do ray-casting! In fact, since you only need 1D for each lamp, you can do them all at once.

Remember, we will be rendering to a texture first...

Have another squad that covers the view. Each row will be a light, each column will be an angle. Take the position of the pixel and figure out what lamb on what angle is that. With that you create a ray director vector that you can use to advance.

We can do something similar to what I was describing about the cube on ray-casting for 3D but for 2D. You would split the screen in four quads vertically. So that each quad correspond to one of the four cardinal directions...

Then you can have a texture with the objects data. In fact, two copies of the data of the objects, one has them arranged vertically and one have them arranged horizontally.

Take the position of the current light (which you pass uniform), and the cardinal direction (which you pass as vertex data), and that will tell you from where and in what order to go over the texture with the objects data. You iterate over the objects data until you find an obstacle. Output a color that represents how far did you have to iterate.

The resulting texture can be used to query if an object is illuminated by a given light by checking if the value in the texture represents a distance lower than the distance to the light. If it is lower, then that means another objects blocks the light.

---

## Collision detection

Put all your collision detection in terms of ray-casts... many game engines has a ray-cast method for this kind of things, it usually works on CPU, we want GPU.

Then we can do all the ray-casts in one pass (or a few). Render to texture, use a quad covering the view, the data of each ray-cast will be in a texture you pass as input.

Take the current pixel position and use it to query the data for the ray that corresponds to it. Build the ray director vector, and proceed to do the ray-casting.

The output texture has the result of your ray-casts.

---

this is not a bad idea anyway. For instance, you have a 3D game where the avatar can jump. You will not check for collision between the avatar and the ground, instead you do a ray-cast to the ground.

Careful, if the source of the ray happens to be below the ground, it will not detect the ground and your avatar will just fall through it. I want to strongly suggest continuous physic simulation to avoid this kind of thing.

---

**Continuous physics simulation with ray-casting**

*The geometry for collision detection is not the geometry the player sees.*

As you know, we use collision volumes. We will do something similar. However, we will not use discrete collision detection, but continuous instead. That means that the approach is not move, check if collide, fix... instead it is check if it will collide then move accordingly.

To deal with moving objects we will create ghost collision volumes that cover the start position of the object and where it will be. *Donnie Darko comes to mind.*

We can figure out where an object will be next frame either by physics or by following animation (or both) depending what we are doing.

The ghost collision volume does not need to be perfect, it is a heuristic. And the easier to check in ray-casting the better. We can model it as cylinder. So we have start position and a director vector (of the motion) that describe a center line for the cylinder, and a thickness that should cover the size of the object. Do not worry of it extending beyond the movement of one frame. Now the ray-cast against the ghost volume reduces to distance line to line. If the distance is less than the width of the cylinder (the size of the object) we have a potential collision.

Next you need to figure out the point where the ray intercepts the cylinder. That is the point on the ray that has distance to the center line of the cylinder equal to the thickness of the cylinder. You can project this point to the center line to find the point on the cylinder. *No, that is not the closest point, but it is the point we care about, because it is where the object would be on collision.*

Since we know how fast the object moves, we know at what instant it would reach the position of collision, and we can check if it is in the future and before the next frame. If it is in the past, no collision. If it is beyond the next frame, no collision. If it is in the future and before the next frame... well, how good do you want the detection collection to be? You could check against the geometry of the object in that instant to refine the collision detection, or just call it a collision.

Once you have your collision, get the time of collision. There other objects to check and some of them could collide before, we want the earliest collision.

*Yes, you can do all that in the GPU, in a fragment shader, rendering to texture.*

---
Tags: opengl, physics, shaders, textures, webgl
---


title: On escape key click make object visible

text:
# Question
Title: On escape key click make object visible
I am using the following code which works, But the first time i press escape nothing happens, if i press it again then the game object shows. Does anyone know why this is?

```
   using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PauseScript : MonoBehaviour
{
    public GameObject PauseMenu;
    bool Paused = false;

    // Start is called before the first frame update
    void Start()
    {
        PauseMenu.gameObject.SetActive(false);

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown("escape"))
        {
            if (Paused == true)
            {
                Time.timeScale = 1.0f;
                PauseMenu.gameObject.SetActive(true);
                Paused = false;
            }
            else
            {
                Time.timeScale = 0.0f;
                PauseMenu.gameObject.SetActive(false);
                Paused = true;
            }
        }
    }
}

```

# Answer
When you start the game, you are deactivating your `PauseMenu` and initializing your `Paused` bool to `false`.

The first time you press the escape key, you are following the else path of your if statement and deactivating the `PauseMenu` again, so nothing will appear.

If I understand correctly what you are trying to do, you simply need to swap your `SetActive(true)` and `SetActive(false)` calls in `Update()`.
> 1 votes

---
Tags: unity, c#
---


# Question
Title: NavMesh - Changing Mesh by Jumping upwards
I have been playing around with the NavMesh and I have seen that there are different situations where an agent has to change meshes.

# When it works:

Everything seems to work alright with links, if I try to make the agent **jump from a mesh to another one**, tweaking the "Jump distance" paramenter

Another scenario is when the agent needs to **fall to another mesh** to reach the target. This one also works, when I tweak the "Drop height" parameter.

# When it does NOT work

But there are 2 different scenarios, where the agent cant reach the target. The first one is when the agent must **jump upwards** instead of dropping.

And the other scenario is when the agent needs to **fall to another mesh that is not directly below** the one he is standing on.

How could I do so that the agent jumps either to move upwards, or to land in a lower mesh?

# Answer
> 1 votes
I managed to use `OffMeshLink` component to jump upwards. I did not try the last scenario you mention, but it should work too. Put the start link at the bottom, end link at the top and tick bi-directional.

`OffMeshLink` component allows you to incorporate navigation shortcuts which cannot be represented using a walkable surface. For example, jumping over a ditch or a fence, or opening a door before walking through it, can all be described as Off-mesh links. Here's the documentation for it.

---
Tags: unity, ai, navmesh
---


# Question
Title: How do you upgrade your Unity license from Plus to Pro?
If I buy a Plus license for Unity for only one month, can I upgrade that license from Plus to Pro in the next month? Or I am in am annual commitment to renew only the Plus license?

If I need to upgrade from Plus license to Pro license a month after publication, what do I do?

# Answer
This is covered in the FAQ of the Unity Plus License:

> **What happens if I upgrade to a higher tier during my commitment period?**
>
> If you upgrade during a commitment period, you will have to commit for a new period of at least 12 months. For example, if you choose to upgrade to Unity Pro 6 months into a 12 month subscription to Plus, you will have to start a new 12 month commitment period for Pro. The prior commitment period for Plus will be removed.

So yes, you can upgrade from Plus to Pro at any time. When you do that, your Plus subscription ends (even if still in the commitment period) and a new Pro subscription begins (restarting the commitment period).

**Note to future visitors:** Back in our time Unity used to change their licensing terms quite often. They might still be doing that in your time. So you might want to verify that the FAQ still says what it said back in March 2019.
> 2 votes

---
Tags: unity, licensing
---


title: OpenGL frustum extraction

text:
# Question
Title: OpenGL frustum extraction
I'm trying to extract frustum planes from the camera.

The algorithm is simple:

1. create clip to world space matrix (inversed projection * inversed view)
2. multiply clip point by clip to world matrix
3. divide xyz by w

This worked fine with glm and c++, but in c# with openTK doesn't.

It might be something with row and column major matrices of openTK (matrix order is reversed).

Frustum is updated on start and when entity is moved.

Can anyone spot the mistake?

I am using entity component system just like in unity.

Monkey head entity has a second component that is using transform.getForward() and transform.Position to create camera/view matrix. Camera is facing forward with the monkey head. Images are of monkey head as it moves forward.

Here is the code:

```
class Frustum
    {
        /*frustum in world space
        0                                               1
        (1,1,1)-----------------------------------------(-1,1,1)
        |                                               |
        |           4                       5           |
        |       (1,1,-1)----------------(-1,1,-1)       |
        |           |                       |           |
        |           |                       |           |
        |           |                       |           |
        |           |                       |           |
        |           |                       |           |
        |           |                       |           |
        |       (1,-1,-1)----------------(-1,-1,-1)     |
        |           7                       6           |
        |                                               |
        |                                               |
        (1,-1,1)----------------------------------------(-1,-1,1)
        3                                               2
        */

        public Frustum()
        {
            worldPoints = new Vector3[8];
            clipPoints = new Vector4[8];
            planes = new Plane[6];

            for (int i = 0; i < 6; ++i)
                planes[i] = new Plane();

            //frusum in clip space
            clipPoints[0] = new Vector4(-1,1,1,1);
            clipPoints[1] = new Vector4(1,1,1,1);
            clipPoints[2] = new Vector4(1,-1,1,1);
            clipPoints[3] = new Vector4(-1,-1,1,1);

            clipPoints[4] = new Vector4(-1,1,-1,1);
            clipPoints[5] = new Vector4(1,1,-1,1);
            clipPoints[6] = new Vector4(1,-1,-1,1);
            clipPoints[7] = new Vector4(-1,-1,-1,1);
        }

        public void Update(Matrix4 cameraMatrixInverted, Matrix4 projectionMatrixInverted)
        {
            Matrix4 clipToWorld = projectionMatrixInverted * cameraMatrixInverted;

            UpdateFrustumPoints(clipToWorld);
            UpdateFrustumPlanes();
        }

        private void UpdateFrustumPoints(Matrix4 clipToWorld)
        {
            for (int i = 0; i < 8; ++i)
            {
                Vector4 wp = clipToWorld * clipPoints[i];
                wp.W = 1.0f / wp.W;
                worldPoints[i] = wp.Xyz * wp.W;
            }
        }

        private void UpdateFrustumPlanes()
        {
            Vector3 n;
            Vector3 a, b;

            //back      ok
            a = worldPoints[6] - worldPoints[7];
            b = worldPoints[4] - worldPoints[7];

            n = Vector3.Cross(a,b).Normalized();
            planes[0].normal = n;
            planes[0].distance = Vector3.Dot(n, worldPoints[7]);

            //up        ok
            a = worldPoints[5] - worldPoints[4];
            b = worldPoints[0] - worldPoints[4];

            n = Vector3.Cross(a, b).Normalized();
            planes[1].normal = n;
            planes[1].distance = Vector3.Dot(n, worldPoints[4]);

            //down      ok
            a = worldPoints[2] - worldPoints[3];
            b = worldPoints[7] - worldPoints[3];

            n = Vector3.Cross(a, b).Normalized();
            planes[2].normal = n;
            planes[2].distance = Vector3.Dot(n, worldPoints[3]);

            //left      ok
            a = worldPoints[7] - worldPoints[3];
            b = worldPoints[0] - worldPoints[3];

            n = Vector3.Cross(a, b).Normalized();
            planes[3].normal = n;
            planes[3].distance = Vector3.Dot(n, worldPoints[3]);

            //right     ok
            a = worldPoints[1] - worldPoints[2];
            b = worldPoints[6] - worldPoints[2];

            n = Vector3.Cross(a, b).Normalized();
            planes[4].normal = n;
            planes[4].distance = Vector3.Dot(n, worldPoints[2]);

            //front     ok
            n = -planes[0].normal;
            planes[5].normal = n;
            planes[5].distance = Vector3.Dot(n, worldPoints[3]);
        }

        public void DrawFrustum(Vector3 color)
        {
            var debug = DebugS.GetInstance();

            debug.DrawLine(worldPoints[0], worldPoints[1], color);
            debug.DrawLine(worldPoints[1], worldPoints[2], color);
            debug.DrawLine(worldPoints[2], worldPoints[3], color);
            debug.DrawLine(worldPoints[3], worldPoints[0], color);

            debug.DrawLine(worldPoints[0], worldPoints[4], color);
            debug.DrawLine(worldPoints[1], worldPoints[5], color);
            debug.DrawLine(worldPoints[2], worldPoints[6], color);
            debug.DrawLine(worldPoints[3], worldPoints[7], color);

            debug.DrawLine(worldPoints[4], worldPoints[5], color);
            debug.DrawLine(worldPoints[5], worldPoints[6], color);
            debug.DrawLine(worldPoints[6], worldPoints[7], color);
            debug.DrawLine(worldPoints[7], worldPoints[4], color);
        }

        private Vector3[] worldPoints;
        private Vector4[] clipPoints;
        private Plane[] planes;
    }

```

# Answer
In openTK you need to transpose matrices to make it work.

Green lines are frustum in world space.

```
public void Update(Matrix4 cameraMatrixInverse, Matrix4 projectionMatrixInverse)
            {
                cameraMatrixInverse.Transpose();
                projectionMatrixInverse.Transpose();

                Matrix4 clipToWorld = cameraMatrixInverse * projectionMatrixInverse;

                UpdateFrustumPoints(clipToWorld);
                UpdateFrustumPlanes();
            }

```
> 2 votes

---
Tags: c#, opengl, opentk, frustum, projection-matrix
---


# Question
Title: Comparing the scale and rotation of (otherwise) identical meshes from vertex data
I am designing a tool that can read an obj file with duplicate meshes in, and export the transformation, scaling and rotation of each duplicate relative to the original model. I can establish the transform from the average of all the vertexes, and I think I can get scale by comparing the maximum and minimum x,y and z values, but I'm completely stumped on rotation. Does anyone have any advice re this?

# Answer
For identical meshes, this should be relatively easy, as opposed to the harder case of pointclouds with unknown correspondence.

In your case, you can just pick an arbitrary triangle, let's say the first one in the (identical) mesh.

And then find the transformation that transforms triangle T0 into triangle T1.

Additionally, there is also a method for mapping point clouds that are noisy, yet have known correspondence.
> 1 votes

---
Tags: opengl, 3d-meshes, point-cloud
---


# Question
Title: Binary space partitioning with floor as an object
I have a conceptual problem. The problems comes with the floor I'm rendering and the count of objects. The idea was to reduce rendering with BSP implementation, but the problem that I hit was that the floor has huge object (triangles that range through the entire scene). Should I put those objects into the parent nodes of the BSP or try to split them into smaller triangles.

# Answer
Yes, split them.

The concept of BSP trees is almost as old as it's possible for something to be, in terms of graphics programming. Their use dates back to the Quake engine in 1996, and the Quake engine and its tools provide a sample implementation that has since been released under the GNU GPL, although you should be aware that the code isn't quite up to modern standards.

Nonetheless,

Michael Abrash's Graphics Programming Black Book also provides some conceptual discussion of BSP trees in its later chapters, as well as some sample code of more generic implementations, and this is also available for free online in multiple places, for example: http://www.jagregory.com/abrash-black-book/ (look from Chapter 59 onwards).
> 1 votes

# Answer
I found this lecture quite usefull to understand when to cut objects. http://ksuweb.kennesaw.edu/~plaval//math4490/bsp.pdf
> 0 votes

---
Tags: rendering, algorithm, binary-space-partitioning
---


# Question
Title: Box2D physics are different on server and client
I'm using C# Box2D library for my server and client, they have similar world.step(), iterations and update function. At the same time they have different physics' results, difference is not fixed, it may be 1-2% or more than 10%. My timestep is 0.02f and 10 iterations(for both). Code of the client and the server is almost the same. I believe it's because of I have the same timestep on both, server and client, but their code execution speed may be quite different. How can I get the same results in different applications/on different computers?

# Answer
Getting two physics systems to do exactly the same thing is a very difficult problem that requires having the physics simulations be entirely deterministic. Even incredibly tiny differences between the two will accumulate into wildly different outcomes given time. Searching about Box2D determinism it seems that you can't count on that in this case due to differences in how different processors handle their floating point math.

That being said, you say that the simulations are still relatively close, so what you can do is allow the client to run its simulation, but periodically have the server send state to the client for it to update its model. Doing things this way *does* mean that the client's version of things will differ in small ways a fair amount of the time so you can't rely on anything the client system says happened until the server verifies... but really for a networked game that is already the case.

The key is going to be to find a happy balance between fluidity (client simulated) and correctness (server simulated) so the game feels as good as possible on all sides while still having all the meaningful gameplay elements in the right places. If you've got purely decorative elements like physics based particle explosions that don't move gameplay elements, feel free to not even bother syncing those and let the simulations fly!
> 1 votes

---
Tags: c#, physics, box2d, physics-engine
---


# Question
Title: Performance of delta force-esque voxel terrain
I've been reading about voxel terrain lately and often see people asserting that it will absolutely kill performance.

What I don't understand is how games like Delta Force managed to have smooth voxel terrain without all these alleged performance issues? Sure, their terrain doesn't look cutting edge but it certainly doesn't (seem to) impose very harsh performance requirements.

Is Delta Force perhaps not actually using voxels for their terrain? How exactly does their engine work and why don't people use the same techniques today?

# Answer
*Rendering* in a certain way, i.e. vertical scanline rendering, as in e.g. Voxlap, *can* be quite slow, because accessing pixels / fragments on modern GPUs is substantially different from the DMA on older video cards, which is part of what solutions like Voxlap use to achieve high performance. This may be where online sources have confused you.

There's nothing inherently slow about a voxel heightmap data structure. It's faster than running through a dense 3D grid to render data, for reasons of data quantity: the curse of dimensionality.

Having said that, per-pixel rendering of complex voxel fields may be costly if not well-optimised but is far from impossible, see for example Voxel Quest and Voxel Farm, and even the much-mocked Euclideon. In fact these are all more complex by far than heightmaps, because they are use 3D grid data which also allows for overhangs; yet they still run at respectable frame rates.

Non-sparse 3D grids are far more challenging for a CPU or GPU to process due to the sheer quantity of data involved, but the abovementioned projects are implemented using sparse, surface-describing 3D data structures such as octrees, KD-trees, and / or point clouds, while the majority of the internal volume (behind walls and floors) is *implicit* (meaning it need not be stored at all). This keeps data quantity down, allowing for rapid throughput when rendering.

You can trust that Delta Force uses voxels. Another approach became more widespread for the creation of high levels of detail - namely, triangle-based meshes. Both of these approaches to rendering came to the fore in the '70s to '80s, but voxels, offering only a blocky description of form (especially on those old systems) fell by the wayside in most cases. Only a few niche contenders carried on using it, and NovaLogic was one of them.
> 1 votes

---
Tags: performance, terrain, voxels, terrain-rendering
---


# Question
Title: When does it make sense to use Index Buffers?
The concept of Index buffers is that certain vertices are shared across faces, hence can be reused to save space of duplicated verticies. A vertex is usually more than 12 bytes (depending on the number of attributes, ie. 3\* 32-bit floats), while an index could be stored in as little as 1 to 4 bytes (depending on max number of vertices).

> **Example:** A cube consisting of 6 quad-faces without using an index buffer would require `6 * 4 * 12 = 288 bytes` But as it only has 8 unique vertices, it could be stored using an index buffer with 4 * 6 indices = `8 * 12 + 4 * 6 = 120 bytes`

However for non-shared vertices the space used by the Index Buffer is effectively wasted - because these vertices could've been drawn without an index buffer (if correct ordering in the vertex buffer is given). Considering only the vertex position as attribute, this trade-off would make sense for most meshes - but meshes in the real-world tend to have also other attributes like normals, texture-coordinates etc. Even if a vertex position is shared across faces, it is rare that all other attributes are also shared - hence the vertex needs to be duplicated in the vertex buffer.

> **Example:** A cube with normals has 8 unique vertices, but each of its 6 faces having a different normal vector. So 48 unique vertices are required, if one vertex is 24 bytes this results in = `8 * 6 * 24 = 1152 bytes` Using an index buffer the same size is needed plus at least 48 bytes to store the indices = `1200 bytes`

Not only would a vertex buffer without index buffer need less memory, it would probably be more cache-friendly as well (as the memory accessed is continous memory).

I try to find out in which scenarios I should use an index buffer instead of a plain vertex buffer, but I failed to find any real-world examples where it would make sense to use an index buffer at all.

**My question is:** Are there any cases in modern graphics-programming where using an index buffer will actually bring a benefit (ie. is there any advantage which I overlooked)?

# Answer
The example you use of a cube is a very specific, and somewhat contrived, one where indexing does not provide it's full benefit. For most real-world examples the constraints you mention do not exist, and indexing has been demonstrated - for approx 20 years - to be effective. This is something that goes back to at least Quake 3 in 1999:

> Quake3’s rendering architecture has been defined with the primary goal of minimizing API calls and focusing as much work as possible in a single place to make optimization more productive.
>
> During gameplay, 99.9% of all primitives go through a single API point:
>
> glDrawElements( GL\_TRIANGLES, numIndexes, GL\_UNSIGNED\_INT, indexes );

I'd encourage you to look at examples such as the Stanford Bunny, which is more representative of the kind of data real applications use. That has 35947 vertices and 69451 triangles, or in other words 35947 vertices and 208353 indices. So therefore each vertex is reused on average 5.7 times.

Saving memory is the naive advantage of indexing. The other two advantages, which are far more important, are:

* Allowing your GPUs vertex cache to work. What this means is that if a recently transformed vertex is reused, it does not need to be transformed again.
* Concatenating primitives. A mesh composed of multiple strips and fans can be handled in a single draw call instead of multiple, and we all like reducing our draw call count.

The important thing to realise is that *even if none of the other advantages apply*, being able to concatenate primitives and reduce CPU overhead for a very small trade-off of slightly increased memory usage is a good thing.

So the answer to your question - when does it make sense to use index buffers - is actually **almost always**.
> 6 votes

---
Tags: graphics-programming, vertex, index-buffer
---


# Question
Title: I'm still not sure how to control each door individual?
What I want to do is something more or less very simple. The main bool flag lockDoors control all the doors and this is working fine now. But now I want to add a flag to each individual door so I can change the door lock state for each specific door. And if I change the lockDoors state it will change all the doors except if I changed some individuals.

I tried to add a new class name DoorControl and made it also Serializable but not sure if this is the way and how to do it.

Example of how it should look like in the Inspector:

```
lockDoors checkbox here (This is the flag for all the doors) and then:

Door1
   checkbox here
Door2
   checkbox here
Door3
   checkbox here

```

So I can keep controlling the whole doors or each door individual.

```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class DoorsLockManager : MonoBehaviour
{
    [System.Serializable]
    public class DoorControl
    {
        public bool doorLock;
    }

    public bool lockDoors = false;
    public List<HoriDoorManager> _doors = new List<HoriDoorManager>();
    public DoorControl[] doorscontrol;

    private bool[] doorsLocks;
    private Renderer rend;
    private Shader unlitcolor;
    private List<GameObject> DoorShieldFXLocked = new List<GameObject>();

    private void Start()
    {
        DoorShieldFXLocked = GameObject.FindGameObjectsWithTag("DoorShield").ToList();
        unlitcolor = Shader.Find("Unlit/ShieldFX");

        var doors = GameObject.FindGameObjectsWithTag("Door");
        foreach (var door in doors)
        {
            _doors.Add(door.GetComponent<HoriDoorManager>());
        }

        doorscontrol = new DoorControl[_doors.Count];

        ChangeDoorsLockStates();
    }

    private void Update()
    {
        ChangeDoorsLockStates();
    }

    private void ChangeDoorsLockStates()
    {
        for (int i = 0; i < DoorShieldFXLocked.Count; i++)
        {
            if (lockDoors == true)
            {
                ChangeColors(Color.red, Color.green, i);
            }
            else
            {
                ChangeColors(Color.red, Color.green, i);
            }
        }

        for (int x = 0; x < _doors.Count; x++)
        {
            if (lockDoors == true)
            {
                LockDoor(x);
            }
            else
            {
                UnlockDoor(x);
            }
        }
    }

    private void ChangeColors(Color32 lockedColor, Color32 unlockedColor, int index)
    {
        var renderer = DoorShieldFXLocked[index].GetComponent<Renderer>();
        renderer.material.shader = Shader.Find("Unlit/ShieldFX");

        if (lockDoors == true)
        {
            renderer.material.SetColor("_MainColor", lockedColor);
        }
        else
        {
            renderer.material.SetColor("_MainColor", unlockedColor);
        }
    }

    public void LockDoor(int doorIndex)
    {
        _doors[doorIndex].ChangeLockState(true);
    }
    public void UnlockDoor(int doorIndex)
    {
        _doors[doorIndex].ChangeLockState(false);
    }
}

```

And this script is attached to each door:

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class HoriDoorManager : MonoBehaviour
{
    private List<DoorHori> doors = new List<DoorHori>();
    private bool doorLockState;

    private void Start()
    {
        if (transform.parent != null)
        {
            Transform parent = transform.parent;
            var children = parent.GetComponentsInChildren<Transform>();

            if(children != null)
            {
                foreach (Transform door in children)
                {
                    if (door.name == "Door_Left" || door.name == "Door_Right")
                        doors.Add(door.GetComponent<DoorHori>());
                }
            }
        }
    }

    void OnTriggerEnter()
    {
        if (doorLockState == false)
        {
            if (doors != null)
            {
               for(int i =0; i < doors.Count; i++)
                {
                    doors[i].OpenDoor();
                }
            }
        }
    }

    public void ChangeLockState(bool lockState)
    {
        doorLockState = lockState;
    }
}

```

# Answer
> 1 votes
Okay I just did a mockup of what I think it is you want:

```
//each door has a DoorControl object which holds the bool variables and handles
//changing the variables
[System.Serializable]
public class DoorControl
{
    public bool doorLock;
    public bool doorLockOverride;

    public DoorControl(bool doorLock = true, bool doorLockOverride = false)
    {
        this.doorLock = doorLock;
        this.doorLockOverride = doorLockOverride;
    }

    public void SetDoorLockState(bool val)
    {
        doorLock = val;
    }
}

public class Door : MonoBehaviour
{
    public DoorControl thisDoorControl;

    private void Start()
    {
        thisDoorControl = new DoorControl();
    }

    private void Update()
    {
        if (thisDoorControl.doorLockOverride)
        {
            OpenDoor();
            return;
        }
        if (thisDoorControl.doorLock)
        {
            OpenDoor();
        }
        else
        {
            CloseDoor();
        }
    }

    private void OpenDoor()
    {
        //open your door
    }

    private void CloseDoor()
    {
        //close your door
    }
}

```

You could then reference each doors `DoorControl` in your manager class and stuff it into a `List<DoorControl>` or an `DoorControl[]` array like this:

```
public class DoorManager : MonoBehaviour
{
    public List<Door> doors = new List<Door>();
    public List<DoorControl> doorControls = new List<DoorControl>();

    //this is just to initialize the list with values from all the doors. You could
    //assign those directly in the inspector
    private void Start()
    {
        foreach(var door in doors)
        {
            doorControls.Add(door.thisDoorControl);
        }
    }

    public void ChangeAllLockOverrides(bool val)
    {
        foreach(var door in doorControls)
        {
            door.doorLockOverride = val;
        }
    }
}

```

The manager then looks like this in the inspector:

Keep in mind that this will open/close the door every frame because I call it in `Update`. This is no good solution and you should not copy paste this if you plan to keep your performance as high as possible. I hope this points you in the right direction.

# Answer
> 1 votes
It's been a while since I used Unity since I moved to UE4, but since no one else is answering, I will try.

I think in this case you should "turn around" the control from doors "asking" about a boolean, and instead, have each door have an individual bool for them. Then, a switch, lever or whatever you are using would have an inspector field "Door to open" of type Door of course. And when you use that switch, you call this door's method to open them.

Obviously, to future proof the game you might use an array of fields so you can open more than one door with one switch if you so desire.

Another way, possibly closer to what you want is this.

A door controller class has the main bool, and an array of bools for each doors. Each door checks the main bool and specific one. And every lever or switch has a variable called "doors index" of type int. Then on usage you would do something along this pseudo-code:

OnLeverUsed{ DoorController-\>doorsOpened\[doors index\] = true; }

I hope this answers your question :)

---
Tags: unity, c#
---


# Question
Title: RTS Balancing for Units with Different Costs
I am creating a space-based RTS. So far, we have three units:

Fighters (cost 5 resources)

Interceptors (cost 20)

Rocket Ships (cost 40).

I've designed this game in a Rock-Paper-Scissors format (Fighters beat Interceptors, Interceptors beat Rocket Ships, Rocket Ships beat Fighters), but the game is designed so that classes beat each other *at cost* (i.e. a single Interceptor will beat a single Fighter, but four Fighters (cost 20) will beat a single Interceptor (cost 20)).

In this case, when I am using the Incomplete Wins technique to calculate the proportions of each ship that I would expect to see, should I calculate interactions using 1v1 interactions or "at cost" interactions? I believe the two will lead to very different results (for example, a single Fighter does 20% of damage to Interceptor before it itself is destroyed, but four Fighters destroy the Interceptor while only losing one ship; the first interaction leads to a 1 resource advantage for the Interceptor player, while the second interaction leads to a 15 resource advantage for the Fighter player). I would think it I should do the latter comparison, but the linked page does a single unit comparison (one Knight vs one Archer, even though Knight costs half that of Archer)

**EDIT:** This RTS is partially derived from Total Annihilation/Supreme Commander, so no projectiles hit instantly and the scale of the game is intended to be somewhat large. In that case, should I instead perform comparisons between armies that cost the same? For example, instead of comparing one Fighter vs one Interceptor or four Fighters vs one Interceptor, should I instead compare 40 Fighters vs 10 Interceptors? Would that be more accurate and also help reduce randomness of projectile hits?

# Answer
(moving my comments to an answer) TL;DR: I think you're using the wrong tool for the job here.

> game is designed so that classes beat each other at cost

This is, by definition, not an intransitive system. If each pair of classes has some equilibrium where the equally-costed groups stalemate with each other, then you're merely described a Rock-SmallRock-LargeRock system, not a Rock-Paper-Scissors system, and it would be pretty boring. If the break-even costs are different for each pair, then you can't analyze it with the win value matrix since the values for each row and column describe different things.

> should I calculate interactions using 1v1 interactions or "at cost" interactions

The balance matrix system assumes discrete decisions. This means "should I build A or B?". Which means it's not a great model for an RTS unit balance. But if you insist on analyzing your balance this way you will definitely need to normalize by cost. If you don't, then you have a GrainofSand-Paper-Scissors system where Scissors is never in danger of being beaten and thus dominates everything else. As you mentioned in your example, the 4 fighters is more than 4 times as efficient than a single fighter due to how power scales with additional units.

> should I instead perform comparisons between armies that cost the same

Scaling up the numbers shouldn't affect the outcome since the values in your matrix are about expected win value.
> 4 votes

# Answer
The other answers cover a lot of points I'd make extremely well, so not going to repeat that advice.

I would add that the "maths" is only a starting point for balance in this kind of scenario, playtesting (and especially automated AI vs AI balancing) is always critical in achieving genuine balance.

Basically there's a whole load of factors that are extremely hard to balance just on maths - as you mentioned, one ship type has considerably longer range than the others. Long range often leads to scenarios where unit number scaling becomes unbalanced - e.g. a hundred rockets are waaaay more than 10x more powerful than ten rockets. But this can also depend on the map/level design - for example if it has lots of tight spaces that make it harder to exploit range/swarm firepower. A very open space is the reverse.

I'd look carefully at how your troop types counter each other:

* Rockets are good against fighters because they have a lot of rapid fire/multi-targeting/area of effect weapons that makes them effective against lots of small, weak ships.
* Interceptors are good against Rockets because they have a very powerful, slow firing weapon that does lots of damage to single, large targets (like Rockets).
* Fighters use weight of numbers. This makes them situationally weak against those fast firing rockets, but strong against the slow firing interceptor (which may get a shot or two off but is quickly overwhelmed).

You can also make arcs of fire and turn rate important to this - maybe rockets have a large fire arc (say 180 degrees), but interceptors have a very narrow one (30 degrees).

As a mental exercise - this kind of scenario seems to lend itself to tactics of 'enough rockets to keep any fighters at bay, then more interceptors than they do'. I think maybe AOE weapons on the Rockets make sense, rewarding good micro/splitting of fighters and making them more practical. You might also want to consider "Carriers" for the fighters, which could help get them closer to the target. Fighters should be relatively cheap as you're going to lose a lot of them.
> 2 votes

# Answer
1. whether one unit of fighters is 1 fighter or 5 fighters should not significantly change anything about how good fighter is. So normalize by cost.
2. You should analyze how they work when used correctly. Therefore ignore that rockets needs scouts (if it's feasible for scout to scout for many rocket's for significant time), or in analysis add fraction of cost of fighter to rocket.
3. You need another analysis for rushing purposes (where 1 fighter can be better than any other unit type, if it destroy their factory before they are built). But in this analysis you don't compare units. You compare player strategies and it depends on map, production model, defense of bases etc.
> 0 votes

---
Tags: game-design, rts, balance
---


# Question
Title: How do you write an unlit shader which supports Ambient Occlusion?
For performance reasons, a scene might use Unlit shaders only.
Is there an Unlit shader which supports Ambient Occlusion?
What is the best way to achieve this look, for moving and static objects, while prioritising performance?

# Answer
One approach is to create AO maps in 3d modelling software (example in blender) and use that in your shader.

```
Shader "Unlit/UnlitColorAO"
{
    Properties
    {
        _Color ("Main Color", Color) = (1,1,1,1)
        //_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}

        _AOTexture ("AO Texture", 2D) = "white" {}
        _AOColor ("AO Color", Color) = (1, 1, 1, 1)
        _AOPower ("AO Texture Power", Range(0, 3)) = 0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            uniform sampler2D _AOTexture;
            uniform fixed4 _AOTexture_ST;
            uniform half3 _AOColor;
            uniform half _AOPower;

            fixed4 _Color;

            static const half3 whiteColor = half3(1, 1, 1);

            struct appdata
            {
                float4 vertex : POSITION;
                half3 normal : NORMAL;
                half3 vColor : COLOR;
                float4 uv0 : TEXCOORD0;
                //float4 uv1 : TEXCOORD1;
            };

            struct v2f
            {
                float4 pos : POSITION;
                //float4 worldPos : TEXCOORD0;
                //float2 uv : TEXCOORD1;
                float2 aouv : TEXCOORD4;

            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                //o.uv = TRANSFORM_TEX(v.uv0, _MainTex);
                o.aouv = TRANSFORM_TEX(v.uv0, _AOTexture);
                return o;
            }

            fixed4 frag (v2f i) : COLOR
            {
                // sample the texture
                //fixed4 col = tex2D(_MainTex, i.pos)*_Color;

                // sample color only.
                fixed4 col = _Color;

                // apply AO
                half4 AOTexVar = lerp(half4(_AOColor, 1), half4(whiteColor, 1), lerp(half4(1,1,1,1), tex2D(_AOTexture, i.aouv), _AOPower));
                col *= AOTexVar;

                return col;
            }
            ENDCG
        }
    }
}

```
> 1 votes

---
Tags: unity, shaders, vertex-shader, ambient-occlusion
---