title: Remove material slot via Unity Script

text:
# Question
Title: Remove material slot via Unity Script
I have a lot of duplicated objects, and I need in editor, not in the game, remove specific (18) material slot. Remove not material in slot 18, but remove slot 18. Manually, by hands, it can be done using this button:

All objects that I need to remove slot from has the next mutuals:

1. Contain "\_lod" in the name;
2. Have the same mesh, with the same GUID

I did not find how to get GUID of the given object, so the search, probably need to go by name.

I have never scripted Unity, I even did not write in C# (although I write in C++).

What I done so far: I created an empty game object and assign cs script below to it as a component. `DestroyImmediate(myMaterials[18])`, works almost that I need, but it removes not the slot, but the material on it (and automatically creates default material). I need to remove exactly the slot.

`LookAtPoint.cs`:

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

using UnityEditor;
[ExecuteInEditMode]

public class LookAtPoint : MonoBehaviour
{
    void Iter(GameObject gameObject) // Itterate children
    {
        for (int j = 0; j < gameObject.transform.childCount; j++)
        {
            GameObject a = (GameObject)gameObject.transform.GetChild(j).gameObject;
            MeshFilter viewedModelFilter = (MeshFilter)a.GetComponent("MeshFilter");

            if(viewedModelFilter && viewedModelFilter.mesh && a.name.IndexOf("_lod") != -1) // check if object has mesh and it's name contains "_lod"
            {
                Material[] myMaterials = a.GetComponent<Renderer>().materials;
                if(myMaterials[18].name.IndexOf("Подоконник")!=-1) // not neccesary check if 18s slot has "Подоконник" name (actually now it is already "Default-Material")
                {
                    DestroyImmediate(myMaterials[18]);
                }
            }
            Iter(a);
        }
    }

    void Start()
    {
        List<GameObject> rootObjects = new List<GameObject>();
        Scene scene = SceneManager.GetActiveScene();
        scene.GetRootGameObjects( rootObjects );

        for (int i = 0; i < rootObjects.Count; ++i)
        {
            GameObject gameObject = rootObjects[ i ]; // get root objects

            for (int j = 0; j < gameObject.transform.childCount; j++) // enumarate them
            {
                Iter(gameObject); // iteratevely process the children
            }
        }
    }
}

```

# Answer
> 0 votes
So, as @DMGregory pointed in comments, instead of destroying material, the element of the materials array with needed material should be removed, and new, resized array should be set as component:

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

using UnityEditor;
[ExecuteInEditMode] // for running in editor

public class LookAtPoint : MonoBehaviour
{
    void Iter(GameObject gameObject) // Itterate children
    {
        for (int j = 0; j < gameObject.transform.childCount; j++)
        {
            GameObject a = (GameObject)gameObject.transform.GetChild(j).gameObject;
            MeshFilter viewedModelFilter = (MeshFilter)a.GetComponent("MeshFilter");

            if(viewedModelFilter && viewedModelFilter.mesh && a.name.IndexOf("_lod") != -1) // check if object has mesh and it's name contains "_lod"
            {
                Material[] myMaterials = a.GetComponent<Renderer>().materials;
                if(myMaterials[18].name.IndexOf("Подоконник")!=-1) // not neccesary check if 18s slot has "Подоконник" name (actually now it is already "Default-Material")
                {
                   Material[] aa = new Material[24]; // new array that will be assign. 24 because current length is 25

                   for(int i = 0; i < 24; i++) // fill new array by existing, except 18' element
                   if(i < 18)
                     aa[i] = myMaterials[i];
                   else if(i >= 18)
                     aa[i] = myMaterials[i + 1];

                   a.GetComponent<Renderer>().materials = aa; // set new array
                }
            }
            Iter(a);
        }
    }

    void Start()
    {
        List<GameObject> rootObjects = new List<GameObject>();
        Scene scene = SceneManager.GetActiveScene();
        scene.GetRootGameObjects( rootObjects );

        for (int i = 0; i < rootObjects.Count; ++i)
        {
            GameObject gameObject = rootObjects[ i ]; // get root objects

            for (int j = 0; j < gameObject.transform.childCount; j++) // enumarate them
            {
                Iter(gameObject); // iteratevely process the children
            }
        }
    }
}

```

Summarizing for newcomers like me:

1. In assets, create C# script with code above (notice, that the file name and class name should be the same);
2. Choose any game object on the scene, and open its properties window;
3. In properties window click `Add Component` at the bottom (scroll might be required);
4. Find and choose the ealier created script by file name;
5. By adding the component, the `Start` method will be called, so that's it;

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


# Question
Title: Why do game developers ask for so much money for their games?
For many years now the cost of video games has been bothering me. I’ll admit. I’ve only been playing videos games since the NES days right up to the PlayStation 2, after that I pretty much switched off. So I missed about 3 generations of consoles. But during my active days you brought a game and everything was included and you simple had to play the game long enough to unlock additional content, for free! I’ve been reading and watching the disastrous launch of Gran Turismo 7 and the constant nonstop backlash it’s receiving for its micro transaction system.

At the moment I’m a solo game developer and I will likely need hire people from other areas such as art and music to help me in developing my title. I can’t hand on heart ask my potential future players to cough up £70 for the base game and then additional money for DLC, micro transactions, in app purchases or whatever you want to call it. I feel it’s plan wrong. And don’t get me started on NFTs like what Konami and others have done!

My question is this. How comes other forms of entertainment like buying the latest blockbuster movie is many times cheaper and would cost roughly the same or even more to make. How do these developers justify asking for so much money, including asking players for more money even after the game has been sold (e.g. for minor extra content like a different re-skin)?

Update Do you think these kind of business practices could end up permanently harming the gaming industry?

Also, as I’m a sole game developer. I have to think about every single aspect of my titles development not just the coding side of things, but also the time and money from my personal savings I see myself having to pump into my project. I have come across others with the same concerns. So I thinks it’s a very valid question as people like me are not paid by the hour and we don’t have the luxury of focusing entirely on the code/tech side of game dev and so I have to worry about my future players/customers (if any) views and concerns they have due to being treated like a cash cow.

# Answer
> At the moment I’m a solo game developer and will likely hire people from other areas to me in developing my title

So I will turn this into actual advice. But not advice on what to say to justify high prices.

---

## Prices do not reflect costs

The relation between the production cost and the selling price is not direct. Since games inmaterial - and even more so with digital distribution - you can sell an unbounded number of licenses.

But don't forget that once a person bought license to a game they are unlikely to buy another. Also, people buy new games only ever so often.

So the question is: How elastic is the market? How much does it respond to price incentives? If people will buy pretty much the same number of licenses if you raise or lower the price, you have the incentive to sell as expensive as they can get away with it.

*However, you don't have to do what the big studios do with their prices.*

Adjusting your prices is a tacit negotiation with everybody. Thus, it is a good idea to study the market to see what people would find to be a reasonable price. And for a gut check, you can ask yourself if you would be willing to pay for it if it was made by somebody else.

---

## Game studio finances

I presume you have a budget for the development of your game. It has to pay for equipment, salaries, and so on. But that budget is not infinite, so there will be a date when it runs out. That is your main dead line. You want your game done before you hit it.

If you starting a video game development studio and you hired employees, I hope you don't lay them off after the first release. But having employees around doing nothing isn't good either. So you have incentive to start another project right away. *So you haven't recoup the first investment and you are incurring in a second one.*

*In fact, for management it makes sense to have a couple projects going at the same time, and move people between them, so they are always stressed.*

Hopefully income arrives and it is greater than expenses so the studio can stay afloat. Thus, if your games can provide income for a long time, it is better for the finance of the studio. And I remind you that once a person bought license to a game they are unlikely to buy another. So you would want to keep attracting new players.

There is soft cap on the number of player due to the time the game will be in the zeitgeist before fading from relevance behind newer titles. And there is a somewhat harder cap in the the market share of the console/platform. *The market is only so elastic.*

*By the way, keeping servers online also has a cost.*

If only games could produce a secondary revenue stream… Ah.

---

Well, if you consider using micro-transactions, consider also a freemium model. Sadly mobile games have given freemium a bad reputation, and price signals effort put in the product. But freemium is a way for players to pay for the game after they know they enjoy it, not before.

That isn't the only option, of course. In particular for an online game, a subscription model makes sense.

**Whatever you decide for the monetization of your games, I would like to encourage transparency.**

---

It is important to be smart with your budget. In particular consider the scenario where you need to make unexpected changes to your game. If it does not imply to pay for voice actors and motion capture and and so on, then making the changes is easier. Thus, if you intent to have those things, it is a good idea to delay them.

It is a mistake to try to plan it all ahead of time with the intention of getting it right the first time… Because chances are you are not going to, and you will have to make changes. On a similar note, test early. If you test and discover you need to make changes, hopefully it does not mean a big sunk cost.

---

## On selling cosmetics

Selling cosmetics means that what you are selling does not affect game play at all. Cosmetics do not make the game easier.

With this monetization strategy, you do not have the incentive to make the game bad (or impossible, i.e. paywalls) to push player to buy something that makes the game easier (pay to win).

So, I would defend selling skins - in particular in freemium games - as long as the player knows what they are getting, and it is not paired with predatory tactics such as fear of missing out. And don't forget some artist had to make those skins, so they do have a cost.

However, yes, we had ridiculously priced golden mounts and also monocles and other things. Don't do that. Unfair prices are unfair. And it is a good thing that people speak up about bad micro transactions. And you don't want to be on the receiving end of that.
> 2 votes

# Answer
These are both good and very warranted questions. It's nothing short of ridiculous paying 70 quid or more for some of the emerging AAA titles. Micro-transactions behind anything but free-to-play is just as much so.

In response to one of your questions, regarding the cost of films vs games..well, it's complex. First and foremost, the majority of films will see more puchases/views than than a typical game will see first-light plays.

Programmers are expensive to hire, particularly if they specialise in something like DirectX. One main reason for the high wages they expect is simply because they're not as common as programmers who specialise in other areas.

