# Question
Title: Iterating through map : need help getting cluster of flags (points) while avoiding duplicates
I have a grid style game where I make use of objects called flags which have points attached to them.

I want to be able to look at the map and find the tile(position) where it maximizes the points (using the cardinal flags North,South,West,East of current position and uses radius to give a bigger search area); while trying to avoid using the same flags.

My method works in the sense that it adds the points up correctly based on the position. However, when I move to the next tile over; if the previous tile uses flags (x,y) and the next tile over uses flags (x,y,z)

Example using method below:

Tile 1 @ Position (3,4)

* Flags (x,y)

Tile 2 @ Position (3,5)

* Flags (x,y,z)

Expected result for Tile 2 : z flag only

```
    //searches each tile for corresponding flag points
    public Map<Map<Integer, List<Flag>>, Position> checkTilePoints(Player player) {
        List<Flag> localFlags = new ArrayList<>();
        Map<Map<Integer, List<Flag>>, Position>tilePoints = new HashMap<>();
        int diameter = 4; //as much diameter as warfrig
        int radius = diameter / 2;
        int squareRadius = radius;
        for (int i = 0; i < context.getMap().getMap().length; i++) {
            for(int j = 0; j < context.getMap().getMap()[i].length; j++) {
                localFlags.clear();
                int pointTotal = 0;
                if(context.getMap().isRock(i, j, player) || context.getMap().isOutOfBounds(i, j)) {
                    continue;
                }
                for (int x = i - squareRadius; x < i + squareRadius; x++) {
                    for (int y = j - squareRadius; y < j + squareRadius; y++) {
                        if((java.lang.Math.pow(x - i, 2) + java.lang.Math.pow(y - j, 2)) < java.lang.Math.pow(radius, 2)) {
                            Flag checkedFlag = context.getMap().getFlag(x, y);
                            if ((checkedFlag != null) && (!localFlags.contains(checkedFlag))) { // add once only
                              localFlags.add(checkedFlag);
                            }
                        }
                    }
                }

                Flag north = context.getMap().getFlag(i, j + radius);
                Flag south = context.getMap().getFlag(i, j - radius);
                Flag west = context.getMap().getFlag(i - radius, j);
                Flag east = context.getMap().getFlag(i + radius, j);

                if ((north != null) && (!localFlags.contains(north))) {
                    localFlags.add(north);
                }
                if ((south != null) && (!localFlags.contains(south))) {
                    localFlags.add(south);
                }
                if ((west != null) && (!localFlags.contains(west))) {
                    localFlags.add(west);
                }
                if ((east != null) && (!localFlags.contains(east))) {
                    localFlags.add(east);
                }

                for(Flag points : localFlags) {
                    pointTotal += points.getSize().getID();
                }
                if(pointTotal != 0) {
                    //TODO - create hashmap to return
                }
            }
        }
        return null;
    }

```

I'm not sure if I explained my problem very well, but overall; I want to fix this method to just add the cluster of flags based on the position without using duplicate flag already checked

# Answer
Use a Java `Set<T>`. Even if you add duplicates to the `Set`, they will not be stored by the data structure.

This will avoid having to use any explicit conditionals in your code to avoid adding / checking duplicates.
> 1 votes

---
Tags: java
---


# Question
Title: Is grass object amount limited in Unity?
I'm using Unity 2019.3.7f1 free version to create a small game project. I have a large terrain which I want to fill with grass. To achieve that I'm using the grass brush tool provided with the terrain.

However I cannot put more than, say 10'000 grass items (arbitrary, I don't know the real limit). Exceeding this amount, the grass objects contained in the first area I filled are removed, one by one, for a reason I cannot figure out. It's like there is a max limit of grass object I cannot exceed, and this is true for both grass textures and detail meshes.

On the other hand the amount of tree seems unlimited, which is puzzling me.

So my questions are:

1. Is there a limited amount of grass objects available in Unity?
2. If yes, how many grass objects are available, and may I increase this limit?
3. Is it a known bug, or a known limitation of the Unity free version?
4. May grass impact the global performances of the game? (I feel that my game is significantly more slow after I added the grass...)

# Answer
> 2 votes
You need to increase detail density or detail resolution per patch. Those can be found in the Terrain's settings. https://docs.unity3d.com/Manual/terrain-OtherSettings.html

But, those limits prevent severe performance issues, so your game will be slower after changing the limit.

---
Tags: unity, performance, terrain
---


# Question
Title: Any problems with flipping a sprite by scale? (2d Platformer)
I am wondering if there are any problems with flipping a sprite on the x-axis using vector2 to tell which direction it is facing/flip. Though doing this helps me write less code for Ray-cast direction and creating single states with a single animation (using 1 animation player facing right than using 2 animation facing left and right). If there is a better solution please tell me and thanks. Btw I am still pretty new and learning.

# Answer
> 2 votes
A negative scale can adversely affect physics features. When you flip a shape backwards, collision/raycast checks that depend on the winding of the collider effectively see it as inside-out. So you might find the object becomes invisible to collisions/clicks when inverted. Changing the scale might also force the physics engine to recompute the object's inertia properties, or it may behave badly in other ways.

To avoid this, I usually like to keep the visual representation of my objects in a child object, while the physics stays at the parent (and colliders live either there or in a sibling). That way I can squash and stretch and flip and wiggle my visuals any way I like, without impacting the physics of the object.

Another method you can use is the `flipX` property (and `flipY`) of the `SpriteRenderer` class. These can be used to reverse the sprite visually, without impacting other components attached to the object. You can also access these as checkboxes in the Inspector:

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


# Question
Title: Can textures change between resolutions?
I'm a beginner in game design and textures have been bothering me. How do they work in video games? Here's what I mean.

Can textures change between resolutions in settings?

Or is it tied to screen resolution? As in your game has 4k textures but the user sets the display to 1080P. And if this is true then what resolution should the textures you put in the game be?

# Answer
I believe the answer to your question is mipmaps. Mipmaps are a sort of Texture resolution hierarchy that allow you to sample different resolutions as needed. So, yes, games will sample different resolutions as needed for things like antialiasing, hierarchial level of detail settings, texture filtering and overall graphical settings.
> 0 votes

---
Tags: textures
---


# Question
Title: Calculate damage values from bullet velocity and size
I'm trying to make a top-down game using Javascript and Pixi which involves multiple different guns.

Instead of giving each gun an individual damage value, I wanted to calculate the damage by the bullet's dimensions and velocity as it leaves the gun (which is all available on Wikipedia).

However, I'm having issues where despite some damage values looking okay (e.g. UMP-45 has about 40, Mac-11 has about 22, TEC-9 has around 35 and Glock has about the same) some values are too high to offer a challenge to the player (AK-47 has 110, M4A1 has 220, Desert Eagle has 100+).

The current calculation I'm using is: \\$ \frac{velocity \times bullet\ length}{1000} \times \frac{bullet\ radius}{2}\\$
Or in pseudocode: `(velocity*bulletLength/1000)*(bulletRadius/2)`

Anyone have any ideas for tackling this issue, or is it best to just use straightforward values? The game would be a horde-like sandbox game, so the damage values can't be too low or it would be almost impossible.

# Answer
> 1 votes
AKs and M4s are very strong. If you've ever played with an FPS like COD, then you know that you can't really do anything useful against a person with a higher end weapon using a pistol.

To balance things you could make the ammo for bigger guns more costy

# Answer
> 1 votes
You could change your calculation to make it more fair. That is just trial and error until you are pleased.

What are the properties common to weapons you want to reduce? If you realize bullet size for example has too much impact, use sqrt(bulletradius) instead, change your values a little bit, see if it fits, then try again if not, until you finally get the formula you want.

# Answer
> 0 votes
http://www.shooterscalculator.com/bullet-kinetic-energy.php It's a bullet kinetic energy calculator.

But I suggest to put all results of calculation to game configs. It is more easy way to balance things. Not reason to re-calculate already calculated things.

Then use pre-defined shapes as multiplier. Let's say you have shape1 = 0.8 and shape2 = 1.4, and you have a flying bullet with kinetic energy = 10; then your damage = 10 * shape1 = 8; or same bullet with different shape will be 10 * shape2 = 14. Same value you can also use to calculate reducing speed of the bullet.

# Answer
> 0 votes
It might sound obvious, but as a game designer, you're in control of the game design.
For the sake of simplicity, games are not accurate representation of reality\*.

You can change another stat of the ammo/weapon (cost, reload time, etc.) for balance, but you can also change stat of the ammo itself such as damage dealt, muzzle velocity, etc. to achieve balance within your game **even if that contradicts real-life statistics**.

In the end, don't forget that it's all up to you and to meat what goals you've set for your game: a more realistic game should obviously try to stick to real-life as possible, but there is a balance to find between realism and gameplay, because no matter how realistic you want your game to be, it won't be real-life.

(\*) Keep in mind that althought games are inspired by reality, they do not mimic it 100%. IRL a bullet in your body might incapacitate you... But it might also just make you feel pain and 9 more extra bullet would be needed to stop you.
This would hold for different weapons: a 9mm Parabellum bullet might kill you while a 12.7mm bullet might only wound you.

---
Tags: mathematics, game-design, bullet-physics
---


# Question
Title: How to play a sound effect at a projectile's impact location?
I am encountering an issue where I have a bullet that is destroyed on impact which is cutting off my bullet impact sound effect due to the audio source being destroyed. I like the idea of the sounds being attached to the projectile, but not sure if that is best practice.

I can play the sound from an NPC script, but not sure if that will open up other issues. Is this a better approach since the NPC material is "metal" so I should store all the "Metal hit" sound effects on the NPC?

...vs. having to store all material variations of impact on the projectile?

# Answer
> 1 votes
One way to avoid the audio ceasing when the projectile is destroyed is to call the static method `AudioSource.PlayClipAtPoint`. This fires a "one-off" sound effect, without being attached to any one specific audio source object.

The downside of this approach is that you can't control the exact falloff or other properties of the sound effect, just its position and volume. If that's a problem though, you can implement your own one-shot-like method. Have a static class or singleton that keeps a pool of audio sources, and on demand configures and deploys one to play a sound with specific settings, then recycles it back to the pool once it's finished playing the sound.

