# Question
Title: Unity - OnTriggerEnter & OnTriggerExit strange behavior
I am having a trouble with OnTriggerEnter with a lot of objects.

I have a NavMeshAgent moving randomly throught the scene, then I have a sphere collider inside a children to detect nearby objects. If the object has an allowed tag it adds to the objects\_near List.

It starts working right, but when it is working a few secs it starts dropping the objects\_near variable to a wrong value, sometimes to 0, then, a few minutes later it drops to 0 permanently.

Is it a Unity bug? Is it my fault because I am using a lot of resources?

https://i.stack.imgur.com/cCNft.jpg

```
    void OnTriggerEnter(Collider col)
    {
        string tagname = col.gameObject.tag;

        for (int i = 0; i < tags_allowed.Length; i++)
        {
            if (tags_allowed[i] == tagname)
            {
                objects_near.Add(col.gameObject);
            }
        }
    }

    void OnTriggerExit(Collider col)
    {
        string tagname = col.gameObject.tag;

        for (int i = 0; i < tags_allowed.Length; i++)
        {
            if (tags_allowed[i] == tagname)
            {
                objects_near.Remove(col.gameObject);
            }
        }
    }

```

# Answer
# EDITED:

**Found a solution not using triggers**.

I have removed Triggers functions and changed the functionality.

First I check all the GameObjects in the scene with the allowed tags. (tags\_allowed is a string array).

Then I check the distance from the IA (NavMeshAgent) to each object in the scene with an allowd tag.

If the GameObject detected is near than a distance I add it to the objects\_near List. And if it is not, I remove it.

### void Update()

```
objects_near_tmp = null;
for (int i = 0; i < tags_allowed.Length; i ++)
{
    objects_near_tmp = GameObject.FindGameObjectsWithTag(tags_allowed[i]);
    for (int j = 0; j < objects_near_tmp.Length; j++)
    {
        float dist = Vector3.Distance(objects_near_tmp[j].transform.position, transform.position);
        if (dist < 20f)
        {
            bool add_object_near = true;
            if (objects_near.Count > 0)
            {
                for (int k = 0; k < objects_near.Count; k++)
                {
                    if (objects_near[k] == objects_near_tmp[j])
                    {
                        add_object_near = false;
                    }
                }

                if (add_object_near == true)
                {
                    objects_near.Add(objects_near_tmp[j]);
                }
            }
            else
            {
                objects_near.Add(objects_near_tmp[j]);
            }
        }
        else
        {
            objects_near.Remove(objects_near_tmp[j]);
        }
    }
}

```
> 1 votes

---
Tags: c#, physics, unityscript, collider
---


# Question
Title: How do I make my glsl RGB displacement map look like this
I want to use a RGB texture as described in this video here.

Here is my texture so far.

The author says the first line has no R channel and ranges from B = 0 to B = 255. While each other line has R channel = 255 and B = 255 to B = 0 as seen.

His colors do not match with mine. I wrote my shader like this:

```
  #version 110
  uniform sampler2D texture;
  uniform sampler2D pattern;
  uniform float progress;

  void main()
  {
    vec4 displacement = texture2D(pattern, gl_TexCoord[0].xy);
    displacement = ((displacement * 2.0) - 1.0) * progress;

    vec2 newTexCoord = gl_TexCoord[0].xy + displacement.xy;
    vec4 pixel = texture2D(texture, newTexCoord);

    vec4 color = gl_Color * pixel;
    gl_FragColor = color;
  }

```

which is based off his earlier videos but I'm not getting the effect at all. At best I see interlaced layers moving away but they move diagonally instead of left-right. Plus they clamp instead of leaving black color behind as seen in his video.

Here's what mine looks like: click to view

# Answer
> 1 votes
The black background is easy to solve. You're missing an if statement from the shader.

The other problem is that you forgot to normalize the displacement at one point.

In my opinion there's a much simpler way to solve this that doesn't require a separate texture to work. First, you need to find out which row you're in. To do this simply take `gl_FragCoord.y` and multiply it by the amount of rows you want, then floor the result. The first row will have an index of 0, the second an index of 1 and so on. Every second row should go to the left. To convert the index into a direction simply take the modulo 2 of the index, multiply by 2 and subtract 1:

```
float direction = mod(index, 2) * 2.0 - 1.0;

```

The new texture coordinate is simply the current texture coordinate plus `vec2(direction * progress, 0)`. Also make sure that when the x coordinate of the new uv coordinate falls outside the \[0, 1\] range, then draw black instead to avoid the clamping issue

---
Tags: shaders, glsl, graphic-effects
---


# Question
Title: Where should I store textures for a game?
I am currently creating a game in SFML using C++ and I'm wondering: what is good practise for a location for textures? Should I store it with my project? Or my executable? Or even in something like the Documents folder? What would be the most efficient when the game would theoretically be released, as it will not simply include the project but rather a compiled and build version of it?

# Answer
> 2 votes
Well you want to store any game assets in a place that people won't usually mess with. Putting them in the documents folder will make it likely that someone comes across them, doesn't recognise them and deletes them.

Storing them in the executable file itself will result in the executable getting extremely large as you add more game assets, this isn't a problem by itself depending on how the OS you're running on handels executable files and memory. But if you ever need to update the game, fix a bug, slightly modify a texture, etc. your users will most likely have to redownload the entire file (which can be massive). Keeping your assets separate should allow you to reuse unchanged parts of the game, reducing download times.

Typically games store their assets with the executable in the installation folder. Usually this is inside `ProgramFiles` on windows but can be other places depending on how it's distributed (Steams game folder for instance).

How you handle the files is another matter, as long as you know where the assets are you should be able to load them in using their location on the hard drive. This could be a relative location, like saying `executable path + Resources + image.png` for instance.

The most efficient way to load your data will depend largely on your game and how it uses textures. Are they all on screen at the same time? Then load everything when the level is loaded in. Are your textures larger than what can fit into memory? Then you need to look into texture streaming or make smaller textures. Do you want to load in standard images and parse the data to make it easier to work with or do you really need more speed in which case you can write a program that will parse it into the same memory format that the game will have and then save that binary data so there is slightly less for the engine todo as it loads it.

In the end the most efficient way will change over time as your OS is updated, can vary from platform to platform, and could be different from one machine to another. Best thing is to make something which works well and focus on your game, if it's closer to release and you have loading issues you can always optimize later especially since you will know how the game uses the data and where the bottlenecks are.

Hope this helps

---
Tags: c++, textures, sfml, file
---


# Question
Title: How to remove a scene after the another one has loaded
\]\[\]I'm having this problem in Unity where I load a new scene, but the original is still overlapping it. How would you remove the original scene?

# Answer
There is a function in `Unity.SceneManagment`, called `SceneManager.LoadSceneASync()`, which is used to determine wheather the loading operation is complete.

One way to use it would be call a Coroutine, and make it run until the scene is fully loaded. Once the loading operation is done Unity will then switch to the fully loaded scene.

When you want to load the scene, you do

```
StartCoroutine(LoadYourAsyncScene());

```

Then you create the coroutine:

```
IEnumerator LoadYourAsyncScene()
{
    AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("YourSceneName"); // change "YourSceneName" with the scene you want to load

    // wait until the scene fully loads
    while (!asyncLoad.isDone)
    {
        yield return null;
    }
}

```
> 1 votes

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


# Question
Title: How to create a decent strategy game without becoming an artist?
I love to make games. But I am not an artist. I never learned to make 2d or 3d models. I spent most of my time on programming. I know there are Game engines for non-programmers. But I am looking a way to create a decent strategy game (medieval theme) without spending time to learn how to model 2d or 3d models it is more time consume than learning how to program for an artist.

# Answer
Your options are:

1. **Source assets** that fit your needs, either from free asset collections like OpenGameArt, or by purchasing the assets you want.

The downside with this method is that the selection may be limited, or assets you find might be mismatched with one another or not precisely the right look or internal setup for your needs.
2. **Pay an artist** to create custom art for your game, or to make corrections and adjustments to assets you've obtained through method 1 (providing the licence you have for those assets permits modifications).

Do not expect skilled artists to do this work for free or less than their time & skill is worth. That includes promising payment when the game sells (most game projects never turn a profit).
3. **Choose a style that you can accomplish with your own skills** and the source assets that you can find. That might mean this first game doesn't fit your ideal artistic vision, but with a little luck, you'll build up skills and resources to get closer to your original vision on your next project, or the one after that.

Your first game will not be your best game, so let it be what it is, and find a way to make that work stylistically within your constraints.

I note you've tagged this - this can include things like procedurally generating images and models through code, or amping up the look of plain assets through the use of shader programs. While a medieval setting is not exactly the easiest fit for these techniques, this is another area where you can shape your style to what tools you have available, finding a look of procedural graphics that you can run with to make a consistent visual identity for your game, using your own skills.
> 4 votes

---
Tags: graphics, graphics-programming
---


# Question
Title: Client-side Prediction and Reconciliation for movement
I've explored the concept of client-side prediction with reconciliation quite a bit and there's one thing that puzzles me a lot.

From what I've seen in most guides, the flow looks a bit like this:

T0. Client sends MOVE command and immediately simulates a predicted result.
T0. Server streams gamestate (server does not know about Client's MOVE command yet and thus the T0 gamestate does not contain results for it).
T3. Client receives gamestate T0 from the server. T0 does not contain any movement and thus Client is forced to reconcile with the Server gamestate.

This way, Client will have to reconcile with the Server every tick it receives because they will never agree. If Client would be delayed by ½RTT before predicting, Client and Server should agree most of the time, but that's an unwanted delay.

If the Client submits a tickstamp with each command sent, the server can apply those commands pasttime. But this would mean that the client is authorative because it can make the server reconcile with its commands. There's also an issue here where players with a high latency will be changing a relatively distant past on the server, potentially undoing/invalidating a lot of already streamed gamestates.

I suppose the Client could simply pretend that T3 is T0 (sync to a different server tick depending on how high the latency to Server is) but I don't know the effect of that when interacting with other non-predictable entities (such as other players). I guess the Client would take longer to reconcile with the correct Server gamestate because of the induced "tick latency".

Is there something I'm missing here? Which is the best way forward for a twitch gameplay competitive game? I.e. Air Hockey or similar.

# Answer
> 1 votes
I think the missing piece here is that. **The server is authoritative**. This means that the server state is the source of truth. The client states are just reproductions of the server state.

The server will apply client input packets as they are received. It doesn't care about client timestamps attached to them. As far as the server is concerned it is the source of truth and the clients' input happened when it received it.

The server will then push state snapshots to the clients. Because the server is the source of truth the clients will hard reset to these snapshots. The clients will also keep track of any input they collected since the last server snapshot was taken. They will then play these inputs back to bring it up to speed.

---
Tags: networking, multiplayer, client-server
---


title: Unity3D Door animation help

text:
# Question
Title: Unity3D Door animation help
i've imported a door from blender to unity. it has two animations, open and close.

i've put an animator and script on it, and everything works fine. it opens and closes when i press x using a box collider, just peachy.

the problem is that the door starts out opened when I run the game. I need it to start out closed. i have it set to closed as the default state, thinking that would work, but what happens is w hen you start the game, it just closes immediately, and then you can open it and close it after that. how would I go about setting it to closed when running the game?

# Answer
so from what i can tell is that unity assigns the default position by alphabetical order in your animations. so if you have an animation named close, and an animation named open, it will start at the first frame of the first animation by alphabetical order. being that the animation to close the door starts in the open position, the door will be open by default.

i fixed this by just adding a 1 before open and a 2 before closed.

add an empty default state in your animator that has no motion and has a transition towards open, which then transitions between open and closed, but no transition back to the default state, and it works fine.

if anyone else has a solution that doesn't involve renaming your animations, that would be nice.
> 1 votes

---
Tags: animation
---


# Question
Title: Manipulating time in Unreal messes up Physics simulation?
I'm trying to achive a Super Hot like gameplay, where the **time only flows when the player moves**.

But **when I stop time, then restart it, physics simulation will be messed up.** Like:

* Cloths starts flying around like they are in a tornado.
* Rigidbodies fly away, like they were shot from a cannon.

**All of these without any kind of forces being applied to them.** They were just standing still, I stopped time, then I restarted Time and Booom, rigidbodies fly around.

I use this in the **player's** `Tick` method:

```
auto settings = GetWorld()->GetWorldSettings();
settings->SetTimeDilation(timeScale);

```

# Answer
The reason why this is happening is because the Physics engine also runs on Tick... so when you manipulate the Time Dilation on Tick as well, you're going to run into these problems.

So you've got two possible solutions:

1. Change the order that your Player's Tick method runs in (which you can do by making a child BP and then changing it in the Class Defaults section)... though you might still run into problems since Time Dilation affects the World tick rate, too... so maybe it's just best to try changing your player's Tick rate to Post-Physics.
2. Instead of making the Time Dilate on Tick, you can set a Timer event Delegate to call every 0.1s or something like that and then just pass in your ne

Here's a link explaining some details about manipulating TickGroup in C++: https://answers.unrealengine.com/questions/231386/tickgroup-how-to-understand-that.html
> 1 votes

---
Tags: physics, unreal-4, unreal
---


# Question
Title: How can I achieve a similar day/night cycle of the sky, but in a 2D game?
I'm currently working on a 2D game, and I was wondering if anyone around here has experience/tips in achieving this sort of day/night transition of the sky?

I've done some reading, and some people do it as a shader and change gradient values in the shader; others swap out planes. I've not done anything similar before, thus my question here.

# Answer
For my small needs i only needed to shift the color of my sprites. through those two scripts.

Cycler : singleton, will go through all the registered sprites and change their color

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

public class DNCycler : MonoBehaviour {
    public static DNCycler Handler { get; private set; }

[Header ("Settings:")]

[Tooltip ("Wether or not the system should change the colors of the world.\nIf set to false, the screen will only darken, and colors will remain the same.\nDefault: True")]
public bool colored;

[Tooltip ("The amount of time in seconds between each non animated sprite's color update.")]
/// <summary>
/// The amount of time it takes for non animated sprites and mic to update their colors.
/// </summary>
[Range(0, 5)]public float staticUpdateFreq;

[Tooltip ("The starting cycle.\n0 = day\n1 = dusk\n2 = night\n3 = dawn")]
/// <summary>
/// The starting cycle.
/// </summary>
[Range(0, 3)]public int startingCycle;

[Tooltip ("The delay for when the Day and Night cycle begins. 0 to disable delay.")]
/// <summary>
/// The amount of time for the day night system to start updating colors.
/// </summary>
public float cycleStartDelay;

[Tooltip ("The amount of time in seconds it takes for each day night cycle to pass.")]
/// <summary>
/// The amount of time it takes for each individual cycle.
/// </summary>
public float cycleTime;
float cycleUpdate;

/// <summary>
/// The lists to hold all the renderers.
/// </summary>
List<SpriteRenderer> AnimatedSprites, StaticSprites;
List<Renderer> MiscRenderers;   // Uncomment this and line 147 - 151 and use this list for misc mesh renderers.

[Header ("Color settings")]

/// <summary>
/// The current world color.
/// </summary>
Color mainColor;

[Tooltip ("The color of the concurrent cycle\nNote: The alpha value corresponds to the overall darkness of the screen." +
    " The alpha will reset to 255 during runtime. This is normal.\nHigher alpha value = darker screen.")]
/// <summary>
/// The colors that the system cycles through.
/// </summary>
public Color day, dusk, night, dawn;

/// <summary>
/// The current cycle that the system is on.
/// </summary>
int cycle = 0;

/// <summary>
/// A time variable used for color lerping.
/// </summary>
float t = 0;

/// <summary>
/// Properly starts the color cycling.
/// </summary>
bool started;

/// <summary>
/// Used for the darkening of the screen.
/// </summary>
Image screenDark;
Color scrnColor, scrnDay, scrnDusk, scrnNight, scrnDawn;

// Use this for initialization
void Start () {
    // Sets the main DayNight handler.
    if (Handler != null && Handler != this) {
        Destroy (gameObject);
    } else if (Handler == null) {
        Handler = this;
    }

    // Sets the proper cycle duration for each of the 4 phases
    cycleUpdate = cycleTime / 4;

    // Creates new lists to store all the renderer variables.
    AnimatedSprites = new List<SpriteRenderer> ();
    StaticSprites = new List<SpriteRenderer> ();
    MiscRenderers = new List<Renderer> ();

    // Creates the proper colors for the screen darkening effect.
    scrnDay = new Color (0, 0, 0, day.a);
    scrnDusk = new Color (0, 0, 0, dusk.a);
    scrnNight = new Color (0, 0, 0, night.a);
    scrnDawn = new Color (0, 0, 0, dawn.a);

    // Resets the default colors' alpha to 255.
    day = new Color (day.r, day.g, day.b, 1);
    dusk = new Color (dusk.r, dusk.g, dusk.b, 1);
    night = new Color (night.r, night.g, night.b, 1);
    dawn = new Color (dawn.r, dawn.g, dawn.b, 1);

    // Gets the image needed for the darkening effect.
    screenDark = GetComponentInChildren<Image> ();

    // Jumps to the specified starting cycle.
    JumpToCycle (startingCycle);

    // Starts the delay and the static updates.
    StartCoroutine ("StartDelay");
    InvokeRepeating ("UpdateStatic", cycleStartDelay, staticUpdateFreq);
}

/// <summary>
/// Delays the start.
/// </summary>
/// <returns>The delay.</returns>
IEnumerator StartDelay () {
    yield return new WaitForSeconds (cycleStartDelay);
    started = true;
}

// Update is called once per frame
void Update () {
    if (started && colored) {
        UpdateMainColor ();
        UpdateAnimated ();
    } else if (started && !colored) {
        UpdateNoColor ();
    }
}

/// <summary>
/// Updates the main color to correspond to the current cycle.
/// </summary>
void UpdateMainColor () {
    switch (cycle) {

    case 0:
        mainColor = Color.Lerp (day, dusk, t);
        scrnColor = Color.Lerp (scrnDay, scrnDusk, t);
        break;

    case 1:
        mainColor = Color.Lerp (dusk, night, t);
        scrnColor = Color.Lerp (scrnDusk, scrnNight, t);
        break;

    case 2:
        mainColor = Color.Lerp (night, dawn, t);
        scrnColor = Color.Lerp (scrnNight, scrnDawn, t);
        break;

    case 3:
        mainColor = Color.Lerp (dawn, day, t);
        scrnColor = Color.Lerp (scrnDawn, scrnDay, t);
        break;
    }

    // Resets t variable and increments the cycle.
    if (t < 1) {
        t += Time.deltaTime / cycleUpdate;
    } else {
        t = 0;

        if (cycle < 3) {
            cycle++;
        } else {
            cycle = 0;
        }
    }
}

/// <summary>
/// Updates the main color to correspond to the current cycle when colored option is turned off.
/// </summary>
void UpdateNoColor () {
    switch (cycle) {

    case 0:
        scrnColor = Color.Lerp (scrnDay, scrnDusk, t);
        break;

    case 1:
        scrnColor = Color.Lerp (scrnDusk, scrnNight, t);
        break;

    case 2:
        scrnColor = Color.Lerp (scrnNight, scrnDawn, t);
        break;

    case 3:
        scrnColor = Color.Lerp (scrnDawn, scrnDay, t);
        break;
    }

    // Resets t variable and increments the cycle.
    if (t < 1) {
        t += Time.deltaTime / cycleUpdate;
    } else {
        t = 0;

        if (cycle < 3) {
            cycle++;
        } else {
            cycle = 0;
        }
    }
}

/// <summary>
/// Updates the color for all animated sprites. This has to be called every
/// frame, otherwise the sprites will flash.
/// </summary>
void UpdateAnimated () {
    for (int i = 0; i < AnimatedSprites.Count; i++) {
        if (AnimatedSprites [i].isVisible) {
            AnimatedSprites [i].color = mainColor;
        }
    }
}

/// <summary>
/// Updates static sprites, as well as misc renderers and the ground if used.
/// </summary>
void UpdateStatic () {
    if (colored) {
        for (int i = 0; i < StaticSprites.Count; i++) {
            if (StaticSprites [i].isVisible) {
                StaticSprites [i].color = mainColor;
            }
        }

        for (int i = 0; i < MiscRenderers.Count; i++) {
            if (MiscRenderers [i].isVisible) {
                MiscRenderers [i].material.color = mainColor;
            }
        }
    }

    screenDark.color = scrnColor;
}

/// <summary>
/// Jumps to selected cycle.
/// 0 = day /
/// 1 = dusk /
/// 2 = night /
/// 3 = dawn
/// </summary>
/// <param name="cycle">The cycle to jump to.</param>
public void JumpToCycle (int selCycle) {

    // Error incase the selected cycle doesn't exist.
    if (selCycle < 0 || selCycle > 3) {
        Debug.LogError ("WHOOPSIE DAISY! Looks like you tried to make the day night handler jump to a cycle that doesn't exist." +
            "\nThe JumpToCycle only accepts values from 0 to 3." +
            "\n0 = day" +
            "\n1 = dusk" +
            "\n2 = night" +
            "\n3 = dawn");
    }

    cycle = selCycle;

    switch (cycle) {

    case 0:
        mainColor = day;
        scrnColor = scrnDay;
        break;

    case 1:
        mainColor = dusk;
        scrnColor = scrnDusk;
        break;

    case 2:
        mainColor = night;
        scrnColor = scrnNight;
        break;

    case 3:
        mainColor = dawn;
        scrnColor = scrnDawn;
        break;
    }

    // Updates the static colors to match that of the new cycle selected.
    UpdateStatic ();
}

/// <summary>
/// Registers a sprite renderer to the day night system.
/// </summary>
/// <param name="render">The sprite renderer to register.</param>
/// <param name="animated">Whether or not the sprite is animated.</param>
public void RegRenderer (SpriteRenderer render, bool animated) {
    if (animated) {
        AnimatedSprites.Add (render);
    } else {
        StaticSprites.Add (render);
    }
}

/// <summary>
/// Registers a miscellaneous renderer to the day night system.
/// </summary>
/// <param name="render">The misc renderer to register.</param>
public void RegRenderer (Renderer render) {
    MiscRenderers.Add (render);
}

/// <summary>
/// Removes a sprite renderer from the registry.
/// </summary>
/// <param name="render">The rsprite renderer to delete from the registry.</param>
/// <param name="animated">Whether or not the sprite was animated.</param>
public void DelRenderer (SpriteRenderer render, bool animated) {
    if (animated) {
        AnimatedSprites.Remove (render);
    } else {
        StaticSprites.Remove (render);
    }
}

/// <summary>
/// Removes a miscellaneous renderer from the registry.
/// </summary>
/// <param name="render">The misc renderer to delete from the registry.</param>
public void DelRenderer (Renderer render) {
    MiscRenderers.Remove (render);
}

/// <summary>
/// Returns the current cycle color.
/// </summary>
public Color GetColor () {
    return mainColor;
}

/// <summary>
/// Returns the time value. Used in the shadow handler, but could be useful for other things.
/// </summary>
public float GetTime () {
    return t;
}

/// <summary>
/// Returns the current cycle.
/// </summary>
public int GetCycle () {
    return cycle;
}
}

```

Register: Attached to sprite gameObjects, subscribe/unsubscribe them to the cycler:

```
public class RegisterDN : MonoBehaviour {
/// <summary>
/// The renderer on this object
/// </summary>
private SpriteRenderer spriteRend; //------------} These are the variables you would set to
private Renderer miscRend; //--------------------} public if you keep getting the below errors.

/// <summary>
/// Whether or not the sprite is animated.
/// </summary>
bool animated;

/// <summary>
/// Finds a renderer attached to this object and register it to the day night handler.
/// </summary>
void Start () {
    // Tries to get a sprite renderer if one is not set manually.
    if (spriteRend == null) {
        spriteRend = GetComponent<SpriteRenderer> ();
    }
    // Tries to get a misc renderer if one is not set manually.
    if (miscRend == null) {
        miscRend = GetComponent<Renderer> ();
    }

    // If a sprite is present, checks if it is animated and registers it to the registry.
    if (spriteRend != null) {
        Animator anim = GetComponent<Animator> ();
        if (anim != null) {
            animated = true;
        } else {
            animated = false;
        }

        DNCycler.Handler.RegRenderer (spriteRend, animated);
    }

    // If a sprite is not present and a misc renderer is found, registers that to the registry
    if (miscRend != null && spriteRend == null) {
        DNCycler.Handler.RegRenderer (miscRend);
    }

    // An error in case the script fails to register any renderers.
    if (spriteRend == null && miscRend == null) {
        Debug.LogError ("OOPS! DayNightRegister error in object (" + this.gameObject.name + "): Could not register any renderers." +
            "\nAre you sure there is a renderer attached to this object?" +
            "\nIf this problem persists, and you have a renderer attached to this object. Try setting the 'Rend variables in this script " +
            "\nto public, and setting the variables manually through the inspector." +
            "\nNote: You do not need to set these for all objects. Only (" + this.gameObject.name + ") would need to be set manually.");
    }
}

void OnDestroy () {
    // Delets the renderer from the registry.
    if (spriteRend != null) {
        DNCycler.Handler.DelRenderer (spriteRend, animated);
    }
    if (miscRend != null) {
        DNCycler.Handler.DelRenderer (miscRend);
    }

    // An error in case the script fails to delete any renderers from the registry.
    if (spriteRend == null && miscRend == null) {
        Debug.LogError ("THERE IT GOES AGAIN! DayNightRegister error in object (" + this.gameObject.name + "): Could not delete any renderers from the registry." +
            "\nAre you sure there is a renderer attached to this object?" +
            "\nIf this problem persists, and you have a renderer attached to this object. Try setting the 'Rend variables in this script " +
            "\nto public, and setting the variables manually through the inspector." +
            "\nNote: You do not need to set these for all objects. Only (" + this.gameObject.name + ") would need to be set manually.");
    }
}

```

}

But beware, doing so you will lose Batching, it might not be production ready.
> 3 votes

---
Tags: unity, c#, 2d
---


title: UI Button Click Animation

text:
# Question
Title: UI Button Click Animation
We have animation states for Normal, Highlighted, Pressed and Disabled. How to set animation when a button is clicked?(after button released not pressed)?

Thanks in advance

# Answer
In order to use animations as UI buttons transition, an Animator component should exist. you can generate it.

in the generated animation controller, just drag and drop your animations into the state inspector.

Doc: https://docs.unity3d.com/Manual/script-SelectableTransition.html

Now, in case you want to fire your events AFTER the button click (onPointerUp), you'll have to use Event Trigger component instead.
> 0 votes

---
Tags: unity
---


# Question
Title: Smooth behaviours at high Time.timeScale
When I set the `Time.timeScale` in unity very high, many scripts seem to do werid things (because of the high deltaTime they use for their logic).

Is there an option to let unity split up one update - call with a high deltaTime to multiple calls per frame, each with a lower deltaTime?

# Answer
> -1 votes
# It's impossible.

This is because of interpolation. The point of `Time.deltaTime` is to interpolate in real-time, as opposed to by frame, which it does by giving a number smaller than 1 (in normal circumstances) that is the part of a second it took between the current and previous frame.

Because by-design, `Update()` is called per-frame, after redrawing the screen. You can't call it more times per second as that would mean upping the framerate, and when your computer is going at the fastest it can handle, well, there's your problem.

When you have lots of things in your scene, your framerate goes down, because the computer can't work fast enough to render everything.

It is also worth noting that modifying `Time.timeScale` is the same as simply the same as using `Time.unscaledDeltaTime * Time.timeScale` (or `Time.deltaTime * someScale`, when `Time.timeScale = 1`).

---

> When I set the Time.timeScale in unity very high, many scripts seem to do werid things (because of the high deltaTime they use for their logic).

The way you get a smooth effect is that when there is enough frames, the intepolation is un-noticible, in the same way that computers update their screens faster than our eyes can visually see. Take for example, old-style film and animated flip-books.

When you have a high `Time.timeScale`, or any large number multiplied into `Time.deltaTime`, there simply isn't enough frames in a second to make it look smooth.

It is like the difference between when you attempt to flip a flipbook animation at the fastest you can, and flipping through each page every second.

---

> Is there an option to let unity split up one update - call with a high deltaTime to multiple calls per frame, each with a lower deltaTime?

On a any computer, there's nothing you can do because, well, the computer is already working at its limit. Sure you could try to get a super-beefy computer to get higher framerates, for really large numbers, 60 and 200 frames aren't going to make a difference.

At that point (also a common technique used in cinematography, since everything is capped to 24 frames, for the most part), you would probably want to apply motion blur, but that itself has its own set of problems.

If you want to simply call `Update()` four times, it is just the same as `Time.unscaledDeltaTime * Time.timeScale * 4`, which only worsens the interpolation effect.

Unless that large number represents a small number of pixels on screen, you may **want to decrease the speed your object moves**.

---
Tags: unity, timestep
---


# Question
Title: Game Make Studio 2 - Grid snap x, snap y
I'm following a GM tutorial that was given in 1.4 but I'm using 2, and there's a feature that I can't seem to get working. The developer is basically changing two settings (Snap X and Snap Y) which are located right on the top bar when editing a room. Changing them from 32 to 16 allows him to have a lot more precision when placing objects using grid snapping.

I can't make this work in GMS2. I have found the grid settings under Preferences and can turn grid snapping on and off from there. But the 'Grid Horizontal Spacing' and 'Grid Vertical Spacing' settings don't seem to do anything, I had assumed they would change the snap settings.

Am I doing something wrong or has this functionality changed?

# Answer
There are some icons at the right bottom area of the room editor. Check the first one of them:
> 4 votes

---
Tags: game-maker
---


# Question
Title: How to check if objects are hidden in godot
I have multiple objects, each has area2d and collision shape, I click it, I hide it.

Now, I create script and attach it to the main Node2d with the following

```
extends Node2D

func _ready():
    if (get_node("matchbox_closed").hide() && get_node("oil").hide()):
            get_node("match").show()

```

it hides the first object in the list automatically, what I want is to check not to hide, but I can't see any boolean that check that or any `isvisible` getter like Libgdx

# Answer
From a Godot QA post there should be a method `is_visible()`. Try `get_node("node").is_visible()`. Looking at the docs this method seems to apply to `CanvasItem`, though so perhaps you have to use `CanvasItem`s if you want to check visibility.
> 6 votes

# Answer
The documentation shows that both CanvasItem and Spatial have a `visible` property.

Note that `CanvasItem` is a parent class to both `Control` (used for GUI) and `Node2d` (used for 2d). When considered with `Spatial` (used for 3d) this means `visible` is available for most nodes that can be drawn.
> 0 votes

---
Tags: godot
---


# Question
Title: Saving and Loading File to Application.persistentDataPat not working on Android device
I am trying to save data and load data on the project i am working on, but i cant seem to get it work in an Android device it works fine on Unity when i play it, not sure what i am missing or done wrong here is the following code i use to save and load data.

using System.Collections; using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO;

public class PlayerInfo : MonoBehaviour {

```
 public static PlayerInfo playerData;
 public int gameCoins;

 void OnDisable()
 {
     BinaryFormatter bf = new BinaryFormatter ();
     FileStream file = File.Create (Application.persistentDataPath + "playerinfo.dat");

     PlayerData data = new PlayerData ();
     data.gameCoins = gameCoins;

     bf.Serialize (file, data);
     file.Close ();
 }

 void OnEnable()
 {
     BinaryFormatter bf = new BinaryFormatter ();
     FileStream file = File.Open (Application.persistentDataPath + "playerinfo.dat", FileMode.Open);
     PlayerData data = (PlayerData)bf.Deserialize (file);
     file.Close ();

     gameCoins = data.gameCoins;

 }

 }
 [Serializable]
 class PlayerData
 {
     public int gameCoins;
 }

```

Anyone can give me an idea of what i need to do or look at i will be very much appreciated, and many thanks in advance for taking the time to help.

# Answer
1. Like @Chris suggested, try adding a "/" before the file name. You can make sure by printing out the final path with Debug.Log, even in editor, and making sure the path is ok.
2. Make sure you have external write permissions on the device. You can set this up in the android player settings:
> 0 votes

# Answer
Application.persistentData could be different from whether AndroidManifest has WRITE\_EXTERNAL\_STORAGE permission or not.
> 0 votes

# Answer
I haven't been able to find a solution for this. It seems like opening a FileStream on Android isn't possible. I found this thread which has a work-around. How to use xmlserializer and filestream on android

You have to "download" the file using the WWW class and then you can open a FileStream on the copy.
> 0 votes

# Answer
Honest way is using

```
Path.Combine(Application.persistentDataPath, "playerinfo.dat")

```

And not need to change "Write access"
> -1 votes

---
Tags: savegame
---


# Question
Title: How to Fetch a Frame Number from Animation Clip
I'm trying to find out how to fetch the frame number from an animation clip accurately. I don't want to get a value between 0 and 1 that shows as a percentage-as-a-decimal how much of the animation has played (example: 0.5 = the 5th frame of 10 frames) because it doesn't seem to be accurate. This also seems impractical, so is there a way to accurately fetch a frame number from an animation clip?

Thanks.

# Answer
Assuming you're only using a single layer in your Animator, where `MyAnimator` is a `Animator` component.

```
MyAnimator.GetCurrentAnimatorClipInfo(0)[0].clip.length * (MyAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime % 1) * MyAnimator.GetCurrentAnimatorClipInfo(0)[0].clip.frameRate;

```

Will return the current "frame", which you can then round appropriately to get an integer value, if that's what you would like.

We mod the current animation state info's `normalizedTime` by 1, because looping animations will go above 1.

... And if you have multiple animations playing at once on a single layer (such as when transitioning from one animation state to another), you may need to check the weight(s) of each animation, but you'll probably be able to get away with the above.

To be honest, relying on this value may or may not be the best route, depending on what you want to accomplish. For any frame/time dependent behavior you want to tie into unity's animation system I'd recommend looking at animation events.
> 2 votes

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


# Question
Title: What resolution should I render art for a 3D game for PC?
I hope this is not too stupid a question. I'm making my first game for PC and I'm wondering what resolution I should render the artwork at. It will be a fixed-perspective game, so I'm using a 2D background with 3D characters moving around.

How big should I render the background? Is 1920x1080 enough these days or should I go even higher? How big should the character textures be?

Thanks a lot!

# Answer
The answer is just not specific. What would you like to support? You can supply with the game a background that has a size of 1920x1080, and scale it down for lower resolutions.

Should you go bigger? Sure, if you can afford that, what if someone want's to play your game on a massive 40" screen? You can supply the biggest graphics, but then that one person with a weak machine and a 15" monitor, has to download massive assets to play your game and endure longer loadings.

So pick the highest resolution you want to support, and stick to that, at least when you are talking about 2D graphics. With 3D graphics, things should be easier as they behave like vector images.
> 1 votes

---
Tags: rendering, resolution, pc
---


title: Random Range Without Duplicates

text:
# Question
Title: Random Range Without Duplicates
**I have an array of gameobjects (some questions) if player hit some triggers a question from the array is displayed randomly, I want to avoid duplication of displaying questions.**

```
 public GameObject[] Q;
 public static int ColliderCounter = 0;
 int WrongAnswerCounter = 0;
 public int i,old;

 private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Obstcle")
        {
            i = Random.Range(0, Q.Length);
            old = i;
            ColliderCounter++;
            Q[i].SetActive(true);
            GetComponent<PlayerMovement>().enabled = false;
        }

    }

 IEnumerator waitWrongAnswer()
    {
            WrongAnswerCounter++;

            yield return new WaitForSeconds(3f);
            Q[old].SetActive(false);
            i++;
            Q[i].SetActive(true);
            old = i;
    }