So while game development can be expensive, platforms like Steam and GamePass are good choices for distribution.
> -2 votes

# Answer
The video game industry is more cut throat than you think. Everyone wants to be here, and nobody wants to work (human nature.) Studios that get funding by massive producers have no choice but to follow orders/deadlines to the T, or they have to lay off Jimmy who has a wife and two kids.

Blockbuster films are no walk in the park, either, I promise you. When you're selling art, in the form of entertainment, you are a luxury item. You are worthless, in a survival aspect. Pair this with how competitive the video game industry is, only the best survive. For lack of a better 'best' barometer, money usually takes the top priority.

Making video games is a lot more involved than my beloved super mario world days. A super mario world can be pooped out by an amature within days. To pull off some of these modern games.. They can require tons of engineers, all working together in the same codebase, with TIGHT deadlines.

I get it. The games industry sucks right now. All industries have highs and lows. What the players want, is what makes the money. What makes the money, is what comes out.

'Ol Tommy can cry online about those microtransactions all day. But the reason why Farmville runs, is because Tommy stole his mom's credit card to buy those tokens. He's crying because he's grounded.

TL;DR: Don't hate the player, hate the game. (Your player is your customer, please don't hate them)
> -3 votes

---
Tags: game-industry, costs
---


title: Why I get indexoutofRangeException

text:
# Question
Title: Why I get indexoutofRangeException
I am not sure why, for the below code, I keep getting `IndexoutofRangeException` for the variable `ResistorBand2`? The error is pointing to the line `ResistorBand2[0]=Random.Range(1,10)` and I cannot spot the error.

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

    public class AdvanceWayPoint : MonoBehaviour
    {
        public Transform player;
        bool CreateResistor;
        int RandNum;
        public GameObject myprefab;
        public GameObject FloatingText;
        public GameObject Resistor;
        public GameObject[] way1;
        public int[] ResistorBand;
        public int[] ResistorBand2;
        public float ResistorValue;
        public float ResistorValue2;

        void Start()
        {
            Random.InitState(System.DateTime.Now.Millisecond);
            CreateResistor = true;
        }

        void Update()
        {
            if (CreateResistor == true)
            {
                Count(1);
                CreateResistor = false;
                Waypoint();
            }
        }

        public void Waypoint()
        {
            Vector3 SpawnPosition = player.transform.position;
            Vector3 ExactSpawnPoint = new Vector3(SpawnPosition.x + Random.Range(1, 10), 0, SpawnPosition.z + Random.Range(1, 10));
            Vector3 ExactResistorSpawnPoint = new Vector3(ExactSpawnPoint.x+Random.Range(1,4), ExactSpawnPoint.y+7, ExactSpawnPoint.z+Random.Range(1,4));

            if (RandNum == 1)
            {
                for (int g = 0; g < 2; g++)
                {
                    ResistorBand[0] = Random.Range(1, 10);
                    ResistorBand[1] = Random.Range(1, 10);
                    ResistorBand[2] = Random.Range(1, 5);
                    ResistorBand[3] = Random.Range(1, 3) * 5;
                    ResistorValue = ((ResistorBand[0] * 10 + ResistorBand[1]) * Mathf.Pow(10, ResistorBand[2]) / 1000);
                    Debug.Log("RUN");
                    Instantiate(Resistor, ExactResistorSpawnPoint, Quaternion.identity);
                }

                way1 = GameObject.FindGameObjectsWithTag("1K ohm");
                Debug.Log(way1.Length.ToString());

                if (way1.Length == 0)
                {
                    ResistorBand2[0] = Random.Range(1, 10);
                    ResistorBand2[1] = Random.Range(1, 10);
                    ResistorBand2[2] = Random.Range(1, 5);
                    ResistorBand2[3] = Random.Range(1, 3) * 5;
                    var go=Instantiate(FloatingText, ExactSpawnPoint, Quaternion.identity);
                    Instantiate(myprefab, ExactSpawnPoint, Quaternion.identity);
                    go.GetComponent<TextMesh>().text = ResistorValue.ToString()+" K ohm +/-"+ResistorBand[3].ToString()+"%";
                    Instantiate(Resistor, ExactResistorSpawnPoint, Quaternion.identity);
                }
            }
        }

        public int Count(int number)
        {
            RandNum = number;
            return RandNum;
        }
    }
}
```
</code></pre>

# Answer
You are declaring your class-level arrays:

```
public int[] ResistorBand;
public int[] ResistorBand2;

```

but you aren't initialising them anywhere, like:

```
ResistorBand = new int[7];    // This array has 7 elements
ResistorBand2 = new int[10];  // This one has 10 elements

```

If you don't initialise them, they will have zero length. Trying to access a 0-length array at any position raises an `IndexoutofRangeException` error.

Since your issue only happens with `ResistorBand2`, this means you're actually assigning values to `ResistorBand` in the editor, from the Inspector. You should do the same with `ResistorBand2`.
> 3 votes

# Answer
It's because you didn't initialize `ResistorBand2`. here's what you should do:

```
int[] ResistorBand2 = new int[4];

```

and by doing so, you shouldn't get the error anymore. but if you want a more easy-to-manage array, you may consider using `List<int>` as you can `add` new members to it:

```
List<int> ResistorBand2 = new List<int> { };
// ...
ResistorBand2.Add(Random.Range(1, 10));

```
> 3 votes

# Answer
I don't see any initializations for `public int[] ResistorBand2`. This creates an array, but doesn't put any elements into it.

You're trying to refer to an element that does not exist yet, so you get the "out of range" error.
> 2 votes

---
Tags: unity
---


title: How to start a game with "3-2-1 go"?

text:
# Question
Title: How to start a game with "3-2-1 go"?
I want my game to start after a "3-2-1 go" countdown.

My Player Script :

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

public class Player : MonoBehaviour {

    private Rigidbody2D myRigidbody;

    private Animator myAnimator;
    private int skor;
    public Text toplamSkor;
    public Text highScore;

    [SerializeField]
    private float hiz;
    private bool sagaBak;

    [SerializeField]
    private AudioSource altinSes;

    // Use this for initialization
    void Start () {
        sagaBak = true;
        skor = 0;
        highScore.text = PlayerPrefs.GetInt ("HighScore", 0).ToString();

        myRigidbody = GetComponent<Rigidbody2D> ();
        myAnimator = GetComponent<Animator> ();

    }

    // Update is called once per frame
    void Update () {

        float yatay = Input.GetAxis ("Horizontal");
        TemelHareketler (yatay);
        YonCevir (yatay);

    }

    private void TemelHareketler (float yatay){
        myRigidbody.velocity = new Vector2 (yatay *hiz, myRigidbody.velocity.y);
        myAnimator.SetFloat ("KarakterHizi", Mathf.Abs (yatay));

    }
    private void YonCevir (float yatay)
    {

        if (yatay > 0 && !sagaBak || yatay < 0 && sagaBak) {

            sagaBak = !sagaBak;
            Vector3 yon = transform.localScale;
            yon.x *= -1;

            transform.localScale = yon;
        }
    }
    void OnCollisionEnter2D(Collision2D other) {

        if (other.gameObject.tag == "altin") {
            other.gameObject.SetActive (false);
            altinSes.Play ();
            skor = skor + 1;
            SkorAyarla (skor);

            if (skor > PlayerPrefs.GetInt ("HighScore", 0))
            {

                PlayerPrefs.SetInt ("HighScore", skor);
                highScore.text = skor.ToString();

            }
        }
}
    void SkorAyarla(int count)
    {
        toplamSkor.text = count.ToString ();
    }

    public void Reset (){
        PlayerPrefs.DeleteAll ();

    }
}

```

# Answer
First you need something to show the countdown in. This is a job for the UI system. A canvas with a simple text field in the center would do:

Now you need a controller for that text field which changes the text from "3" to "2" to "1" to "Go" in intervals of 1 second each. A good way to do timed events like this is a coroutine which you start at the beginning. Here is an example of a `CountdownController` script:

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

public class CountdownController : MonoBehaviour
{
    public Text countdownTextField;

    void Start()
    {
        StartCoroutine(CountdownCoroutine());
    }

    IEnumerator CountdownCoroutine() {
        countdownTextField.text = "3";
        yield return new WaitForSeconds(1.0f);
        countdownTextField.text = "2";
        yield return new WaitForSeconds(1.0f);
        countdownTextField.text = "1";
        yield return new WaitForSeconds(1.0f);
        countdownTextField.text = "Go!";
        // start the game here
        yield return new WaitForSeconds(1.0f);
        countdownTextField.text = "";
        yield return null;
    }

}

```

Add this script to any persistent game object in your scene (I would either recommend the canvas or the text field itself) and then drag the text field to the "Countdown Text Field" of the script in the inspector:

When you now start the game, the timer text should count down and disappear (technically it doesn't disappear. It is still there, it just shows an empty string).

You might notice that this script shows the countdown but doesn't actually do anything on on "Go!". I just added a comment "Start the game here".

The reason why I omitted this is that depending on your game you likely need to do far more than just unlock the player controlls. Start the enemy controllers, enable game physics, initialize timers etc.. Maybe you don't even want to spawn the player prefab before the countdown reached zero. You need to know what "starting the game" actually means for your specific game and program it yourself.
> 6 votes

# Answer
I will offer my option:

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

namespace Core
{
    public class CountDown: MonoBehaviour
    {
        [SerializeField] private int _countdownTime = 3;
        [SerializeField] private Text _countdownDisplay;

        void Start()
        {
            StartCoroutine(Countdown(_countdownTime));
        }

        IEnumerator Countdown(int seconds)
        {
            _countdownDisplay.gameObject.SetActive(true);

            int count = seconds;
            while (count > 0)
            {
                // display something...
                _countdownDisplay.text = _countdownTime.ToString();

                yield return new WaitForSeconds(1);
                count--;
            }

            // count down is finished...
            _countdownDisplay.text = "GO!";
            yield return new WaitForSeconds(1);
            _countdownDisplay.gameObject.SetActive(false);
             StartGame();
        }

        void StartGame()
        {
            // do something...
            // GameController.Instance.BeginGame();
        }
    }
}

```
> 0 votes

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