To avoid storing a lot of different material hit sound effects on each and every projectile, you can define a type deriving from `ScriptableObject` that's something like a "Sound Set" data container. Load up this type with fields/methods to store and select the right sound effect for each material. Then you can create multiple sound sets as assets in your project folder, and share them between many projectiles. Each projectile can hold a single reference to a sound set, and delegate to it the complexity of selecting the right audio clip for the circumstance, keeping your projectile scripts focused on the work of being projectiles.

---
Tags: unity, audio
---


title: Collision Filtering in Box2D

text:
# Question
Title: Collision Filtering in Box2D
I have four bodies in my Box2D World. Each are polygon shape, with some physics parameters.

Now when the game start, I need one of the bodies from the World (BodyA) to not be allowed to collide with another (BodyB). It should be allowed to collide with others.

To clarify, BodyA and BodyB cannot collide with each other, but can collide with rest of the bodies in the Box2D world.

How could make this kind of mechanism in Box2d ?

Please help me about this query. Thanks & Regards,

# Answer
> 4 votes
In Box2D, this is called Collision Filtering.

> Collision filtering allows you to prevent collision between fixtures. For example, say you make a character that rides a bicycle. You want the bicycle to collide with the terrain and the character to collide with the terrain, but you don't want the character to collide with the bicycle (because they must overlap). Box2D supports such collision filtering using categories and groups.

Take a look at the Box2D manual, and search for Collision Filtering. It will explain to you everything you need to know to get started.

http://box2d.org/manual.html

---

**Edit**

> Box2D supports 16 collision categories. For each fixture you can specify which category it belongs to. You also specify what other categories this fixture can collide with. For example, you could specify in a multiplayer game that all players don't collide with each other and monsters don't collide with each other, but players and monsters should collide. This is done with masking bits. For example:

```
//code
playerFixtureDef.filter.categoryBits = 0x0002;
monsterFixtureDef.filter.categoryBits = 0x0004;

playerFixtureDef.filter.maskBits = 0x0004;
monsterFixtureDef.filter.maskBits = 0x0002;

```

> Collision groups let you specify an integral group index. You can have all fixtures with the same group index always collide (positive index) or never collide (negative index). Group indices are usually used for things that are somehow related, like the parts of a bicycle. In the following example, fixture1 and fixture2 always collide, but fixture3 and fixture4 never collide.

```
//Code
fixture1Def.filter.groupIndex = 2;
fixture2Def.filter.groupIndex = 2;

fixture3Def.filter.groupIndex = -8;
fixture4Def.filter.groupIndex = -8;

```

# Answer
> 0 votes
I am implementing a 2.5D app, so I need layers. For example this horse has about 5 layers.

I'm not sure, but I think that given two bodies with mask and category (m1,c1) and (m2,c2), they will collide only if the m1&c2!=0 AND m2&c1!=0.

By default I want a body to be very thick so that it occupies all layers, so I set the default m = c = 65535. If I want the body to only occupy layer 1, then I set m = c = 1. If I want the body to only occupy layer 5, then I set m = c = 32. If I want the body to be a little thick so that it occupies layers 1+2+3 then I will set m = c = 7.

I don't use the group index at all. It is always 0.

---
Tags: collision-detection, iphone, cocos2d-iphone, box2d
---


# Question
Title: How do I add auto login system firebase auth Unity?
I want to add an auto login/sign in ability into my game, so when the player quits the game or goes to main menu, the login panel is gone and the player is automatically logged in. Then, I want the player to be logged out and no longer automatically sign in when he presses the "sign out" button.

Here are some previews of my game:

I'm sure this code works like this, but I have low experience on firebase. Additionally, there is lack of documentation on it with Unity so I don't know what is wrong with this script.

```

void Awake()
    {
        //Check that all of the necessary dependencies for Firebase are present on the system
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
        {
            dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                //If they are avalible Initialize Firebase
                InitializeFirebase();
            }
            else
            {
                Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
            }
        });

        //singleton
        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            DontDestroyOnLoad(gameObject);

        }

    }

    private void InitializeFirebase()
    {
        Debug.Log("Setting up Firebase Auth");
        //Set the authentication instance object

        if (auth != null)
        {
            _MainMenuUI.instance.loginPanel.SetActive(false);
        }
        else
        {
            auth = FirebaseAuth.DefaultInstance;
            DBreference = FirebaseDatabase.DefaultInstance.RootReference;
        }
    }

```

# Answer
Taken from the documentation with some added comments to explain. The main difference between this and the other answer is, that it includes the check against `user`. While that may not be making much of a difference in your app, it could lead to the problem depending on how you store data - are you using the user or the auth.user - if they are not the same, you might persist data under the wrong user.

```
void AuthStateChanged(object sender, System.EventArgs eventArgs) {
  //This checks if the user (your local user) is the same as the one from the auth
  if (auth.CurrentUser != user) {
    //this seems the same, but user could have been null before
    bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null;
    if (!signedIn && user != null) {
      Debug.Log("Signed out " + user.UserId);
    }
    //this is important step, this user is the one you should be working with
    user = auth.CurrentUser;
    if (signedIn) {
      Debug.Log("Signed in " + user.UserId);
    }
  }
}

//it does not directly log the user out but invalidates the auth
void OnDestroy() {
  auth.StateChanged -= AuthStateChanged;
  auth = null;
}

```

Another thing is, the `AuthStateChanged` callback might not be only called on your login screen. You could get reference errors to your panels in case it happens outside of the scene. (Many games have the option to login/ logout from an option setting that might be reachable from anywhere in the game). Instead on your loginscreen you should just check if the user is the same as the auth.user and none of them are null, the same as the `bool signedIn` but not handling the UI from `AuthStateChanged`. Start or Awake might be a better place for handling it.
> 1 votes

# Answer
so i've read some doc the point is the firebase is do auto login

so I've change my script like this, base on doc firebase.