```

**And I want to know how to check if all questions are displayed do something.**

**Thanks in advance**

# Answer
**Common approach**

1. Shuffle your array. A simple Fisher–Yates shuffle will do. The result is that you will have your array of `GameObject` in a random order.
2. When picking a `GameObject` to activate, just pick the next one. To do that, you keep an `int index` field that tells you where you are so far, it starts at zero... then, on the event, you pick the `GameOBject` at that `index`, and increment the `index`.

The result is that they are activated in a random order (because, remember, you did shuffle them) and there is no chance of duplicates.
3. It also very easy to tell when you activated all of the objects (`index == Q.Length`).

To give you an intuition of this method, think of your questions as a deck of cards, you start by shuffling it, and then you deal the cards knowing they are already shuffled. You know that you have dealed all the cards when you reach the end of the deck. There are no duplicates because each card is only once in the deck.

I would advice to implement the Fisher–Yates algorithm yourself, it is only four lines of C#, so do not be intimidated by it.

**Alternative approach**

Let us say that you do not want the order to be selected before hand (even if the user does not know the order). In that case, this is what you do:

1. Have a field `List<int> L` and initialize it with the numbers from `0` to `Q.Length - 1` inclusive (this is a simple for loop, or a linq query if you want to be fancy - don't be fancy).
2. When picking `GameObject` to activate, select an `int index` at random from `0` to `L.Count - 1` inclusive (you do something similar to this in your code) and activate `Q[L[index]]` (that is the element of `Q` which index is the element of `L` which index is `index`). Afterwards, remove it from the list (`L.RemoveAt(index)`).

As you can see, you are selecting the items at random from a list that contains all items yet to be selected. By removing the one selected each time, you make sure that there are no duplicates.
3. It is very easy to tell when you are done (`L.Count == 0`).

To give you an intuition of this method, imagine each question is a person, and each person has a number, then you make papers with the numbers of each person and throw them into a bag, and take them one by one - at random - you know that you have taken all when the bag is empty. There are no duplicates because you do not add the same number in the bag twice.

Have a read about `Random.Range`, notice that it returns a `float`, also notice that both `min` and `max` are inclusive (they are possible results).

---

**Notes**

The alternative method is more memory intensive than the common one because it requires to create a new list.

The only advantage that the alternative method has is that it makes it easier to implement a save and load feature such that the questions that are yet to be revealed appear in a different order on every load. This is still possible with the common approach, however it requires a careful re-shuffle (re-shuffle only the questions yet to be revealed).

Notice also that logic of both methods is similar in abstract terms. The main difference is that common approach is eager to randomize, while the alternative is lazy.
> 5 votes

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


# Question
Title: Develop on Oculus Go using Java and OpenGL
I have recently done some game development using Java and OpenGL (with the JOGL library), and I was thinking about trying to learn how to develop on an Oculus GO. However, all guides seem to assume that the developer is going to use Unity. Is it possible to develop Oculus GO applications with Java and OpenGL directly? Is there any good documentation or guides for this?

# Answer
Quoting the Oculus Mobile SDK documentation:

> The Oculus Mobile SDK includes libraries, tools, and resources for native development for Oculus Go and Gear VR.
>
> **SDK Contents**
>
> * VrApi for third-party engine integration (not required for Unity or Unreal).
> * Native application framework for building high-performance VR Applications from scratch.
> * Native project sample applications and source to provide reference model for creating your own VR applications.
> * Tools and resources to assist with native development.
> ...
>
> **Developing for Oculus Go and Gear VR**
>
> For the most part, developing apps for Oculus Go and Gear VR is the same.

So yes, development without an existing engine like Unity is supported, and the Oculus site provides documentation about how to set up your Java development environment to do this, along with sample projects.

In future, please do not neglect to read the manufacturer's published documentation when you have a question about what their products support - they're the best authorities on this topic.
> 2 votes

---
Tags: java, virtual-reality, jogl, oculus
---


title: Darkness Emitting Light Source Unity

text:
# Question
Title: Darkness Emitting Light Source Unity
I was wondering if it was possible to create a light source in Unity, one that "sucks" light from the environment.

Negative value does not seem to work in Unity, as pointed out by many.

It is quite surprising that there is nothing that I could find that has information on this topic. All year old posts that mentioned this contained only dead links.

# Answer
It's possible to get this effect if you programmatically set the color value of the light with negative values.

For instance, light.color = new Color(-1f,-1f,-1f); //C#

The values are clamped if you try to set them in the editor, but through code it works just fine. You can also use this to go above the 1.0 value limit if Unity's cap on light brightness is giving you trouble.
> 4 votes

# Answer
In **Deferred Lighting mode only**, you can hack the light's color to be negative. Since the built-in color selector is clamped to normalized colors, you cannot use it. You can set negative colors from code, like, `l.color = new Color(-0.4f, -0.4f, -0.4f, 1);` or just use the following script and attach it to a light, then hack as you like.

```
using UnityEngine;