title: Libgdx - accelerating string displaying

text:
# Question
Title: Libgdx - accelerating string displaying
My renderBoard is slow and it's because of font.draw function. I read that I should use stringBuilder instead of string, but it didn't help at all. I suppose I'm using it wrong. Could you guide me to the right way?

```
public void renderBoard(SpriteBatch sb, BitmapFont font) {
    int L = 0;
    String string;
    ...
    // "size" is a private variable of the class, the same goes for "stringBuilder"
    for(int k = - size + 1; k <= size - 1; k++) {
        for (int j = 1; j <= size - Math.abs(k); j++) {
            string = L + "";
            for(int g = 0; g < string.length(); g++) {
                stringBuilder.setCharAt(g, string.charAt(g));
            }
            sb.draw(
                    this.getTexturesArray().get(L),
                    x_j_k_position,
                    y_j_k_position
            );
            font.setColor(Color.WHITE);
            font.draw(
                    sb,
                    stringBuilder,
                    x_j_k_position,
                    y_j_k_position
            );
            L++;
        }
    }
}

```

If I comment out the font.draw line, the game accelerates, so I guess here lies the problem.

# Answer
> 0 votes
I assume your font uses a different texture/image than your sprites. If it does, the slowdown may be caused by texture binding.

In your loop, you are drawing a sprite using texture `A` (`sb.draw()` call) and immediately after you draw text using texture `B` (`font.draw()` call). These calls alternate many times, causing OpenGL to switch texture (which is an expensive operation) many times in a single `render()` call.

To solve this, you could use two loops:

```
for(int k = - size + 1; k <= size - 1; k++) {
    for (int j = 1; j <= size - Math.abs(k); j++) {
        //draw the sprite - sb.draw(...)
    }
}
for(int k = - size + 1; k <= size - 1; k++) {
    for (int j = 1; j <= size - Math.abs(k); j++) {
        //draw the text - font.draw(...)
    }
}

```

Note: The code above may not be optimal and it's here just to give you an idea what I mean. Nevertheless, if your problem is caused by texture binding, it should speed up the game significantly.

---

Another reason why your code may not be performing well is because you use `StringBuilder` incorrectly.

```
string = L + "";

```

gets compiled into

```
string = new StringBuilder().append(L).append("").toString();

```

... and creates a new `StringBuilder` object each time - more work for garbage collector.

Since variable `L` is a number, you don't need `StringBuilder` at all (nor you need string concatenation) and you can use `String.valueOf()` method to get the String value of the number.

```
string = String.valueOf(L);
//you don't need the StringBuilder loop

```

# Answer
> 0 votes
Unfortunately, the default text rendering methods come with a performance cost on most graphics platform and should be used for things like debugging only.

Might I suggest using a bitmap as the source for your text? Bitmap font renderers are a much faster means of displaying text. There are countless examples of how to do this, along with tools you might need to create your font bitmap. Check out LMNOpc Bitmap Font Builder.

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


title: object array positioning-LibGdx

text:
# Question
Title: object array positioning-LibGdx
In my game,if I touch a particular object,coin objects will come out of them at random speeds and occupy random positions.

```
public void update(delta){
if(isTouched()&& getY()<Constants.WORLD_HEIGHT/2){
         setY(getY()+(randomSpeed * delta));
         setX(getX()-(randomSpeed/4 * delta));
         }
  }

```

Now I want to make this coins occupy positions in some patterns.Like if 3 coins come out,a triangle pattern or if 4 coins, rectangular pattern like that.

I tried to make it work,but coins are coming out and moved,but overlapping each other.Not able to create any patterns. patterns like:

This is what I tried

```
int a = Math.abs(rndNo.nextInt() % 3)+1;//no of coins
        int no =0;

        float coinxPos = player.getX()-coins[0].getWidth()/2;
        float coinyPos = player.getY();
        int minCoinGap=20;
        switch (a) {
        case 1:
            for (int i = 0; i < coins.length; i++) {
                if (!coins[i].isCoinVisible() && no < a) {
                    coins[i].setCoinVisible(true);

                    coinxPos = coinxPos+rndNo.nextInt()%70;
                    coinyPos = coinyPos+rndNo.nextInt()%70;
                    coins[i].setPosition(coinxPos, coinyPos);
                    no++;
                }
            }
            break;
        case 2:
            for (int i = 0; i < coins.length; i++) {
                if (!coins[i].isCoinVisible() && no < a) {
                    coins[i].setCoinVisible(true);
                    coinxPos = coinxPos+minCoinGap+rndNo.nextInt()%70;
                    coinyPos = coinyPos+rndNo.nextInt()%150;
                    coins[i].setPosition(coinxPos, coinyPos);
                    no++;
                }
            }
           break:
          ......
          ......
          default:
            break;

```

may be this is a simple logic to implement,but I wasted a lot of time on it and got confused of how to make it work. Any help would be appreciated.

# Answer
> 1 votes
You can use sin and cos to get the points each coin should be from the object. This example will create 3 coins around the exploding object.

```
    explodedItems = new Array<Vector2>(); // array to hold coin positions
    Vector2 explodingObject = new Vector2(10,10); // object location that has coins explode from it
    int amountOfItemsToExplode = 3; // amount of items to explode out
    int distance = 5;
    float angleIncrement = 2 * PI / amountOfItemsToExplode;
    // use sin+cos to get points coins explode from
    for(float i = 0; i < amountOfItemsToExplode; i++){
        float x = (float) Math.sin(i * angleIncrement) + explodingObject.x;
        float y = (float) Math.cos(i * angleIncrement) + explodingObject.y;
        explodedItems.add(new Vector2(x*distance,y*distance));
    }

```

# Answer
> 0 votes
> Now I want to make this coins occupy positions in some patterns.Like if 3 coins come out,a triangle pattern or if 4 coins, rectangular pattern like that.

For this, I'll use a circle:

1. Use a random number as the radius
2. Let's say you have `x` coins, the position of each one can be calculated like this:

`new Vector2(cos(i * (360 / NumberOfCoins) + Offset) * Radius, sin(i * (360 / NumberOfCoins) + Offset) * Radius);`

whereas `Offset` means how much to rotate the whole thing (can be used for more randomization and is in degrees) and `i` counts from 0 to `NumberOfCoins - 1`

Final Note: I'm not familiar with `libgdx` so the code I've written may need to be changed but the logic behind it is the same

---
Tags: libgdx
---


# Question
Title: How are map/room/world-related game assets usually organised and implemented?
I'm trying to build a simple 2D Shoot 'Em Up type of game in C++ using SDL2 and an Entity Component System, which I've already implemented. The idea is to have different maps/rooms where you have to kill all enemies before moving on to the next. Each room has different types of obstacles and those obstacles are positioned differently in each room.

I already have the design of the first map with all the obstacles in it. However, I suspect I should really separate the actual "map", i.e., wherever you can walk on, from the obstacles' assets in order to keep them as separate entities with their own (static) Hitbox components. This would still require me to place each and every obstacle on the map "by hand", i.e., tweaking their coordinates on the map until it looks like my current design.

My question is simply: is there a more efficient way to do this? How is this usually dealt with in the (indie) gamedev community?

If possible, I would also like to know if keeping each tree, box, wall... as separate entities with different IDs is actually a good idea. And if so, would that also be the way to implement invisible walls as map limits?

Thanks in advance for your time!

# Answer
> 2 votes
I'm not sure how you've got your mapping implemented and wondered if you'd considered tile-based mapping? If I'm not mistaken, your concerns are based around an efficient way to construct your game map. (placing objects, etc.)

I wrote a game similar to what you've described and when faced with level design, I incorporated editing into the engine, allowing me to quickly construct maps, define areas where the player cannot pass, etc. and test in real-time. This is not as complex as it may sound.

There are many examples of tile engines out there and they are very easy to implement -- an array of `Tile` structures is all that is required. Add a `Blocked` property to the `Tile` structure in order to define whether or not a player can pass into that area. I also stored the source co-ordinates for a tiles image in the `Tile` structure, to save looking it up when drawing the map.

Having some experience with mapping, I'd like to assist if I can.

---
Tags: architecture, sprites, assets, sdl2, entity-component-system
---


# Question
Title: How can I get the color of a pixel in a SharpDX Direct2D bitmap or render target?
I am working on a simple drawing game and I need to get a Flood Fill algorithm working for a Paint Bucket tool.

I have the game running on WinForms at the moment which is extremely slow, but I have a working Flood Fill algorithm there, I could get the code to support SharpDX if I could get the color of a pixel (either from a `SharpDX.Direct2D1.Bitmap` or from a `SharpDX.Direct2D1.RenderTarget`), but I can't find a way to do so.

# Answer
Since the algorithm I am using accepts `System.Drawing.Bitmap` I only needed a way to capture a rendered frame onto one and then render the result, this is far from efficient but I've got a solution.

The solution uses PrintWindow from the WIN API.

```
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);

```

This would probably only work if an embedded SharpDX control is used as capturing the control via handle won't do, but capturing a parent control, in this case the form, will return the desired image.

```
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

Graphics g = Graphics.FromImage(bmp);
IntPtr hdcBitmap = g.GetHdc();

PrintWindow(Handle, hdcBitmap, 0);

g.ReleaseHdc(hdcBitmap);
g.Dispose();

// Crop the image to return only the part that we need, without control borders.
bmp.Clone(new Rectangle(SharpDXControl.Location.X + 1, SharpDXControl.Location.Y + 1, SharpDXControl.Width - 2, SharpDXControl.Height - 2), bmp.PixelFormat);

```

To draw the image, I created a new `SharpDX.Direct2D1.Bitmap` instance and used the pixel data (bits) from the `System.Drawing.Bitmap` instance.