void Start()
    {
       InitializeFirebase()
    }

 void InitializeFirebase()
    {
        auth = FirebaseAuth.DefaultInstance;
        DBreference = FirebaseDatabase.DefaultInstance.RootReference;
        auth.StateChanged += AuthStateChanged;
        AuthStateChanged(this, null);
    }

    void AuthStateChanged(object sender, System.EventArgs eventArgs)
    {
        if (auth.CurrentUser != null)
        {
            bool signedIn = auth.CurrentUser != null;
            if (!signedIn)
            {
                Debug.Log("Signed out " + User.UserId);
                loginPanel.SetActive(true);
            }
            User = auth.CurrentUser;
            if (signedIn)
            {
                Debug.Log("Signed in " + User.UserId);
                loginPanel.SetActive(false);
                userNameShowText.text = User.DisplayName;

                //emailAddress = user.Email ?? "";
                //photoUrl = user.PhotoUrl ?? "";
            }
        }
        else
        {
            // haven't login yet
           // your code
           loginPanel.SetActive(true);
        }
```

> 0 votes

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


# Question
Title: Deterministic Procedural Wave Function Collapse
**I've been looking into the Wave Function Collapse algorithm and was wondering if there is a way to make it (appear) deterministic regardless of starting position.**

I can see how this is trivial if the starting position remains the same. We can simply always collapse the tile with the lowest entropy and use a seeded pseudo random number generator or a noise function to decide which is next whenever there isn't a clear winner.

Now what would be the best solution if I wanted to procedurally generate a world around the player? Say I generate the world in chunks. If a player moves far enough away distant chunks get unloaded and new chunks are generated. This works perfectly fine until the player starts to backtrack. Since tiles depend on their neighbors, a revisited chunk might very well look completely different if approach from a different direction.

I can think of two possible solutions:

**a) Always generate the world from a set starting position.**

This doesn't seem feasible in big worlds, as it would require more resources the further away from the starting position the player is.

**b) Only generate chunks once and then save them.**

I don't really like this approach, because it could potentially require a lot of disk space. It's also not really deterministic, because the order in which the player explores the world would still influence what individual chunks look like.

Is there a solution I'm overlooking or is this simply not possible because of how the algorithm works? Keep in mind that I don't care if the algorithm itself is actually deterministic regardless of starting position. The result just has to appear that way, so that already visited chunks can be recreated unchanged.

# Answer
One solution is to decouple each chunk from its neighbours.

Let's suppose you have nxn chunks, with a 1-tile wide border strip between them, forming a grid lattice.

We'll generate the corners of this grid first, then use the neighbouring corner information to generate the border edges, then use the completed border frame to fill the chunk.

So, starting with the corners. You know you have a corner at every pair `(i * (n+1), j * (n+1))` where i and j are integers.

Run this coordinate through a hash function, and use the resulting scrambled bits to select a tile to place here. You can also fold your world seed into the hash to get different corner patterns for different seeds.

This way, the tile selected at each corner depends only on its position and the world seed, not its neighbours or the order in which they were generated. You can use other generation strategies here too, say if you want to create large scale structure to your world, you could sample a noise function at each corner to decide whether it's sea or lowland or mountain, rather than selecting them in an uncorrelated random fashion.

So, we now have the 4 corners of the chunk we want to generate picked out. Next we generate the edges.

First, seed a random number generator with the coordinates of the middle tile in this edge (and your world seed). We'll use that for all the random choices ahead, so they depend only on the edge's position in the grid, not the history of what you generated before.

Take the 1 x (n+2) rectangle of tiles spanning from one corner to its next neighbour, and run a modified wave function collapse on that strip. This modified version will match only neighbours to the left and right, and ignore neighbours above and below (or vice versa when generating the vertical edges).

You might need to constrain the tiles you can select at/near the corners just to make sure you can't create a situation that's impossible to fill in later, like....

```
A     B

C     ?

```

where A is the corner of a chunk, A & B are valid neighbours, A & C are valid neighbours, but no tile exists that can match with a B above and a C to the left. If your tileset is reasonably permissive then this situation shouldn't require major constraints to avoid.

After repeating this process for each edge surrounding our chunk, we have neighbours on all sides, and we're ready to fill it in.

Again we'll spin up a seeded random number generator with the coordinates of the middle of this chunk, so we don't leak previous generator state into our subsequent choices. Then we'll run the big wave function collapse pass on this inner square, using the border of already-collapsed neighbours we have on all four sides.

Since the interior depends only on the edges, and the edges depend only on the corners, and the corners depend only on position, we'll generate the same corners/edges/chunk interior in a given location, no matter what order we generated them in.

---

The method I presented above will work with many tilesets, but not all, and it has a risk of showing a bias. The pattern of tiles you get from the 1-dimensional strip WFC we use on the edges between chunks might not have the same statistical properties as a randomly chosen 1-tile-wide strip carved out of 2D WFC with the same tile set. Interactions with tiles chosen on adjacent rows can create/propagate additional constraints that change the distribution we observe.

Here's an example of a tileset that would cause trouble for this algorithm (assuming no tile rotation/flipping is allowed). The constraints of the corner tiles in the top and bottom row mean that yellow "north" roads and red "south" roads can only appear in alternation, and the number of blue gaps we expect to see between them is a function of the transition probabilities of the orange horizontal road. But when looking at a single strip at a time, WFC doesn't know that. It knows an empty blue tile can go next to a yellow road or a red road, and a yellow road or a red road can go next to a blue tile, so it might place blue-yellow-blue-yellow with no red in-between, or even if adjusted to avoid this (such as by distinguishing "left of road blue" from "right of road blue"), may still be prone to creating improbable spacings between the reds and yellows.

Even in less drastic scenarios than this, there might be multi-tile formations that span across rows and skew the observed probability of certain left-right pairs in a single row, compared to WFC's baseline probabilities.

To solve this issue, Boris the Brave suggests a layered block-based generation strategy. It proceeds like so:

1. Initialize your world to an empty tile or default pattern of your choosing. (Could even be a large-scale Perlin noise autotile, etc.)
2. Split the world into blocks, with 1-tile gaps between them. Run WFC on the interior of those blocks, using the tiles in the gaps as the initial constraints.

Because of the separation, each of these blocks can be computed independently. Seed your randomizer with the coordinates of the block to ensure each one is deterministically generated, regardless of order.
3. Now shift your block grid by half a block space, so that the new blocks cross what had been the vertical edge between blocks in the previous pass. Repeat. (So we erase most of the tiles we just generated in step 2, keeping only the tiles in the gaps)
4. Shift the block grid again, to span the horizontal edge between blocks in the previous pass. Repeat.
5. Shift the block grid once more, to span the vertical edge from the previous pass. Repeat.

So we've run the generator 4x times, re-doing a lot of work. But now every tile that's left was generated from the interior of a 2D WFC at some point in the chain, and so any slice we take of the resulting map should have all the statistical properties we expect, without bias between edges / chunk centers.

There's a great animation here demonstrating how this ensures you only ever need to evaluate a finite number of blocks to get a deterministic output block.

Based on this, I do wonder if you could get "good enough" anti-biasing in fewer passes, by getting rid of the 1-tile gaps between blocks/chunks, and populating them in a checkerboard pattern. Say all "black" squares get populated first, with no edge constraints at all. Then all "white" squares get populated based on their four adjacent black squares, ensuring connectivity. You could then follow up with a third pass at an offset to the original checkerboard in case it shows visible biases along its grid. This would mean something like 8-9 block evaluations for a single output block, rather than 13 for the scheme above. Something to experiment with!
> 4 votes

---
Tags: procedural-generation
---


# Question
Title: Help understanding radar sweep effect in shader code
Several days ago I asked about this question: How to construct a propeller clock in Unity? But I don't understand how the answer works.

I have 0 knowledge about shaders, so I picked up a tutorial to understand the math functions, but that still didn't helping much in understanding the code.

I cut off part of the code to check the effect on an image, and I want to understand why the code has this effect.

1. What is the range of values for the parameters `i.uv.y` or `i.uv.x`?
2. Next I discarded part of the code, simplifying the fragment shader to just:

```
fixed4 frag (v2f i) : SV_Target
{
    // Simulate the strip of LEDs spinning around very fast.
    float headAngle = _Time.y ;

    // Compute the angle of the pixel we're rendering.
    float angle = atan2(i.uv.y, i.uv.x);

    float difference = frac( angle / (2.0f * 3.141592653589f));

    return difference;
}

```

And I rendered this on a plane:

According to the documentation, `atan2` gives an angle value in between -pi and pi. So the range of `angle / (2.0f * 3.141592653589f))` is in between -0.5 and 0.5.

I tested with `frac(0.3)`, `frac(0.25)`, which is the same as `return 0.3` or `return 0.25` since `frac` preserves only the decimal number. But why I couldn't generate the same gradient image as the one above? Instead, the plane is all one shade of grey, no matter what number I use.
3. Next I tried the code `float difference = frac(headAngle)` and got an image which is constantly varying between dark and bright images like these:
4. Putting this together:

* From the 1st picture, I have an image with a gradient that's dark in the 1st quadrant and bright in the 4th quadrant.
    * From the 2nd & 3rd pictures, I have all four quadrants at the same brightness, constantly varying between them.

What I don't understand is how the sum of these two pieces of code works. If I combine them like this:

```
float difference = frac(headAngle + angle / (2.0f * 3.141592653589f));

```

Shouldn't I get a gradient that stays in one place, like the 1st image, but just changes in brightness like in images 2 & 3?

Instead I get a A brightness gradient that is sweeping in a circle around the plane:

...and I don't understand why.

# Answer
> 1. What is the range of values for the parameters i.uv.y or i.uv.x?

Usually a quad's texture coordinates will run from 0 to 1 on the u (x) axis, and 0 to 1 on the v (y) axis.

That matches the normalized sampling coordinates we use for looking up into a texture:

* (0, 0) = bottom left
* (1, 1) = top right

(In some contexts, 0 is the top instead of the bottom, but let's call it the bottom here for simplicity)

But in this code, you can see I remap the range inside the vertex shader:

```
v2f vert (appdata v)
{
     v2f o;
     o.vertex = UnityObjectToClipPos(v.vertex);
     // Shift our texture coordinates so 0 is in the center,
     // and we go to -1 ... +1 at the edges.
     o.uv = (v.uv - 0.5f) * 2.0f;
     return o;
}

```

This output structure `o` gets interpolated for each pixel in the triangle formed by three vertices, and those interpolated versions get passed to the fragment shader as the input structure `i`.

By subtracting 0.5, I ensure the middle of the quad becomes the origin (0, 0). Then by scaling by 2, I ensure a circle with radius 1 centered at the origin exactly touches the edges of the quad.

Then in the fragment shader, we convert the texture coordinates of the pixel we're drawing into polar coordinates. This code gives us the angle of our pixel around the center of the quad, measured counter-clockwise from the positive u (x) axis.

```
// Compute the angle of the pixel we're rendering.
float angle = atan2(i.uv.y, i.uv.x);

```

That's why, when you plot this value as a greyscale colour, you get a gradient that gets brighter as you look around the quad in a counter-clockwise direction - that's the measured angle to this pixel.

As you reasoned, since the range of `atan2` is from \\$-\pi\\$ to \\$\pi\\$, dividing this by \\$2 \pi\\$ gives us a range from -0.5 to 0.5. The `frac` function then takes the negative values and wraps them around to positive. We can visualize this as a graph in the angular domain:

So here we have a function that varies over space with the angle of the pixel - from 0 (black) at the start of quadrant I to 1 (white) at the end of quadrant IV. But it doesn't vary over time.

The next bit of code you tried does the opposite: it varies over time, but it doesn't vary across space.

```
float headAngle = _Time.y;
float difference = frac(headAngle)

```

`_Time` is a built-in variable that Unity populates with various different scaled measures of the time elapsed in the game (the y component happened to contain a convenient scale for the effect I was making). So its value constantly increases from one frame to the next. But within a single frame, it's a constant - no matter what pixel looks up `_Time.y`, they'll all get the same value. That makes a graph that looks like this:

Here I've visualized multiple consecutive frames. You can see in any one frame, `_Time.y` is a constant, horizontal line in this graph: it's the same at any angle. But from one frame to the next that line rises. Eventually it hits the top of the `frac` range and wraps back down to zero, then rises again.

Now we're ready to put these two pieces together. Let's take our red plot of `frac(angle/(2*pi))` we had before, and imagine what happens when we add this lifting influence of time to it:

Increasing the time offset lifts the whole graph up. But then `frac` cuts off any parts that go above 1 and wraps them back around to the bottom.

Each time we lift the line, more of the right (counter-clockwise) side of it goes above 1, so we trim that part off and move it down to zero. Which means that effectively the peak value of the graph moves to the left (clockwise) as time goes on.

That's what makes our radar-like gradient sweep around the circle.
> 1 votes

---
Tags: mathematics, shaders, hlsl, graphic-effects
---


# Question
Title: How do you call game mode where the time is running out and player can increase time by collecting coins
I am working on an arcade game and I want to make a game mode, where the player has some time to collect coins. When a coin is collected player gets extra time, so the game can continue infinitely. But when the time is run out the game ends.

I don't know how to name this game mode. Do you have any suggestions? Something like: Time attack?

# Answer
> 1 votes
If it isn't required that you have "coins" and "a timer" then I've seen such modes called "Survival" modes with a few tweaks.

Simply replace the "coins" with some kind of heath pickup, and replace the "timer" with a slowly draining health bar. In fact, even without those changes "Survival Mode" still describes it pretty well.

If the timer is important (as in the case where speed running is encouraged or something like that), then "Time Trial" or "Time Attack" would both be fine, though they bring to mind finishing as fast as possible rather than lasting as long as you can.

If this isn't the primary mode of play in your game, then "Arcade Mode" would be a good fit as well.

---
Tags: game-mechanics, terminology
---


# Question
Title: How to get correct axis for scaling from transformed space?
I have scaled and non-scaled representation of model so that I don't destroy verticis information if model will be scaled to plane, for example. Now I trying implement scaling on model elements (face, edge), I set up axis of scale tool on dislplay (scaled) model, but I stucked with produce inverse transformed axis for correct scaling in non-scaled model version. What I mean:

Here not rotated not scaled cube.

Then I rotate and scale by global X axis (1, 0, 0), for rotated model this will be X Y axis. Faded axis is original axis, more bright is axis that scale tool produce and with which user interact.

This is how scale tool axis looks after just straight full inverse transform, under "straight" I meen just muliplying on inverted matrixs in right order. That actualy expected result because they orthognal in scaled space, but not correct result for perform correct scaling.

I have been trying to find an answer for several weeks now, trying many combinations of transformation order, after I realize that I am just starting to randomly place the matrix I was looking at options maybe I could somehow construct or line up vector of axis but not succesefull.

Here I want emphasize that inverted axis not necessary should be line up with origin axis (1, 0, 0) (0, 1, 0) (0, 0, 1), they can point in any direction, case that I take above just for simplicity. I think that my knowlend in linear algebra just not enough and it's actually possible tusk even if it's not one line matrix multiplication in some tricky order. Or maybe not:).

**Edit:** For clarification because maybe unlear what I trying to do

In post, as I said that I seting up axis in global space, in wich model full transformed and in wich user interact with scale tool, because scaling direction must match how user see axis I try transform this axis to how they will look in model space (non-scaled not-rotated). For this I try apply inverse transform and as I said was trying this in different variations but not succes. I attached a screenshots for showing how looks my data (initial, constructed, and inverted axis).

After DMGregory answer I checked what his said and I find out that:

1. this still not produce orthogonal axis
2. I cant align axis after transform because this solution can steel produce incorect result for X and Y axis also in some case (attached additional screenshots in comment)

**Edit 2:**

*I use row-major matrix so multiplication will be from left to right*

I do this for building axis in global space for model face. For case with multiple selected face I just return identity matrix for now.

```
m3x3
SetAxisForTool(work_model *Model, element_id_buffer *Selected, u32 ElementTarget)
{
     m3x3 Result = {};
     ...
     switch (ElementTarget)
     {
         ...
         case ModelTargetElement_Face:
         {
             model_face *Face = Model->Data.Faces + ElementID;
             face_vertex Vertex = GetFaceVertex(Model, Face);

             v3 OriginZ = V3(0, 0, 1);
             Result.Z = GetPlaneAvgNormal(Vertex);

             f32 ZDotResult = Abs(Dot(Result.Z, OriginZ));
             if (ZDotResult == 1.0f)
                 OriginZ = V3(-1, 0, 0);

                Result.Y = Normalize(Cross(OriginZ, Result.Z));
                Result.X = Cross(Result.Y, Result.Z);
         }
     }

    return Result;
}