[ExecuteInEditMode]
[RequireComponent(typeof(Light))]
public class HackedLight : MonoBehaviour {

    public Vector4 hackColor;
    public float multiplier = 1;

    void Update ()
    {
        var light = GetComponent<Light>();
        light.color = new Color(hackColor.x, hackColor.y, hackColor.z, hackColor.w) * multiplier;
    }
}

```
> 1 votes

# Answer
There is an asset called Foggy Lights which "appears" to be able to do this. I haven't tested it myself but it uses custom, alpha blended lights to create dark volumes. Check it out here, there's a screenshot towards the bottom of the page: http://forum.unity3d.com/threads/foggy-lights.239062/page-2
> 0 votes

# Answer
I know there are other answers, but I wanted to contribute to the idea pool here with another option for future readers. Others have already stated you can simply modify the `Color` property of the `Light` object to achieve this; however, a smooth and versatile option would be to implement a `DarkZone` that has a falloff.

---

## Basic Application

To apply this idea in it's basic form, you could just loop over every light in the scene, and change the `Intensity` of each light that is close enough to the `DarkZone`:

```
// Pseudo code.
Dictionary<Light, float> originalIntensities = new Dictionary<Light, float>();
DarkZone darkness = new DarkZone();
foreach (Light l in lights) {
    if (!originals.ContainsKey(l))
        originals.Add(l, l.Intensity);

    float length = (darkness.Position - l.Position).Length();
    if (length < darkness.Radius)
        l.Intensity = (originals[l] - darkness.Intensity) * distance;
}