```
SharpDX.Direct2D1.Bitmap dxbmp = new SharpDX.Direct2D1.Bitmap(renderTarget, new SharpDX.Size2(bmpWidth, bmpHeight), new BitmapProperties(renderTarget.PixelFormat));
dxbmp.CopyFromMemory(bmpBits, bmpWidth * 4);
renderTarget.DrawBitmap(dxbmp, 1F, SharpDX.Direct2D1.BitmapInterpolationMode.Linear);
dxbmp.Dispose();

```

The algorithm I am using is a slightly modified version of the Queue-Linear Flood Fill Algorithm.
> 0 votes

# Answer
In case someone wishes to access pixel data in Direct2D...

Pixel data from a `Direct2D1.Bitmap1` is available to access colors.

The `Bitmap1` whose pixel data we wish to examine must be created using the `Direct2D1.BitmapOptions.CannotDraw` **AND** `Direct2D1.BitmapOptions.CpuRead` flags in the `Direct2D1.BitmapProperties1`, which is passed to the `Bitmap1` constructor.

The Direct2D documentation fails to mention that both flags are required.

The `Map` method of `Direct2D1.Bitmap1` returns a `Direct2D1.DataRectangle`. This features two members: `DataPointer` and `Pitch`:

`DataPointer` is an `IntPtr` which points to the start of the memory occupied by the `Bitmap1` we're working on. Under GDI this is referred to as Scan0.

`Pitch` is the width of the `Bitmap1` expressed in bytes but includes padding (a 245x245 image yields a Pitch of 1024, suggesting byte alignment padding).

Here's some code which demonstrates the copying of data to and from a `Bitmap1` using `Marshal.Copy`:

```
' Create array of bytes for pixel data
m_Bytes = New Byte(m_Bitmap.PixelSize.Width * m_Bitmap.PixelSize.Height * 4 - 1) {}
' Lock the bitmap
m_DataRectangle = m_Bitmap.Map(MapOptions.Read)
' Copy pixel data to array
Marshal.Copy(m_DataRectangle.DataPointer, m_Bytes, 0, m_Bytes.Length)
' Copy pixel data array back to DataRectangle
Marshal.Copy(m_Bytes, 0, m_DataRectangle.DataPointer, m_Bytes.Length)
' Unlock bitmap
m_Bitmap.Unmap()

```
> 0 votes

---
Tags: sharpdx, direct2d
---


title: Changing part of a sprite in 2D game

text:
# Question
Title: Changing part of a sprite in 2D game
Let's say I have a character and certain things (shoes, vest, hat, etc.) can be changed (visually, just the color changes).

What came to my mind was creating each of them as a separate sprite and then using the appropriate one at a time. but this makes a LOT of sprites (considering animations too) and wastes a lot of my time just repainting them manually.

After that, I thought about changing pixels (my game is in pixel-art style) with a certain color with another color (like changing all `#563125` to `#137426`) but I have no idea how to do this and if I did, how to save the new sprites instead of the old ones (sprites are in `.psd` format)

So my question is: How can I do this in Unity?

# Answer
> 1 votes
When you want to build a 2d character from multiple sub-sprites, then you might want to look into the 2d animation package. It allows you to create a rig for a 2d sprite which allows to move sub-sprites via the animation system and even deform sprites. This can greatly reduce the number of individual frames you need to draw. It also comes with a SpriteSwap feature which allows you to exchange individual sub-sprites while still using the same rig with the same animations.

Regarding recoloring sprites: Unity can change how a sprite is rendered through the shader assigned to the material assigned to the corresponding SpriteRenderer.

Note that the sprite renderer has a "Color" property, which you can set in the inspector or via script.

The SpriteRenderer communicates this color to the pixel shader via the vertex colors. The shader of the default sprite material already makes use of this information to implement some simple color tinting. So you might be able to do what you want to do by simply changing the color property of the SpriteRenderer.

However, when you want a more advanced coloring effect, like say only recolor parts of the sprite or use a different recoloring algorithm, you will have to look deeper into programming your own sprite shader. When you need any help with this, feel free to open a new question.

---
Tags: unity, 2d, sprites, color, pixel-art
---


# Question
Title: What can I set in rigid body and collidable objects to ensure that the angle after collision is larger?
I have a rigid body with sphere shape attached and a static collidable box. When sphere hits the box at an angle, for some reason, the angle that it bounces off from is really small: https://imgpile.com/i/59FC34

I want to increase this angle somehow. What properties can I change in a rigid body to control this angle? NVIDIA PhysX allows changing interia, center of mass, mass, linear and angular dampening, restitution and friction (shape).

# Answer
After @DMGregory's suggestion, I started to play around with the friction. All the objects had both static and dynamic friction set to 1.0. So, I just set them to 0.0 to ensure that no energy was lost due to friction, which solved my problem. In order to improve collision even further, I also applied a bit of torque to the ball to make it roll.
> 2 votes

---
Tags: physics, physics-engine, physx
---


# Question
Title: How do I enlarge my gameobject(circle) in one straight go instead of enlarge it little by little (frame by frame) when hit the collision?
```
 public class Player : MonoBehaviour
{
    CircleAttack _Attack;
    [SerializeField] GameObject _circle;
    float getHit;
    float CircleTimer;

    public event System.Action OnPlayerDeath;

    private void Awake()
    {
        _Attack = _circle.GetComponent<CircleAttack>();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.tag == "Shards")
        {
            Destroy(collision.gameObject);
            getHit++;
            if (getHit >= 1)
            {
                _Attack.Expanding();
            }
        }
    }

```

This was a reference to this script of a gameobject that I want it to expand.I mean like gradually increases it continuously, not frame by frame. sorry I didn't phrase it properly

```
 public class CircleAttack : MonoBehaviour
{
    public void Expanding()
    {
        transform.localScale += new Vector3(2, 2, 2) * Time.deltaTime;
    }

```

# Answer
As I understand, what you want to do is this: call the function once, and then let it expand the object.

Well, that's a job for `coroutine`s as they won't run just in a frame. Here's what you should write instead:

```
public IEnumerator Expanding()
{
    while (transform.localScale != DesiredScale)
    {
        transform.localScale *= Speed * Time.deltaTime;
        yield return null;
    }
}

```

So basically what it does is this:

while the object's scale isn't the same as what you want it to be (`DesiredScale`) the coroutine will make it bigger by `Speed * Time.deltaTime` (the value of `Speed` depends on how fast you want the sphere to expand) and then waits until the next frame.

I suggest that you read more about `coroutine`s as they are, in my own experience, very useful and time-saving
> 0 votes

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


# Question
Title: My sprite is hovering slightly above my tilemap in Unity 2D
I have a simple object with a `Rigidbody 2D` and a `Box Collider 2d`, that's supposed to fall and land on a tilemap with a static `Rigidbody 2D` and a `Composite Collider 2D`. However, it slightly hovers above, as seen in the below picture. I've tried fiddling with edge radius and other settings, however, it doesn't seem to work. The gap can be seen in both the scene view and the play mode, so it's not a rendering problem. Any ideas?

# Answer
> 3 votes
There are several ways to fix this:

1- Go to Project Setting and then Physics 2D and change the value of Default Contact Offset to something smaller

2- make the collider slightly smaller than the sprite

3- use an Edge Collider instead of a Box Collider

Personally, I would go with the second option as the other two have their own issues:

* Edge collider doesn't call functions like `OnCollisionEnter2D` and that may become a problem for you
* changing the value of Default Contact Offset may result in a "glitchy" gameplay (like when the player jumps and then collides with the ground)

---
Tags: unity, 2d, tilemap, collider
---


# Question
Title: How to differentiate between enemy and something else in Godot?
So, I have a simple **3D** game with a player, an enemy, and walls. I've figured out how to detect collisions between my player (RigidBody) and an enemy or wall (Static Body). I want to know how can I group all the enemies so that the player collision can detect whether it's collided with an enemy or a wall, kind of like tags in Unity?

# Answer
> 3 votes
Godot has groups, that work like Unity tags but are more powerful and versatile.

You can assign nodes to one or more groups, and check for group membership when a collision occurs.

Objects in the same group can belong to different layers. If you don't need layer-based collisions, just use groups; otherwise, Arian Keshvari's answer is the additional way to go.

# Answer
> 3 votes
> kind of like tags in unity

that's what you should do in Godot too, but not the tag, rather the layer.

For instance, you can put all of your enemies in a layer named `Enemy` or the player in a layer named `Player`. It's called `Collision Layer` on Godot and the `Collision Mask` is just like the `Layer Collision Matrix` in Unity and can define which layers can collide with each other.

If you need to know the layer of an object you just have to use this code:

`object.get_collision_layer()`

And it can be used to determine further actions like taking damage, interacting with NPCs, opening doors, etc.

---
Tags: collision-detection, 3d, godot, gdscript
---


title: How to 2D shadow image transformations

text:
# Question
Title: How to 2D shadow image transformations
I'm writing a 2D top-view game and I will have to draw shadows. Sun will always be at North-West. My game has, for example, tanks. I have tank image and tank's shadow image:

My idea is to draw first the shadow image, then (on top of shadow), the tank image. Like the left part of previous image.

But, when my tank rotates, I simply rotate the tank by its center. But how to transform the shadow image according to the north-west sun ? Is there a classic 2D game algorithm for that ?

# Answer
Order of rotation and offset is the key.

I presume you had tried the following wrong order and it didn't work right:

1. Offset (!) the shadow
2. Rotate (!) the shadow
3. Draw the shadow
4. Rotate the tank
5. Draw the tank

This would be the correct order:

1. Rotate the shadow
2. Offset the shadow
3. Draw the shadow
4. Rotate the tank
5. Draw the tank

Note that the shadow offset may depend on the objects vertical position (height) - e.g. airborne vehicle's (or jumping tanks's) shadow offset will be larger.
> 1 votes

# Answer
> Sun will always be at North-West.

As I can see, the shadow you use is no different from the tank itself, and it has a fixed position (relative to the tank) so you may consider using a `Shadow` component and changing the `offset` value a bit so it will look as if the sun in at north-west.
> 0 votes

---
Tags: 2d
---


