# Question
Title: Convert Kafka Thread related code example into Unity3d
I have code snippet of Kafka Consumer which i have developed with the help of this and here it is:

```
static void Main(string[] args)
        {
            string bootstrapServers = "localhost:9092";
            string schemaRegistryUrl = "Production163:8081";
            string topicName = "player";
            string groupName = "avro-generic-example-group";

            //CancellationTokenSource cts = new CancellationTokenSource();
            //var consumeTask = Task.Run(() =>
            //{
            using (var schemaRegistry = new CachedSchemaRegistryClient(new SchemaRegistryConfig { SchemaRegistryUrl = schemaRegistryUrl }))
                using (var consumer =
                    new
                    ConsumerBuilder<string, GenericRecord>(new ConsumerConfig { BootstrapServers = bootstrapServers, GroupId = groupName })
                        .SetKeyDeserializer(new AsyncAvroDeserializer<string>(schemaRegistry).AsSyncOverAsync())
                        .SetValueDeserializer(new AsyncAvroDeserializer<GenericRecord>(schemaRegistry).AsSyncOverAsync())
                        .SetErrorHandler((_, e) => Console.WriteLine($"Error: {e.Reason}"))
                        .Build())
                {
                    consumer.Subscribe(topicName);

                    try
                    {
                        while (true)
                        {
                            try
                            {

                            var consumeResult = consumer.Consume();//This line getting hange in unity
                            Avro.Field f;

                            //consumeResult.Value
                            consumeResult.Value.Schema.TryGetField("favorite_number", out f);
                            Console.WriteLine(consumeResult.Value["favorite_number"]);
                            Console.WriteLine(consumeResult.Value["name"]);

                            }
                            catch (ConsumeException e)
                            {
                                Console.WriteLine($"Consume error: {e.Error.Reason}");
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // commit final offsets and leave the group.
                        consumer.Close();
                    }
                }
            //});
        }

```

This is example is running fine in my console application. Now i want to move this example into Unity environment, for this reason i have make these changes. 1. Wrap the code inside coroutine, so it simultanously run with main unity thread. 2. Comment out catch block as i can't use them yeild return

```
 void Start()
    {
        StartCoroutine(Main());

    }

    IEnumerator Main()
    {

        string bootstrapServers = "localhost:9092";
        string schemaRegistryUrl = "Production163:8081";
        string topicName = "player";
        string groupName = "avro-generic-example-group";

        //CancellationTokenSource cts = new CancellationTokenSource();
        //var consumeTask = Task.Run(() =>
        //{
        using (var schemaRegistry = new CachedSchemaRegistryClient(new SchemaRegistryConfig { SchemaRegistryUrl = schemaRegistryUrl }))
        using (
            var consumer = new ConsumerBuilder<string, GenericRecord>(new ConsumerConfig { BootstrapServers = bootstrapServers, GroupId = groupName })
                .SetKeyDeserializer(new AsyncAvroDeserializer<string>(schemaRegistry).AsSyncOverAsync())
                .SetValueDeserializer(new AsyncAvroDeserializer<GenericRecord>(schemaRegistry).AsSyncOverAsync())
                .SetErrorHandler((_, e) => Debug.Log($"Error: {e.Reason}"))
                .Build())
        {
            Debug.Log("subscribe");
            consumer.Subscribe(topicName);

            //try
            //{
            while (true)
            {
                //try
                //{
                //CancellationTokenSource cts = new CancellationTokenSource();
                //cts.Token
                if (consumer == null)
                {
                    Debug.Log("Consumer is null");
                }
                var consumeResult = consumer.Consume();//TimeSpan.FromMilliseconds(50000)
                yield return consumeResult;
                Debug.Log($"Key: {consumeResult.Message.Key}\nValue: {consumeResult.Value}");
                Debug.Log(consumeResult.Value.Schema);
                Debug.Log(consumeResult.Value.Schema["favorite_number"].GetProperty("favorite_number"));
                Debug.Log(consumeResult.Value.Schema["favorite_number"]);

                Avro.Field f;

                //consumeResult.Value

                consumeResult.Value.Schema.TryGetField("favorite_number", out f);

                Debug.Log(consumeResult.Value["favorite_number"]);
                Debug.Log(consumeResult.Value["name"]);

                //consumeResult.Message.Value.TryGetValue("favorite_number");

                //Debug.Log(f.);
                yield return new WaitForSeconds(1);

                //}
                //catch (ConsumeException e)
                //{
                //    Debug.Log($"Consume error: {e.Error.Reason}");
                //}

            }
            //}
            //catch (OperationCanceledException)
            //{
            //    // commit final offsets and leave the group.
            //    consumer.Close();
            //}
        }
        //});
        Debug.Log("Main end game.");
    }

```

Now with above code is my unity player get **hanged**. I try to debug and found that the problem is, in this line

```
var consumeResult = consumer.Consume();

```

The documentation suggest that there are two variants. One with TimeSpan and other with CancellationToken

> Poll for new messages / events. Blocks until a consume result is available or the operation has been cancelled.

# Answer
> Wrap the code inside coroutine, so it simultanously run with main unity thread

You have fundamentally misunderstood how coroutines work. Consulting the Unity documentation:

> A coroutine is like a function that has the ability to **pause execution and return control to Unity** but then to **continue where it left off** on the following frame.

(Emphasis added)

So: coroutines are not threads. They do not run simultaneously with the main thread. They take turns.

Each frame, Unity's main thread will iterate over each Coroutine that's set to resume at that time (based on its last `yield return` value), and call `MoveNext()` to run it until it hits its next `yield return`, `yield break`, or the end of the function. Only then does control return back to Unity to pump the next coroutine or continue with updating the game state and rendering the frame.