```

Where `distance` is some `float` value between `0` and `1`.

---

## Explanation

The basic example above will have the following effects:

* Closer lights will be completely turned off.
* Distant lights will be minimally impacted.

The example can be (and needs to be) expanded to gradually kill light in the surrounding area. This is a nice and smooth technique for accomplishing the effect, and is more appealing than the option of strictly killing the lights within the effective radius. Achieving that is more simplistic, but more grotesque compared to the example given above.

```
// Pseudo code.
foreach (Light l in lights) {
    if (!originals.ContainsKey(l))
        originals.Add(l, l.Intensity);

    float length = (darkness.Position - l.Position).Length();
    l.Intensity = length < darkness.Radius ? 0 : originals[l];
}

```

---

## Important Note

Storing the original intensities is a very important part of this example. Reason being, if you have a `Light` with an intensity of `0.5` and you move the `DarkZone` away from it, without the original intensity stored off, how do you know what to set it back to? Setting it to `1` may just have bad effects if that `Light` in particular is set to `0.5` for a reason.
> -1 votes

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


# Question
Title: elements of list are changing their values
I'm making an app that's similar to an alarm, the user enters time and days, for days I'm using toggles,and storing the values of toggles states in a list which is stored in a list that contain all the inputs of the type days, then the user could edit any of his inputs, his old input are supposed to be shown there , but the problem is even when I'm storing them, old values are changing when I add new elements,(that's when currentToggle is changing) so when he press edit values aren't the same as he entered them

I think it has something to do with nested lists but I can't figure out how, ( assigning hours and minutes is perfectly working and both are normal lists)

the confirm method is for when the user confirm his choice, and there's edit button that open a panel ,its values are the same as the user entered them before

the index gives the number of the selected group of input, dayholder is the gameobject that contains all the toggles , and that's the part of the code that's related to what I've said

```
Toggle[] toggles;
List<bool> currentToggle = new List<bool>();
List <List<bool>> daysAll = new List<List<bool>>();

void Start () {
    toggles = dayHolder.GetComponentsInChildren<Toggle>();
}
public void confirm()
{

    checkON();
    daysAll.Add(currentToggle);
}
 public void editBut()
{
    GameObject panelC = EventSystem.current.currentSelectedGameObject.gameObject.transform.parent.gameObject;
    int index = panelC.transform.parent.gameObject.transform.GetSiblingIndex();
    assignDays(index);
}
void assignDays(int index)
{
    for (int i = 0; i < daysAll[index].Count; i++)
    {
        if (daysAll[index][i] == true)
            toggles[i].isOn = true;
    }
}
public void checkON()
{
    currentToggle.RemoveAll(item => item != null);
    for (int i = 0; i < toggles.Length; i++)
    {
        if (toggles[i].isOn)
            currentToggle.Add(true);
        else
            currentToggle.Add(false);
    }

}

```

# Answer
> 0 votes
It's a bit hard to say without a more complete example, but from what we can see so far, it looks like you're populating your `currentToggle` list using the current states of the `Toggle` components configured by the user, then putting that list into your `toggles` list.

Are you assuming that this creates a *copy* of the `currentToggle` list, saving its values so that the next time you call `checkON()` and clear the list, the previous copies saved in `toggles` should retain their values?

If so, that could be the cause of the error you describe. Lists in C# are reference types, meaning that when you write

```
myListOfLists.Add(myList);

```

you're storing a *reference to* `myList` into `myListOfLists` \- and that reference still points to the same data structure / the same memory as the `myList` variable. No data has been copied, so if you later change the contents `myList`, you're also changing the contents of the version referenced via `myListOfLists`.

If you want to clone a list, so that the clone retains its values no matter what you do to the original list, you can instead write:

```
myListOfLists.Add(new List(myList));

```

which will retain the list's Add/Remove functionality, or

```
myListOfArrays.Add(myList.ToArray());