```

Then after I get scale factor on axis that user see I try to process this transform like this. (For finding scale factor I just find difference between points on ray and gets length of this vector).

`Model->Axis` is orientation of model in global space, `Tool->Axis` is axis that I get from code above. `IsGlobalSpace` tell that I map scaling along original axis ((1,0,0)(0,1,0)(0,0,1)) to model space, so it's no need in invering scale this works in all case in expected way. Without scaling another branch also work in expected way.

```
void ApplyScale(work_model *Model, scale_tools *Tool, element_id_buffer
 *UniqIndeces,  model_target_element TargetElement, b32 IsGlobalSpace)

{
    ...

    u32 AxisID = GetIntAxisID(Tool->InteractAxis);
    v3 ScaleV = {};
    ScaleV.E[AxisID] = 1.0f * ScaleFactor;
    ScaleV += V3(1.0f);

    switch (TargetElement)
    {
       case ModelTargetElement_Model:
       {
            m4x4 MAxis = ToM4x4(Model->Axis);
            m4x4 InvRot = Transpose(MAxis);

            m4x4 ResultScale;
            if (IsGlobalSpace)
            {
                ResultScale = ScaleMat(ScaleV);
                ResultScale = MAxis * ResultScale * InvRot;
            }
            else
            {
                ResultScale = ScaleMat(ScaleV);
            }

            Model->ScaleMat = Model->ScaleMat * ResultScale;
            m4x4 Transform = Model->ScaleMat * MAxis;

            for (u32 Index = 0;
                 Index < Model->Data.VertexCount;
                 ++Index)
            {
                v3 VCache = VerticesCache[Index];
                DisplayVertices[Index] = VCache * Transform;
            }
       } break;

       case ModelTargetElement_Face:
       case ModelTargetElement_Edge:
       {
            m4x4 MAxis = ToM4x4(Model->Axis);
            m4x4 InvRot = Transpose(MAxis);
            m4x4 ModelTrans = Model->ScaleMat * MAxis;

            m3x3 S = ToM3x3(Model->ScaleMat);
            m4x4 InvScale = ToM4x4(Inverse(S));

            v3 ScaleOrigin = Tool->P - Model->Offset;
            ScaleOrigin = ScaleOrigin * InvRot * InvScale;

            m4x4 ResultScale;
            if (IsGlobalSpace)
            {
                ResultScale = ScaleMat(ScaleV);
                ResultScale = MAxis * ResultScale * InvRot;
            }
            else
            {
                m4x4 ScaleAxis = ToM4x4(Tool->Axis) * InvRot * InvScale;
                ScaleAxis.Row0.xyz = Normalize(ScaleAxis.Row0.xyz);
                ScaleAxis.Row1.xyz = Normalize(ScaleAxis.Row1.xyz);
                ScaleAxis.Row2.xyz = Normalize(ScaleAxis.Row2.xyz);
                m4x4 InvScaleAxis = Transpose(ScaleAxis);

                ResultScale = InvScaleAxis * ScaleMat(ScaleV) * ScaleAxis;
            }

           //m4x4 Transform = TranslateMat(-ScaleOrigin) * ResultScale * TranslateMat(ScaleOrigin);

            for (u32 Index = 0;
                Index < UniqIndeces->Count;
                ++Index)
            {
                u32 VertexIndex = UniqIndeces->Elements[Index];
                v3 VCache = VerticesCache[VertexIndex];

                VCache -= ScaleOrigin;
                VCache = VCache * ResultScale;
                VCache += ScaleOrigin;

                VerticesCache[VertexIndex] = VCache;
                DisplayVertices[VertexIndex] = VCache * ModelTrans;
            }
        } break;
    }

    Model->AABB = ComputeMeshAABB(Model->Data.Vertices, Model->Data.VertexCount);
}