# Question
Title: Unreal Engine Character Replication. Where to find out what exactly is being replicated? Is the Material replicated?
I have been experimenting with Steamworks SDK and Unreal Engine. I have managed to successfully code the connectivity part (ie. I can connect to a Steam Lobby with several players and it will then travel us into the game map with one client then being the host server.).

Everything went swimmingly to begin with (all the player locations/rotations are being replicated), but if I set the material of the player on the server it didn't seem to replicate down to the clients.

I spent a long while reading the documentation and also trying to read through the Engine code, but sadly I cannot confirm or deny if the material is supposed to be replicated as part of the default replication in the UE4 Character class.

Should I be able to set the material only on the server, or should I instead do it on ALL clients, for EACH player?

# Answer
> 1 votes
By default, material and material instances are not replicated. You need to make sure that they are set to be replicated and use a RepNotify to pass the info to the server.

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


# Question
Title: View Full File Name in Project View Unity
Is there any way to view the full name of a file in Unity Project view without having to click on it?

This picture sums up my frustration:

# Answer
The quick way is to switch to a "detailed" view of the files, by sliding the zoom slider to the left:
> 6 votes

# Answer
## Use two project views

(An improvement on Galandil's answer)

Open two project views, one zoomed out to list ("detailed") view and the other in some larger convenient size (thumbnails view):

When an asset is selected in one project view, it is also focused/highlighted in the other.

Based on this Unity forum post by user thomascrozelonpro.
> 4 votes

---
Tags: unity
---


# Question
Title: How to make camera smoothly follow behind player in Unity 3D?
Following the advice posted here, I made a camera that follows a player behind with:

```
    public Camera roomCam;
    public GameObject playerGO;
    private float camMotionSpeed = 5f;
    private float camRotationSpeed = 50f;

    void Start() {
        camOffset = new Vector3(0, 3, -8);  //x=sideways, y=up/down, z = forward/back
        roomCam.transform.position = playerGO.transform.position + (roomCam.transform.forward * camOffset.z) + (playerGO.transform.up * camOffset.y);
        roomCam.transform.LookAt(playerGO.transform.position);
    }

    private void UpdateCameraPosition() {

        //Move
        Vector3 newCamPosition = playerGO.transform.position + (playerGO.transform.forward * camOffset.z) + (playerGO.transform.up * camOffset.y);
        newCamPosition = Vector3.Slerp(roomCam.transform.position, newCamPosition, Time.smoothDeltaTime * camMotionSpeed); //spherical lerp smoothing
        roomCam.transform.position = newCamPosition;

        //Rotate
        Quaternion newCamRotation = Quaternion.LookRotation(playerGO.transform.position - roomCam.transform.position);
        newCamRotation = Quaternion.Slerp(roomCam.transform.rotation, newCamRotation, camRotationSpeed * Time.smoothDeltaTime); //spherical lerp smoothing
        roomCam.transform.rotation = newCamRotation;

    }

    private void LateUpdate() {
        UpdateCameraPosition();
    }

```

This works correctly in general, but the smoothing function which is just meant to make the camera slowly "catch up" in position and rotation to the user as they move around is quite jerky.

Smoothing specifically is done by the lines:

```
        newCamPosition = Vector3.Slerp(roomCam.transform.position, newCamPosition, Time.smoothDeltaTime * camMotionSpeed); //spherical lerp smoothing
        newCamRotation = Quaternion.Slerp(roomCam.transform.rotation, newCamRotation, camRotationSpeed * Time.smoothDeltaTime); //spherical lerp smoothing

```

Is there some better way of smoothing this that can be applied that will not create so much jerking or wobbly jello motion?

Thanks.

# Answer
> 1 votes
Solution was described here: forum.unity.com/threads/camera-jitter-problem.115224

If you're following a physics based object you need to run `UpdateCameraPosition()` on `FixedUpdate()` not `LateUpdate()`.

---
Tags: unity, 3d, camera
---


# Question
Title: Why do colliders have a tendency to spin and develop crazy angular velocity in Unity when used as my "player"?
I am trying to create a basic collider for a rigidbody player in Unity 3D. I have been experimenting with numerous shapes but found it hard to get what I want.

The primary issue seems to be if the object does not have a square and large base with which to contact the floor, it will develop a tendency to accumulate angular velocity and spin like a top, even if you just try to make it walk forwards/back, and especially if a turn is initiated.

However, I need smaller objects and ones that can go over small bumps, which a big large cube can't.

I have tried:

***1) Capsule***

If I increase the mass these seem to behave okay and don't spin when walking straight. They can climb small bumps. But if you put one on a rotating platform, it is not rotated by the platform, since it presumably only has one contact point with the ground and thus can't be rotated by it.

***2) Beveled Cylinder***

I thought the logical solution would then be a beveled cylinder which looks like this:

However this spins like crazy! It develops angular velocity in the Y axis even when just moving it forward or back. And I can't seem to damp the angular velocity with my code either. I don't know where it's coming from or why but it's unusable.

***3) Beveled Cube***

The next idea I then had was for a beveled cube. This works okay if the base and overall cube is very large, but if you shrink the base to make it better able to climb bumps or make it more "human sized" it also starts spinning like crazy:

I am at a loss for how you are supposed to move around 3D characters as rigidbodies.

My motion code I've been testing is:

```
 private void CheckKeyboardMovementCommand() {
        if (Input.GetKey(KeyCode.UpArrow)) {
            //Move the Rigidbody forwards constantly at speed you define (the blue arrow axis in Scene view)
            playerRB.velocity = new Vector3(playerGO.transform.forward.x * playerMotionSpeed, playerRB.velocity.y, playerGO.transform.forward.z * playerMotionSpeed);
        }

        if (Input.GetKey(KeyCode.DownArrow)) {
            //Move the Rigidbody backwards constantly at the speed you define (the blue arrow axis in Scene view)
            playerRB.velocity = new Vector3(-playerGO.transform.forward.x * playerMotionSpeed, playerRB.velocity.y, - playerGO.transform.forward.z * playerMotionSpeed);
        }

        if (Input.GetKey(KeyCode.RightArrow)) {
            //Rotate the sprite about the Y axis in the positive direction
            playerRB.angularVelocity = new Vector3 (0, 3, 0);

        }

        if (Input.GetKey(KeyCode.LeftArrow)) {
            //Rotate the sprite about the Y axis in the negative direction
            playerRB.angularVelocity = new Vector3(0, -3, 0);
            //playerGO.transform.Rotate(new Vector3(0, -1, 0) * Time.deltaTime * playerTurnSpeed, Space.World);
        }

        if (Input.GetKeyDown(KeyCode.Space)) {
            playerRB.velocity += new Vector3(0, 9, 0); // add a jump velocity
        }

        if (Input.GetKeyUp(KeyCode.UpArrow) || Input.GetKeyUp(KeyCode.DownArrow)) {
            playerRB.velocity = new Vector3 (playerGO.transform.forward.x * 0, playerRB.velocity.y, playerGO.transform.forward.z * 0);
            playerRB.angularVelocity = new Vector3(0, 0, 0);

        }
        if (Input.GetKeyUp(KeyCode.RightArrow) || Input.GetKeyUp(KeyCode.LeftArrow)) {
            killAngularVelocity = true;
            playerRB.angularVelocity = new Vector3(0, 0, 0);
        }
    }
        // Update is called once per frame
    void Update()
    {
        CheckKeyboardMovementCommand();
    }

```

However, even putting in commands to kill the angular velocity on releasing a button don't work. These "spinning" rigid bodies will maintain high angular velocity in the editor display and keeping spinning inappropriately.

I have my player object frozen in the z and x axis so it doesn't fall over, but otherwise I need the y-axis unfrozen for movements and to be rotated, eg. by platforms.

Can anyone explain what might be going on or how I can have a collider that:

* doesn't spin like a top
* can also climb small bumps
* works whether big or small
* can be rotated by an underlying rotating platform?

Why do these objects develop such crazy angular velocities that don't go away even when you stop their motion or try to directly zero it out? Even when they're not moving and appear to be perfectly still the angular velocity can persist in the Editor panel.

Thanks.