So, if you want to use threads to run in parallel (and you're not targeting WebGL), then *use threads*.

You can set up a producer-consumer queue, where your Kafka Consumer thread acts as the producer, stuffing results into a queue that scripts on your main thread can then extract and work with. It might look a bit like this:

```
public class MultithreadedExample : MonoBehaviour {

   bool _keepThreadRunning = true;
   Thread _thread;
   CancellationTokenSource _cancel;

   // The Concurrent version is important here, since we're
   // accessing each end of this queue from a different thread.
   ConcurrentQueue<string> _stringsReceived;

   void Start() {
       // Prepare to cancel the operation if we need to.
       _cancel = new CancellationTokenSource();

       // Spin up our thread.
       _thread = new Thread(KafkaReader);
       _thread.Start(_cancel.Token);
   }

   void OnDestroy() {
       // If we never started our thread, we're done.
       if(_thread == null)
           return;

       // Tell the thread to stop on its next loop.
       _keepThreadRunning = false;
       // Abort the current consume action.
       _cancel.Cancel();
       // Wait until the thread has completed.
       _thread.Join();

       // Here the thread has safely exited, and we can clean up anything else we need.
   }

   void Update() {
       // Print out all messages we received since last frame.
       string message;
       while(_receivedStrings.TryDequeue(out message)) {
           Debug.LogFormat("{0} - received message: {1}", Time.time, message);
       }
   }

   void KafkaReader(CancellationToken cancellationToken) {

       // Set up your Kafka connection here.

       while(_keepThreadRunning) {
           try {
           var consumeResult = consumer.Consume(cancellationToken);

           // Do stuff with the values you've consumed.
           _receivedStrings.Enqueue(consumeResult.Value["favorite_number"]);

           // Handle or log errors...
           } catch (ConsumeException e) {
               _receivedStrings.Enqueue("Consume error: " + e.Error.Reason);
           }
       }

       // Disconnect and clean up your connection here.
   }
}

```

If you need to target a platform that does not support threads, like Unity's WebGL target, then your best bet is to use the `TimeSpan` version of `Consume()`, with a short enough timespan that waiting on it will not disrupt your framerate.
> 2 votes

# Answer
Use the timeout alternative, with a zero second timeout, and wait for it to return non-null:

Turn this

```
var consumeResult = consumer.Consume();
yield return consumeResult;

```

Into this

```
ConsumeResult<string, GenericRecord> consumeResult;
do {
  consumeResult = consumer.Consume(TimeSpan.Zero);
  yield return consumeResult;
while (consumeResult == null);

```
> 0 votes

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


# Question
Title: What technique can I use to animate interaction between tiny objects in a sim game?
In simulation games like Sim City and Factorio, there are numerous interaction between tiny objects that needs to be animated. e.g. random people walking on the sidewalk, then waits for a bus, then board the bus; tiny cars waiting in line for each other at the traffic junction; thousands of items on a convey belt and the robotic arm needs to wait for an item to arrive in front of it to pick it up; conveyor belt sections transferring items from one to another.

I expect the collision detection check for every tiny object independently will eat a lot of CPU; what technique can I use in such a game to avoid the heavy computation and make it look like it's realistic?

# Answer
> 6 votes
More often than not: it's all for show.

In Stone Librande's GDC 2013 talk "Simulating a City, One Page at a Time" he illustrates this with the original SimCity, where even on those primitive computers we had back then you could see individual cars driving around all the roads!

Or could you? (See ~18 minutes in)

As this close-up on the intersection shows, the game isn't actually simulating individual cars driving all around town. It just has a "traffic level" associated with each road tile, and it selects an animated frame to show for each tile independently, using its traffic level. This causes seams where a high-traffic road borders a low-traffic road, where cars can apparently appear out of or vanish into nowhere.

Most of the sophistication we've gained since then is in hiding those seams. ;)

In modern city games, we still generally don't simulate hundreds to millions of commuters each with their own origin and destination to pathfind to. Instead we have designated spawn & despawn points out of the view of the player - just off the screen, around the corner, down an alley or in a garage. Every so often (on a timer or based on current density / budgets), we spawn a vehicle appropriate to the neighbourhood we're in. It might be given a pre-destined despawn point, in which case it doesn't even have to navigate unless disturbed - we're more or less just tweening it between waypoints until it's safely out of sight and can despawn again. Since we're tweening all the cars within a compatible range of speeds, they don't need to sense each other to avoid collision - it's all orchestrated. Only at intersections do we need to decide whether to keep this car going the same direction, or turn to fill a road segment that's too low on traffic, or to get out of view so we can despawn it.

Try following a car in most city games - you'll find their paths don't necessarily make sense globally - they might circle a block or take unnecessary detours - they just need to look plausible locally, to create the right set dressing for the scene.

One notable exception here is SimCity 2013, which as Stone was explaining actually simulates some number of individual agents, not just tiles of map. So a truck might actually contain a resource that it's transporting from a production site to a consumption site. I don't know whether this accounts for all of their traffic, or if it's a minority and they still fill in extra purposeless vehicles for set dressing.

But even here we get benefits from orchestration. The truck has its origin and destination pre-set: it's not changing its mind about where to go based on each other car it passes on the way. As soon as we have the beginning and endpoint, we can choose the route all these deliveries will take, and only re-path when the road network is changed. Our path is just a sequence of turns, and between the turns the truck is essentially an item in a queue belonging to a road segment, allowing us to space the vehicles out along the available lane space without individual collision checks. So ticking all the traffic forward one step can still be vastly lighter-weight than simulating hundreds or thousands of autonomous vehicles driven by decision-making AI characters.

Similarly, the people walking down the sidewalk and waiting at the bus stop aren't individually jostling for positions and running avoidance routines: they're assigned lanes and slots and then just animate to the orchestrated position for their next pre-ordained action.

Taking the example of conveyor belts in Factorio, the tile grid gives us a similar degree of predictability. While the sprites of the various objects may be quite detailed, the game state is just grids of numbers like tile type, content ID, power, exit time. We can plow through this grid doing minimal updates: oh, this conveyor's exit time is the current time tick? Clear its content ID and assign it one tile over. We don't need to do detailed polygonal collision detection every frame, just check whether the adjacent tile has `contentID == 0`. The actual animation of the objects moving on the conveyors is again, just for display: we can tween it from one side of the tile to the other based on `currentTime - exitTime` and the conveyor's direction, for only the tiles drawn in the current view.

So, that's as close to a recipe as we can get:

1. Find out what actually matters to your sim. It's probably not "is this millimetre of this object touching that millimetre of that object" but something much more discretely chunked.
2. Simulate the actions that matter at the coarsest level. eg. the conveyors deciding when an object switches from one tile to another, or the truck progressing discretely through the list of road segments in its pre-planned path.
3. Animate the visible execution of those actions only where the player can see it. eg. the object moving predictably along the conveyor. This is cheap, because you're basically just tweening or moving along a spline - no fancy collision logic or AI decision-making happens here.

---
Tags: collision-detection, animation, simulations
---


# Question
Title: VS2017 (and 2019) Community Intellisense only showing part of the Unity class/method information, missing descriptions
If I hover keywords like `Input.GetKeyDown`, for example, I know it should tell me something about using it for autofire.

I get autocompletion and the syntax examples / override counts, all great things, but no descriptive text blurbs.

I would really like to get those descriptions turned on.

I yanked a screenshot of an old Unity forum post that has visual evidence of the problem I'm having. I know that the text blurbs exist because I've watched enough Unity videos now with VS being used and more info.

>

This second image is a screenshot from a video. In my editor, I do not see the line "Base class for all entities in Unity scenes." I only see the first line "class UnityEngine.GameObject"... helpful but not as helpful as it could be. Same thing is missing in every class/method.

How can I get these Intellisense description texts to show in my version?

# Answer
> -1 votes
This behavior no longer happens after upgrade to 2019.1.4f1

---
Tags: unity, visual-studio
---


title: Restarting a level but with more time?

text:
# Question
Title: Restarting a level but with more time?
So I'm trying to add a "Rewarded video ad" with the reward being more time to play in the next game. my RewardedAd.cs:

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

public class RewardedAd : MonoBehaviour
{
    public static RewardedAd singleton;

    private void Awake()
    {
        if (singleton == null)
        {
            singleton = this;
        }
        else if (singleton != this)
        {
            Destroy(gameObject);
        }
    }

    public void ShowRewardedAd()
    {
        if (Advertisement.IsReady("rewardedVideo"))
        {
            var options = new ShowOptions { resultCallback = HandleShowResult };
            Advertisement.Show("rewardedVideo", options);

        }
    }

    private void HandleShowResult(ShowResult result)
    {
        switch (result)
        {
            case ShowResult.Finished:
                Debug.Log("The ad was successfully shown.");
                StartCoroutine(NewGameWithTime());
                break;
            case ShowResult.Skipped:
                Debug.Log("The ad was skipped before reaching the end.");
                SceneManager.LoadScene(0);
                break;
            case ShowResult.Failed:
                Debug.LogError("The ad failed to be shown.");
                SceneManager.LoadScene(0);
                break;
        }
    }

    IEnumerator NewGameWithTime()
    {
        Debug.Log("NewGame Started");
        GameOverManager.singleton.GameOverAfterRewardAd();
        SceneManager.LoadScene(1);
        Timer.singleton.AddBonusTime(20);
        Debug.Log("NewGame Ended");
        yield return new WaitForSeconds(1);
    }
}

```

and my Timer.cs:

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

public class Timer : MonoBehaviour
{
    public static Timer singleton;
    public Text timeTF;
    private float seconds = 10f;

    private void Awake()
    {

        if (singleton == null)
        {
            singleton = this;
        }
        else if (singleton != this)
        {
            Destroy(gameObject);
        }
    }
    private void Update()
    {
        if (seconds > 0f)
        {
            seconds -= Time.deltaTime;
            TimeSpan timeSpan = TimeSpan.FromSeconds(seconds);
            string timeLeft = string.Format("{0:D2}",timeSpan.Seconds);
            timeTF.text = timeLeft;
            TimeLeftCheck(seconds);
        }
    }

    public void AddBonusTime(float bonusTime)
    {
        seconds += bonusTime;
        Debug.Log("New Timer script:");
        Debug.Log(seconds);
    }

    private void TimeLeftCheck(float _time)
    {
        if (_time < 5)
        {
            //Debug.Log("RunningOutTime sound");
            //SoundManager.singleton.Sound_RunningOutofTime();
        }
        if (_time < 2)
        {
            //Debug.Log("Out of Time sound");
            //SoundManager.singleton.Sound_OutofTime();
        }
        if (_time < 1)
        {
            Debug.Log("Game Over");
            GameOverManager.singleton.GameOver();
        }
    }

```

The video ad is playing fine and it's resetting my ad counter in my game over manager but I can't seem to figure out how to start the next game with more time (20 seconds to so) but ONLY if they've watched the ad.

Also, I'm still learning so any suggestions or things I can improve, more than happy to take that criticism too!

# Answer
```
IEnumerator NewGameWithTime()
{
    Debug.Log("NewGame Started");
    GameOverManager.singleton.GameOverAfterRewardAd();
    SceneManager.LoadScene(1);
    Timer.singleton.AddBonusTime(20);
    Debug.Log("NewGame Ended");
    yield return new WaitForSeconds(1);
}

```

The order of events here might not be what you expect:

1. We ask the `SceneManager` to unload this scene when the engine is ready to do so, and load the new scene.

This call doesn't block until the new scene is initialized, so our next line runs right away:
2. We ask our `Timer` class for its current `singleton` member. Because the new scene hasn't loaded and initialized yet, this points to the `Timer` instance *in the current scene*.

So we add 20 seconds of extra time to the scene that we're leaving.
3. We `yield` control back to the Unity engine.

Now it can finish unloading our scene (destroying this object, so it never resumes after the `yield return new WaitForSeconds(1);` so that might as well have been a `yield break;`) and loading the new scene.
4. The `Timer` instance in the new scene is instantiated and runs its `Awake` method, setting the `singleton` member to point at itself - but this is now long after we tried to use it, so it doesn't get the 20 seconds of bonus time.

So, instead, I'd recommend that you create an object whose job it is to carry information between scenes. Let's call it a Bonus Tracker, and we'll create it as a `MonoBehaviour` so you can use the `Inspector` to peek at its state and verify it's tracking the data you want. We'll use `DontDestroyOnLoad` so that it persists between scenes once one exists, and construct it lazily so you don't need to remember to place it in each scene (but we'll check for that case and handle it to be safe).

```
public class BonusTracker : MonoBehaviour {
    static BonusTracker _instance;

    public BonusTracker GetInstance() {
        if(_instance == null) {
            var go = new GameObject("Bonus Tracker");
            go.AddComponent<BonusTracker>();
        }
        return _instance;
    }

    private void Awake()
    {
        if (_instance == null) {
            _instance = this;
            DontDestroyOnLoad(gameObject);
        } else {
            Destroy(gameObject);
        }
    }

    int _bonusTime = 0;
    public void AddBonusTime(int time) {
        _bonusTime += time;
    }

    public int ClaimBonusTime() {
        int time = _bonusTime;
        _bonusTime = 0;
        return time;
    }
}

```

Now before we load the next scene we can say:

```
BonusTracker.GetInstance().AddBonusTime(20);

```

And when we start a new timer sometime much much later in a different script, it can say:

```
seconds += BonusTracker.GetInstance().ClaimBonusTime();

```
> 0 votes

---
Tags: unity
---


title: Problem picking up a value, Delegate

text:
# Question
Title: Problem picking up a value, Delegate
I'm having trouble passing values that are inside an int function to an onclick delegate.

this script causes the object to move in vector3 (-1 to the left and 1 to the right), these two values are inside the (int value), but I am trying to pass them to a delegate, but when inserting it it is adding different values than being in the script

video of the problem

```
private int index, index2 = 0;
[SerializeField]
private Vector3[] Myposic1, Myposic2;
[SerializeField]
private Button left, right;//here I change the positions of Myposic1, Myposic2
[SerializeField]
private float time;
public int slide = 0;//index between Myposic1, Myposic2.

void Update() {
    call();
}

public void previous()
{
    slide--;
    call();
}

    public void next()
{
    slide++;
    call();
}

void call()
{
    if (slide <= 0)
    {
        slide = 0;
    }

    if (slide >= 1)
    {
        slide = 1;
    }

    if (slide == 0)
    {
        left.onClick.AddListener(delegate { player(-1); });
        right.onClick.AddListener(delegate { player(1); });
        this.transform.position = Vector3.Lerp (this.transform.position, Myposic1[index], Time.deltaTime*time);
        if (index == Myposic1.Length - 1)
            right.interactable = false;
        else
            right.interactable = true;

        if (index == 0)
            left.interactable = false;
        else
            left.interactable = true;
        Debug.Log("1");
    }

    if (slide == 1)
    {
        left.onClick.AddListener(delegate { player2(-1); });
        right.onClick.AddListener(delegate { player2(1); });
        this.transform.position = Vector3.Lerp (this.transform.position, Myposic2 [index2], Time.deltaTime*time);
        if (index2 == Myposic2.Length - 1)
            right.interactable = false;
        else
            right.interactable = true;

        if (index2 == 0)
            left.interactable = false;
        else
            left.interactable = true;
        Debug.Log("2");
    }
}

public void player(int valor) {
    index = index + valor;
}

public void player2(int valor2) {
    index2 = index2 + valor2;
}

```

# Answer
I'm not sure if I got the exact problem you were facing, but I will point out a few suggestions. Hopefully, one of them solves the issue.

1. In the `call` method, you have clamped the value of slide between 0 and 1. And then you have the two if conditions checking if the value is equals to 0 or 1. So it is bound to go into either one of the two if clauses.

Here, you are doing `left.onClick.AddListener` or `right.onClick.AddListener`, which is not a good idea, since you are calling the method `call` in Update. If you have to do this, then you might want to remove the listener you have already added

2. `Myposic1` and `Myposic2` are arrays, which I do not see initialized. You are trying to use it here, however `this.transform.position = Vector3.Lerp (this.transform.position, Myposic2 [index2], Time.deltaTime*time);`

I think this is the reason for the IndexOutOfRangeException being thrown.

3. I will talk about `player2` and `index2` for explaining, but I think the same will apply for `player` and `index`.

Consider this snippet of code that you've written:

`right.onClick.AddListener(delegate { player2(1); });
 this.transform.position = Vector3.Lerp (this.transform.position, Myposic2 [index2], Time.deltaTime*time);
 if (index2 == Myposic2.Length - 1)
 right.interactable = false;`

So what will happen here is that, player2 will get called on the `onClick` event of the button. But the code that you have written after the delegate, will run on the same frame (on every frame in this case, as it is called in Update)

So when you are checking `if (index2 == Myposic2.Length - 1)`, it will always pick the current value. If you want to get the updated values when doing this check, you would want to move the following code into the delegate as well.
> 0 votes

# Answer
You are adding a listener during the `Update` function. That means every update-tick, another listener gets added, but the already existing listners don't get removed. When you then finally click on the button, there are already a couple hundred listeners registered on those buttons. All the listener get executed and each one increments the value by one. So you get an increase of several hundred instead of just one as you would expect.

If you only want to register your listeners once, do so in the `Start` method. If you want to change the functionality of a button by registering a different listener, you need to remove the previous listener. You can do that with `.onClick.RemoveListener(method)` if you want to remove a specific listener (in that case you will have to keep a reference to your delegate around so you can remove it later) or `.onClick.RemoveAllListeners()` to get rid of any listeners on that button.

However, I would recommend you to avoid adding listeners with code if possible and instead add listeners via the inspector of the Button component. This is far less error-prone because you have a much better visualization of what a button does if you select it in the inspector. If you need the button to do something different depending on the current state of the game, then consider to make the decision about what to do in the button handler method itself.
> 0 votes

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


# Question
Title: How to change Texture2D type to Sprite during runtime (Unity)
How can we convert the Texture2D type to "Sprite" using the script (not in Editor)? It seems that the Texture2D retrieved from file is by default Normal Map. I need to convert the TextureType to "Sprite".

```
Texture2D texture = LoadPNG("D:/download.jpg");
testPlaneRenderer.material.SetTexture("_source",texture);

```

LoadPNG method code:

```
 public static Texture2D LoadPNG(string filePath)
{

    Texture2D tex = null;
    byte[] fileData;

    if (File.Exists(filePath))
    {
        fileData = File.ReadAllBytes(filePath);
        tex = new Texture2D(2, 2);
        tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
        Debug.Log("File Exists!");
    }
    else
    {
        Debug.LogError("File not exists!");
    }
    return tex;
}

```

It seems that this texture is set as "Default" or "Normal" Type when imported from file and then assigned to Material dynamically. As the particular shader I'm using, works best if the Texture Type is set to Sprite (I tested it by manually placing the texture file in Project and then assigning the texture to Material).

I need to change Type of Texture to Sprite before assigning it to the material. I've seen options like "AssetImporter" but it only works in Editor.

The effect of the shader (which takes two texture types

a) Inverted & Blurred Texture

b) GrayScale Texture

And then returns a Sketch Effect to the object. I convert the original image to inverted & blurred, grayscale texture using some image processing code (C#, Unity -\> working around with GetPixels and SetPixels)...

Output with Defualt Texture Type

Output with Sprite Texture Type

# Answer
> 3 votes
As I'd mentioned in the comments earlier, a Sprite in Unity isn't really a "type" of texture. It's a slice of texture data.

The "Sprite (2D and UI)" import mode you see is a bit of a shortcut to both import the Texture2D texture with some default settings suitable for sprite use AND create one or more Sprite objects sliced from it, as one bundled asset (hence the expansion arrow in the Project folder).

So, we just need to figure out which of those "Sprite (2D and UI)" default settings is different from what you're getting when you load your texture by code.

```
tex = new Texture2D(2, 2);

```

This creates a texture with mipmaps by default. When you import a Sprite into Unity, it defaults to not including mipmaps. So, this is a likely source of the difference you're seeing.

Without mipmaps, when we draw the texture at less than native size, we'll tend to see aliasing artifacts - edges will look sharper than normal, and in high detail areas we might get noisy speckling. Mipmaps solve this by blurring together adjacent pixels of the texture when rendering at reduced size, but for your case that doesn't seem to be the effect you want. In your second image, slight mipmap aliasing could be what's giving you sharper detail and more speckling in the hair.

So, try loading your image without mipmaps:

```
public static Texture2D LoadPNG(string filePath, bool generateMipMaps = false)
{

// ...

    tex = new Texture2D(2, 2, TextureFormat.RGBA32, generateMipMaps);

```

Does that make the dynamically loaded texture behave more like your Sprite asset?

Just beware that turning off mipmaps can produce some very distracting artifacts if you're scaling the image down significantly, or if it's going to move or be displayed in perspective. You might instead want to adjust your image filtering code to give it a sharper response even when working on mipmap filtered input.

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


# Question
Title: How to get collision area within a circle in libgdx
I have a ball inside of a multi-colored circle, the ball will hit the inner area of the circle like this bellow circle image

And the Circle will be rotated clockwise or anti-clockwise based on user input. How would I know, where the ball hit the Big Colored circle.

I just need to identify in which color of my circle sprite has made a collision with the ball.

I have tried a lot, googled a lot but still, the solution has not been found yet.

Experts, please help me.

# Answer
If you want to make something like color switch and you want to detect the collision with the circle.

Your circle is described by the class:

```
public class Circle {
    public Vector2 pos = new Vector2();  // Circle center position
    public float angle = 0f;  // Rotation angle, between 0 and 2*pi

    public float innerRadius = 100f;  // Inner radius
    public float thickness = 10f;  // Thickness

    // The list of colors in the circle in anticlockwise order.
    // Each color takes the same portion of the circle.
    public Color[] colors = new Color[]{Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE};

    // a constructor here probably, setters, getters...
}

```

And your ball by the class:

```
public class Ball {
    public Vector2 pos = new Vector2();  // Ball center position
    public float radius = 10f;  // The ball radius
    public Color color = Color.WHITE;

    // probably more attributes like vertical speed

    // a constructor here probably, setters, getters...
}

```

On each frame, you update the ball position, circle rotation and then check for collision.

If you want to check if the ball collides with a circle, you have two possibilities:

1. The ball is completely inside or completely outside the circle. That means the ball can't be colliding with the circle.
2. Otherwise the ball touches the circle outline. The angle of the ball in the circle must be found to check if the color is right to decide of the collision.

It could look like this:

```
public boolean isBallCollidingWithCircle(Ball ball, Circle circle) {
    // Compute the distance between the circle and ball centers
    double dx = (double) (ball.pos.x - circle.pos.x);
    double dy = (double) (ball.pos.y - circle.pos.y);
    double distance = Math.hypot(dx, dy);

    if (distance < circle.innerRadius - ball.radius ||
            distance > circle.innerRadius + circle.thickness + ball.radius) {
        // No collision possible.
        return false;
    }

    float angle = Math.atan2(dy, dx);
    int colorsCount = circle.colors.length
    // Not entirely sure about this line, basically find the circle color from the angle.
    Color collisionColor = circle.colors[((angle + circle.rotation) / (2 * Math.PI) * colorsCount  + colorsCount) % colorsCount];
    if (collisionColor.equals(ball.color)) {
        // Same color, no collision.
        return false;
    }

    // Not the same color, collision.
    return true;
}

```

Make sure all the coordinates are in a Y-up system since `atan2` needs that. I included `x` coordinates but I'm not sure if that's necessary for Color Switch.

I cut some corners obviously, for example if the ball inside the circle outline, no collision will be detected until the ball center touches the wrong color (and not the ball outline). If you really plan on making a game similar to Color Switch, I encourage you to use box2d for easier collision detection. (circle-circle collision is simple, but circle-polygon is something else...)
> 1 votes

---
Tags: java, libgdx, android, box2d
---


# Question
Title: How to change the value of variable from actor Y by the blueprint of actor X?
I have a project, and it has: 1 NPC (**actor X**), 2 target points and 1 tower (**actor Y**).

**Image of components in level:**

These rose arrows demonstrate part of the NPCs path.

**I added a Event Begin Overlap in the blueprint of the NPC so that when it collides with the tower it loses 10 of life every second:**

**Image of print of variable life:**

When the NPC gets 0 life, it goes to the next target point.

But I would like to know how to also modify the life of the tower by the same blueprint (NPC).

The code is already in my mind, it is kind of obvious to speak the truth.

**"Code" of NPC blueprint:**

I do not want to have to create a new Event Begin Overlap on the blueprint of the tower.

And I think using the blueprint level would not be a good idea.

One of the links below indicated something like **Blueprint Interface**, but I'd like to know if I can do what I want for the NPCs own blueprint.

**Links:**

https://forums.unrealengine.com/international/brazil/89438-pegar-vari%C3%A1vel-de-outro-blueprint

https://answers.unrealengine.com/questions/21386/communication-between-2-blueprints.html?sort=oldest

https://answers.unrealengine.com/questions/24773/how-to-call-a-blueprint-variable-from-another-blue.html

https://docs.unrealengine.com/en-us/Engine/Blueprints/UserGuide/Types/Interface

# Answer
**The simplicity won!**

I had given up for a moment to solve this problem and I went to learn other things.

Viewing this video about arrays (https://www.youtube.com/watch?v=0otLohaPkXk&list=PLnwVxZ2WVVpl1sOPaEzK--4fXzq2ZQvE-&index=44), I can develop a very simple solution to my problem.

**Just add a Custom Event to the Tower blueprint:**

**In the NPC blueprint, after the Cast To Tower just call and write the name of the Custom Event:**

Another way, which would be what I thought at the time I asked the question.

**Also using the Cast To Tower (NPC blueprint):**

To be able to use the result in the While Loop.

From this second method you do not need to create an Custom Event.
> 0 votes

---
Tags: unreal-4, blueprints
---


title: How to render a trimmed sprite?

text:
# Question
Title: How to render a trimmed sprite?
I used TexturePacker to create an atlas for me and I've read it into my game. I can use unrotated and untrimmed sprites and it works fine. Now I would like to support trimmed sprites and I'm running into a conceptual issue.

I'm not sure how to do the untrimming. What do you do with the trim information?

My sprite is rendered as a quad with 4 vertices and 4 uv's.

Let's say the original sprite was:

```
size.width = 100;
size.height = 100;

```

Let's say that it exists in the atlas at:

```
location.x = 0;
location.y = 0;
location.width = 100;
location.height = 100;

```

To draw this untrimmed image, I do the following.

1. Compute 4 vertices for the sprite. I use the height/width ratio to adjust the top right and bottom right vertices. That way the sprite's aspect ratio is what you would expect
2. Compute 4 UV for the sprite. In the above case, if the atlas is 1024 pixels square, then the UVs would form a box between the points (0.0, 0.0) to (0.1, 0.1)

And this works fine. I can see an untrimmed image exactly as you would expect.

Enter trimming....

Let's say the original sprite was:

```
size.width = 100;
size.height = 100;

```

Let's say that it was trimmed in the atlas too:

```
trim.x = 5; // it was trimmed "in" from the left by 5 pixels
trim.y = 5; // it was trimmed "down" from the top by 5 pixels
trim.width = 15; // it was trimmed "in" from the right by 15 pixels
trim.height = 15; // it was trimmed "up" from the bottom by 15 pixels

```

So now the final location in the atlas is:

```
location.x = 0;
location.y = 0;
location.width = 80;
location.height = 80;

```

What I'm confused about is how to "untrim" the image when it is drawn. I tried:

* Moving the UV's by the amount that was trimmed. This resulted in a stretched image and in other tests, I saw parts of the adjacent sprites. You can't really move a UV.
* Moving the vertices by the amount that was trimmed. Some of my sprites are actually animations. This causes some frames to have different heights and widths -- sprite appears to "bounce". It's bounding box shifts around too with the trimming. (Currently, I have AABB's formed tightly around the vertices of the sprite -- which is what you would expect when the sprite is not trimmed.)

I clearly am missing the concept here. How does one "untrim" the sprite during a render? (I'm using OpenGL) Am I supposed to move around the vertices, but not the bounding box?

# Answer
> 2 votes
What you have to do is roughly the following:

1. Pretend that your sprite has the original size in your game. This is important to keep animations aligned.
2. Instead of rendering the original sprites' quad you have to

* use the quad of the trimmed sprite: Trim offset with trimmed sprite size
    * apply the scene transformations (rotation, scale , translation)
3. Don't modify the UVs.

I can't give you an exact formula because this depends on several other factors (scene coordinate system orientation, pivot point / anchor point on your sprite, your sprite coordinate system,...) but I hope this gives you an idea.

This image shows you the trimmed sprite inside the virtual "full" sprite. The trim offset is shown as a green line from the sprite's origin (black circle). The blue line stands for the sprite's transform (calculated from translation, scale and rotation).

Another option for you would be to use the Polygon Trim Mode. The difference here is that you get a list of triangles instead of a quad with the original coordinates in the source sprite.

---
Tags: opengl, sprites, spritesheet, spritebatch, texture-atlas
---


# Question
Title: How to make a proper release build - Unity Android - x86, ARM32, ARM64
I'm trying to create a release on Google Play.

I currently have `Build App Bundle` checked in the build settings, and it helps decrease the build size.

In player settings I've `IL2CPP` set as the scripting backend, and `x86` \+ `ARM32` \+ `ARM64` checked as target architectures.

Once built it creates `*-symbols.zip` in addition to just `aab`.

My questions are,

* Do I need `x86` \+ `ARM32` \+ `ARM64` all checked? (I want to comply with Google's new 64-bit requirement)
* Can I build split aab's similar to 'split APKs by target architecture'? If so can I have the same version code for aab's which targets different architectures? Is there any advantage of doing so?

# Answer
> 2 votes
Google’s requirement is only for ARM64 support. You don’t need x86.

You do not normally split aab files. The aab has all of the architectures in it, and it is split into the correct apk by the Play Store, based on what device is downloading it. You can use bundletool to generate an apk to test with, or you can upload it to the Play Store and set it to alpha/internal testing to test the splitting when actually downloaded.

Normally during testing though, it’s recommended to just build an apk, as it is faster to build an apk than an aab and then an apk from that.

---
Tags: unity, android, google-play
---


# Question
Title: How to connect to a server without hard coded passwords?
I have two features in my game that need to connect to a server of some kind that requires authentication: a bug reporter and a leaderboard.

The bug reporter will take the users report and add it as a card to my trello board. In my code I have my personal accounts key and token, the board name, and the list name. This is hard coded so if someone ever decompiles my game, they could destroy my trello board. They could spam it, add new lists, delete my existing lists etc.

The leaderboard can't use something like steamworks leaderboards or gamecenter leaderboards as I intend to sell my game on many different stores, some of which don't have leaderboard systems. I also don't want to have to manage different leaderboard systems for every store - that will get messy.

How can I connect to my own server with a database of scores without hard coding the password into my script?

I've seen people say to put it into App.Config, but I believe that it is only for WinForms/WPF etc. Some say to store it in an encrypted config file, but then I will need to store the key to decrypt it somewhere... Others say it's completely pointless and futile.

Surely there must be a way!

# Answer
> 5 votes
Don’t. You cannot secure your password indefinitely. What you can do is restrict access remotely. I don’t know anything about trello, but if it allows multiple logins with multiple permissions, you could create a user with more restrictive permissions and include those credentials in the game.

Another alternative, if this is not supported, is to make a second server which the game connects to, and that server turns requests from the game into requests to trello. The server is what holds the trello credentials. Make an entirely separate API on this second server, just for you bug reporter. The server then processes the content, making sure it’s valid before passing it on using trello API calls. You can have another form of credentials to access the bug reporter if you want, although as mentioned earlier, they won’t be secret forever.

Same thing with your leaderboards. You can’t keep it secure forever. You can introduce player logins, cryptographic signing at multiple levels of complexity, and encryption to deter casual hacking, but consider how important it is for your leaderboard remain 100% accurate before heading down that rabbit hole. The only way to be sure is to run the game on a server, instead of on the player’s device. Probably not necessary. Just make sure you have an API on the server for handling the leaderboard, rather than directly exposing the database to the internet.

---
Tags: unity, server, databases, encryption, authentication
---


# Question
Title: Unity - I can't change the "colorOverLifetime" property of the "Particle System" via script
The goal is to remove the particles via script with fade effect. But I'm not just interested in an alternative, I want to understand why my code doesn't work.

The code below is modified to show only the important parts. I can't know before what time the particles will be dissolved, so I can't set the parameter from the editor.

`StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys` This is the important point (see the log image). The gradient does not take my new values but `alphaKey` is correct.

**Why ?** *Thanks*

```
private bool FadeStarts = false;

void Update()
{
    if (FadeStarts) return;
    StartCoroutine(fadeStars(false));
}

private IEnumerator fadeStars(bool show)
{

    FadeStarts = true;

    ParticleSystem.ColorOverLifetimeModule c = new ParticleSystem.ColorOverLifetimeModule();

    c = StarsConfig.Stars.colorOverLifetime;

    Gradient g = c.color.gradient;

    Debug.Log("OFF " + c.color.gradient.alphaKeys[0].alpha + " --> " + g.alphaKeys[0].alpha);

    GradientAlphaKey[] alphaKey = new GradientAlphaKey[2];
    alphaKey[0] = c.color.gradient.alphaKeys[0];
    alphaKey[1] = c.color.gradient.alphaKeys[1];

    while (c.color.gradient.alphaKeys[0].alpha > 0f) {

        alphaKey[0].alpha -= StarsConfig.VelocityAlpha * Time.deltaTime;
        alphaKey[1].alpha -= StarsConfig.VelocityAlpha * Time.deltaTime;

        StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys(c.color.gradient.colorKeys, alphaKey);

        Debug.Log("g " + alphaKey[0].alpha + " --> " + StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[0].alpha);

        /*
        StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys(
            new GradientColorKey[] { new GradientColorKey(Color.white, 0f),
                                    new GradientColorKey(Color.white, 1.0f) },
            new GradientAlphaKey[] { new GradientAlphaKey(StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[0].alpha - (StarsConfig.VelocityAlpha * Time.deltaTime), 0f),
                                    new GradientAlphaKey(StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[1].alpha - (StarsConfig.VelocityAlpha * Time.deltaTime), 1f) });

        */

        yield return 0;
    }

    StarsConfig.Stars.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);

    FadeStarts = false;
}

```

**UPDATE**

Ed\_Marty's suggestion is correct, and the solution is there (thanks!). But I would like to understand what is the difference between these two codes.

**This code works**

```
var col = StarsConfig.Stars.colorOverLifetime;
while (col.color.gradient.alphaKeys[0].alpha > 0f) {

    float alpha = StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[0].alpha - (StarsConfig.VelocityAlpha * Time.deltaTime);

    Gradient grad = new Gradient();
    grad.SetKeys(
        new GradientColorKey[] {
            new GradientColorKey(Color.white, 0.0f),
            new GradientColorKey(Color.white, 1.0f) },
        new GradientAlphaKey[] {
            new GradientAlphaKey(alpha, 0.0f),
            new GradientAlphaKey(alpha, 1.0f) });

    col.color = grad;

    yield return 0;
}

```

**And this doesn't work**

```
while (StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[0].alpha > 0f) {

    float alpha = StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys[0].alpha - (StarsConfig.VelocityAlpha * Time.deltaTime);

    StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys(
        new GradientColorKey[] { new GradientColorKey(Color.white, 0f),
                                 new GradientColorKey(Color.white, 1.0f) },
        new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0f),
                                 new GradientAlphaKey(alpha, 1f) });

    yield return 0;
}

```

# Answer
> 3 votes
`ColorOverLifetimeModule.color` is a property getter that returns a *copy* of the `MinMaxGradient` struct's values.

So your first earlier code `StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys(...)` takes this copy, and modified the copy... then discards it. Since you were modifying the copy, your particle system's original values remain unchanged.

The magic line in the new code is `col.color = grad`, which takes the modified gradient you've made and hands it back to the module to update its internal state.

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


title: Custom inspectors cropped since 2019.1

text:
# Question
Title: Custom inspectors cropped since 2019.1
Since updating to 2019.1, I have noticed that my custom editors are not drawing properly. It is kinda like they were being cropped, for some reason.

Here is an example:

```
public override void OnInspectorGUI()
{
    serializedObject.Update();

    EditorGUILayout.PropertyField(scale);
    EditorGUILayout.PropertyField(threshold);
    EditorGUILayout.PropertyField(index);
    EditorGUILayout.PropertyField(seed);

    Rect r = new Rect(50, 50, 100, 100);
    EditorGUI.DrawRect(r, Color.red);
    serializedObject.ApplyModifiedProperties();
}

```

As you can see, the objects rendered with EditorGUILayout seem to be rendering fine, but when I draw the Rect with `EditorGUI`, the inspector crops part of the Rect.

What is going on??

# Answer
Inside the `EditorGUILayout` methods, Unity keeps track of how much space each control uses, so it can arrange the following ones to avoid overlap.

But non-Layout methods like `EditorGUI.DrawRect`, it doesn't use this layout system or track the space you're using.

It looks like older versions of Unity would let drawing overflow past the layout-reserved space, while the version you're using limits the drawing area to what you've reserved. (Or clears unclaimed area below where it thinks the bottom of the control sits)

We can fix this by reserving some extra space with:

```
float extraHeight = 100f;
var space = EditorGUILayout.GetControlRect(false, extraHeight);

```

This doesn't draw a control on its own, just holds space for whatever you want to draw there.
> 1 votes

---
Tags: unity
---


# Question
Title: Ubuntu-Unity3D All Compiler Errors Problem
Before 2 weeks ago I can develop games on Ubuntu with Unity3D but after some updates or somethings I give "***all compiler errors have to be fixed before you can enter play mode***" messages. If I compile code on Intellij Rider it's ok, no problem. There is nothing on Unity console and I am researching about it since 2 weeks but I can not find any solution. I tried to install mono and .net core, yesterday find line ending problem an try to different editor but they don't work.

Produce Steps:

* Create new 2D project
* Add empty object to scene
* Add script to empty object
* Compile

ubuntu: 18.04

unity3d: 2017.4.26f1 and 2019.1

# Answer
> 1 votes
Finally I find solution. First, I tried to compile on MonoDevelop and it compiled successfully but one error. It was about `/usr/lib/mono/*` after than I changed owner for this directory with `sudo chown -R $USER:$USER /usr/lib/mono/` and it works!

---
Tags: unity
---


# Question
Title: Gamemaker Running Animation Flashing, showing single frame, and displaying jump and run sprites at same time
EDIT: I changed the origin of the run sprite to the center, and it is no longer hovering above the jumping sprite. It now flashes in the same location as the run sprite when moving to the side. Everything else is the same.

When I move side to side, the jump sprite moves along the ground while a single frame of the running sprite animation shows up above it and to the side. Both of the sprites flash when this happens. While moving sideways, the sprite slowly sinks into the floor. Jumping works just fine.

I'm very new to game maker and programming in general, so I'm probably making some dumb mistakes. Everything was working fine before I added the "animate" section. Here's the code I'm using:

```
//get player input
key_right = keyboard_check(vk_right);
key_left = -keyboard_check(vk_left);
key_jump = keyboard_check_pressed(vk_space);

//react to imput
move = key_right + key_left;

hsp = move * movespeed;

if (vsp < 10) vsp += grav;

if (place_meeting(x,y+1,obj_wall))
{
    vsp = key_jump * -jumpspeed
}

//horizontal collisions
if (place_meeting(x+hsp,y,obj_wall))
{
    while(!place_meeting(x+sign(hsp),y,obj_wall))
    {
        x += sign(hsp);
    }

    hsp = 0;
}

x += hsp;

//vertical collisions
if (place_meeting(x,y+vsp,obj_wall))
{
    while(!place_meeting(x,y+sign(vsp),obj_wall))
    {
        y += sign(vsp);
    }
    vsp = 0;
}

y += vsp;

//animate

if (move!=0) image_xscale = move;

if (place_meeting(x,y+1,obj_wall))
{
    if (move!=0) sprite_index = spr_player_run; else sprite_index = spr_player_idle;
}
//else
//{
   if (vsp < 0) sprite_index = spr_player_jump //; else sprite_index = spr_player_fall;

   if (vsp > 0) sprite_index = spr_player_jump
//}

```

# Answer
I haven't tested the code but I can foresee one possible problem. Once you change the sprite to spr\_player\_jump you don't change it to spr\_player\_idle or spr\_player\_run until there is a place meeting at x,y+1, obj\_wall.

Normally this might be okay but if your origin is at the center and not the bottom of the sprite's feet it won't trigger. The x,y location looks at the exact point of the origin rather than the whole sprite.

While you're working with this, try something that might help with debugging. Turn your sprite changes into a series of else ifs and have a catch all else statement at the bottom.

```
if(place_meeting(x,y+1,obj_wall)){
  //logic to change sprite to run or idle
}
else if (vsp<0 or vsp>0){
  //logic to change to jump
}
else{
  /*have some kind of debugging info here to detect if none of the above conditions are
  being satisfied. Maybe turn the sprite into some other sprite completely so you know
  something went wrong. That would help know what part is causing the problem.*/
}

```
> 1 votes

# Answer
Your code is fine as is, maybe some lines can be written better and optimizations are possible. But it does work. The reason your character animation glitches is because of the related collision mask.

When your character runs, his legs move and - right like in real life - there's a brief moment when both of them aren't touching the ground. Because of the precise collision mask your sprites have, there will be a step in which your code will be checking for collisions below (`place_meeting(x,y+1,obj_wall)`) when your character *actually* isn't touching the ground in position `(x,y+1)`, assuming then he's jumping/falling.

So, when moving downwards because of gravity, your character will change animation from falling to idling/running, and the glitch repeats.

The solution to your problem is simple: change the collision mask of the sprites you're using (a custom shape is better than "automatic"), or even better use a mask sprite for your `obj_player` so that changing sprites won't affect the collision check: if you run and then stop because a wall, there shouldn't be more space to walk further!
> 1 votes

# Answer
Make sure that your `spr_player_idle` is not middle centred, as this might cause an issue of going through the ground.
> 0 votes

---
Tags: animation, sprites, game-maker
---


title: Capsule to Sphere Collision

text:
# Question
Title: Capsule to Sphere Collision
For my Maths unit at university, we have to manually calculate if a sphere is colliding with a capsule collider.

The information I have to go with is this;

You have the following Sphere:

* LadyBird3 - CentrePoint = (0, 0, 0), Radius = 18.0

And the following capsule

* Sanic - BottomPoint = (0,2,6), TopPoint = (0, 12, 6), Radius = 5.0

Determine if the following pair-wise collision occurs:

## Sanic & LadyBird3

In our lecture, we are told the following;

NOTE: Normalizing at this step is unimportant

First, we are going to check the Dot Product of AC and AB

* If this Dot Product is less than 0, that means the closest point from the line segment to C is A
* So we can just return the squared length of AC and stop any further calculations
* Now we perform the same test with the Dot Product of BA and BC
* Once again, if the Dot Product is less than 0, B would be the closest point on the line segment to C, so we would just return the length of BC and stop any further calculations.

Projection... If the dot product returned \> 0 for both points of the line segment, we need to project C onto AB to get the distance. There's an efficient way to get the squared distance if this is all we care about:

* SquaredDistance = AC.LengthSq - (AC . AB) * (AC . AB) / AB.LengthSq
* When performing the dot product here, we need to make sure that it is NOT normalized.

And the final step is to use this squared distance and compare it to the sum of both radii squared to determine if there is an intersection.

---

So, I'm trying to calculate if they are intersecting or not using the information from above.

All I've managed to come up with is this (Taking away the LadyBird3 positions from Sanics position (TP, BP))

AC = (0, 2, 6)

AB = (0, -10, 0)

Dot Product = -20

BA = (0, 10, 0)

BC = (0, 12, 6)

Dot Product = 120

It feels like with the values I'm getting are not correct, or the process I'm doing is wrong... Is anyone able to point me in the right direction?

# Answer
> 0 votes
With those test values you were given, it's clear that sanic is standing above ladybird (both points of the capsule have a larger y coordinate). Looking at the dot products confirms this:

The dot product of AC and AB was -20, which is less than 0. From your notes:

> If this Dot Product is less than 0, that means the closest point from the line segment to C is A

This makes sense if you think about it. If I were to stand above you, the smallest distance between us would be the distance between your head and my feet.

---
Tags: collision-detection, mathematics
---


# Question
Title: How to determine if and when a point and triangle moving uniformly will collide?
**TLDR;** I just learned this problem can be simplified to: **How to determine the time at which a uniformly moving point will intersect with a stationary triangle?** Also, how to figure out the time when the point will exit the triangle?

I have a player with a triangular line of sight ("field of vision" would be more a accurate term here). I also have an NPC, represented by a point. Currently I have the server update the client about both their positions only when one of them changes speed or direction of movement.

Without a limited field of vision, I was able to solve this. How I intend to solve this new problem is as follows:

* Each time either the player or NPC changes speed or direction (speed is a boolean at the moment, 1 or 0, and will probably remain that way), figure out if a line drawn from the point NPC to the edge of the game "room" at the angle of it's current direction, is within a triangle consisting of one point at the player's current position, and the other two points at the location they would be if the player were to reach the edge of the room moving at their current angle.
* If the above is false, we can ignore the following steps because it means the NPC can't enter the vision field. But if true, continue.
* Figure out at what time the NPC will intersect the player's field of vision. This, I do not know how to do, but I expect there is some formula I can use instead of checking every tick.
* But once I do have this formula, I will use it's return value to set a timer that, when it goes off, will have the server update the client and tell it the location of the NPC.
* Then I will have to also figure out at what time the NPC will **exit** the field of vision, and tell the client to delete or inactivate that NPC.

Does anyone know what mathematical formula I'm looking for? I need to figure out when a moving point will intersect a moving triangle, when they are both moving uniformly (not changing direction or speed). Also, the point in time when the point will exit the triangle.

# Answer
> 0 votes
Everytime you shoot the ball through a triangle, it will hit exactly 2 sides before it exits from it. So you can just get the 2 sides it will collide with, the one it does it first with will be the one it enters through, the other one is the one it exits through.

Let's say the ball is at position \\$(x\_0; y\_0)\\$, moves at a speed of \\$(vx; vy)\\$ and the 2 points of one side of the triangle are \\$(x\_1; y\_1)\\$ and \\$(x\_2;y\_2)\\$. These are the constants. The time the ball hits the side at this speed will be \\$t\\$. This is the unknown.

We can write the equation ot the side like so:

$$y(x)=x(y\_2-y\_1)/(x\_2-x\_1)$$

The position of the ball at time \\$t\\$ is

$$x\_b=x\_0+t\cdot vx$$ $$y\_b=y\_0+t\cdot vy$$

The ball hits the side when these two values satisfy the equation presented earlier. If we substitute these values, we get

$$y\_b=x\_b(y\_2-y\_1)/(x\_2-x\_1)$$ $$y\_0+t\cdot vy=(x\_0+t\cdot vx)(y\_2-y\_1)/(x\_2-x\_1)$$

We need to find \\$t\\$ so we need to rearrange the equation

$$y\_0+t\cdot vy=x\_0(y\_2-y\_1)/(x\_2-x\_1)+t\cdot vx(y\_2-y\_1)/(x\_2-x\_1)$$

$$t\cdot vy-t\cdot vx(y\_2-y\_1)/(x\_2-x\_1)=x\_0(y\_2-y\_1)/(x\_2-x\_1)-y\_0$$ $$t(vy-vx(y\_2-y\_1)/(x\_2-x\_1))=x\_0(y\_2-y\_1)/(x\_2-x\_1)-y\_0$$ $$t=\frac{x\_0(y\_2-y\_1)/(x\_2-x\_1)-y\_0}{vy-vx(y\_2-y\_1)/(x\_2-x\_1)}$$

Since everything on the right side is known, you can calculate t. Do this for every side. The 4 possible outcomes:

* One t is negative, the other two are positive: the smallest of the two positive ones is the entry point, the largest is the exit
* Only one t is positive: This means that the start point is inside the triangle, the only positive side is the exit.
* Neither are positive: The ball won't hit the triangle.
* One calculation isn't possible, because the denominator is 0: this means the the side and the direction of the ball are paralell. Just treat it as a very large negative number.

---
Tags: line-of-sight, fog-of-war
---


title: Z axis in slick2D

text:
# Question
Title: Z axis in slick2D
Firstly, I'm very new to slick2d, java, and coding in general, so if I apologise for any very obvious or basic errors that I've made.

I'm developing a JRPG type thing in slick 2d and the battle system revolves around players and enemies moving around a 7x4 grid, being able to move one space each turn before their normal action. I'm having problems getting different sprites to render in a set order so that an illusion of a three dimensional space is created, with sprites on the bottom row of the grid rendering above sprites in the second row, which in turn renders above the third row and so on.

I've found a few different sources on this website and others saying that the best way is to sort the characters by their y axis position and render them in that order, I've got as far as creating variables for each characters y axis position, put them into an array and made an algorithm that sorts them from lowest to highest, ie. from sprites I'd like to render at the bottom to sprites that should be rendered on the top. I can't figure out how to actually use this sorted array to draw the sprites in the correct order though.

Someone in another thread said:

"Sort the array based on the Y of those objects, from lower to higher. Now when you draw these objects, draw them from 0 to array.length, objects with low value will be drawn first, then objects with higher value will be drawn on top of them."

but I don't know how to draw them from 0 to array.length. Sorry if this is a silly question.

Edit:

for drawing the characters so far I just have:

```
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
    Backdrop.draw(0,0);
    Grid.draw(0,0);

    P3Stance.draw(p3x, p3y);
    P2Stance.draw(p2x, p2y);
    if(Helmeton) {
            P1Stance.draw(p1x, p1y);
        }
    if(Helmetoff) {
            P1StanceU.draw(p1x, p1y);
        }
    }

    Hud.draw(0,0);

```

the x and y values of the characters are just set to static values for now.

For the array and the sorting I have:

```
float[] zarr = new float[8];

```

and in my update method:

```
    zarr[0] = p1y;
    zarr[1] = p2y;
    zarr[2] = p3y;
    zarr[3] = p4y;
    zarr[4] = e1y;
    zarr[5] = e2y;
    zarr[6] = e3y;
    zarr[7] = e4y;

    int n = zarr.length;
    float temp = 0;
    for(int i=0; i < n; i++){
        for(int j=1; j < (n-i); j++){
            if(zarr[j-1] > zarr[j]){
                temp = zarr[j-1];
                zarr[j-1] = zarr[j];
                zarr[j] = temp;
                }
            }
        }

```

# Answer
You have correctly identified that sorting the y positions on their own will not help you draw things in the right order. What you need to do is bundle together the data needed to draw a character, and sort those bundles, then draw the bundles in that order. If it helps you can think of playing cards with the characters' pictures and x and y positions on them. We need to sort the stack of cards by the y position and then look at cards of the stack one by one and draw them.

It looks like you have your character data in separate variables right now, so you'll need to collect them together into bundles so we can sort them. The way data is usually bundled together in Java is with Objects. So let's make a character object. (I have not used slick2D in particular so I'm guessing that `P2Stance` and `P3Stance` are instances of something called a `Stance`. If that guess is not correct you'll have to correct this code slightly.)

```
public class Character {
    public float x;
    public float y;
    public Stance stance;

    Character(float x, float y, Stance stance) {
        this.x = x;
        this.y = y;
        this.stance = stance;
    }
}

```

The above code defines a class of Objects called `Character`. So now you can make new `Character`s with `new` like so:

```
    Character p3 = new Character(p3x, p3y, P3Stance);
    Character p2 = new Character(p2x, p2y, P2Stance);

```

And then you should be able to draw them like this:

```
    p3.stance.draw(p3.x, p3.y);
    p2.stance.draw(p2.x, p2.y);

```

Now you have some special logic for the first player character so we need to handle that case in particular. There are multiple ways to deal with that. The best way depends on the how many characters have helmets. From the code you've shown I can only assume that only the first character will have a helmet. If that is the case, the way that requires the fewest other changes would be to do the check when you make the character object.

```
   Character p1;
   if(Helmeton) {
        p1 = new Character(p1x, p1y, P1Stance);
   } else {
        p1 = new Character(p1x, p1y, P1StanceU);
   }

```

I'm assuming here that `Helmeton` is always `true` when `Helmetoff` is `false` and vice-versa. In that case `Helmetoff` is unnecessary. if you need to do something only when the helmet is off then you can use `!Helmeton`, where `!` means "not" so `!Helmeton` is `true` when `Helmeton` is `false`.

Now that things are bundled you can put the **characters** in an array and sort them by their y positions. Following the way you did it with the floats:

```
    Character[] charactersArray = new Character[8];

    charactersArray[0] = p1y;
    charactersArray[1] = p2y;
    charactersArray[2] = p3y;
    charactersArray[3] = p4y;
    charactersArray[4] = e1y;
    charactersArray[5] = e2y;
    charactersArray[6] = e3y;
    charactersArray[7] = e4y;

    int n = charactersArray.length;
    Character temp = null;
    for(int i=0; i < n; i++){
        for(int j=1; j < (n-i); j++){
            if(charactersArray[j-1].y > charactersArray[j].y){
                temp = charactersArray[j-1];
                charactersArray[j-1] = charactersArray[j];
                charactersArray[j] = temp;
            }
        }
    }

```

Then you can loop over the `charactersArray` and draw all of the characters, in the proper order:

```
int characterCount = charactersArray.length;
for(int i = 0; i < characterCount; i++){
    Character c = charactersArray[i];
    c.stance.draw(c.x, c.y);
}

```

I hope that helps!
> 2 votes

---
Tags: java, slick
---


# Question
Title: How do I make my Unity application quit programmatically?
I made a script and I want to make my game quit, but this does not work. How should I go to make the app quit?

```
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class LevelManager : MonoBehaviour {
  public int Index;

  public void SceneLoad()
  {
    SceneManager.LoadScene(Index);
  }

  public void Quit()
  {
    Application.Quit;
  }
}

```

# Answer
> 5 votes
Use the code below

```
public void QuitGame()
{
    Application.Quit();
}

```

# Answer
> 2 votes
You can check for some button in `Update()`, for example, `Esc` (PC) or `Back` (Mobile):

```
void Update()
{
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        Application.Quit();
    }
}

```

# Answer
> 1 votes
First, this answer assumes that your code works and the only problem is that the `Application.Quit ()` command does not execute.

The `Application.Quit ()` command does not work when testing the application in the **Unity Editor** (for example, by pressing the "Play" button). It would close the **Unity Editor**.

To test, go to the "Files / Build and Run" menu.

This will build and execute the project and `Application.Quit()` will be execute properly.

# Answer
> -2 votes
Application.Quit() method should be inside the Update() message inside a conditional statement wating becoming true to end the application.

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


# Question
Title: Reading data from files in Unity on Android
I have successfully read in and written level data using .dat files on unity PC builds, but compiling for android stops me from being able to read in information from the resources folder. I was under the impression that when it's compiled the resources folder was still accessible? I could create a .dat file in the persistent data path but that means hard coding the information only to serialize it, rather than the data originating from the .dat file itself. How can I include this data within the apk without hard coding it?

Here is my code, working on PC:

```
    Stream file = File.Open("Assets/Resources/levelData.dat", FileMode.Open);

    levelData = (LevelDataFile)bf.Deserialize(file);

    file.Close();

```

Edit: for context, the level data is very simple as this is just a puzzle game, and each level will just have a few starting positions and obstacles etc, and there will be 100+ levels, hence I'm not doing a scene per level.

# Answer
There are two things you can do here.

1. You can continue to keep using the Resources folder, which will be available in android. But the thing is, in android, you have to use file:/// or similar prefix to get the file. Also, I’m not sure if you can use the relative path.

What you can do is, you can access the dat file using the `Resources.Load<TextAsset>(path);` where the path will be relative, and not absolute.

2. You do not need to worry about the absolute path, if you put the dat file in the streaming assets folder instead. You can pick up the file using StreamReader.
> 2 votes

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


# Question
Title: Remove or change graphic of InputField target graphic
I am working on a game in Unity and I have to use an InputField but I would like it to not have a border. Currently it has a black border with a border radius that needs to go.

Through my initial searching, I came across this question and thought I found the answer to my problems.

However, I cannot seem to change or remove this TargetGraphic. If I use the button to the right to pick a new one and set it to none, it just reverts right back to the default graphic. It doesn't accept images and I even tried to set the target graphic programmatically but it didn't work.

This is the current look of the input, you can see the black border.

I also tried (without really hoping for much) to set it like so:

```
public InputField inputField;

void Start()
{
    inputField = GetComponent<InputField>();
    inputField.targetGraphic = null;
}

```

# Answer
Unity provides a default set of image assets. If you set the targetGraphic to null, then it will take the default UI shader, which is why you will see an entirely white patch where your InputField is located.

The default image (32x32), which is provided by Unity, has a black border around the image. If you want to not have a border, then you will have to import your own image, and use that, or you can try to add a few UI effects to get another effect if you want.

When you add an image to Unity, make sure that the image is set as Sprite (2D and UI) in the inspector. You can not use textures in the Source Image of the Image component. If your project was created with the 3D template, then the default setting is set to texture rather than Sprite.

Also, you may be trying to drag and drop the new image into the Target Graphic property of the InputField component. The InputField component take an image target. The same GameObject will have another component which is called `Image`. You want to change the `Source Image` of this component.
> 1 votes

---
Tags: unity, input
---


# Question
Title: Actor does not perform action when spawned?
In the level blueprint I made a code so that after 5 seconds an NPC was spawned, it happens that it does nothing.

Only the NPC I added by the level editor acts correctly.

**Image of what happens:**

**Level Blueprint:**

**NPC Blueprint:**

I did a search, because I imagine that to solve this is to just modify the event to some of the type: **When created** or **when spawned**.

**Search:**

I also thought of something like an event involving the collision between the NPC and the ground, but I considered it silly.

**Link I found and at first I'm thinking that the solution may not be as simple as this:**

https://answers.unrealengine.com/questions/204154/event-dispatcher-on-a-spawned-actor.html

---

**EDIT 1 (Attempt based on ColdSteel's comment)**

**I added 2 impressions to see if the Event Begin Play was not even running:**

**The event is being started correctly and the loop is also:**

But the NPC does not go towards the target points and I do not know the reason.

# Answer
Go to the NPC blueprint at the top of the screen, click **Class Defaults**, search for the **Auto Possess AI** option on the Pawn menu and select the **Placed in World or Spawned** option.

**Image to facilitate:**

I had help from user **Grot13** (https://forums.unrealengine.com/development-discussion/blueprint-visual-scripting/1624007-actor-does-not-perform-action-when-spawned).
> 0 votes

---
Tags: unreal-4, spawning, blueprints
---


title: Finding texture coordinates for plane

text:
# Question
Title: Finding texture coordinates for plane
I am creating a 3D ray tracer and want to add textured planes.

My planes are stored using a position vector and a normal vector.

I want to use a square texture and map it repetitively onto the plane.

How do I figure out a transformation from points (3D vectors) on the plane and points (2D vectors) on a texture? Once I know how to do this transformation, I don't think making it repetitive will be hard, as we can just apply modulo arithmetic.

I thought I could make a basis on the plane by calculating a vector B1 perpendicular to the normal, and then another one, B2, perpendicular to the normal and B1. But once I have these two vectors, I still don't know how to express the point (which is the argument for the function below) in this basis.

```
Vector3 position, normal;
Bitmap texture;

public override Vector3 GetColor(Vector3 point) {
    int u = ?
    int v = ?

    return texture.GetPixel(u, v);
}

```

# Answer
> 1 votes
To go from a point in worldspace, **p = (x, y, z)** and on the plane to texture coordinates **u, v**, you must first create a basis of 2 vectors, **e1, e2** of the plane.

Given that **N** is the plane's normalized normal vector, we first create a vector perpendicular to this normal and some random other vector not parallel to the normal:

```
e1 = Vector3.Normalize(Vector3.Cross(N, new Vector3(1, 0, 0)));

//If normal and (1,0,0) are parallel, change e1
if (e1 == new Vector3(0, 0, 0)) {
    e1 = Vector3.Normalize(Vector3.Cross(N, new Vector3(0, 0, 1)));
}

```

And then we create the second basis vector by taking the cross product of the first basis vector and the normal, so that it is perpendicular to the normal, not parallel to the other basis vector, and thus in the plane:

```
e2 = Vector3.Normalize(Vector3.Cross(N, e1));

```

Then we can get the texture coordinates **u, v** by taking the dot product of the point in worldspace, **p**, with **e1** and **e2** respectively:

```
u = Vector3.Dot(e1, p);
v = Vector3.Dot(e2, p);

```

You might still have to do some scaling by texture sizes.

*Source: UV World mapping in shader with Unity. and @DMGregory*

---
Tags: textures, uv-mapping
---


title: gravity simulation implementation

text:
# Question
Title: gravity simulation implementation
```
this.attract = function () {
        for (let i = 0; i < numofplanets; i) {
            var r = Math.sqrt(Math.pow(blackhole.x - planet[i].x, 2) + Math.pow(blackhole.y - planet[i].y, 2));
            planet[i].acclx = (blackhole.mass(blackhole.x - planet[i].x)) / Math.pow(r, 3);
            planet[i].accly = (blackhole.mass - (blackhole.y - planet[i].y)) / Math.pow(r, 3);
            // planet[i].acclx=(blackhole.x-planet[i].x)/60000; without force implementation in which planets get sucked inside the blackhole
            // planet[i].accly=(blackhole.y-planet[i].y)/60000; without force implementation in which planets get sucked inside the blackhole)
            planet[i].speedy += planet[i].accly;
            planet[i].x += planet[i].speedx;
            planet[i].y += planet[i].speedy;
        }
    }

```

i am trying to create gravity simulation model for a game in JavaScript.i need planets to move around a black hole in elliptical orbits. first i calculate acceleration and then add it to velocity and according to that i calculate the next position of planet. i first tried with just calculating distance vector between planets and black hole but in that scenario planets directly gets sucked inside the black hole and i need them to move in elliptical orbits. i tried calculating acceleration due to gravity but i think formula is wrong so can you correct it or provide some other implementation.

# Answer
The planets need an initial velocity to avoid being sucked into the hole.

If you spawn a planet motionless in space, it will immediately start moving towards the black hole in a straight line.
> 2 votes

# Answer
@Bramm has the right answer. To be more specific, if you want a circular orbit, the planet starts at distance \\$r\\$ from the black hole and the acceleration is \\$a\\$ you want to give the planet an initial velocity of $$ v = \sqrt{r a} $$ perpendicular to \\$r\\$. If you change the speed a little they will enter an elliptical orbit. If you change it too much they'll either get sucked in or fly out in a hyperbolic path.

You might have some slight instabilities from computing the evolution in discrete time steps rather than continuously, but unless you have huge acceleration I don't think this will be a problem.
> 3 votes

---
Tags: physics, mathematics, javascript, simulations
---


# Question
Title: How to update model transform of components when using physics?
I implemented a high level components system for my renderer and am curious about the right way to update the transforms components of models that have a physics rigidbody attached. I am using bulletsharp. To clarify. Transformcomponents holds the model matrix that is used for rendering. Rigidbody holds the worldmatrix that is getting modified by step simulation of bulletsharp. I want my rigidbody and transformcomponents matrices to stay synced.

My idea is to do it like this per render loop:

1. Always use transformcomponent for rendering
2. Execute physics step simulation
3. Update all transformcomponents with new matrices from rigidbody
4. Whenever transformcomponent gets a matrix update from user input and not physics... Update the matrices recursive for the attached rigidbody and all children
5. Render with matrices of transformcomponents

Is there a better way to implement rigidbody physics in a components system for rendering? I use the physics mainly for raycast picking and OBB collision detection.

And when I use the term "better", I mean more efficient in terms of least updates on scene components. Syncing two components matrices seems tedious and I want to know if there is a solution without syncing.

# Answer
> 1 votes
The approach you suggest seems fine to me.

To be the most optimal, you'll want your transformcomponents and Rigidbody matrices be of the same size and organized the same way, so that you could just copy a memory chunk when you update the transformcomponents from Rigidbody.

But to be honest, updating your components matrices is quite trivial when you compare to the work that Bullet does, or that your renderer does, so I would not worry about that as it really seems premature optimization to me.

That being said, you'll want to profile once in a while, just to make sure you keep your architecture in check.

---
Tags: c#, game-loop, entity-component-system
---


# Question
Title: Unity build error "Value cannot be null. Parameter name: path1"
I'm getting this error when trying to build my game for Android, I've googled it but there's only 1 result about it and it didn't work for me as I use 64-bit windows. How can I fix this and what's causing it?

> ArgumentNullException: Value cannot be null. Parameter name: path1 System.IO.Path.Combine (System.String path1, System.String path2) (at :0) UnityEditor.Android.AndroidComponentProperties.Read (System.String directory) (at :0) UnityEditor.Android.AndroidComponentProperties.GetPackageRevision (System.String directory) (at :0) UnityEditor.Android.AndroidSDKTools.BuildToolsVersion () (at :0) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK+SDKBuildToolsDetector.GetVersion (UnityEditor.Android.AndroidSDKTools sdkTools, UnityEditor.Android.AndroidJavaTools javaTools) (at :0) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK+SDKComponentDetector.Detect (UnityEditor.Android.AndroidSDKTools sdkTools, UnityEditor.Android.AndroidJavaTools javaTools, System.Version minVersion, UnityEditor.Android.PostProcessor.ProgressHandler onProgress) (at :0) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (UnityEditor.Android.AndroidJavaTools javaTools, System.Version minVersion, UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK+SDKComponentDetector detector) (at :0) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at :0) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at :0) UnityEditor.Android.PostProcessAndroidPlayer.PrepareForBuild (UnityEditor.BuildOptions options, UnityEditor.BuildTarget target) (at :0) UnityEditor.Android.AndroidBuildPostprocessor.PrepareForBuild (UnityEditor.BuildOptions options, UnityEditor.BuildTarget target) (at :0) UnityEditor.PostprocessBuildPlayer.PrepareForBuild (UnityEditor.BuildOptions options, UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:106) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
>
> Error building Player: ArgumentNullException: Value cannot be null. Parameter name: path1
>
> Build completed with a result of 'Failed' UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

# Answer
Uninstalling Unity/Visual Studio and installing them again fixed the problem for me.
> 1 votes

# Answer
restarting unity fixed the problem for me
> 1 votes

---
Tags: unity, android
---


# Question
Title: How to use AssetBundles with Unity WebGL
I have a Unity WebGL project that tries to load AssetBundles, but I get an error:

> Unable to open archive file: http://localhost:50212/StreamingAssets/Bundles/language\_english

The code that creates the AssetBundles:

```
using UnityEditor;
using System.IO;
using UnityEngine;

public class JC_Bundler: Editor
{
    [MenuItem("Assets/Build AssetBundles")]
    static void BuildAllAssetBundles()
    {
        string path = Path.Combine(Application.streamingAssetsPath, JC_Bundles.Directory);
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
        AssetDatabase.Refresh();
    }
}

```

I can see the AssetBundles do get created and it works on other Windows Standalone and Android platforms.

The code that read the AssetBundle:

```
public void PrepareLanguageAssets(SystemLanguage language, UnityAction onDone, UnityAction onFail)
{
    StartCoroutine(LoadBundle("language_" + language, bundle => {
        if (bundle == null)
        {
            onFail();
        }
        else
        {
            if (languageBundle) languageBundle.Unload(true);
            languageBundle = bundle;
            onDone();
        }
    }));
}

public void LoadLanguageAsset<T>(String name, UnityAction<T> callback) where T : UnityEngine.Object
{
    StartCoroutine(LoadAsset(languageBundle, name, callback));
}

IEnumerator LoadAsset<T>(AssetBundle bundle, string objectNameToLoad, UnityAction<T> callback) where T: UnityEngine.Object
{
    AssetBundleRequest asset = bundle.LoadAssetAsync<T>(objectNameToLoad);
    yield return asset;

    callback(asset.asset as T);
}

```

So when I switch my Unity Editor Platform to WebGL and do a "Build And Run" with the same project I see the above mentioned error.

How can I load AssetBundles in WebGL?

# Answer
> 4 votes
Got it working with the following LoadBundle method:

```
IEnumerator LoadBundle(string bundleName, UnityAction<AssetBundle> callback)
{
    string path = Path.Combine(Application.streamingAssetsPath, Directory, bundleName.ToLower());
    Debug.Log(path);
#if UNITY_WEBGL && !UNITY_EDITOR
    UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(path);
    yield return request.SendWebRequest();

    if (request.isNetworkError || request.isHttpError)
    {
        Debug.LogError(request.error);
    }
    else
    {
        // Get downloaded asset bundle
        callback(DownloadHandlerAssetBundle.GetContent(request));
    }
#else
    var assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(path);
    yield return assetBundleCreateRequest;
    callback(assetBundleCreateRequest.assetBundle);
#endif
}

```

It seems like WebGL cannot open bundles with AssetBundle.LoadFromFileAsync(path), but the UnityWebRequestAssetBundle.GetAssetBundle(path) works. It is probably a better approach for WebGL anyways.

---
Tags: unity, unity-webgl, assetbundle
---


title: Unable to destroy collider Unity3d

text:
# Question
Title: Unable to destroy collider Unity3d
So I was making an android game in unity3d. I wrote a script to draw straight lines with touch what I do is I first create a gameobject named temp and add line renderer to it and give the line renderer properties. Then I create a collider gameobject , parent it to the line and change its dimensions to the dimension of the line. What I am trying to do is add two colliders one while the line is being moved i.e "touch.phase == TouchPhase.Moved" and delete this collider and add another collider when "touch.phase == TouchPhase.Ended". For some weird reasons I am not able to delete the first collider.

Here is my code

```
void Update()
{

    foreach (Touch touch in Input.touches)
    {

        if (touch.phase == TouchPhase.Began)
        {
            temp = new GameObject();
            temp.AddComponent<LineRenderer>();
            temp.layer = LayerMask.NameToLayer("lines");

            lr = temp.GetComponent<LineRenderer>();
            lr.positionCount = 2;
            lr.SetWidth(0.2f, 0.2f);
            lr.material = new Material(Shader.Find("Sprites/Default"));
            lr.SetColors(Color.black, Color.black);

            temp.transform.position = camera.ScreenToWorldPoint(touch.position) + camOffset;
            fingerUp = camera.ScreenToWorldPoint(touch.position)+camOffset;

            lr.useWorldSpace = true;
            spawnCollider = false;

        }

        //Detects Swipe while finger is still moving
        if (touch.phase == TouchPhase.Moved)
        {
            lr.SetPosition(0, fingerUp);
            fingerDown = camera.ScreenToWorldPoint(touch.position)+camOffset;
              lr.SetPosition(1,fingerDown);
            spawnCollider = true;

            lastLine = temp;

            // The first collider temporary one

            BoxCollider2D col1 = new GameObject().AddComponent<BoxCollider2D>();
            col1.transform.parent = temp.transform;
            float lineLength = Vector2.Distance(fingerUp, fingerDown);
            col1.size = new Vector2(lineLength, 0.2f);
            Vector2 midPoint = (fingerUp + fingerDown) / 2;
            col1.transform.position = midPoint;
            float angle = (Mathf.Abs(fingerDown.y - fingerUp.y) / Mathf.Abs(fingerDown.x - fingerUp.x));
            if ((fingerUp.y < fingerDown.y && fingerUp.x > fingerDown.x) || (fingerDown.y < fingerUp.y && fingerDown.x > fingerUp.x))
            {
                angle *= -1;
            }
            angle = Mathf.Rad2Deg * Mathf.Atan(angle);
            col1.transform.Rotate(0, 0, angle);

        }

        if (touch.phase == TouchPhase.Ended)
        {
            if (spawnCollider == true)
            {
                Destroy(col1);  // Deleting the first collider

                // Adding the final collider
                BoxCollider2D col = new GameObject("Collider").AddComponent<BoxCollider2D>();
                col.transform.parent = temp.transform;
                float lineLength = Vector2.Distance(fingerUp, fingerDown);
                col.size = new Vector2(lineLength, 0.2f);
                Vector2 midPoint = (fingerUp + fingerDown) / 2;
                col.transform.position = midPoint;
                float angle = (Mathf.Abs(fingerDown.y - fingerUp.y) / Mathf.Abs(fingerDown.x - fingerUp.x));
                if ((fingerUp.y < fingerDown.y && fingerUp.x > fingerDown.x) || (fingerDown.y < fingerUp.y && fingerDown.x > fingerUp.x))
                {
                    angle *= -1;
                }
                angle = Mathf.Rad2Deg * Mathf.Atan(angle);
                col.transform.Rotate(0, 0, angle);
            }
        }

    }

}

```

I have added comments where I am doing what.

# Answer
I assume that col1 is also declared elsewhere in the code, otherwise I don't understand how this would've compiled.

Notice this line:

```
BoxCollider2D col1 = new GameObject().AddComponent<BoxCollider2D>();

```

You're re-declaring col1 within a limited scope, and so you're not setting the external col1, which is used when the touch phases ends. Use

```
col1 = new GameObject().AddComponent<BoxCollider2D>();

```

Instead, and it should work, although you will get a new collider on every move, which sounds excessive.

On a side note, try to avoid calls to AddComponent/GetComponent in the Update() method - it will incur a significant performance hit. These should be cached in a local field once, instead of queried repeatedly. Also, avoid creating temporary game objects.

I'm not near a work machine, so I haven't tested this code, and it'll probably need some adjustment for it to compile, but I think it shows the gist of my suggestion.

```
GameObject temp;
private LineRenderer lr;
private BoxCollider2D move_collider;
private BoxCollider2D final_collider;

void Start() {
    temp = new GameObject();
    lr = AddComponent<LineRenderer>();
    lr.positionCount = 2;
    lr.SetWidth(0.2f, 0.2f);
    lr.material = new Material(Shader.Find("Sprites/Default"));
    lr.SetColors(Color.black, Color.black);
    temp.layer = LayerMask.NameToLayer("lines");
    lr.useWorldSpace = true;
    move_collider = temp.AddComponent<BoxCollider2D>();

}

void Update()
{
    foreach (Touch touch in Input.touches)
    {

        if (touch.phase == TouchPhase.Began)
        {
            temp.transform.position = camera.ScreenToWorldPoint(touch.position) + camOffset;
            fingerUp = camera.ScreenToWorldPoint(touch.position)+camOffset;
            move_collider.enabled = true;
            final_collider.enabled = false;
        }

        //Detects Swipe while finger is still moving
        if (touch.phase == TouchPhase.Moved)
        {
            lr.SetPosition(0, fingerUp);
            fingerDown = camera.ScreenToWorldPoint(touch.position)+camOffset;
              lr.SetPosition(1,fingerDown);

            lastLine = temp;

            float lineLength = Vector2.Distance(fingerUp, fingerDown);

            move_collider.size = new Vector2(lineLength, 0.2f);
            Vector2 midPoint = (fingerUp + fingerDown) / 2;
            move_collider.transform.position = midPoint;
            float angle = (Mathf.Abs(fingerDown.y - fingerUp.y) / Mathf.Abs(fingerDown.x - fingerUp.x));
            if ((fingerUp.y < fingerDown.y && fingerUp.x > fingerDown.x) || (fingerDown.y < fingerUp.y && fingerDown.x > fingerUp.x))
            {
                angle *= -1;
            }
            angle = Mathf.Rad2Deg * Mathf.Atan(angle);
            move_collider.transform.Rotate(0, 0, angle);
        }

        if (touch.phase == TouchPhase.Ended)
        {
            if (spawnCollider == true)
            {
                move_collider.enabled = false;
                final_collider.enabled = true;

                // Adding the final collider
                final_collider.transform.parent = temp.transform;
                float lineLength = Vector2.Distance(fingerUp, fingerDown);
                final_collider.size = new Vector2(lineLength, 0.2f);
                Vector2 midPoint = (fingerUp + fingerDown) / 2;
                final_collider.transform.position = midPoint;
                float angle = (Mathf.Abs(fingerDown.y - fingerUp.y) / Mathf.Abs(fingerDown.x - fingerUp.x));
                if ((fingerUp.y < fingerDown.y && fingerUp.x > fingerDown.x) || (fingerDown.y < fingerUp.y && fingerDown.x > fingerUp.x))
                {
                    angle *= -1;
                }
                angle = Mathf.Rad2Deg * Mathf.Atan(angle);
                final_collider.transform.Rotate(0, 0, angle);
            }
        }
    }
}

```
> 2 votes

---
Tags: unity, android, touch
---


title: Non-Uniform Random Placement of Sprites

text:
# Question
Title: Non-Uniform Random Placement of Sprites
I'm creating a space game in Godot that has procedurally generated nebulae. A nebula is comprised of between 50 and 200 child particles, all with the same shader assigned to them which creates an effect as follows:

https://gyazo.com/41aa6fb9695a626ece10f7aff144ecba

My issue is that the more particles that are placed, the more the nebula itself starts to resemble a square shape.

I want to be able to place these particles in a way that more closely resembles a cloud formation, which I imagine will use some sort of noise function (Perlin, Simplex?) to do so - but I've only ever used noise for generating graphics, not placing items.

The parent object of the particles can vary in size, as can the number of particles placed within it.

How would I place these particles randomly, while ensuring they more closely resemble cloud formations?

The language I'm using is C#, but Pseudocode is more than fine.

# Answer
The simplest solution would be to use a Gaussian random variable for the x, y and z (if 3d) coordinates. It won't be as inhomogeneous as your example image though (see below on how to improve), but it could work well if you have only 50-200 elements. You can generate Gaussian random variables combining uniform random variables, see here for example (first answer)

https://stackoverflow.com/questions/218060/random-gaussian-variables/218600#218600

A Gaussian random variable will generate a cloud that has a decreasing density. To improve inhomogeneity, you could combine several gaussians together, each with different mean and variance. You might also want to cut points outside a maximal radius.
> 1 votes

---
Tags: c#, godot
---


# Question
Title: ForceMode in AddTorque in Unity game development
In UNITY game development platform while programming in C# I came across a method to add torque to component: **public void AddTorque(float x, float y, float z, ForceMode mode = ForceMode.Force);** In this Function what is meant by **ForceMode**?

# Answer
> 2 votes
ForceMode is an enumeration. It has 4 values,

ForceMode.Acceleration = Constant change not affected by mass

ForceMode.Force = Constant change which is affected by mass

ForceMode.Impulse = Instant change which is affected by mass

ForceMode.VelocityChange = Instant change which is not affected by mass

For more details, watch the Official Unity tutorial for AddForce. https://www.youtube.com/watch?v=MBDWTjn05eg

---
Tags: unity, c#, visual-studio, torque
---