```

# Answer
> 1 votes
Here I'm going to assume your goal is to keep the red and green vectors in the plane of the face in both the original and transformed coordinate spaces, and keep the blue vector perpendicular to the face in both spaces. If that's not accurate, please edit the question to be more precise about what vectors you want here.

If you have a matrix \\$M\\$ that takes vertex *positions* from the original space to the transformed space...

$$\vec v\_{\text{transformed}} = M \vec v\_{\text{original}}$$

and its inverse matrix takes those transformed vertices back to the original space...

$$\vec v\_{\text{original}} = M^{-1}\vec v\_{\text{transformed}}$$

Then you can also use this same matrix to transform tangent-space vectors along the *surface* of your models, or offsets between points *on* your model. Just remember to set the `w` component of these vectors to 0, so they're not affected by the translation component of the matrix, unlike position vectors which should have `w = 1`.

To transform vectors *perpendicular* to the faces of your model (ie. face normals or vertex normals), you need to use the Inverse Transpose of that matrix:

$$\hat n\_{\text{transformed}} = (M^{-1})^T \hat n\_{\text{original}}$$

$$\hat n\_{\text{original}} = M^T \hat n\_{\text{transformed}}$$

So in this example you'd use \\$M^{-1}\\$ and \\$M\\$ to transform your red and green vectors back and forth between coordinate spaces, and \\$M^T\\$ and \\$(M^{-1})^T\\$ to transform your blue vector back and forth.

(Note that the length of the vectors can be affected by this transformation, so if you need them to be unit vectors, be sure to re-normalize them after transforming)

---
Tags: transformation, linear-algebra
---


# Question
Title: How should I store the objects to render?
From what I understand, in order to show all elements of a 2D game in the proper way, I need to render them in order, from the further away from the camera to the closest. So I should sort them by depth before displaying them. Since sorting a list 60 times per second seems kinda clunky, would it be a better idea to store the objects to render in a binary search tree? Is there an ideal way to do store these objects? Or did I get something wrong? about this?

# Answer
> 1 votes
I would implement a Z level system: create a draw\_texture function that takes the Z level of the object (which could be determined by its position), and instead of rendering, store the texture and src/dst rects in an array representing the Z level (you could have one array for each level, or a matrix, where each row would be a Z level).

Then create a function to render all of then (just go through the matrix, rendering each texture), and call it before sdl\_present().

---
Tags: sdl2, tree, sorting
---


# Question
Title: Should I downgrade my Unity project to the latest LTS version?
I created my Unity project with a 2020 version and now I'm using 2020.2.0f1. Recently, I realized that using the latest LTS version is the best choice for games that are in production or about to ship. I tried downgrading to the latest LTS (2019.4.18f1) but since Unity doesn't support downgrading, all my objects disappeared and I got a lot of weird errors in console. My question is:

Should I continue developing the game with the version that I'm using right now or downgrade to the latest LTS version?

# Answer
The LTS branches are mostly intended for people who started a long-term project on an older version of Unity and are now afraid of upgrading to a more recent version because it might break too many things.

So when you started your project on 2020.2, then you might want to stay on the 2020 branch and switch to the 2020 LTS branch as soon as it becomes available... or switch to 2021 depending on how well that upgrade goes.
> 1 votes

---
Tags: unity, version-control
---


# Question
Title: Rotating a button in Unity UI by -180 on the Y and it stops working
If I rotate my button by -180 on the Y axis I can't even click on it. If for example I rotate it 180 on the Z axis everything is fine. Why does this happen and how can I fix it ?

# Answer
This also works, Canvas \> Graphics Raycaster \> Uncheck Ignore Reverse Graphics
> 3 votes

# Answer
Easy fix is to set your Source Image to None, reset y rotation to 0, Color full transparent, Raycast Target Check. Then you add your Image as a child, set rotation y 180 and Uncheck Raycast Target (not needed anymore because the image is flipped, the raycast will pass trought it anyway). Set your child Image as Target Graphic in the Button component and there you go.
> 1 votes

---
Tags: unity, gui
---


title: OpenGL Rendering Pipeline

text:
# Question
Title: OpenGL Rendering Pipeline
I've been learning OpenGL graphics programming and I've decided I'd quite like to make a simple game using OpenGL.

Drawing something in OpenGL, needless to say, is quite the endeavour. However it usually follows the following steps:

1) Use an array to outline where the vertices are of what I want to draw, as well as

2) Create a vertex array object VAO to store the vertex buffer objects and store how the data is formatted, etc.

3) Generating vertex buffer objects VBOs and element buffer objects EBOs (if applicable). Binding the relevant buffer data to them (ie, passing in the vertex data to the VBO and vertex drawing order to the EBO).

4) Instructing OpenGL on how the data is actually formatted within the array I defined at the start (the vertex coordinates, texture coordinates, etc) using glVertexAttribPointer.

5) Binding the textures if necessary, enabling the vertex and fragment shaders, binding the vertex array, and then finally drawing.

6) Unbinding the vertex array

Since I'm almost always following these 6 steps when I want to draw things I thought I'd be able to abstract it. I thought I could do this by passing in a batch of vertices to a 'render' class every render call which would do these steps every time for me so I can render things more easily without the great big spiel that takes a good 20 lines of code every time I want to draw a box.

This would be immensely helpful. For example, suppose I wanted to draw a heightmap. All I'd have to do would be to pass in the vertex locations/textures to bind/shaders to use, etc, and it'd draw it for me! Possibly even alongside some trees/rocks that I could pass in to that one render call.

However I've realised that there're a lot of technical limitations with this and I'm beginning to question whether this is even a fundamentally correct approach to OpenGL rendering.The reason why I think this is fundamentally wrong is because it still doesn't really avoid the big spiel of code that I have to go through every time I want to draw some vertices - I just create a 'middleman' class inbetween, which is a bit useless and unnecessary.

What are the best practises when it comes to creating a simplified and easy-to-use rendering 'pipeline' like what I'm trying to describe?

# Answer
For most rendering use cases, the vertices of a model don't change every frame. Much of what we want to draw in a game is either completely static geometry, like the terrain or buildings; re-used props that need the same vertex buffer every time, just different transforms/materials; or character meshes that might animate according to a skeleton, but still use the same underlying mesh every frame.

So it's wasteful to create and dispose of the vertex data every frame, when we could just leave that data in video memory and reference it when we need it.

Instead you'll usually create a data structure to represent your mesh, that references the appropriate buffers/attribute bindings to use when drawing. You create this data structure once when the mesh is loaded/created and its data uploaded to video memory, and any object that needs to be drawn with this mesh will reference this data structure.

When you draw a frame, you look up into this data structure to find and use the appropriate, already-populated buffers, rather than re-creating them from scratch.

So, there's still a middle-man, but the extra layer does most of its work when assets are loaded / unloaded, and provides just a minimal bit of boilerplate reduction in each draw call. Your main savings is moving the rest of the work outside your draw loop entirely.
> 1 votes

# Answer
Yes as mentioned I've found creating a 'Mesh' base class works quite well. A Mesh nicely ties together the large number of OpenGL objects needed to render even a simple object and ensures I don't repeat verbose GL object setup code.

When creating an instance of Mesh, I specify the vertex format, provide vertex and index data, supply an array of textures, and finally the shader program (vert and frag shader).

The vertex format is itself just a struct containing primitive fields (x,y,z etc) and a function that knows how to setup (multiple VertexAttribPointer calls) the OpenGL vertex attributes for this format. Keeping the fiddly OpenGL vertex attribute right inside the vertex format itself really makes changing formats simpler. Vertex data provided to the Mesh is just an array of this struct.

A Mesh has a base class method Render() that I call as required to actually draw it. Render() takes care of all the boilerplate of activating shaders, binding the vao, calling GL.DrawElements, unbinding vao and deactivating shaders etc.

Internally each mesh contains an instance of a VertexArrayObject, VertexBufferObject and IndexBufferObject class that take care of correctly binding and buffering data etc to OpenGL as required.

Each mesh can be static or dynamic. A static mesh sends the provided vertex/index data to the GPU once and and saves memory by not storing the client side data. A dynamic mesh expects that the vertex data will be changed and keeps a copy to allow manipulation and sends it to the GPU when requested.

The ShaderProgram and Shader class encapsulate loading (from file/string), attaching, linking/compiling etc.

In summary this level of abstraction is about as far as I would go. Any higher abstractions such as Character, Screen, Sprite etc might be quicker for you to use but will often be slower for the GPU unless you are very careful.
> 1 votes

# Answer
This may be opinionated, but imo there is no such thing as a "a fundamentally correct approach to OpenGL rendering".

For "a simplified and easy-to-use rendering 'pipeline'" I wouldn't abstract too much, espcially when you're sure you're not going to switch graphics APIs.

Assuming your objects have a simple lifecycle of setup() - render() - cleanup(), the middle being called per frame, the outer ones on startup and when leaving the renderer. Maybe frame-specific preparations like state changes or dynamic data could be included in prepare\_frame() and end\_frame() methods if you don't want to clutter render() too much, called before and after calling an object's render() method.

Besides this render-"framework", a class for wrapping shader compilation is ok, imo, which could also handle single uniform objects. Generic buffers objects and their allocations would also be candidates for a wrapper in such a simplified framework. But I wouldn't abstract specific uniform buffers or vertex arrays with their respective buffers. There are too many special cases, data formats, etc. In OpenGL they are built with just a few API calls that easily fit in a render object's methods mentioned above.

With that simplistic approach one can already do a lot, a skybox only needs s-r-c as it is static, a text renderer may additionally need the prepare() method for the dynamic per-frame-data, and so on. You also have a pretty easy control of state changes.

I would also recommend to get the OpenGL Programming Guide 9th edition and the OpenGL Shading Language Cookbook 3rd edition to learn the details of object handling. Most if not all internet tutorials are outdated.
> 1 votes

---
Tags: opengl, rendering, graphics-programming
---


# Question
Title: Issues detecting if position is inside a Polygon2DCollider
I have a Polygon2DCollider set in my scene that I am using `Physics2D.OverlapPoint(position, 0)` to see if the set position collides with anything. Initially, the collider is stored in memory and then deactivated for future use. When I want to use it I do the following:

```
targetColliderObj.SetActive(true);

Collider2D collider = Physics2D.OverlapPoint(testPosition, 0);
if (collider == null || collider.tag != targetColliderObj.tag)
{
    Debug.Log("Unable to move down a floor.");
}

```

In the code above I activate the target gameobject for the Polygon2DCollider and check to see if the testPosition is within the collider. The collider is always null even though I am placing the testPosition inside of the collider. Also, I am checking on layer mask 0. The gameobject of the Polygon2DCollider is also on the Default layer (0).

# Answer
> 0 votes
I was able to resolve this issue by using `Collider.OverlapPoint();` rather than what I was originally trying. Here is the simple change that was necessary:

```
targetColliderObj.SetActive(true);

PolygonCollider2D collider = targetColliderObj.GetComponent<PolygonCollider2D>();
if (collider.OverlapPoint(testPosition))
{
    Debug.Log("The collider was hit!");
}

```

---
Tags: unity
---


# Question
Title: How can I set a ui image canvas to be in front of anything else?
In the Hierarchy I have a Canvas set to Screen Space - Overlay the canvas name is Scene Fader. and a child disabled ui Image and also a child name Scene Fader Child that is a gameobject with a script attached to it name Scene Fader :

The script that attached to Scene Fader Child is :

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

public class SceneFader : MonoBehaviour
{
    #region FIELDS
    public GameObject fadeOutUIGameobjectImage;
    public float fadeSpeed = 0.8f;
    //public SaveLoad saveLoad;

    private Image fadeOutUIImage;

    private void Start()
    {
        SceneManager.sceneLoaded += SceneManager_sceneLoaded;
    }

    public enum FadeDirection
    {
        In, //Alpha = 1
        Out // Alpha = 0
    }
    #endregion

    #region FADE
    public IEnumerator Fade(FadeDirection fadeDirection)
    {
        fadeOutUIGameobjectImage.SetActive(true);

        float alpha = (fadeDirection == FadeDirection.Out) ? 1 : 0;
        float fadeEndValue = (fadeDirection == FadeDirection.Out) ? 0 : 1;
        if (fadeDirection == FadeDirection.Out)
        {
            while (alpha >= fadeEndValue)
            {
                SetColorImage(ref alpha, fadeDirection);
                yield return null;
            }
            fadeOutUIGameobjectImage.SetActive(false);
        }
        else
        {
            fadeOutUIGameobjectImage.SetActive(true);
            while (alpha <= fadeEndValue)
            {
                SetColorImage(ref alpha, fadeDirection);
                yield return null;
            }
        }
    }
    #endregion

    #region HELPERS
    public IEnumerator FadeAndLoadScene(FadeDirection fadeDirection, string sceneToLoad)
    {
        yield return Fade(fadeDirection);

        SceneManager.LoadScene(sceneToLoad);
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        if (MenuController.LoadSceneForSavedGame == true)
        {
            var saveLoad = GameObject.Find("Save System").GetComponent<SaveLoad>();
            saveLoad.Load(null, null);
        }

        if(MouseHover.loadingwithfolder)
        {
            var saveLoad = GameObject.Find("Save System").GetComponent<SaveLoad>();
            saveLoad.Load(MouseHover.folder, MouseHover.savedGameFName);
            MouseHover.loadingwithfolder = false;
        }
    }

    private void SetColorImage(ref float alpha, FadeDirection fadeDirection)
    {
        if(fadeOutUIImage == null)
        {
            fadeOutUIImage = fadeOutUIGameobjectImage.GetComponent<Image>();
        }

        fadeOutUIImage.color = new Color(fadeOutUIImage.color.r, fadeOutUIImage.color.g, fadeOutUIImage.color.b, alpha);
        alpha += Time.deltaTime * (1.0f / fadeSpeed) * ((fadeDirection == FadeDirection.Out) ? -1 : 1);
    }
    #endregion
}

```

When in this script I'm enabling true the fadeOutUIGameobjectImage I want that this Image will become in front of anything else all the ui elements and other stuff.

Now there is some ui elements that are in front of it.

This screenshot show the default main menu when running the game :

Then when starting a new game everything is fade out the screen get black using the Scene Fader script but the left ui element is in front of the image in the scene fader script :

# Answer
> 2 votes
The solution is to change the canvas sort order to value 1.

For testing I enabled the Image and set the Image alpha color to 255. Then in the canvas Scene Fader I set the Sort Order to 0. The result :

Now I changed the Sort Order to 1 :

In other words the solution is to set the canvas that should fade out it's sort order value to be any value bigger then all the other ui elements. In this case the value 1 is high enough.

And because I'm changing the image alpha color back to 0 when I get back to the main menu in the game I don't have to change the canvas sort order again.

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