# Answer
> 2 votes
Set `playerRB.angularVelocity = Vector3.zero` each frame. Or tick the "Freeze Rotation: y" constraint in the `Rigidbody` component inspector. (Don't worry, this only prevents physics forces from twisting the object - your own code can still force the object to yaw with `MoveRotation()`)

What's happening is that one edge of this collider brushes against a wall, obstacle, or even a bump/slope in the floor, imparting a torque to the body. If nothing opposes that torque, the body will develop a small angular velocity causing it to turn. Angular drag is fairly mild by default, so this small bump can cause a spin that lasts for quite a while, unless you expressly block it.

As Philipp suggests in the comments, a `CapsuleCollider` is a much better solution than the mesh you've shown. It's significantly more efficient for computing collisions, smoother, and will show fewer collision artifacts than a mesh collision.

`MoveRotation()` should also be preferred over `Transform.Rotate()` for physics bodies. You should treat the `Transform` component as read-only and direct every change in position and orientation through the physics system.

---

Your updated code working with angular velocity doesn't work because you are zeroing angular velocity only on the one frame when the player releases the arrow key, not on all the other frames when the body could pick up unwanted angular momentum. Your code should read something more like this:

```
float rotation = 0f;

if (Input.GetKey(KeyCode.RightArrow))
        rotation += playerTurnSpeed;

if (Input.GetKey(KeyCode.LeftArrow))
        rotation -= playerTurnSpeed;

playerRB.angularVelocity = new Vector3(0, rotation * Time.deltaTime, 0);

```

Note that this controls the angular velocity on every frame, not only the frames when the key is currently held or just recently released.

---

You'll also want to consider not hard-coding a specific keyboard key for each direction, and instead link these two directions to an axis. Using the old Input Manager, that would look like this:

```
float rotation = Input.GetAxis("Horizontal") * playerTurnSpeed;

```

(Note we no longer need two `if` statements - this one liner handles turning left, right, and stopping. It also supports gamepads and multiple synonymous key options out of the box)

Or using the new Input System, something like this:

```
 float rotation = steeringAction.ReadValue<float>() * playerTurnSpeed;

```

...where `steeringAction` is an Action that can be remapped flexibly to different inputs of your choosing.

---
Tags: unity, physics, rigidbody, collider, rigid-body-dynamics
---


# Question
Title: Casting from APawn* to MyCustomCharacter* ? Is this ok?
So I am still learning C++ but been using it for quite a while. But I have a function which is not working properly (separate question posted here: Calling Client RPC in order to assign a Team value to clients. How to check the Role properly? - Development Discussion / Multiplayer & Networking - Unreal Engine Forums).

I am starting to think the problem MIGHT be about how I cast from the APawn\* to APlayerMallet\* (which is actually extending ACharacter not APawn).

```
APlayerMallet* mallet=(APlayerMallet*)gamestate->PlayerArray[i]->GetPawn();

```

The code compiles and it does find the function in APlayerMallet if I change the IF statement to force it to call the function in APlayerMallet.

I suppose here I am just looking for confirmation that it is ok to do such a cast.

# Answer
why not use the UE's Cast function?

```
APlayerMallet* mallet=(APlayerMallet*)gamestate->PlayerArray[i]->GetPawn();

```

Becomes:

```
APawn* ThePawn = gamestate->PlayerArray[i]->GetPawn();
APlayerMallet* mallet= Cast<APlayerMallet>(ThePawn); //returns nullptr if failed
if(!mallet)
{
//return or error handle
}
mallet->DoStuff();

```
> 3 votes

---
Tags: c++, unreal-4, unreal
---


# Question
Title: How do I make several Image components transparent collectively as one sprite with a CanvasGroup?
I've run into a problem where using the CanvasGroup component to fade in/out several Image components under a hierarchy produces an unwanted result, where each individual sprite that overlaps with another sprite will "blend" its color values in the overlapping areas like so:

The intended effect I'd want is for the red and blue squares to fade out together like they were one sprite.

As you can see, the overlapping parts of the squares are not "blending together".

One hack is to just overlay a blank image of the same size as all of the image components shown on the screen and just fade that. However, this doesn't work at all if the overlayed image also has several other image components.

I would like to know if there are any other alternatives that aren't too complicated.

# Answer
*CanvasGroup* applies its `alpha` value to each child UI element individually. That's why your sprites don't blend like they were one.

You can avoid this problem using a **Render Texture** before applying transition effects. This temporary texture contains all your UI elements in a single image. Then, you change its alpha value to fade it out.

### Arrange the UI elements

We will render certain UI elements separately from the others. To do so, we first create a new *Canvas* GameObject. Then, we move the UI elements of interest in the Hierarchy as its children. Note: such new *Canvas* has no *CanvasGroup* Component. Let's call it **FadeCanvas** for simplicity.

### Set up the *Canvas* Component

Select the **FadeCanvas** GameObject, and change the *Canvas* Component `Render Mode` value to 'Screen Space - Camera'. Unity will prompt you to specify a Render Camera.

Create a new Camera as a child of your Main Camera. (It's a child just for in-editor management purposes). Let's call it **UICamera**, and set its `Culling Mask` to 'UI' only.

Now, select **FadeCanvas** again, and drag and drop **UICamera** in the `Render Mode` field box.

### Create and assign the Render Texture

Create a Render Texture from the Project window (or via *Assets \> Create \> Render Texture*). Select the **UICamera**, and drag and drop the Render Texture in the `Target Texture` field box.

Note: you need to set the Render Texture size to the current screen size via code. Otherwise, the Render Texture won't be the correct size when rendering.

### Display the Render Texture

In your primary *Canvas* GameObject, create a *RawImage* and assign the Render Texture as its `Texture` source. Transparency is achieved by changing the alpha value of the `color` attribute.

If the Render Texture's size is the same as the screen's, stretch it across the whole *Canvas* via *RectTransform*'s Anchor Presets.

---

This solution may be a bit tricky to set up. I recommend it for complex, dynamic UI setups. If no elements are overlapping, fall back to *CanvasGroup*s and `alpha` values. If objects overlap but then nothing else moves, you can optimise by rendering UI on the Render Texture only when changes occur. If you deactivate the **UICamera**, the Render Texture will contain the last rendering pass.
> 1 votes

# Answer
It would be better if you told about what the objects really are and why all of them can't be a single sprite, but given what you said, I suggest using a `sprite mask`:

In your example, add a `sprite mask` component and set the sprite to the blue box, and set the `Mask interaction` to `not visible under mask` so the part of the red box under the blue box will be ignored
> 0 votes

---
Tags: unity, 2d, sprites, unity-ui
---


# Question
Title: instantiateInWorldSpace vs. worldPositionStays in Unity
I'm trying to instantiate an object using `Object.Instantiate()` like this:

`Instantiate(carrot, transform, true);`

according to the below snippet from the documentation, this is what I should be allowed to do.

However, when I try to highlight this in my code, it instead shows me this:

As far as I can tell (though I am very limited in my knowledge of this stuff) this shouldn't be possible. Do I have any other way to show which version I want to use? I need to use this specific version because I want the instantiated object to inherit the scale of the object that's instantiating it. I've used this solution before when instantiating objects, I don't know what's changed.

# Answer
> 1 votes
These are just two ways of naming the same thing. All they did was change the name of the parameter, but the interpretation is the same:

> pass true to position the new object directly in world space. Pass false to set the Object’s position relative to its new parent.

So, you don't have to do anything to select a different overload. This is the only one that exists. If this overload is not giving you the behaviour you want, post about that issue, and we can help you write alternative code that does give the behaviour you want.

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


# Question
Title: Finding average input value over time in seconds
I'd like to find the average input value from a controller over the last n seconds (say the last 0.1 seconds) and do this every frame.

I can see how to do this for the past n frames by storing a list of values for the last n frames and averaging that total every frame, but I want to account for a variable frame rate as the resulting output is driving a character controller and should feel precise and consistent. I tried storing a list of value pairs containing the input value and delta time value for every frame, then counting back through the list of delta time values until they sum to n seconds, then using the total of those input values to work out the average, but it seems a bit clunky and means I have to guess how big the list should be to store enough values, is there a better way?

# Answer
> 2 votes
Two options:

## 1. Arithmetic average (worse)

Have a 2-column table that has sufficiently many rows to be able to store all values for your chosen time (0.1 s in your question) at the potentially highest possible, supported frame rate - say 300 fps (unless you limit it to for example 60). 300 fps would mean 30 rows, in order to store all values for the last 0.1 seconds. During each frame, (over)write the oldest one row in the table, in a circular fashion; ie. have an index counter that wraps back to 1 after 30 (or whatever the number of rows is).

Each row holds a time stamp (a time, not a delta time!) and the controller value at that time stamp.

When calc'in the average (sum of values / number of values), per frame apparently, use only rows with a timestamp that is greater than Tnow - 0.1. Ignore other rows, but if all rows are to be ignored, ensure you use at least the most recent row.

Weakness: Potentially much data and calculation, result not necessarily better than \[below\].

## 2. Quasi-average (better)

```
NewValue = [read from controller]
NewShare = min(1, FrameDeltaTime / 0.1)
OldShare = 1 - NewShare
ThisValue = (OldValue * OldShare) + (NewValue * NewShare)
OldValue = ThisValue // Use ThisValue for whatever needed

```

This gives a nice "rubber band affect", removes some stutter from unstable controllers etc., and above all, it is a minor calculation that produces an equally good result as in /1/ above; additionally itäs easy to trim the 0.1 s into whatever is the good value, by trial and error.

* if FrameDeltaTime is 0.0001, it takes 0.999 of the old and 0.001 of the new
* if FrameDeltaTime is 0.0167 (60 fps), it takes 0.83 of the old and 0.167 of the new. Doing that repeatedly "seeks" towards whatever the controller outputs.
* if FrameDeltaTime is 0.1 it takes 0 of the old and 1 of the new (ie. 0.1 s is the "break point")
* if FrameDeltaTime is 5 (eg. a long blocking load delay) it takes 0 of the old and 1 of the new

# Answer
> 5 votes
Expanding on Stormwind's lead, I'd be curious whether your application needs a windowed average with equal weights per unit of time, or if an exponential moving average may suffice. The latter is very simple to implement, and can be adapted to a variable framerate like so:

```
 float weight = 1 - pow(1 - responsiveness, dT * referenceFPS);
 smoothedValue += (currentValue - smoothedValue) * weight;

```

Similar to a windowed average, this smooths-out fluctuations in an input signal, and gives the value a degree of "memory" or "inertia," while being much simpler to calculate. The differences is that it weighs the newest samples much more heavily than old samples, and has no absolute cutoff age like a windowed average.

Here's an example of how this compares against a 0.1s windowed average for a signal with a variable sampling rate. Here I'm using `responsiveness = 0.5` and `referenceFPS = 30`

You can see the exponential moving average gives a fairly similar profile to the windowed average, especially when the value changes continuously. For sharp changes in the input value, you can see the exponential average has a somewhat sharper attack, and then closes in on a new sustained value asymptotically (where the moving average is guaranteed to reach a sustained input value by the end of the window duration).

In practice, we can usually tune the `responsiveness` value to get the desired behaviour.

If your application really needs a windowed average, let us know and we can show you how to implement it efficiently with a ring buffer, albeit with more code complexity than the exponential example above.

# Answer
> 0 votes
The answer by stormwind was exactly what I needed to smooth out a calculation that was getting jittery when the delta time wasn't perfectly the same.

I discovered that UnrealEngine has the quasi-average solution in his post already in its library as `FMath::WeightedMovingAverage(float CurrentSample, float PreviousSample, float Weight)`

For the `Weight` parameter, you would pass in `FrameDeltaTime / SamplingTime` and use `0.1` for `SamplingTime` based on what the original poster wanted for this question.

---
Tags: timer, timestep, time-management
---


# Question
Title: How to make a capsule Rigidbody player "kick" a Rigidbody sphere (ball) in Unity?
I am just learning the basics of physics simulation with rigidbodies. I am trying to simulate some basic real world functions like kicking a ball.

Let's say I have a simple capsule mesh/collider as my player and a sphere as a ball. I want when the player comes close enough to the sphere for them to be able to "kick" the ball, exerting a velocity on the ball along the vector from the player's front face towards the ball.

I am new to all the angle systems of rigidbodies so I'm having a bit of difficulty.

The best I could come up with was to add this code to the control of the player capsule:

```
        if (Input.GetKeyDown(KeyCode.B)) {
            Collider[] hitColliders = Physics.OverlapSphere(playerGO.transform.position, 1f);
            foreach (var hitCollider in hitColliders) {
                if (hitCollider.gameObject.GetComponent<Rigidbody>()) {
                    //if (objectWithinFrontRangeOfPlayer) { // use playerGO.transform.forward
                        Vector3 positionDiff = hitCollider.transform.position - playerGO.transform.position;
                        Quaternion angleOfImpact = Quaternion.LookRotation(positionDiff);
                        hitCollider.GetComponent<Rigidbody>().velocity = new Vector3(angleOfImpact.x, angleOfImpact.y, angleOfImpact.z) * 30f;
                    //}

                }
            }
        }

```

So the steps I see are:

1. Upon player pressing "kick" button (B), check for any colliders in the area, then check for which have rigidbodies.
2. If rigidbody is found within kicking range, I should ideally then check if it is within a certain angle tolerance like +/- 60 degrees of the `playerGO.transform.forward` direction (one can usually only kick effectively things in front of how you are facing). I am not sure how to do this.
3. I then need to calculate the angle/vector at which the velocity should be applied to the sphere. I tried using `Quaternion.LookRotation(hitCollider.transform.position - playerGO.transform.position);` but then I don't know what to do with the Quaternion. If I had it as a normalized unit vector I could do what's written above and multiply the intended velocity from the kick to each axis. But as a Quaternion, while what I wrote above certainly "kicks" the back, the vector is not correct.

Any tips on how to fix this code and make it work roughly correctly?

Thanks a bunch.

# Answer
> 1 votes
```
Quaternion angleOfImpact = Quaternion.LookRotation(positionDiff);
hitCollider.GetComponent<Rigidbody>().velocity = new Vector3(angleOfImpact.x, angleOfImpact.y, angleOfImpact.z) * 30f;

```

A few things wrong with this:

* A quaternion is not an angle, nor a collection of angles like an Euler triplet. Don't name a `Quaternion` variable "angle" or you will confuse anyone trying to read your code, including yourself.
* The x, y, z components of a quaternion form a vector parallel to the *axis* the object needs to rotate *around* to reach this orientation, not a vector in the direction that the resulting orientation faces. So if you tried to kick the ball to the right with this code (along `(1, 0, 0)`), the quaternion's x, y, z would point along the world up vector `(0, 1, 0)` (because I have to yaw around the y axis to look right) - 90 degrees apart from what you want!
* This axis vector gets smaller as the angle gets smaller. So if you tried to kick the ball straight ahead with this code (along `(0, 0, 1)`), the quaternion you'd get would be `(0, 0, 0, 1)` \- so you would set the velocity to zero!

As a rule: just don't touch the individual x, y, and z components of a quaternion. Unless you're very deliberately manipulating 4-dimensional imaginary numbers, it's almost guaranteed that you are doing the wrong thing.

There is no reason to bring quaternions into this at all. A rigidbody's velocity is just a cartesian vector in world space, nothing angular/rotation-y about it. So if you want to kick the ball along the line joining the player to the ball, then just use that line:

```
Vector3 positionDiff = hitCollider.transform.position - playerGO.transform.position;
// Flatten the offset to the horizontal xz plane.
positionDiff.y = 0;

// Check the angle relative to our facing direction,
// and abort if it's too far away.
if (Vector3.Angle(positionOffset, playerGO.transform.forward) > kickDegreeRange)
    continue;

// Here you might want to add some y back to the positionOffset
// so that you get a velocity that points slightly upward.

// Keep the direction of the offset, discard the length (make it a unit vector).
Vector3 kickDirection = poisitionDiff.normalized;

// Set the velocity to point in this direction, with a fixed speed.
hitCollider.GetComponent<Rigidbody>().velocity = kickDirection * kickSpeed;

```

The same notes I left on your previous question about not hard-coding keys for game actions apply here too. Prefer something like `Input.GetButtonDown("Kick")` or `kickAction.WasPerformedThisFrame()`, so that your code isn't coupled to just one fixed control scheme.

---
Tags: unity, collision-detection, physics, projectile-physics
---


# Question
Title: I can't use both of the Xbox 360 gamepad's analog triggers at the same time in my game
I am using a Xbox 360 controller on my Windows computer, with this control scheme:

* Squeezing LT aims down the sights of the weapon
* Squeezing RT shoots the weapon

Each of these actions works individually, but whenever I try to shoot while aiming (ie. squeezing both triggers at once), it just lowers the gun.

I know that it has to do with the fact that LT and RT are read as the positive and negative ends of the 3rd joystick axis in Unity, but is there a way to fix this? I am using javascript if it requires scripting.

# Answer
### *"3rd Axis"* represents the two triggers, together. Use *"9th Axis"* and *"10th Axis"* to reference them, individually.

I am going to assume you refer to the previous question you asked, in how to reference the Xbox controller. While the answer provided by Philipp gives you insight, it does not give you the actual answer; it only gives you the *almost* identical interpretation of the particular system application.

In Unity, you can reference both triggers as "3rd Axis". As you have found out, you can not have a single axis representing "true" for both sides. It would be like having a single analog stick that is both *up* and *down* at the same time. It is logically impossible.

Alternatively, you can reference ***LT*** as `9th Axis` and ***RT*** as `10th Axis`. Referencing them *separately*, you can have both triggers operate independently.

As I addressed in answering your other question, it is worth pointing out that these buttons ***must*** be referenced as *axis*. This means you use `InputManager` to register them, and call them as `Input.GetAxis()`. This is because the triggers are *not* basic buttons. They interpet pressure, so rather than turning *on* and *off*, they start at *0* and move to *1*. In other words, you could register a `0.5` by pressing the trigger in half way.
> 2 votes

# Answer
I found the solution for the LT and RT buttons not working simultaneously if you have this problem checkout my reddit post here the link: https://www.reddit.com/user/Qosh\_manuel/
> 0 votes

---
Tags: unity, javascript, joystick
---


# Question
Title: What can help make my Resource-Management game into a FUN game?
I am working on a "life simulator" resource-management game where the player has to go to work, go studying, pay rent,... and basically increase his resources and use them to unlock perks, that help him even further.

The game is all about trading resources and making profit.

3 of the most common resources are: "Time", "Energy" and "Money".

And then there are others like... "Food, Drink, Reputation, Confidence,..." etc.

But I feel like something is "missing". Like... It's simply not "fun".

You can not play in a "smart way","creative" or "take risks". All you do is trading resources randomly.

One solution I had was: Making random things happen every day (your money gets stolen, you get blackmailed, or you find some random items...)

But I feel like.... I am missing "something".

Do you have a suggestion to make a resource-management fun?

# Answer
> 4 votes
Resource management games are all about making difficult decisions involving tradeoffs.

* Should I solve this problem spending resource A or resource B?
* Should I take a reward in form of resource A or resource B?
* Is trading some resource A for some resource B a good deal right now?

Random events (or events which *appear* random but are actually chosen by a director system) are a good way to present choices to the player. But remember: **Management means making choices.** Do not just give or take the players resources. Present them with difficult choices.

In order to make those choices non-obvious, the resources need some different characteristics:

* How bad is it for the player to run out of a resource? Some resources might be minor inconveniences, others might cause serious harm, others might even be an instant game-over. This might change depending on the situation of the game.
* How useful is it to have a lot of a specific resource? For example, the player might know that one specific resource helps them to unlock some very desirable piece of content, so they should think twice before spending it on something else.
* How easy are resources to acquire? Some might be trivial to acquire or even regenerate automatically. Others might only offer circumstantial opportunities to acquire them.

# Answer
> 0 votes
What should be the root cause of fun?

* Living your life in amusing train-wreck mode? Are there 100 humorous ways to day with achievements? Did you "Freeze solid from being naked on the way to work"?
* Learning new tricks as you go? Did you "Learn to wash dishes as soon as you use them! Gain 10 minutes every day!" or "Buy bus pass instead of paying daily, gain $30 every month!"

You may want to look at "Jones in the Fast Lane" as a computer example of this type of game. Another example is the Poverty Simulation, which is usually a live-action version of this meant to teach about poverty.

# Answer
> -2 votes
Satisfyingly tools to automate and a selection of different views like cost heatmaps like in the new sims city

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


# Question
Title: XInput (SharpDX) not returning 0 on thumb sticks when they're idle
When querying XInput for the status of the thumb sticks, it doesn't return 0 when the sticks are not in a moved position.

Instead, it returns an arbitrary value which is a small portion of the value the stick was moved to before returning to idle state. Every other button and trigger on the controller correctly returns 0 when not engaged.

I poll the controller in the main loop with `Controller.GetState`, so the state of the device should always be current.

The XInput documentation asserts that a value of 0 is to be expected when the sticks are not in use.

I've worked around the problem by moving the player only if the stick is moved by 10% or more of it's possible movement limit, but I'd like more precise stick control.

Any assistance would be gratefully received.

# Answer
> 2 votes
This sounds like a fairly normal issue. Analog sticks are notoriously imprecise, and develop a drift over their lifetimes. (If you've ever had such a well-used gamepad that when you boot up some games, your character has a bit of a lean to one side or even moves slightly when the stick is "idle", that's this effect).

Games typically compensate for this by processing the raw stick value to apply what's called a "deadzone" — a cutoff value below which small drifts are considered zero. The same can be applied at the high end, to ensure the distance from the center caps out at exactly one in every direction, rather than having a bias in some direction.

Searching for "analog deadzone" will let you find different strategies for applying this, such as this previous answer.

The XInput documentation itself calls this out as something to be aware of and gives guidance for how to implement deadzones in your game code:

> In order for users to have a consistent gameplay experience, your game must implement dead zone correctly. The dead zone is "movement" values reported by the controller even when the analog thumbsticks are untouched and centered. There is also a dead zone for the 2 analog triggers.
>
> > **Note**
> >
> > Games that use XInput that do not filter dead zone at all will experience poor gameplay. Please note that some controllers are more sensitive than others, thus the dead zone may vary from unit to unit. It is recommended that you test your games with several Xbox controllers on different systems.
>
> Applications should use "dead zones" on analog inputs (triggers, sticks) to indicate when a movement has been made sufficiently on the stick or trigger to be considered valid.
>
> Your application should check for dead zones and respond appopriately

---
Tags: input, sharpdx
---


title: How to generate mesh for any shape?

text:
# Question
Title: How to generate mesh for any shape?
I have shape stored in sprite. Shape is stored as white color. I want to generate mesh for given shape. Maybe just like sprite collider do. What algorithm I have to choose? Are there any libs for Unity that can do that?

# Answer
> 1 votes
Ok, I found easy solution.

I have used Unity-SpriteAssist library.

This method generates new mesh data according to the initial parameters:

```
maskSprite.GetVertexAndTriangle3D(spriteConfigData, out Vector3[] vertices2D, out int[] triangles2D, MeshRenderType.Opaque);

```

# Answer
> 0 votes
You might find the Marching Squares algorithm handy.

This is a C++ implementation, which shouldn't be too hard to port to C#:

https://github.com/sjhalayka/Marching-Squares

https://en.wikipedia.org/wiki/Marching\_squares

---
Tags: unity, mesh
---


# Question
Title: How to give two GameObjects references to each other?
I have two GameObjects and would like both to have a reference to the other. I know this can be done by creating public properties and setting them with Unity's inspector, but my preference is to stay in code whenever possible. Something like this:

```
public class Object1 : MonoBehavior
{
    private Object2 _object2;

    public void Start()
    {
        _object2 = GetComponent<Object2>();
    }
}

public class Object2 : MonoBehavior
{
    private Object1 _object1;

    public void Start()
    {
        _object1 = GetComponent<Object1>();
    }
}

```

I understand this doesn't work because one Start has to run before the other, but I'm not sure what alternative would be the best from a code quality standpoint.

* I could refactor so Object2 doesn't have a reference to Object1, but then it can't call any functions on Object1. Instead, Object1 would have to constantly query Object2 for whether or not it should do something.
* I could get the other component in Update rather than Start, but that seems like a bad strategy from a performance standpoint - searching for an object every frame even though it's always the same object.
* I could solve it outside of Start / Update. For example, Object2 could have a SetObject1 function that Object1 calls, or an EventManager could be used to communicate between objects. This seems like it might be a tad overkill for something as commonplace as this.

Are any of these a common practice among Unity devs? Is there another option I'm missing?

# Answer
> 2 votes
> I understand this doesn't work because one Start has to run before the other.

No, it **does** work. Even if the two `Start()` functions execute one after another, the Components they are referencing already exist. You can test it for yourself by adding `Debug.Log(_objectX)` after using `GetComponent<>()`.

> Object1 would have to constantly query Object2 for whether or not it should do something.

This is called *polling* and it's perfectly fine, especially if you want to decrease interdependence among your classes and entities. Alternatively, you can expose some events and invoke callbacks accordingly.

> I could get the other component in Update but that seems like a bad strategy.

Yes, it is.

> I could solve it outside of Start / Update.

Unity encourages using `Awake()` for script referencing rather than `Start()`. This way, when `Start()` executes, all your scripts own a working reference regardless of their execution order.

> An EventManager could be used to communicate between objects.

It would also help you avoid mutual references among objects. The EventManager may expose UnityEvents that trigger ObjectX's callbacks when needed.

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


# Question
Title: Unity - jagged shadows when export as apk?
Alright, I found this question with the same problem but it's out of date Jagged shadows with default settings

My problem is a discrepancy between shadow quality settings in editor vs apk built to Oculus Quest. I don't know if VR is a factor here. I have desktop and Android set to the same default quality settings, which are determined by the same Universal Render Pipeline Asset -

In editor, shadows are nice and soft, although if you increase shadow distance they get a bit jagged -

This is exacerbated on Quest apk -

I've tried all the options and turning off shadow cascades - that just results in more spread out jaggedness. What can I do to get the highest quality soft shadows in apk built to Oculus Quest?

# Answer
I know this question is almost a year old now, but I ran into a similar problem and couldn't find a lot of info. What happened for me was I just created a template scene and was testing things out and realized the controllers' shadows on the ground were extremely pixelated only when running on the headset. When in the editor they look crisp. I tried to change the settings and deleted all the quality presets except for ultra, but that didn't change anything.

What did work was when I changed the ground plane's scale from (10, 10, 10) to (1, 1, 1). Once I did that and tested the build on my headset, the shadows looked great. Probably not the best solution as it probably wouldn't work the same for the UI since it has to be scaled really high to just show up, don't know if there's any way around that. But I thought at least I'd put up some sort of solution for others who also come upon this question.
> 2 votes

---
Tags: unity, c#, shadows, virtual-reality
---


# Question
Title: I don't get why ECS is considered more performant than OOP
Let's say I have an ECS with physics and I want to kill the player when a arrow hit him. So I have a callback when there is a collision. Now there is of course different behaviors with different collisions within 2 bodies (heal with heart, damage livings with weapons, etc...) so plenty of combinations of collisions.

I would think in ECS I will check the components each body has and call the appropriate behavior, but of course the more behaviors I have the more it will cost, because each combination should be checked for each collision.

More generally, don't ECS add more cost when there are more behaviors ? In traditional way (OOP with inheritance), no matter how many different behaviours you have (the count of derived classes), you will always pay only one method call. In ECS, you update each system at each frame, so the more systems you have the more it will cost, even if there is no entities that use it.

# Answer
With an OOP architecture, you usually end up with code which if unrolled to a purely procedural style would look like this:

```
for each entity
   if entity can move
        move(entity)
   switch entity attacking type
       when shooter
         shoot(entity)
       when melee
         meleeAttack(entity)
       when nothing
         doNothing(entity)
   if entity has health
        checkIfDead(entity)

```

While with an ECS architecture, the resulting logic would look more like this:

```
for each entity which can move
    move(entity)
for each entity which can shoot
    shoot(entity)
for each entity which can meleeAttack
    meleeAttack(entity)
for each entity which has health
    checkIfDead(entity)

```

Instead of one long loop over all entities, you get a series of short loops. Why is the second usually faster?

1. Smaller loops are easier to optimize. This applies to both your compiler and to the CPU microcode.
2. ECS allows those loops to only iterate over those objects which actually have those components. OOP needs to check at runtime. Polymorphism isn't magic. When you call a method of a base-class or interface, then it might look like a simple method call in your code. But what actually happens at runtime is a hidden `switch` statement to pick the correct implementing method based on the actual type. ECS, on the other hand, can pre-compute lists of which entities are relevant for each system and only needs to update those lists when the composition of an entity changes. So it no longer needs to check every tick.
3. Memory locality. The move-loop only requires the move-components. The check-if-dead-loop only requires the health-components, and so on. In a well-designed ECS architecture, the data of all components of the same type will be stored in an array, which will be a contiguous section in memory. Contiguous memory section are very quick to load from RAM into CPU. In an OOP design, on the other hand, you are doing a loop over all the data of all the entities at the same time. Which means they all need to be loaded from RAM into the CPU cache. When you don't have enough CPU cache to hold them all, then this is going to get slow.
4. Parallelizability. This is not something you get automatically. But if you want to design an engine which utilizes multiple CPU cores well, then ECS usually makes that easier than OOP. The main problem with parallelization is finding units of processing which don't share any data. The reasons for that would make this answer too long. So just trust me that you don't want two threads to access the same memory, especially not when at least one of them needs to change that data. The data-oriented design of ECS makes that much easier, because it makes it far more visible which systems use which data. That means it is usually easy to tell which systems can be run in parallel and which systems can use parallelization internally. But with OOP, every object is a black box (intentionally!). You don't know what data an object accesses, and you don't *want* to (it's called abstraction). That makes it very hard to judge what can be parallelized and what can not.
> 14 votes

# Answer
Usually, you don't have a single event to manage per frame, you need to manage a lost of asynchroneous events, periodic events, updates, etc., so the situation is more like "managing a variable but maybe huge number of things vs iterating on all the components".
ECS forces you to iterate over every component in your game/scene, but they are laid out in arrays, which favorizes fast-access on modern CPU architectures via the use of caches.
If you have very few events per frame, this can indeed by more costly to iterate over every component (but is this really an issue? cf below), but it might not be the case with more events.

As always, we can always formulate general guidelines, but the hard truth about software development is that it can be totally counter-intuitive due to the complexity of modern processors and the numerous efficient optimizations that compilers are capable of.
For this reason, in order to determine which way is the more efficient and where are your bottlenecks, you need to test and profile your application instead of relying on 'rules'.

When developing software, you don't try to have the best performance possible. Instead, you set up a target performance (which depends on the target hardware) and you try to achieve it. There is no need to spend 2 months trying to get your game loop running 2% faster if is already runs fast enough!

You also have to remember that performance is only one aspect to take into account with your code/architecture. It might be the most important constraint for a project, but this is usually the case only for embedded systems with very limited processing power. In general, it is part of a trade-off with other aspects: simplicity, maintainability, development speed, etc.
ECS can help with those because it is a very flexible architecture, which allows to make changes to entities easily.

Considering all of these, we can say that ECS is not per se a costly architecture performance-wise, and that performance depends both on the implementation and the specificities of your project.
Performance is only one criterion competing with others, and the best solution is always a trade-off between all of them that is specific to each project.
> 3 votes

---
Tags: entity-component-system
---