```

if you don't need to resize the collection again, and can deal with the copy as a fixed-size collection going forward.

You could also use the `CopyTo()` methods to write your list's contents into an existing array, to save allocating fresh memory for the copy.

---
Tags: unity
---


# Question
Title: Which DirectX Version to use for a low poly game?
Which DirectX Version (10, 11 or 12) is recommended to use, if you want to have a low-poly game with shaders, shadow and aliasing. But not normal or height maps. Moreover my question is, because once we upgraded from directx 9 to 11 now, the GPU usage for the game was like duplicated. I can not even play it with CPU at all. It means directx 11 has higher usage even then 9.

If using Directx10, could it help to decrease the gpu usage? (Which was caused by directx upgrade)

# Answer
You generally want to use the latest version that is compatible with your target platform. For most people that means DirectX11, since DirectX12 is not supported on versions of Windows (i.e. Windows 7) that are still widely used.

But, with every version, you need to make sure that you are using it in the most efficient way. Just swapping the calls for the newer version won't necessarily work efficiently, and you may also need to make changes to your resources to make them work with the new version. If you do this correctly, you should not find that DirectX11 is slower than DirectX9.
> 3 votes

---
Tags: directx, directx11, directx9, directx10
---


# Question
Title: Splice enemy array to destroy enemy (js game)
I am currently working on a basic space invaders game. So far I have created the enemies, a main character, and a laser beam, collision detection between enemy and bullet, however when my bullet collides with my enemy sometimes one enemy is destroyed other times all or a couple of enemies are destroyed. Can you please inform me in what I am doing wrong.

```
this.crashWith = function(otherobj) {
    var myleft = this.x;
    var myright = this.x + (this.width);
    var mytop = this.y;
    var mybottom = this.y + (this.height);
    var otherleft = otherobj.x;
    var otherright = otherobj.x + (otherobj.width);
    var othertop = otherobj.y;
    var otherbottom = otherobj.y + (otherobj.height);
    var crash = true;
    if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
        crash = false;
    }
    return crash;
}
}

 function updateGameArea() {
var x, y;
for (y = 0; y < myObstacles.length; y += 1) {
    if (myGamePiece.crashWith(myObstacles[y])) {
        var ctx = myGameArea.context;
         ctx.fillText("Game Over", 150, 150);
         myGameArea.stop();

    }
 for (i = 0; i < bullets.length; i += 1) {
  if(myObstacles[y].crashWith(bullets[i])) {
   myObstacles.splice(myObstacles[y], 1);
}
}
}

```

Thank you in advance.

# Answer
> 0 votes
The way I solved this is by splicing one enemy from the array of enemies when they collide with the bullet array. Then I would splice one bullet as well. Below is the basic collision and removal of the enemy.

```
this.crashWith = function(otherobj) {
    var myleft = this.x;
    var myright = this.x + (this.width);
    var mytop = this.y;
    var mybottom = this.y + (this.height);
    var otherleft = otherobj.x;
    var otherright = otherobj.x + (otherobj.width);
    var othertop = otherobj.y;
    var otherbottom = otherobj.y + (otherobj.height);
    var crash = true;
    if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
        crash = false;
    }
    return crash;
}
}

  function updateGameArea() {
   var x, height, gap, minHeight, maxHeight, minGap, maxGap;
   for (y = 0; y < myObstacles.length; y += 1) {
        if (myGamePiece.crashWith(myObstacles[y])) {
           myGameArea.stop();
           return;
       }
     for (i = 0; i < bullets.length; i += 1) {
        if(myObstacles[y].crashWith(bullets[i])) {
          myObstacles.splice(y, 1);
          bullets.splice(i, 1);
         }
      }
     }

```

# Answer
> 0 votes
When you splice array, you remove the element. In your case, you are iterating over 'myObstacles' from 0 to length-1. When splicing arrray in such manner you need to iterate from length-1 to 0, so the indexes od 'myObstacles' are not changed. Like this:

```
for (y = myObstacles.length - 1; y >=0; y--)

```

Then you continue to iterate bullets over the myObstacles\[y\], which might at that point already be removed. After splicing array, you need to **break** from the for loop.

# Answer
> -1 votes
You can try to use other iterable objects than arrays, they allow faster and easier deletion and accessing of elements, which makes them more suitable for handling collections of game objects. Check Map or Set API.

---
Tags: collision-detection, javascript, html-canvas
---


# Question
Title: game maker place_meeting multiple objects
I am working on a simple game that contains two objects the player and the ground, and I used place\_meeting to make the player walk on the ground object and it works fine but when I try to add another object to make the player walk on it, it didn't work and the game freeze, here is my code:

```
// vertical collision
if place_meeting(x,y+vsp,ground1) or place_meeting(x,y+vsp,ground2)
{
while ((!place_meeting(x,y+sign(vsp),ground1 )) or (!place_meeting(x,y+sign(vsp),oground1=2 )))

 y+=sign(vsp);

    if (sign(vsp) ==1)
    {
    grounded = 1;
    }

    vsp =0;

 }
else
{
grounded = 0;
}
y+= vsp;

```

# Answer
> 4 votes
You will get into all sorts of problems with complex if statements. Here is the solution I use, and it works for any number of grounds.

1. Define an object `obj_ground`. Put no code in this object, and do not define a sprite.
2. Create your two types ground objects.
3. For each of your ground objects, define `obj_ground` as their parent. This means that every time you reference `obj_ground`, you check both! Look up parent and child in the user manual, it is one of the tools that makes GameMaker so good.

# Answer
> 0 votes
I am to understand that **ground1** and **ground2** are your 2 types of walkable objects.

So, on line 3 of your code, in your while loop, the object in your last check is incorrect. It shoud be **(!place\_meeting(x,y+sign(vsp),ground2 ))**

```
while ((!place_meeting(x,y+sign(vsp),ground1 )) or (!place_meeting(x,y+sign(vsp),ground2 )))

```

Try that.

# Answer
> 0 votes
Here's mine

```
//Horizontal Collision
if (place_meeting(x+hspeed,y,obj_wall))
{
    while(!place_meeting(x+sign(hspeed),y,obj_wall))
    {
        x += sign(hspeed);
    }
    hspeed = 0;
}
x += hspeed;

//Vertical Collision
if (place_meeting(x,y+vspeed,obj_wall))
{
    while(!place_meeting(x,y+sign(vspeed),obj_wall))
    {
        y += sign(vspeed);
    }
    vspeed = 0;
}
y += vspeed;

```

---
Tags: game-maker
---


title: Water cut off effect in UE4

text:
# Question
Title: Water cut off effect in UE4
Working on a side scroller game in **Unreal Engine 4** and I need to create a **water cut off effect** like seen in the screenshot of Ori and the Blind forest.

Basically need a side perspective on water bodies like lakes and ponds where I can see objects underwater as well as above water. Water may be subject to ripples and disturbances (caused by player or fish swimming in the water).

Thanks

# Answer
> 1 votes
I asked this question to Antoine Louisia, his answer - "The mesh i used to create this water is a cube, and i added vertex color (G Channel) only on the top of this cube. This way, you get a mask that you may use for the displacement and the foam (not for the color), so it doesnt affect the sides of your cube. They may be a lot of other ways to achieve this, but this one works perfectly fine !"

---
Tags: shaders, unreal-4, water
---


title: Cannot access an animation from script

text:
# Question
Title: Cannot access an animation from script
I want to change the reload speed of my player when a button is pressed in the pause menu.

I created a button and attached the following script to it (as suggested by the documentation here: https://docs.unity3d.com/ScriptReference/AnimationState-speed.html ):

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

public class PauseUpgrade : MonoBehaviour {

public Animation reloadAnim;
private float startSpeed;
// Use this for initialization
void Start () {
    startSpeed = reloadAnim["Reloading"].speed;
}

public void upgradeSpeed()
{
    reloadAnim["Reloading"].speed += 0.5f;
}

```

But this does not work. I cannot seem to drag the reload animation into the public variable declared above. Is this the correct way to solve this?

The above image shows my animation controller for my player. I am trying to change the speed of the "reloading" animation clip.

I am trying to drap the animation clip from my projects folder into the public variable below, but I get a cross sign preventing me from dragging it in as if its the wrong type or something.

Thanks

# Answer
> 0 votes
I managed to solve this. Unity provided a solution for this but is not clear in the documentation. It has been explained in detail here: https://forum.unity.com/threads/mecanim-change-animation-speed-of-specific-animation-or-layers.160395/page-2

To summarize(as provided by gevarre):

Goal: Change the playback speed of a particular Mechanim animation state in script at runtime.

> 1. Set up the states in an Animation Controller. (We'll call the animation state we want to change "VariableAnimState".)
> 2. In the Animator Controller editor window, select the "Parameters" tab.
> 3. Click the "+" sign and create a float parameter.
> 4. Name this new float parameter "VariableAnimSpeed".
> 5. By default, the value of the float will be 0, so change it to 1 (If you want the animation to start at normal speed...)
> 6. Now select the animation state that you want to change so you can see it in the inspector. (In our case, it's VariableAnimState)
> 7. In the inspector, notice there is a field labeled "Speed". Leave this at default, which will normally be 1.
> 8. Below the Speed field, there is a blank field labeled "Multiplier". Click the checkbox to the right of it labeled "Parameter".
> 9. Now back in the Multiplier field, click the dropdown arrow and select the parameter you want to control it. (In our case it's "VariableAnimSpeed")
>
> Note: if you don't create the float parameter first, you will get an error. You have now finished setup.
>
> 10. In script, here are the relevant bits. Change as needed:

```
public Animator animator;

void ChangeStateSpeed()
{
    animator.SetFloat("VariableAnimSpeed", 2.0f);
}

```

---
Tags: unity, animation
---


# Question
Title: Unity3D Orbit around orbiting object (transform.RotateAround)
The best way to explain this is I'm attempting to make a small model solar system (not to scale or anything complicated, just simple rotation as a learning exercise). There's a sun, a planet, and that planet's moon. The planet orbits like normal, however the moon orbiting around the planet shoots off and makes an extremely large and far-away orbit.

My code is as follows (where "target" is the object being orbited around, and "transform" is the orbiting object itself. Both are "Transform" objects.):

```
public class RotateAndOrbit : MonoBehaviour {
    public Transform target;
    public float RotationSpeed = 100f;
    public float OrbitDegrees = 1f;
    void Update () {
       transform.Rotate(Vector3.up, RotationSpeed * Time.deltaTime);
       transform.RotateAround(target.position, Vector3.up, OrbitDegrees);
    }
}

```

I'm not sure how to compensate for this or even what my mistake is called, but any help would be appreciated.

# Answer
> 9 votes
Make the moon a child of the planet object, and the planet a child of the star. Now, if the moon wasn't orbiting, it will stay with the planet in its orbit.

You can easily rotate an arbitrary point around another arbitrary point with the following:

```
public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Quaternion angle) {
   return angle * ( point - pivot) + pivot;
}

```

When everything is set up in the parent/child fashion as I said above, you can easily create a generic script to handle the orbits. Then just drop that script onto the bodies you want to orbit their parents. Update the orbit by adding the rotation for that step:

```
transform.position =
    RotatePointAroundPivot(transform.position,
                           transform.parent.position,
                           Quaternion.Euler(0, OrbitDegrees * Time.deltaTime, 0));

```

# Answer
> 1 votes
I know exactly what's going on and it's a tricky one:)

In time, since one orbits after the other (the update functions do not happen at the same time), their distance increases or decreases little by little. Right when the planet orbits a bit, you want your moon to do exactly the same motion so that their distance does not change. Otherwise you'll make an orbit around a slightly different radius. Your planet, before doing its orbit step, can remember where it was and where it went to, and tell the moon to move in the same direction with the same amount. To show you how to do that, I would need access to your planet code as well. However, it's simple subtractions and additions of transform.position values, you can also figure it out.

In the meantime, below is a hacky fix that should remedy the situation if both the planet and the moon are orbiting around Vector3.up. I wasn't sure about how you use the orbit angle, so I changed that a bit. This works for me here:

```
public class RotateAndOrbit : MonoBehaviour {

    public float RotationSpeed = 100f;
    public float OrbitSpeed = 50f;
    public float DesiredMoonDistance;
    public Transform target;

    void Start () {
        DesiredMoonDistance = Vector3.Distance(target.position, transform.position);
    }

    void Update () {
        transform.Rotate(Vector3.up, RotationSpeed * Time.deltaTime);
        transform.RotateAround(target.position, Vector3.up, OrbitSpeed * Time.deltaTime);

        //fix possible changes in distance
        float currentMoonDistance = Vector3.Distance(target.position, transform.position);
        Vector3 towardsTarget = transform.position - target.position;
        transform.position += (DesiredMoonDistance - currentMoonDistance) * towardsTarget.normalized;
    }
}

```

# Answer
> 0 votes
I think both rotate and rotatearound is trying to affect transforms rotation is the issue here. You could try placing the transform inside an empty game object and placing orbit script on that parent object leaving the rotate script on the transform.

# Answer
> -3 votes
The answer is time. The time each started on it path and rotation in time. You figure that out and you have figured out the beginning of time 0:00

---
Tags: unity, rotation, orbit
---


# Question
Title: How to improve load times of audio files without loosing too much quality for HTML5 game?
I'm creating an HTML5 game. We have high fidelity composed music, in the format of `wavs` and `mp3s`— some `ogg`. Game engine we are using is melon JS.

The `wav` files are generally 3x time size of mp3s, but even loading the mp3s is by far the slowest asset to load on the web game.

I've tried compressing file mp3s at http://www.mp3smaller.com/, @ `mp3 Bitrate 32Kbps` which resulted in 89% reduction in file size. This significantly improves load time of the game, but it's as though we lost 89% of the quality.

Any recommendations for lossless (or close to) compression services/techniques with significant file downsize but little quality loss?

In images, I know we can take a `.png` and save as `.jpg` at lower fidelity, saving about 70-80% in space...but to the eye, it's impossible to tell.

# Answer
When you take an audio clip which is already encoded in a lossy compression format and then re-encode it again with a different lossy compression, then any compression artifacts will accumulate and the quality will get a lot worse than it should be. This is as if you take a picture with a camera, print it, and then take another picture of the printout.

If you want to experiment with encoding your audio files in different formats and with different compression settings, then always do so by creating an MP3/OGG from the original WAV file. You will get much better results that way.

Also, different encoders might give you different results with the same bitrate. They might also provide you with further encoding parameters to experiment with. So investing some time into finding the best encoder and settings for your particular target bitrate and style of music can be worth it.

If the filesize-to-quality rating is still too bad for your purposes and you are willing to invest a lot of work into your audio system in order to minimize filesize, then you could use a trick from the demo scene: Program a system to generate your music procedurally. The HTML5 Web Audio API has become quite powerful and can be used to build digital synthesizers, sequencers and effect filters.

But if you go this route, then you can't just take any pre-made music track and drop it into the game. You will have to work directly with your composer and have them compose specifically for your system. Also, as of writing this answer, the Web Audio API doesn't work in Internet Explorer (but it does work on Edge and all other mainstream web browsers).
> 3 votes

# Answer
I will assume that you have exhausted all that may come from encoding and compression.

First off, load only what you need next, use a load scene when appropriate.

Now, what you probably want is to stream the audio, and not simply serve audio files, so that the server does not wait to load the whole file in memory to start sending data, and the client can start playing before finishing downloading. How to do it depends on the server side technology you are using. However you might not be in control of the server and working in a server that does not allow that. Addendum: streaming can still be slow.

Also, you might want to cache your audio files between sessions (ideally with the help of a service worker), so that the game can work with audio from local cache instead of asking the server every time.

Aside from that:

1. Split your music in smaller chunks.
2. Encode each chunk in multiple qualities.
3. Have a measure how good the download is\*, and decide what audio quality it is worth to download such that it can be downloaded fast enough.
4. Start downloading the selected quality chunks, and switch to play those as soon as possible.
5. If the audio happens to download too slow to be ready in time, go back to 3.

\*: Measuring the download time on some asset, any asset. You might aswell download the lower quality in order to measure the download speed, which also has the bonus that the lower quality would be available to play if there was no time to download a better one. Also keep updating this measure using the time to download the chunks.

This will also allow you to provide the user with a setting to change to a lower audio quality. Users that are playing from a cellular network will appreciate it. Ah, and do not forget to provide the "no audio" option.

---

Addendum: People playing on a network that charges by the amount of transferred data will prefer it if your game transfers less data. Furthermore, unless the user is using headphones, the audio quality from the speakers of the mobile device is not the best anyway. Also, smaller files means less data to crunch, and less data to crunch means more battery life. I am not saying this is the case for everybody... in fact, some could be playing on WiFi, on a decent device and with headphones... but not everybody, some will prefer your poor audio quality version and appreciate you give them the option.
> 2 votes

# Answer
One option, given with reservations, is to try MIDI. Unlike MP3, OGG or WAV files, a MIDI file is not an audio recording. Instead, it is a set of instructions used to recreate audio on demand. It's sort of like having the sheet music indicating the notes, pitch, tempo, etc, rather than the music itself. Because the format, it typically uses a fraction of the space space required for the equivalent recorded audio. Before the advent of CDs, most game audio was either MIDI or some in house equivalent. For web development spcifically, there's Web MIDI

That being said, it does come with some possible drawbacks:

* First, composing music in MIDI is its own somewhat niche skill set. As such, there's fewer pre-made off the shelf assets to choose from & finding the talent to make custom assets may be harder.
* Second, to my knowledge there's not a particularly great way to automatically convert recorded audio into MIDI.
* Third, again, to the best of my knowledge, it doesn't support lyrics. It can handle vocals, things like a choir singing "ahhhs", "laaaas", etc. It is my understanding that if you need actual words, they need to be layered in separately.
* Forth, browser support may be a problem. Presently, Web MIDI isn't directly adopted outside of Chrome & Opera. Some casual searching suggests most developers work around this using the Web MIDI API Shim.
> 1 votes

# Answer
* **Lazy loading**. Even if you have 100 levels with unique soundtracks, you probably don't need them all at the start of the game. You can improve user experience by having a loading screen with minimal assets, or sneakily load the first level assets in the background while the player is occupied with the game menu. Here's an example of Phaser displaying a loading animation.
* **Compression**. Both high fidelity music and 32Kbps MP3 are overkill, but in opposite ways. Game audio, especially for web games, don't need to be high quality. See this answer for good ways to compress audio for games: https://gamedev.stackexchange.com/a/99121/26250
> 1 votes

---
Tags: html5, audio, compression
---


# Question
Title: There is something wrong (2D car sprite changes after moving right or left)
**this is car controller**

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

    public class CarController : MonoBehaviour
    {
        public float acceleration;
        public float steering;
        private Rigidbody2D rb;

        void Start()
        {
            rb = GetComponent<Rigidbody2D>();
        }

        void FixedUpdate()
        {
            float h = -Input.GetAxis("Horizontal");
            float v = Input.GetAxis("Vertical");

            Vector2 speed = transform.up * (v * acceleration);
            rb.AddForce(speed);

            float direction = Vector2.Dot(rb.velocity, rb.GetRelativeVector(Vector2.up));
            if (direction >= 0.0f)
            {
                rb.rotation += h * steering * (rb.velocity.magnitude / 5.0f);
                //rb.AddTorque((h * steering) * (rb.velocity.magnitude / 10.0f));
            }
            else
            {
                rb.rotation -= h * steering * (rb.velocity.magnitude / 5.0f);
                //rb.AddTorque((-h * steering) * (rb.velocity.magnitude / 10.0f));
            }

            Vector2 forward = new Vector2(0.0f, 0.5f);
            float steeringRightAngle;
            if (rb.angularVelocity > 0)
            {
                steeringRightAngle = -90;
            }
            else
            {
                steeringRightAngle = 90;
            }

            Vector2 rightAngleFromForward = Quaternion.AngleAxis(steeringRightAngle, Vector3.forward) * forward;
            Debug.DrawLine((Vector3)rb.position, (Vector3)rb.GetRelativePoint(rightAngleFromForward), Color.green);

            float driftForce = Vector2.Dot(rb.velocity, rb.GetRelativeVector(rightAngleFromForward.normalized));

            Vector2 relativeForce = (rightAngleFromForward.normalized * -1.0f) * (driftForce * 10.0f);

            Debug.DrawLine((Vector3)rb.position, (Vector3)rb.GetRelativePoint(relativeForce), Color.red);

            rb.AddForce(rb.GetRelativeVector(relativeForce));
        }

    }

```

**and this is camera controller**

```
using UnityEngine;

public class CameraController : MonoBehaviour {

    public Transform player;
    public Vector3 offset;

    void Update()
    {
        transform.position = new Vector3(offset.x + offset.x, player.position.y + offset.y, offset.z); // Camera follows the player with specified offset position
    }
}

```

# Answer
I solved this problem (Rotation Distorts Object) with putting car sprite as a child of empty gameobject.
> 0 votes

---
Tags: unity
---


title: Calculating distance using Job System

text:
# Question
Title: Calculating distance using Job System
I am trying to find out the distance between game objects and the player position using Job System, But I am getting an error of unsafe pointer race condition. Can anyone tell me how to access transform in job system? to measure distance. Following is the code.

```
struct PositionUpdateJob : IJobParallelForTransform

{

    public TransformAccessArray Object;

    public float DIst;

    public void Execute(int i, TransformAccess transform)

    {

         DIst = (transform.position- Object[0].position ).sqrMagnitude;
        if (DIst < 20)
        {
           // Do Something
        }
    }

}

```

This is the Main script which measures gameObject position against its children

```
public Transform Player;
public List<Transform> ChildList = new List<Transform>();
public TransformAccessArray Transformz;
public float Dist;
PositionUpdateJob m_Job;
JobHandle m_PositionJobHandle;
public TransformAccessArray Mey;
void Start ()
{
    Transformz = new TransformAccessArray(0, -1);
    Mey = new TransformAccessArray(0,-1);
    Mey.Add(transform);
    GetChildRecursive(gameObject);
    }
private void GetChildRecursive(GameObject obj)
{
 //To Get All childrens for transform access array
}
void Update()
{
    m_PositionJobHandle.Complete();
    m_Job = new PositionUpdateJob()
    {
        DIst = Dist,
        Object = Mey
};
    m_Job.Schedule(Transformz);
  }
private void LateUpdate()
{
    m_PositionJobHandle.Complete();
    Transformz.Dispose();
}

```

# Answer
So after getting some help from the unity forum I fixed the problem. I am posting code below hope it will help someone:)

```
struct PositionUpdateJob : IJobParallelForTransform

{
    public NativeArray<float> _distances;
    public Vector3 _playerPosition;

    public void Execute(int i, TransformAccess transform)
    {
        _distances[i] = Vector3.Distance(_playerPosition, transform.position);
    }
}

PositionUpdateJob job = new TransformDistanceCheckJob()
    {
        _distances = distances,
        _playerPosition = Player.position,
    };
    JobHandle jobHandle = job.Schedule(Transformz);
    jobHandle.Complete();
    for (int i = 0; i < distances.Length; i++)
    {
        UnityEngine.Debug.Log("distance for for index " + i + ": " + distances [i]);
    }

```

Ps: Performance is great on 5000 children with burst compiler it takes around 2ms where without job system it was 8ms.
> 1 votes

---
Tags: unity, multithreading
---


# Question
Title: Trying to mix and mingle 3d physics with the Unity UI
I have recently created a drag drop system where I drag stuff from a UI menu and then drop it to another UI. The child of the draggable UI object is a 3d model. I have attached box collider and rigidbody to this 3d object and moving the Object with rigibody.MovePosition and rigidbody.MoveRotation. The object doesn't respond to physics like if there is a box collider in the way, it just goes through it without showing any physical reactions. I wanted to know if I can do this mixing of Unity UI which helped me in creating this drag drop and also helped scaling the UI and the 3d physics engine to get my job done. My Project is basically an interactable toy train system where user will create a track and run the carts on it.

the snake/train follows a spline. and runs on it. Here is a demo https://drive.google.com/open?id=1L\_ZTtYqfcJXsvjHmcNaK6gfRHRHio8h4

I am also extensively rotating the object and it's facing forward so that could be an issue ????

# Answer
Bad of me. I just didn't realize that I am making my rigidbody kinematic. I somehow wandered here and there but didn't look upon that. After making my rigidbody non-kinematic the physical collision, hinge joint and everything started working fine.
> 1 votes

---
Tags: unity, physics, gui
---


title: How to align 2 IMUs' quaternions?

text:
# Question
Title: How to align 2 IMUs' quaternions?
Suppose I have 2 IMUs that output 2 quaternions.

I place one IMU on my left hand and another one on my right hand.

I put both my hands flat on the table and point it forward to the same direction. What I expect is that they should give very similar quaternion. But it turns out that the IMUs reading differs about 10-20 degrees around the Y axis when plotted in Unity3D.

This means I cannot just apply the quaternion to the hand model inside Unity directly. I need to know the exact offset of this 10-20 degrees error in order to make the hand model point in the same direction.

**How do I figure out this offset automatically? Or is there another way that I can align both IMUs? How do people deal with this IMU problem?**

PS. Putting the IMU on the hand is just an example. I can put them both directly on the table near each other and they still give slightly different quaternions.

# Answer
> 2 votes
The resting yaw rotation is determined by the magnetometer - it's the only one of the three sensors that has an absolute reference direction in the horizontal plane.

Unfortunately, it's also the most fiddly of the sensors. Metal components inside the device can cause its detected magnetic field vector to be shifted (hard iron distortion) or stretched/rotated/skewed (soft iron distortion).

The most robust way to solve this is to calibrate the device prior to use.

If you ask the user to tumble the sensor around in all directions, the magnetic field vector that you read from the magnetometer will trace out an ellipsoid. Once you have enough samples around the whole surface of the ellipsoid, you can estimate its shape. You can then compute a minimal transformation that maps the ellipsoid to a unit sphere centered at the origin.

This can be as simple as keeping track of the min & max you've observed on each axis, shifting the result by `- (min+max)/2` and scaling it by `2/(max - min)`, though if you have substantial soft iron distortions that skew/rotate your ellipsoid, or misalignments of the sensor chip itself, you may need a more sophisticated correction.

Now you can apply this calibrating transformation to your magnetic field samples before passing them as input to your routine to estimate the device orientation. This should minimize the differences in the two devices' estimates.

---

A simpler but less robust calibration you can try is to ask the user to set the two devices on a flat surface in a standard orientation (it helps if the devices have a flat bottom to rest on, and a clear line somewhere to point forward).

Wait a moment for the orientation estimate to settle, then compare the quaternions you get from each device.

```
// Total difference in orientation.
// (Optionally, you can filter this to consider only the difference in yaw)
Quaternion AtoB = deviceB.rotation * Quaternion.Inverse(deviceA.rotation);

// We'll average-out the two and meet in the middle:
// correcting A halfway to B's orientation,
// and B halfway to A's.
Quaternion aCorrection = Quaternion.Lerp(Quaternion.identity, AtoB, 0.5f);
Quaternion bCorrection = Quaternion.Inverse(aCorrection);

```

Now you can apply this correction as

```
Quaternion correctedA = aCorrection * deviceA.orientation;
Quaternion correctedB = bCorrection * deviceB.orientation;

```

The reason I say this is less robust is because it assumes the same yaw offset applies all the time - but this can be sensitive to the orientation of the device. You could repeat the calibration process in multiple orientations (standing on end, on its side, etc...), saving multiple different correction quaternions, and then blend between them depending on the current device orientation. We're still treating the symptom here (differing yaw estimates) rather than the root cause (differently-biased magnetometer readings).

---
Tags: unity, rotation, quaternion, virtual-reality, orientation
---


# Question
Title: Toon/cel shading with variable line width?
I see a few broad approaches out there to doing cel shading:

1. Duplication & enlargement of model with flipped normals (not an option for me)
2. Sobel filter / fragment shader approaches to edge detection
3. Stencil buffer approaches to edge detection
4. Geometry (or vertex) shader approaches that calculate face and edge normals

Am I correct in assuming the geometry-centric approach gives the greatest amount of control over lighting and line thickness, as well eg. for terrain where you might see the silhouette line of a hill merging gradually into a plain?

What if I didn't need pixel lighting on my terrain surfaces? (And I probably won't as I plan to use cell-based vertex- or texturemap-based lighting/shadowing.) Would I then be better off sticking with the geometry-type approach, or go for a screen space / fragment approach instead to keep things simpler? If so, how would I get the "inking" of hills *within* the mesh silhouette, rather than *only* the outline of the entire mesh (with no "ink" details inside that outline? (AKA *suggestive contours*, *creases*).

Lastly, is it possible to cheaply emulate the flipped-normals approach, using a geometry shader? My concern with this is that I could certainly duplicate every single vertex and scale these accordingly, but how would I approach flipping normals, and distinct colouring in the fragment shader?

**What I want - varying line thickness with intrusive lines inside the silhouette...**

**What I don't want...**

---

**EDIT: Further research has turned up the following...**

Since I have a massive vertex count on terrain, even considering distance-based LoD, neither flipped-normals nor a geometry shader based approach (even with frustum culling) would be a sensible option due to sheer computational complexity involved in duplication & scaling of all uploaded vertices.

Considering that I don't need per-pixel lighting in the form of solid-tone shading on the terrain surfaces, it also becomes less prudent to consider any face-normal based approaches -- otherwise a requirement for correct surface lighting -- as these are naturally quite expensive to calculate. It is however true that they give the finest degree of control; for example, the ability to shade edges using "artistic" strokes: Beautiful, but again, not really viable for a massively complex game environment.

Stencil buffers are something I'd rather avoid as I'd prefer to do all work in shaders. (The above example with the red outline was done with a stencil buffer -- old school.)

This leaves fragment shader image-space approaches. Computational complexity is reduced to the number of fragments rather than the number of vertices (in my case, this is 10-100x fewer operations than I would have to do in the geometry shader). This requires more than one render pass in order to generate a g-buffer (consisting of a normal buffer and optionally a depth buffer as well) to which we can apply discontinuity filters (eg. Sobel operator). Depth discontinuity is what enables suggestive contours and creases. My only quibble with this approach is the inability to provide finer control over inked edge widths, though with the right algorithm in the fragment shader, I'm sure this would be possible.

**So the question now becomes more specific:** How exactly would I go about getting variable edge widths, particularly on the outer silhouette, in a fragment shader?

# Answer
> 4 votes
I've decided to go with a fragment shader approach via discontinuity filtering of the depth buffer. Reasons for this are:

1. World vertex count is very, very high due to immense view distances, even with mesh LoD;
2. I am doing a number of other fragment shader operations, such as DoF blur which can benefit by the same structures (box or gaussian sampling/filtering) in the same pass.

Having tested it, I would say that in future projects I'd go for a geometry-based approach instead, for complexity reasons. The reason is that (as others suggested in the comments), fragment shader approaches to edge detection can be computationally intense, particularly with DoF implementations where the circle of confusion radius, and thus the number of samples per fragment, can be quite high. This is fortunately less of a concern for outline shaders.

# Answer
> 0 votes
There is actually a very easy general solution if you can use an after effect. The great thing is, it doesn't matter how high your poly-count is. Render a Depth map as greyscale, then create a dot in the line color you want, when the contrast between two adjacent pixels is higher than a threshold value. You can make the dot bigger according to the contrast and or light-level of the image you rendered.

I invented the toonShader algorithm back in 2000/2001, even before that French dude, who created this solution. Mine was based on actual materials geometry. Then there are basically two ways to do it: 1. look at normals, if normals two planes connected to a line are facing away and towards the camera, render that line, you can then use depth, lighting etc as cues for linedepths. 2. Look at rendered geomerty (so after perspective transformation) Take each linesegment, if the vertices of the connecting planes are on the same side of this linesegment, you render the line.. You can then do the same for line-thickness as in method 1. 3. You could make combinations of these three techniques, but I mentioned the first, because you indicated a huge poly-count.

---
Tags: 3d, shaders, glsl, geometry-shader, fragment-shader
---