title: Jittery collisions in Unity 2D

text:
# Question
Title: Jittery collisions in Unity 2D
I tried to implement a simple movement to my object. My object moves perfectly fine but I'm having issues with its collision. When I keep on moving object towards the obstacle/ground, collision are jittery.

Here the code for what I've written.

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

public class TempScript : MonoBehaviour
{
    [SerializeField] float walk_speed = 5f;
    [SerializeField] float jump_speed = 10f;
    [SerializeField] float max_up = 7f;
    [SerializeField] float max_low = -1.5f;

    void Update()
    {

        PlayerMovement();

    }
    void PlayerMovement()
    {

        if (Input.GetKey(KeyCode.W) && transform.position.y <= max_up)
            transform.position = transform.position + Vector3.up * jump_speed * Time.deltaTime;

        if (Input.GetKey(KeyCode.S) && transform.position.y >= max_low)
            transform.position = transform.position + Vector3.down * jump_speed * Time.deltaTime;

        if (Input.GetKey(KeyCode.D))
            transform.position = transform.position + Vector3.right * walk_speed * Time.deltaTime;

        if (Input.GetKey(KeyCode.A))
            transform.position = transform.position + Vector3.left * walk_speed * Time.deltaTime;
    }

}

```

The cube goes below the ground and bounces right back up. making it look like its jittering. what i want is movement should stop when its colliding with object. just like it happens with addForce method.

for now you can ignore `max_up` and `max_down` variable, it was just to make sure its in the camera.

# Answer
> 1 votes
I think the problem is that you are changing the position of the body by directly changing the coordinates, thus you are putting your object beyond the border of a collider (over the wall). At the next physics step (which is not executed every frame) the collider system resets your rigidbody to the correct position).

It is usually not recommended to change the position of a physics-simulated object directly. Instead, use "AddForce" or "MovePosition", or other physics-related methods to manipulate your objects. You can limit the maximum speed of your object as well, so you can make sure that your character moves at the correct speed when you are applying force.

You may have to set also your surface properties so it won't "bounce" of the wall.

# Answer
> 1 votes
This effect is explained very well in one of the Unity official beginner tutorials (Ruby's Adventure: 2D Beginner), in particular in the World Interaction Chapter

> Jittering happens because the Physics System uses a simplified copy of the Scene that only contains the Colliders. This Physics Scene make computations simpler for the Physics System, but the Physics System needs to:
>
> * Move its copy of the GameObject in the physics Scene whenever the GameObject with the Rigidbody moves in your Scene.
> * Apply forces and compute collision.
> * Move the GameObject in your Scene to the new position calculated in the physics Scene.
>
> In this case, that leads to the following events:
>
> * You move the character during the frame update.
> * The Physics System moves its copy to that new position.
> * The Physics System finds that the character Collider is now inside another Collider (here the box) and moves it back, so that it is no longer inside the box. -The Physics System synchronizes the Ruby GameObject with that new position.
>
> You are constantly moving Ruby inside the box and the Physics System is moving her back. The fighting between what you tell your code to do and what the Physics System does causes the jittering.

# Answer
> 0 votes
A simple movement script usually looks similar to this.

```
void FixedUpdate(){
   float moveHorizontal = Input.GetAxis("Horizontal");
   float moveVertical = Input.GetAxis("Vertical");
   Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
   rb2d.AddForce (movement * walk_speed);
}

```

Don't use hard coded keys, use the input manager. Physic based movement should be handled in fixed update (independent of frame rate).

---
Tags: unity, c#, collision-detection, physics, collider
---


# Question
Title: I want camera to be positioned on the player also x axis should move continuosly by .05f in unity 2d
I am creating an 2d platformer and I am newbie to Unity; any help will be highly appreciated. I want the camera to be positioned on the player and also the X axis should move continuously by .05f. And if player is not moving or stuck somewhere and if player is behind camera player (because X axis is automatically moving by .05f) then player should die.

Is it doable? I am using Cinemachine and any script logic will be appreciated.

# Answer
> 0 votes
1. Create a gameObject and attached cinemachine to this object
2. Attached script to this , FollowObject is the player

```
public GameObject FollowObject;
private Rigidbody2D rb;

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

private void FixedUpdate(){
    float MoveSpeed = rb.velocity.magnitude > Speed ? rb.velocity.magnitude : Speed;
    transform.position += Vector3.right * MoveSpeed * Time.deltaTime;
}

```
3. Player script, if player is not visible by main camera he dies(currently reloading the screen)

```
 void Update()
 {
     var planes = GeometryUtility.CalculateFrustumPlanes(Camera.main);
     var isvisible = GeometryUtility.TestPlanesAABB(planes, collider2D.bounds);
     if (!isvisible)
     {
         SceneManager.LoadScene("Gamestart4");
     }
 }

```

PS: Suggestions for improvement is accepted

---
Tags: unity
---


title: Flicking issue on Linux build only

text:
# Question
Title: Flicking issue on Linux build only
I'm about to release my second game in the next couple of days. A tester now reported that he has a flicker issue running the game on Linux. It´s related to objects like the water, the hex tiles and object on top of the hextiles. In Windows everything works like a charm but on Linux all the graphics flicker. I think it´s a graphical problem related to the Z-buffer since the flicking objects all have the same world space position. I´m using the URP and created all the shader by Unity Shader Graph. Does anyone know how I can fix the issue?

This it how it looks:

Any kind of help is appreciated! Thanks in advance!

# Answer
Here are some ways to fix Z-buffer:

1. **Physically move the objects further apart.** Simply increasing the distance between the fighting objects should fix z-fighting in most cases. This is the most obvious solution but sadly not always possible depending on the situation, but if it is then always try increasing distances between objects if there’s no disadvantage from doing so.
2. **Increase the near clipping plane and decrease the far clipping plane of the camera.** The lower the range of your camera clipping planes the more the depth buffers precision isn’t wasted.
3. **Nudge the shader depth offset to force an object to be rendered on top.** Sometimes you may want an object inside another object but still want one forced on top. (such as graffiti on walls, dirt on ground etc) In these cases you can adjust the shader offset. This will offset the rendering of the rendered object without physically moving the vertices.

I found this from here.
> 0 votes

---
Tags: unity, graphics
---


title: How to get a specific button component

text:
# Question
Title: How to get a specific button component
I'd like Unity to get a specific button with:

```
GetComponent<Button>().interactable

```

But how do I get a specific button with a name?

# Answer
> 2 votes
Remember, `someObject.GetComponent` gets a component attached to `someObject`.

If you don't lead with a specific object to look in, and just type `GetComponent` on its own, it refers to "this" object: the same one that the component running the script you're writing is attached to.

The best way to reference a specific button (or any other component) is to expose it as a member variable at the top of your class, outside of any methods:

```
public Button buttonIWantToUse;

```

This will create a slot in the Inspector where you can assign a reference to the button directly, with no searching at runtime.

If searching can't be avoided in your case, you can look up an object with a specific name in the active scene with:

```
var soughtObject = GameObject.Find("Some Name");
var buttonOnSoughtObject = soughtObject.GetComponent<Button>();

```

But I recommend avoiding looking up objects by name. It's not as fast or reliable as storing a reference, and it's easy to get downright baffling bugs that way.

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


# Question
Title: Pass equations into shaders to define graphics - HLSL or other shaders
Is it possible with HLSL (or other popular shader languages) to pass instead of an image, an equation that would define the pixel color / position output by the shader? This would allow for more dynamic drawing of smooth shapes that could be sampled with infinite detail. They would also by able to change and morph in real time.

Not sure how this is possible without passing a string with the eq to the shader and having it parse it. Seems like that might lose all the performance gained by putting it onto the GPU.

# Answer
> 0 votes
Why not simply define enumeration values at the top of your shader and use a switch statement to select the equation you wish to use, then upload the corresponding integer value you wish to use to select the equation from the switch statement?

I’m not a great graphics programmer, but i believe this technique is called an uber shader

If you require more than just one switch statement, you could use bit packing to store several values in one float, and then unpack them in the shader.

---
Tags: shaders, hlsl, geometry-shader, vertex-shader, surface-shader
---


title: Unity - Build failed with error

text:
# Question
Title: Unity - Build failed with error
I don't know how this happened but yesterday building just works fine for me until I tried it again and it gave me an error while building, I am using the same folder every time I build. (Builds Folder). Is there a way to resolve this?

Here are the errors that I got:

BuildFailedException: Burst compiler (1.1.1) failed running

stdout:
Burst requires Visual Studio (installable via Add Component in the Unity Installer) or the C++ build tools for Visual Studio, along with the Windows 10 SDK in order to build a standalone player for Windows with X86_SSE4
Failed to determine visual studio installation path - is Visual Studio installed?
stderr:

Unity.Burst.Editor.BurstAotCompiler+BclRunner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.burst@1.1.1/Editor/BurstAotCompiler.cs:663)
Unity.Burst.Editor.BurstAotCompiler+BclRunner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.burst@1.1.1/Editor/BurstAotCompiler.cs:601)
Unity.Burst.Editor.BurstAotCompiler+BclRunner.RunManagedProgram (System.String exe, System.String args, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.burst@1.1.1/Editor/BurstAotCompiler.cs:575)
Unity.Burst.Editor.BurstAotCompiler.OnPostBuildPlayerScriptDLLsImpl (UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.burst@1.1.1/Editor/BurstAotCompiler.cs:290)
Unity.Burst.Editor.BurstAotCompiler.OnPostBuildPlayerScriptDLLs (UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.burst@1.1.1/Editor/BurstAotCompiler.cs:46)
UnityEditor.Build.BuildPipelineInterfaces.OnPostBuildPlayerScriptDLLs (UnityEditor.Build.Reporting.BuildReport report) (at <7d90b28560b644ce87b8263efcc36eed>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

BuildFailedException: Burst compiler (1.1.1) failed running

stdout:
Burst requires Visual Studio (installable via Add Component in the Unity Installer) or the C++ build tools for Visual Studio, along with the Windows 10 SDK in order to build a standalone player for Windows with X86_SSE4
Failed to determine visual studio installation path - is Visual Studio installed?
stderr:

Unity.Burst.Editor.BurstAotCompiler+BclRunner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.burst@1.1.1/Editor/BurstAotCompiler.cs:663)
Unity.Burst.Editor.BurstAotCompiler+BclRunner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.burst@1.1.1/Editor/BurstAotCompiler.cs:601)
Unity.Burst.Editor.BurstAotCompiler+BclRunner.RunManagedProgram (System.String exe, System.String args, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.burst@1.1.1/Editor/BurstAotCompiler.cs:575)
Unity.Burst.Editor.BurstAotCompiler.OnPostBuildPlayerScriptDLLsImpl (UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.burst@1.1.1/Editor/BurstAotCompiler.cs:290)
Unity.Burst.Editor.BurstAotCompiler.OnPostBuildPlayerScriptDLLs (UnityEditor.Build.Reporting.BuildReport report) (at Library/PackageCache/com.unity.burst@1.1.1/Editor/BurstAotCompiler.cs:46)
UnityEditor.Build.BuildPipelineInterfaces.OnPostBuildPlayerScriptDLLs (UnityEditor.Build.Reporting.BuildReport report) (at <7d90b28560b644ce87b8263efcc36eed>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Error building Player: BuildFailedException: Burst compiler (1.1.1) failed running

stdout:
Burst requires Visual Studio (installable via Add Component in the Unity Installer) or the C++ build tools for Visual Studio, along with the Windows 10 SDK in order to build a standalone player for Windows with X86_SSE4
Failed to determine visual studio installation path - is Visual Studio installed?
stderr:

Build completed with a result of 'Failed' in 17 seconds (17004 ms)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

UnityEditor.BuildPlayerWindow+BuildMethodException: 4 errors
  at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x002bb] in <7d90b28560b644ce87b8263efcc36eed>:0
  at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in <7d90b28560b644ce87b8263efcc36eed>:0
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
```

# Answer
It appears that you are missing some crucial resources in order to compile. Here are the resources necessary I found in the error codes:

1. You need **Visual Studio** and/or the C++ build tools for Visual Studio (required for Burst to compile)
2. **Windows 10 SDK**

Those are all the requirements I could find in the log.
> 1 votes

# Answer
Did you add any packages that had dependencies on the Burst Compiler, as I added a Animation Rigger and forgot the compiler and got exact same message. Try looking at dependencies listed on package in Unity \> Package Manager \> PACKAGE Good luck.
> 1 votes

---
Tags: unity, build-process
---


# Question
Title: Effective solution for showing the outline of the player sprite when behind objects or tiles that are meant to be in foreground
I'm very new to Unity and I'm now experimenting with possible ways to show the player outline when he/she is behind objects or tiles. This is what I came up with:

## My setup

* Built-in rendering pipeline
* Renderers sorted using based on Order in Layer. **All the Tilemaps and the Player are at the same Z**
* Transparency Custom Axis: (0, 1, 0). (All default sprite shaders are in the same Transparent Queue)
* Three Tilemaps: Bottom (grass, order in layer -2), Middle: (fence, order in layer -1), Top (house and player, order in layer 0)

## My solution

* Create a Sprite GameObject (let's call it OutlineSprite) with the same sprite used by the player. Assign it as child of the PlayerSprite
* Assign, to the OutlineSprite, a "Order in Layer" greater than anything else.
* Assign, to the OutlineSprite, the same animator used for the Player sprite (and modify the c# script that sends notification to the animation controller whenever the player moves so that it sends notification to the OutlineSprite animation controller too)
* Assign, to the OutlineSprite, a material which uses a shader able to render the outline of a given sprite (I just copy/pasted a shader I found online which does more or less what I wanted, I'm not anywhere near to understand how to write a shader right now)
* Modify the player Sprite outline so that it exactly match the shape of the sprite
* Put a Sprite Mask in every place you need to create this effect (in the screenshot is just over the house roof)
* Configure the Player sprite to be "Visible outside mask" and the OutlineSprite to be "Visible inside mask"

This solution seems to do what I need but has many cons that I'd like to address, if possible.

Pro:

* simple solution that doesn't require extensive knowledge of advanced concepts

Cons:

* the player animation runs twice
* tedious to manually configure the outline of all the animation sprites
* tedious to manually place the sprite mask where needed

## My question

Is there another (or multiple) solution to this problem that involve the least amount of changes and work (so that the setup fast and maintenance is minimal)? Ideally I'd like to only change the player's shader, if possible.

# Answer
> 2 votes
Following the "are you open to solutions that do swap the tile shader to write to the depth buffer?" suggestion by DMGregory on a comment in my question I implemented another possible solution which greatly simplifies the maintenance of the project.

## Disclaimer

This solution is implemented using shaders. Saying that I'm new to shaders is an understatement. Take everything I say with caution, it might be wrong. Also, this is just a proof of concept and not a full implementation of a production ready shader. In fact the resulting shader will just paint the hidden part of a given color.

## The idea

The idea is to write just one shader for the player so that when parts of the player sprite are behind another "object" (be it a gameobject or a tile), those part are visibile through the object and rendered differently than the rest of the sprite (as in the picture in my question, so to speak)

## What we need

In a shader, to check if a certain pixel is in front, behind, or at the same level of a pixel **already written in the frame buffer** the ZBuffer is used. This means that, in the new PlayerShader, we have to make use of the ZTest to discriminate which pixel has to be written using the normal sprite assigned to the player or using the custom color. This immediately brought up the first problem: the unity official Sprite-Default shader (the default one used for sprites and tiles) has the **ZWrite** set to **Off**, which means that they do not write on the ZBuffer and so we cannot interrogate it and expecting a sounding answer about the pixel position. This is easily solved but requires a break in our initial idea: we have to modify the shader assigned to the tiles and not only the one assigned to the player.

But this is still not enough, and here lied one of the misconception I had. I initially thought that **Z**, in the ZBuffer, was the distance to the camera calculated using the sorting priorities already discussed. It took me a while to understand that the sorting priorities only deal with the order in which the renderer gets executed and this might create the effect that one element is on top of another, even tho they are at the very same distance from the camera. So, to make use of the ZBuffer, I think, objects have to be at different distance from the camera.

## Changing in the setup

In order to implement the player shader, I had to make a few modifications in my setup:

* Create a new material with a news shader for the tiles. The new shader is simply a copy-paste of the official Sprite-Default.shader with **ZWrite On** instead of Off
* Modify the Z for the **Top** tielemap (the one containing the house, but in general for all objects/tiles that need to be on top of the player) to a number greater than the Z of the player (but less than the camera)

## Player Shader

As I said: this is just a proof of concept, far from working in every situation. The important parts are:

* The queue is Transparent+1 so that it gets rendered after all other sprites. At this point the Top tilemaps with the house should have already written in the ZBuffer the information on its position.
* The first pass is again the same copy-paste of the default unity sprite shader, with the exception that we only execute it when **ZTest LEqual**
* The second pass is executed when **ZTest Greater** instead and it's its job to paint the outline of the player behind the object. In this case we just color it without doing anything fancy.

```
  Shader "Test/PlayerShader"
  {
    Properties
    {
      _OutlineColor ("Outline Color", Color) = (0,0,1,1)
      [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
      _Color ("Tint", Color) = (1,1,1,1)
      [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
    }
    SubShader
    {
      Tags
      {
          "Queue"="Transparent+1"
          "IgnoreProjector"="True"
          "RenderType"="Transparent"
          "PreviewType"="Plane"
          "CanUseSpriteAtlas"="True"
      }

      Cull Off
      Lighting Off
      ZWrite On
      Blend One OneMinusSrcAlpha

      Pass
      {
          Name "ForeGround"
          ZTest LEqual
          CGPROGRAM
          #pragma vertex vert
          #pragma fragment frag
          #pragma multi_compile _ PIXELSNAP_ON
          #include "UnityCG.cginc"

          struct appdata_t
          {
              float4 vertex   : POSITION;
              float4 color    : COLOR;
              float2 texcoord : TEXCOORD0;
          };

          struct v2f
          {
              float4 vertex   : SV_POSITION;
              fixed4 color    : COLOR;
              float2 texcoord  : TEXCOORD0;
          };

          fixed4 _Color;

          v2f vert(appdata_t IN)
          {
              v2f OUT;
              OUT.vertex = UnityObjectToClipPos(IN.vertex);
              OUT.texcoord = IN.texcoord;
              OUT.color = IN.color * _Color;
              #ifdef PIXELSNAP_ON
              OUT.vertex = UnityPixelSnap (OUT.vertex);
              #endif

              return OUT;
          }

          sampler2D _MainTex;
          sampler2D _AlphaTex;
          float _AlphaSplitEnabled;

          fixed4 SampleSpriteTexture (float2 uv)
          {
              fixed4 color = tex2D (_MainTex, uv);

  #if UNITY_TEXTURE_ALPHASPLIT_ALLOWED
              if (_AlphaSplitEnabled)
                  color.a = tex2D (_AlphaTex, uv).r;
  #endif //UNITY_TEXTURE_ALPHASPLIT_ALLOWED

              return color;
          }

          fixed4 frag(v2f IN) : SV_Target
          {
              fixed4 c = SampleSpriteTexture (IN.texcoord) * IN.color;
              c.rgb *= c.a;
              return c;
          }
      ENDCG
      }

      Pass {
          Name "Background"
          ZTest Greater
          Blend SrcAlpha OneMinusSrcAlpha

          CGPROGRAM

          #pragma vertex vert
          #pragma fragment frag

          float4 vert(float4 vertexPos : POSITION) : SV_POSITION
          {
          return UnityObjectToClipPos(vertexPos);
          }

          float4 _OutlineColor;

          float4 frag(void) : Color
          {
              return _OutlineColor;
          }

          ENDCG
      }
  }
}

```

---
Tags: unity, 2d
---


# Question
Title: How to set transparency in DirectX 7 surfaces, which contain 32BPP BMP files?
The following is my working code. Everything functions and I can animate my sprite but the sprite has no transparency color. It has a white background on every frame. I am using DirectX 7.0 and 32BPP BMP files. My sprite is in a rectangular box. It uses 2D images and I have my own code to animate in 3D using static images, to fool the observer.

```
void Surface::Create(int width, int height, SURFACE &the_surface)
{
    TRACE("Surface::Create invoked width = %i height = %0i\n", width, height); // the width and height in this TRACE statement must equal that in Surface::Write

    LPDIRECTDRAW7 pDDraw = Video::GetDdraw();

    // clear the structure
    memset(&the_surface.desc, 0, sizeof(the_surface.desc));
    the_surface.desc.dwSize = sizeof(the_surface.desc);

    //memset(&the_surface.ddsurf, 0, sizeof(the_surface.ddsurf));

    // --------
    //
    // We want to allocate system memory to cache the bit map image
    // that is not the primary surface or back buffer surface
    // later we will want to detect direct draw hardware so we
    // can write to either system memory or video memory
    // by defualt we write to system memory
    the_surface.desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
    the_surface.desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
    the_surface.desc.dwWidth        = width;
    the_surface.desc.dwHeight       = height;

    try
    {
        //
        // create a complex implicit surface and attach it to ddraw
        // this surface may NOT be detached
        if (width < 1 || height < 1)
            throw SURFACE_EXCEPTION;    // should never be here
        hrRetVal = pDDraw->CreateSurface(&the_surface.desc, &the_surface.ddsurf, NULL);
        if (DD_OK != hrRetVal)
            throw SURFACE_EXCEPTION;

        //
        SetColorKey(1,1,the_surface);   // what color do we want to be transparent? default = white my sprite background is white
    }

    catch ( int exception )
    {
        TRACE("%Xh exception caught by Surface::Create hrRetVal was: ", exception);
        Surface::Check(hrRetVal);
        if (exception == SURFACE_EXCEPTION)
        {
            TRACE("SURFACE_EXCEPTION caught by Surface::Create, width = %i, height = %i\n", width, height);
            TRACE("VIDEO_EXCEPTION thrown by Surface::Create\n");
            throw (VIDEO_EXCEPTION);
        }
    }  // end catch
}

void Surface::Write(IMAGE &an_image, SURFACE &into_surface)
{
    TRACE("Surface::Write invoked width = %d height = %d\n", an_image.width, an_image.height); // the width and height in this TRACE statement must equal that in Surface::Create
    try
    {
        // what part of the surface do we want to lock?
        // all of it
        into_surface.surfrect.left   = 0;
        into_surface.surfrect.top    = 0;
        into_surface.surfrect.right  = an_image.width;
        into_surface.surfrect.bottom = an_image.height;

        // frame-buffer access
        // obtain access to the entire direct draw surface created by Surface::Create
        hrRetVal = into_surface.ddsurf->Lock(&into_surface.surfrect, &into_surface.desc, DDLOCK_SURFACEMEMORYPTR | DDLOCK_NOSYSLOCK | DDLOCK_WAIT, 0);
        if (DD_OK != hrRetVal)
            throw (SURFACE_EXCEPTION);

        //-------------
        //
        // Copy bitmap bits from bmp image to direct draw surface
        //
        DWORD* to_video = (DWORD*)(into_surface.desc.lpSurface);                    // cast the surface pointer
        DWORD* from_image = (DWORD*)(&an_image.buffer[((an_image.width) * (an_image.height - 1))]);
        DWORD pixelsperrow = into_surface.desc.lPitch / (BYTESPERPIXEL);
        DWORD* SurfacePtr = (DWORD*)into_surface.desc.lpSurface;                // cast the surface pointer

        // copy a row at a time
        for (int i = 0; i < an_image.height; i++)           // copy from [0,0] upper left to [0, image height]
        {
                wmemcpy((wchar_t*)to_video, (wchar_t*)from_image, an_image.width * 2);      // copy to_video system memory, from bmp image count of characters to copy in this case, copy the entire line

                to_video += pixelsperrow;                   // next line in video, lPitch is returned by lock

                // previous line in memory
                from_image -= an_image.width;
        }
        // release access of the direct draw surface important
        hrRetVal = into_surface.ddsurf->Unlock(NULL);
        if ( DD_OK != hrRetVal)
            throw (SURFACE_EXCEPTION);
    }  // end try

    catch ( int exception )
    {
        TRACE("%Xh exception caught by Surface::Write hrRetVal was: ", exception);
        Check(hrRetVal);
    }  // end catch
}

void Surface::Show(int row, int col, SURFACE &the_surface)
{
    TRACE("Surface::Show invoked.\n");

    LPDIRECTDRAWSURFACE7 backsurf = Video::GetBackSurface();

    // perform a source copy blit or transparent blit using a source
    // or destination color key. This method will always attempt an
    // asynchronous blit if this is supported by the hardware

    TRACE("surface.rect TR = [%d, %d] BL = [%d, %d]\n", the_surface.surfrect.top, the_surface.surfrect.left, the_surface.surfrect.bottom, the_surface.surfrect.right);
    hrRetVal = backsurf->BltFast(row, col, the_surface.ddsurf, &the_surface.surfrect, DDBLTFAST_SRCCOLORKEY | DDBLTFAST_WAIT);
    if ( DD_OK != hrRetVal)
    {
        TRACE("Surface::Show hrRetVal was: ");
        Check(hrRetVal);
    }
}

void Surface::SetColorKey(DWORD low,DWORD high, SURFACE &the_surface)
{
    TRACE("Surface::SetColorKey invoked\n");
    DDCOLORKEY ddck;    // transparent colors

    ddck.dwColorSpaceLowValue=low;
    ddck.dwColorSpaceHighValue=high;

    TRACE("ColorKey is Low = %u, High = %u\n", low, high);

    hrRetVal = the_surface.ddsurf->SetColorKey(DDCKEY_SRCBLT, &ddck);
    Check(hrRetVal);
}

```

# Answer
> 0 votes
```
// we load 32 bit BMP files into a directx back surface
// first we setup the directx primary surface and back surface
// we then instantiate a SURFACE class object, which when created we set the color key
// here this method is called for all surfaces, equally for background or sprite ADT
// for the sprite ADT we are usign a cirularly linked dynamic queue template which works nicely
// for loading all of a given sprites bmp images
// in my case we converted legacy 8 bit bmp files to 32 bit using NCH Suite of software specifically Pixillion Plus Image Converter
//
// The solution to the post was the one line consiting of: SetColorKey(0xffffff, 0xffffff, the_surface);
//
// we also took previous feedback to heart and change BltFast to Blt in Surface::Show.
// i.e. hrRetVal = frontsurf->Blt(&rcFill, the_surface.ddsurf, (tagRECT*)&the_surface.surfrect, DDBLT_WAIT | DDBLT_KEYSRC, &the_surface.ddbltfx);
// Following is the working code
void Surface::Create(int width, int height, SURFACE &the_surface)
{
    TRACE("Surface::Create invoked width = %i height = %0i\n", width, height); // the width and height in this TRACE statement must equal that in Surface::Write

    LPDIRECTDRAW7 pDDraw = Video::GetDdraw();

    memset(&the_surface.desc, 0, sizeof(the_surface.desc));
    the_surface.desc.dwSize = sizeof(the_surface.desc);

    // --------
    //
    // We want to allocate system memory to cache the bit map image
    // that is not the primary surface or back buffer surface
    // later we will want to detect direct draw hardware so we
    // can write to either system memory or video memory
    the_surface.desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
    the_surface.desc.ddsCaps.dwCaps = DDSCAPS_VIDEOMEMORY;
    the_surface.desc.dwWidth        = width;
    the_surface.desc.dwHeight       = height;

    try
    {

        //
        // create a complex implicit surface and attach it to ddraw
        // this surface may NOT be detached
        if (width < 1 || height < 1)
            throw SURFACE_EXCEPTION;
        hrRetVal = pDDraw->CreateSurface(&the_surface.desc, &the_surface.ddsurf, NULL);
        if (DD_OK != hrRetVal)
            throw SURFACE_EXCEPTION;

        // the next line of code is the solution to this post
        SetColorKey(0xffffff, 0xffffff, the_surface); // what color do we want to be transparent? default = white; using white

    }

    catch ( int exception )
    {

        TRACE("%Xh exception caught by Surface::Create hrRetVal was: ", exception);
        Surface::Check(hrRetVal);
        if (exception == SURFACE_EXCEPTION)
        {
            TRACE("SURFACE_EXCEPTION caught by Surface::Create, width = %i, height = %i\n", width, height);
            TRACE("VIDEO_EXCEPTION thrown by Surface::Create\n");
            throw (VIDEO_EXCEPTION);
        }

    }  // end catch

} // end Surface::Create

```

---
Tags: directx, transparency
---


# Question
Title: How to make an upgrade a building and replace it with the Level 2 prefab?
I want to to have multiple prefabs like canon level 1 and then level 2.

When the player has enough coins, they can upgrade it to level 2.

I want to make a game similar to Clash of Clans so I will have many buildings that can go through different levels.

How can I do this?

# Answer
One way to do this (there is never just one way to do something) is to simply replace the old building with a new one by `Destroy()`ing the gameObject of the old building and then `Instantiate()`ing one of the next level with the same position, rotation and parent.

One drawback of this method is that the building loses all of its internal state when you upgrade it. If that is a problem, then you might want to create two separate gameObjects for each building with a parent-child relationship. The parent persists during upgrades and carries all the functionality which is independent from the upgrade level of the building. The child which contains all the components where the upgrade level matters (including the SpriteRenderer/MeshFilter that stores the appearance). That way you can replace the level-dependent child but retain the level-agnostic parent.

I could also imagine several other solutions to the problem of managing state during upgrades, all with their own advantages and disadvantages. But I don't know what your requirements are, and I don't know how familiar you are with more advance programming concepts (like ScriptableObject's or C# Attributes). So I will leave that for another question.

**Storing the prefab for the next upgrade level**

You could either implement this on a global manager-object which has prefab-references to all upgrade levels of all buildings and also contains the information what's the next upgrade level for each building. Or you could implement it on the buildings themselves. Give the script that handles the upgrading a reference to the prefab for the next upgrade level. Both could work, and which one you choose is mostly a question of how you prefer to structure your project.

**Getting the cost of the next upgrade level**

In either case, it is possible to access variables of an uninstantiated prefab. It's rarely a good idea to *change* variables of prefabs at runtime, but there is no reason to not *read* them. So you can put the cost for upgrading a building into a public variable on the prefab for the next upgrade level.

So you can simply add a `bool CanUpgrade` method to the script which handles the upgrading which compares the cost of the prefab for the next upgrade level to the current resource count of the player. Then the script which handles the UI can use that method to determine if it should enable or disable the upgrade button.
> 3 votes

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