# Question
Title: Why are multiple Nav Mesh Agents jittery when the target is inaccessible?
I have a simple scene. Most of the land is flat, except for three raised cylindrical platforms coming up from the ground. I have several enemies with Nav Mesh Agent components attached, with their target being the player. I used the Standard Assets' ThirdPersonCharacter script, and then called `character.Move(agent.desiredVelocity, false, false);` within the `Update()` of a character control script.

The agents work great when the player runs around on the ground. When the player hops on the platform (about 2 units above the ground), an agent will walk toward the edge of the platform and then stop, just as expected. However, if I throw in a second agent, both agents work fine only until the player stands on the platform. Then they start to jitter, like they cannot make up their minds on whether to turn left or right when they should really just walk straight. If I add even more agents, the jittering gets worse. With enough, they don't even move forward and simply turn left and right rapidly.

Clearly, there is a problem with interference, and I understand the agents are designed to avoid obstacles as well as each other, but here is what I found and tried so far:

* I switched the obstacle avoidance quality to None. The jitter still happens just as much.
* Some other posts suggested setting IsKinematic to true for moving obstacles. I cannot do this because the character script depends on the rigidbody not being kinematic.
* I adjusted the height of the platform and re-baked the navmesh. It had no effect. It must be the fact that the platform is not actually accessible, so that the agents can only make a partial path.
* I messed with the pathfinding settings on the agent, such as turning auto repath off, since it has to do with partial paths. There were no noticeable changes.

Does anyone know what might be causing the jitters and how I could fix this?

# Update

As requested, here is how my Nav Mesh agent is configured:

# Answer
I had this problem and I was messing around with the Nav Mesh Agent and found out turning off "Auto Braking" fixed the problem.
> 2 votes

# Answer
Try setting the priority of all the Agents very low, except one, and see if this exact Agent is also facing the same issue as the others. To me it sounds like the agents were constantly trying to find a new path, as the other agents get too close.
> 0 votes

# Answer
When having the stopping distance at 0.3 with no autobreaking a weird behaviour shows where they reach the destination but then move back a bit. Setting the stopping distance to 1 works.
> 0 votes

---
Tags: unity, navmesh
---


# Question
Title: How to apply Image effect only on specific part of objects?
I need a way to censore part of characters' bodies like Cyberpunk 2077.this is mean I want to apply Image effect only to specific parts of bodies that you can see in the below Image:

# Answer
> 5 votes
# Solution 1

### Using GrabPass

> GrabPass is a special pass type - it grabs the contents of the screen where the object is about to be drawn into a texture. This texture can be used in subsequent passes to do advanced image based effects.
>
> Just GrabPass { } grabs the current screen contents into a texture. The texture can be accessed in further passes by \_GrabTexture name. Note: this form of grab pass will do the time-consuming screen grabbing operation for each object that uses it.

`GrabPass { "TextureName" }` grabs the current screen contents into a texture, but will only do that once per frame for the first object that uses the given texture name. The texture can be accessed in further passes by the given texture name. This is a more performant method when you have multiple objects using GrabPass in the scene

so first you should grab behind of object:

```
GrabPass{ "_GrabTexture" }

```

Initializing position and grab position in shader:

```
    v2f vert(appdata_base v) {
        v2f o;
        // use UnityObjectToClipPos from UnityCG.cginc to calculate
        // the clip-space of the vertex
        o.pos = UnityObjectToClipPos(v.vertex);
        // use ComputeGrabScreenPos function from UnityCG.cginc
        // to get the correct texture coordinate
        o.grabPos = ComputeGrabScreenPos(o.pos);
        return o;
    }

```

pixelating results:

```
    float _PixelSize;
    sampler2D _GrabTexture;

    float4 frag(v2f IN) : COLOR
    {
        float2 steppedUV = IN.grabPos.xy / IN.grabPos.w;
        steppedUV /= _PixelSize / _ScreenParams.xy;
        steppedUV = round(steppedUV);
        steppedUV *= _PixelSize / _ScreenParams.xy;
        //Sampling GrabTexture according to screen capture positon, tex2DProj is equivalent to tex2D (grabPos.xy / grabpos.w)
        return tex2D(_GrabTexture, steppedUV);
    }

```

so this is our pixelate shader:

```
Shader "Custom/Pixelate"
{
    Properties
    {
        _PixelSize("Pixel Size", Float) = 10
    }

    SubShader
    {
        Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" }
        Blend Off
        Lighting Off
        Fog{ Mode Off }
        ZWrite Off
        LOD 200
        Cull Off

        GrabPass{ "_GrabTexture" }

        Pass
        {
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct v2f
            {
                float4 pos : SV_POSITION;
                float4 grabPos  : TEXCOORD0;
            };

            v2f vert(appdata_base v) {
                v2f o;
                // use UnityObjectToClipPos from UnityCG.cginc to calculate
                // the clip-space of the vertex
                o.pos = UnityObjectToClipPos(v.vertex);
                // use ComputeGrabScreenPos function from UnityCG.cginc
                // to get the correct texture coordinate
                o.grabPos = ComputeGrabScreenPos(o.pos);
                return o;
            }

            float _PixelSize;
            sampler2D _GrabTexture;

            float4 frag(v2f IN) : COLOR
            {
                float2 steppedUV = IN.grabPos.xy / IN.grabPos.w;
                steppedUV /= _PixelSize / _ScreenParams.xy;
                steppedUV = round(steppedUV);
                steppedUV *= _PixelSize / _ScreenParams.xy;
                //Sampling GrabTexture according to screen capture positon, tex2DProj is equivalent to tex2D (grabPos.xy / grabpos.w)
                return tex2D(_GrabTexture, steppedUV);
            }

            ENDCG
        }
    }
}

```

# Solution 2

## Using two cameras that I explained before

1.Make secondary camera

2.On second camera, in Clear Flags set it to Don't clear

# Solution 3

## Using Command Buffer

we know, that the GPU can work on stuff in parallel. But what’s about the communication between CPU and GPU? Does the CPU has to wait until the GPU finished the job before it can receive new commands?

No! because this communication would create bottlenecks (e.g. when the CPU can’t deliver commands fast enough) and would make parallel working impossible.bottleneck, as for how it is named, occurs when there is a limit on how much data is being sent for processing or how much data can be processed at the same time.

The solution is a list where commands can be added by the CPU and read by the GPU – independent from each other! This list is called: Command Buffer.

## What is Command Buffer?

Command buffers hold list of rendering commands ("set render target, draw mesh, ..."). They can be set to execute at various points during camera rendering (see Camera.AddCommandBuffer), light rendering (see Light.AddCommandBuffer) or be executed immediately (see Graphics.ExecuteCommandBuffer).

## How it work?

The command buffer makes it possible that CPU and GPU can work independent from each other. When the CPU wants something to be rendered, it can push that command into the queue and when the GPU has free resources, it can take the command out of the list and execute it (but the list works as a FIFO – so the GPU can only take the oldest item in the list (which was first/earlier added than all others) and work on that).

By the way: there are different commands possible. One example is a draw call, another would be to change the render state.

https://vulkan-tutorial.com/Drawing\_a\_triangle/Drawing/Command\_buffers

https://developer.nvidia.com/engaging-voyage-vulkan

Let's Start to use command buffer  Masking part of character with sphere:

```
 Stencil
     {
         Ref 1
         Comp Always
         Pass Replace
     }

```

create a command:

```
var commandBuffer = new CommandBuffer();
commandBuffer.name = "pixelate";

```

Temporarily copy the rendering result to the Render Texture:

```
  int tempTextureIdentifier = Shader.PropertyToID("_PostEffect");
        commandBuffer.GetTemporaryRT(tempTextureIdentifier, -1, -1);
        commandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, tempTextureIdentifier);

```

Apply the rendering result to the material that you want to apply image effects:

```
commandBuffer.Blit(tempTextureIdentifier, BuiltinRenderTextureType.CameraTarget, material);

```

Release temporary render texture:

```
commandBuffer.ReleaseTemporaryRT(tempTextureIdentifier);

```

Register where you want to add the command buffer Below is a high-level overview of how Cameras use the Forward or Deferred pipeline to render a Scene in Unity.

* Black boxes represent an internal Unity process. Blue boxes represent
* a CameraEvent where you can add Command Buffers.

```
camera.AddCommandBuffer(CameraEvent.BeforeImageEffects, commandBuffer);

```

add Image effects to where Ref is equal to 1

```
   Stencil
    {
        Ref 1
        Comp Equal
    }

```

adding color to pixelated area

## More Examples!

pixelating specific objects

grayscale where that is not equal to Ref 1

```
Stencil
{
    Ref 1
    Comp NotEqual
}

```

References:

https://simonschreibt.de/gat/renderhell-book1/

https://gurutaka-log.com/commandbuffer-stencilbuffer

---
Tags: unity, shaders, image-effects
---


# Question
Title: Is there a wall building tool in unity3d?
I'm currently building a maze game in unity 3d and after building a few levels by placing and repositioning cubes by hand as walls, I think, that it would be nice if there was a tool to place walls, which are cubes with constant height and width, but have different length and rotations on the y-axis, by joints: you click to place a joint, and a wall goes in straight lines beetwen joints. So is there a tool like that?

# Answer
> 0 votes
Pro Builder allows you to model static geometry right in the Unity editor. It's an optional package you have to install using the package manager.

But if this is going to become a larger project, then you might look into editor scripting and write your own level editor.

---
Tags: unity, editors, map-editor
---


# Question
Title: Java create a Polygon for each island in tile game
I am making a 2d top-down tile based game, which is randomly generated each new world.

What I want to do is create a Polygon (or other more appropriate shape I don't know of) for each landmass not disrupted by land, basically each unseparated landmass/island, I want to do this for where my player is to spawn in the world, I want to have it so it has a higher chance of spawning on the biggest landmass in the world, rather than spawning on a tiny several tile island. So, all I need to know is how would I create some sort of shape system to recognise different islands.

The reason I suggest a Polygon is because the player would randomly spawn in that area so it has to be accurate to the land, it can't start of by spawning in water nearby.

If a Polygon is obsolete for this idea, and another system would be better let me know.

# Answer
For the main island I would do something like this. I would choose how many sides the polygon has to have. Then, I would choose a value, how far the farthest point of the island can be. Then I would create an array of coordinates of my polygon like this:

```
public class Island{

    public static void main(String[] args){

        int numberOfPoints = 10;
        float [][] islandCoordinates = float[numberOfPoints][2];//array of coordinates
        float maxDistance = 1000;

        float stepAngle = 2 * Math.PI / numberOfPoints;

        for(int i = 0;  i < numberOfPoints; i++){
            float dist = maxDistance * Math.random();
            float xcoordinate = Math.cos(stepAngle * i) * dist;
            float ycoordinate = Math.sin(stepAngle * i) * dist;

            islandCoordinates[i][0] = xcoordinate;
            islandCoordinates[i][1] = ycoordinate;
        }

    }

}

```

This would make the island look very simple, but I think with playing with the values you could make it a lot nicer.

Good luck!
> 0 votes

---
Tags: java, tilemap
---


# Question
Title: Confused about why my projection matrix works
My projection matrix was buggy, I'm not great at mathematics, but I checked it against the the songho tutorial, and the broken one seems correct to me but switching nearplane to farplane seems to have fixed it. What am I missing? My nearplane and farplane values are positive, nearplane is small about 0.01, 1.0f last time i ran against both; farplane is usually relatively large about 1000.0f, 500.0f the last time I ran it against both.

```
f32 l = left;
    f32 r = right;
    f32 t = top;
    f32 b = bottom;
    f32 n = nearplane;
    f32 f = farplane;

    m4x4 Result =  //TODO why did changing n to f in 0 and 5 fix it? and make sure it is fixed
    {
#if 0 // works
        2*f/(r-l), 0, (r+l)/(r-l), 0,
        0, 2*f/(t-b), (t+b)/(t-b), 0,
        0, 0, -(f+n)/(f-n), -2*f*n/(f-n),
        0, 0, -1, 0,
#else // doesn't
        (2*n)/(r-l), 0, (r+l)/(r-l), 0,
        0, (2*n)/(t-b), (t+b)/(t-b), 0,
        0, 0, -(f+n)/(f-n), (-2*f*n)/(f-n),
        0, 0, -1, 0,
    };
#endif

```

# Answer
> 1 votes
Probably your intended nearplane and farplane variables mapped reversely.So it clipped out eveything that supposed to be rendered on the screen.

**Possible Reasons**

* (**Possible**)There might be a transpose operation somewhere in your code.
* (**Possible**)There is chance which **songho's** tutorial displays projection matrix as a one way and its possible Opengl uses it as another.For example **Opengl** and **Directx** uses different approaches when it comes to matrixes.One is using row\_major layout other one is using column\_major.Your case could be something like that.
* (**Not likely**)It could be something with your vertex shader.
* (**Sorry for even considering it**)Are you sure you passed the n,f variables correctly?

---
Tags: opengl, mathematics, perspective, projection-matrix
---


# Question
Title: Why baked light differ so much from realtime light?
I'm trying to figure why Baked light differ so much from realtime lightning (whose final result I like and prefer!)

Left one: baked light, right one: realtime.

I've placed a:

* Directional light
* 3 spot light
* 1 Reflection probe

There is also post processing beahviour with bloom enabled.

Follow my light settings:

I can't enable Realtime GI because is a webGl application.

# Answer
**Its all about performance.**

Rendering soft light transport is harder than we presume.

When we need a light which renders/refreshes every frame we should be careful about how intense quality it should contain.More quality more FPS decrease. But when it comes to baked lights,theoretically you shouldnt care about how much time it consumes when its baking in the first place because real focus in here is game view right?.

That was the chit-chat lets look at what's so different about them systematically.

**Real Time Lights**

To utilize the parallel computing power of the GPU cores game developers created a way which considered one of the most effiecent real time light rendering solution.That is,think the light in your scene as another camera which does not contain COLOR values in it but only depth values. Each light renders the scene from another point view as depth values and stores them on a texture.

On your main camara's each pixel light calculations calculated as follows(**PER LIGHT**)-\>

* Calculates the world position of your pixel.
* Computes the distance between the pixel on your camera and the light position.
* If the distance between your pixel and the light position is higher than light's depth texture's corresponding pixel's depth then its blocked by an object and couldnt reach the light source THUS this pixel receives no light from that light source.

These calculations leads to a HARD shadows,fake soft shadows achieved by tweaking some values and with some blur operations.

There is something worth to be mentioned here.Its the light bounce count.Well there is no light bounce in the above solution right ? Beacause it's considered a single light bounce.

There is no way to achieve multiple bounce without having a huge performance impact.They tried to make an hardware to carry out such a workload but it didnt perform quite efficiently(RTX).

**Baked Lights**

Baked lights are using totally different approach.Baked lights computation model is completely same with the programs such as Blender3D,Maya which the programs used in movie industry.

Instead of rendering scene from another point of view it shoots bunch of RANDOM rays to scene and traces them.(Monte Carlo)

* Shoot random rays to scene
* Trace them store their interaction
* Compute ray's interaction and give final color for the pixel on the scene.
* Avarage the result of many rays and create a final color

If you ask why shooting random rays instaed of fixed rays.Appearently it takes too much bounces to form a desireable image when tracing a single ray to end.However if you shoot bunch of random rays to the scene and shoot more random rays when a ray intersects leads a quicker and better image quality.(This is why you get noisy image at the beginning of your baking and noisy image at first when you render a image on blender3D or maya)

And thats why baked light gives you more soft and warm image where as realtime gives you fast and crispier image.
> 2 votes

---
Tags: unity, lighting
---


# Question
Title: Performing image based lighting in an open world game
I finally have a PBR implementation in an engine that I'm writing for a game I'm developing but I'm stuck on how to use IBL in real situations. Most IBL tutorials use it just to show a single mesh or group of spheres but nothing that I can immediately translate to an in-game application.

So I was wondering, in an open world, how would someone go about implementing image based lighting? Different areas will require different environment maps to be generated and then there's the issue of time of day. I guess for that, you could just use values that you would use in your day and night shader to change the colours being sampled from the environment map but you still have the issue of having a large map.

Update: I've read about light probes and perhaps that's how this is achieved? Create probes around the whole map and then sample and interpolate between the probes that are near the camera. Is this how large open-world games achieve image-based lighting? This way you can have one light probe based on the skybox and multiple light probes spread across the scene and inside rooms.

# Answer
You can use **deferred** rendering.

Deferred rendering pipeline holds several **render textures**,such as one for storing **color** sampled from the view,**normal color** sampled from the view and **depth** and it goes on.

You can create **your custom render textures** by targeting your needs.For example you need a time of day effect on your openworld game,so create a **pixel shader** which only samples texture color of your entire game view and then do your custom calculations to achieve your desired daytime effect.This way you will now have an color data + daytime data stored in **one render target** already.

By using this technique you will partially eliminate the big map effect and clamp your other shader calculations to a screen space complexity where each shader costs fixed amount of calculation power.Beacause deferred rendering removes to **overdraw** of the **overllaped triangles** along the **long distances**.

If you knew about this stuff then..

Try adding several different level of detail to your meshes and textures(I Guess **mipmaps** does this automatically)

If the engine you're using supports deferred rendering then you should check it out,if not then you are to implement it yourself (if the engine lets you)
> 1 votes

---
Tags: lighting, pbr, hdr
---


# Question
Title: Good data structure for storing graph-like map
I'm creating a strategy-based kingdom expansion game, where you start with one city and try to expand as far as possible from there. All the cities fit on a hexagon-grid and are connected by the edges of the hexagons.

Here's a diagram to illustrate what I'm trying to achieve:

Each city must be connected to another city by road, which means that all the cities are connected. At this point, I began to realize that this map is very similar to a graph, with the cities being nodes, and the roads being edges. I've already done some graph theory and implement multiple algorithms. However, when implementing it in a graph format (`Map<Node, List<Edge>>`), I ran into 2 problems:

There is no way to force that each node can only have 3 connections, with each being a multiple of 120º If it was stored in this format, it would be very difficult to render just loop it through for updating. I'm wondering if any of you have any better data structures that can be used for this. Any criticism, suggestions, or advice is welcome.

Thanks!

Ps. I've seen other questions that are somewhat related, however they either do not have an accepted answer or do not solve my problem.

# Answer
Your first problem can be solved by implementing a custom list object or (as you only need three items) a custom tuple object instead of the default List\<\>. This way when you insert tiles you can do a quick sanity check to make sure the tiles are at a 120 degree angle. Something like:

```
public class NeighbourTuple {
    private Node city1, city2, city3;

    public NeighbourTuple(Node city1, Node city2, Node city3) {
        if (!citiesAt120DegreeAngle(city1, city2, city3)) {
            this.city1 = city1;
            this.city2 = city2;
            this.city3 = city3;
        } else {
            thrown new Exception("Cities are not at the correct angle!");
        }
    }

    private bool citiesAt120DegreeAngle(City city1, City city2, City city3) {
         ...
    }

}

```

Your second problem can be solved by using a secondary list (held by some central game manager or something) that holds every single tile in the game so you can update all of them easily.

Alternately you can do what people usually recommend when making a tile based game and just use a coordinate system. That is make a 2D array where each position corresponds to a city then just insert the cities into the array. Then you could get the neighbours using some algorithm. This might sound complicated but if you just shift some of your nodes up and down like so:

it becomes a lot more clear.
> 1 votes

---
Tags: java, architecture, data-structure, data
---


# Question
Title: How can I create light shafts like Journey's in Unity?
I'd like to create cartoon looking sun / light shafts that look very close (or identical) to the ones in very well known and loved games like Journey:

and Ori:

How can I accomplish this?

# Answer
> 4 votes
Use stretched particle to get the effect. In Renderer, choose "Stretched Billboard". Change Length Scale as you need. This can be used in both 3D and 2D scenes.

If you are actually into effect stuffs learn Shader. Mostly vertex and fragment shader. Drawing things is not always a solution. Build size increases due to extra artworks. Talking about overall effects. See Hearthstone's gold card effect.

# Answer
> 8 votes
You mention you're using Unity so you can use their official "Sun Shafts" feature; it's built right into the engine: You can read these Unity Docs to get a good idea of what they're capable of and this YouTube video can walk you through implementing it.

By the way, you'll need to download the Unity Standard Assets in order to use then.

# Answer
> 2 votes
This is what we're doing and the results look somewhat like they do in Ori.

You need a texture for your light shaft that loops vertically. This is from our project (hence the watermark, sorry)

You add it to a particle material, and add the material to a Plane primitive. It should look nice and glowy.

Two more steps. One, you stretch the plane really tall. As tall as need be. And two, you animate the vertical offset of the texture via shaders or scripting. This makes the light look alive. Add tiny dust particles for extra finesse.

You could add a sort of fall-off effect too with shader scripting, but that's a more complicated matter.

# Answer
> 0 votes
When using Unity 2019.3, Universal Renderpipeline (URP) and specifically the 2D renderer, you can use 2D Sprite Lights. You need a texture (like what volvis shows), add a new "light/2D/Sprite Light 2D" to your scene and you can then select that texture as a 'sprite' in the property inspector.

For an official Unity sample, check out "Lost Crypt", look in the scenegraph under "Lights/Forest/Light Group-shafts", see the following image (note: the effect is more subtle originally, intensity was increased in the below image). If you try it, also check out the 'sun spots' which is very similar and also gives a nice effect.

https://assetstore.unity.com/packages/essentials/tutorial-projects/lost-crypt-2d-sample-project-158673

---
Tags: unity, lighting
---


# Question
Title: How to make a simple score system for my game?
I'm making a simple game and I can't seem to impliment a simple score system. As the object moves 10 units forward the score should increase by 10. My issue is that when I turn the object around and move backwards the score decreases.

# Answer
> 2 votes
So just store the maximum seen z value, and then calculate the score with a division, a floor and then a multiplication:

```
#include <algorithm>
#include <cmath>

maxZ = std::max(currentZ, maxZ)
const int score = static_cast<int>(std::floor(maxZ / 10.0f)) * 10;

```

See a graph of this here: https://www.desmos.com/calculator/39z7sfnhas

---
Tags: game-design
---


# Question
Title: How to give depth to a top-down shooter?
I'm working on a **top-down shooter** kind of game, but it **lacks the feeling of depth**.

When you have a **sun**, it's a bit easier, because the **sun can cast shadows**. But it's even harder, when there is **no sun**, **like underground**.

How do you simulate an **ambient occlusion kind of thing**? I think that's what it lacks, but maybe I'm wrong.

*(And this could be also applied to levels with sun as well, further enhancing the feel)*

Example: I have floors and walls, but even if the walls would be a bit thicker, it would lack depth. How could I fix this? I.e. rendering small shadows at floors' edges which are neighbouring walls?

# Answer
> 7 votes
You can't give ambient occlusion to things when there is no light. After all ambient occlusion effectively simulates shadows.

## Add more light sources (and use shadows)

If you add light sources to the game (lava, camp fires, mining lights, glowing mushrooms, etc.) you can go in and start giving things shadows which will make it seem more 3D and add details. Now this might not be possible depending on the theme of the game or technology of the engine.

## Parallax scrolling

This is something that a lot of 2D games do. Basically create a bunch of layers and have the layers closer to you scroll faster than those further away. In a cave with the camera looking down this will be a little harder but should be possible if there is a difference in height or you can put dust in the air which would move more the closer it is to the camera (ie higher).

## Flying NPCs

You could add NPCs which fly, this would put them above the ground and allow for something that can cast shadows onto the ground and move in the air which would give the impression of high ceilings. These NPCs wouldn't have to be big or even intract-able, something as simple as a bat would do the trick.

## Use Scale

Depth in 2D is really just about showing that the area is large in the Z-axis (in and out) so you could create enemies which are very large and require the camera to zoom out. As the camera zooms out it puts into perspective how big you are in relation to the enemy and the room/cave your inside.

## Bake perspective into the Sprites

If take your game and create the assets in 3D then render them out as 2D sprites you can put perspective into each model so that you can easily tell that one thing is closer/further away than something else. This will likely be limited by your art style though, so it may not be applicable to your game.

## Go 3D

If your game doesn't necessarily have to be 2D but still top down you could make the assets in 3d and move around like you would in 2D. This way the sides will change as you get closer to them. If full 3D sounds like a lot of work you could try a hybrid approach with only the static environment or tall objects being in 3D and the rest of the game still using 2D assets. This way movement will give depth and you have an easier time adding shadows to the level.

# Answer
> 5 votes
# Consider using 3/4 top-down perspective.

This is the look that most old-school top-down games used specifically to create depth.

Some examples:

Old Zelda games

Old Final Fantasy Games

Pokémon (even once they transitioned from pure pixel art)

Binding of Isaac (Rebirth) is a good non-RPG example, it involves a lot of shooting:

(the room walls aren't strictly in 3/4 but everything else is; extra depth is achieved by having shadows under everything that is off the ground, with different distance depending on height above ground)

# Answer
> 2 votes
I will describe an approach I used for a similar game some time ago.

# Depth imitation

This only applies if your perspective is not orthogonal and directly from the top.

For each sprite that has depth I have the normal color bitmap and a height bitmap. So for example the wall sprite could look like this

Heightmaps use only the `r` component. Each sprite is drawn to a different buffer. Lights are rendered to the third buffer. Those three buffers get baked into a final image in a fragment shader. Heightmap values are used to offset probing from light texture.

You could store normals and material type per pixel along with the heightmap to allow for more sophisticated lighting models.

One other advantage is that you can use this data for depth-testing. Sometimes sprites cannot be topologically ordered if you use a weird projection.

Creating dynamic shadows for more detailed objects would require raytracing, but in this case it can be implemented just using the heightmap if the objects don't have visible holes. This is probably an overkill though and a simple shadow below the feet should do.

# Lights

I'm not sure how you handle light with walls, because you haven't posted any pictures, so I'll post this part as it may be relevant.

A light is a rectangle with a texture that determines brightness over distance. It should use transparency so the colors are properly mixed when drawn on top of each other, allowing simple additive lighting.

The initial light rectangle is being trimmed by the nearby geometry. For this I refer to https://www.redblobgames.com/articles/visibility/ and https://ncase.me/sight-and-light/. The algorithm is very fast and can handle hundreds of light updates per frame.

The last step is to blur the light to avoid sharp edges on where it was trimmed. For this I use a 2 pass gaussian blur frament shader and temporary buffers.

Overall effect:

# Answer
> 0 votes
I beleive this situation demands basic type of approach.

You can play with your objects' **orientation** in some way that which can give you the illusion of distance considering your light position.

**For Example**

You have ground object and a character.If you lower your ground object along the y-axis and add a basic point light between your character and the ground.This will enable the light to simulate light attenuation on each sprite like its a 3D world.If you lower your ground object even more the light attenuation on the ground sprite will fade which will give you the illusion of distance.

**Consider Adding Normal Map**

You can write a sprite shader which uses a normal,with this way you can achieve even more depth to your objects.

**Maybe Some Volumetric Light(Godrays)**

There are many volumetric light solutions out there,i bet if you implement one of them to your game it will look even more 3D/Volumetricc ??

**Passionate Input**

Considering the dungeon image you given us above,i assume you have a single sprite object which contains the floor texture right ?,consider creating seperate sprite objects for your each tile on the ground(texture),with this now you have the control over the each tile and with some tweak along the y-axis and a well positioned light you can achieve alot,and with normal maps even more.

---
Tags: 2d, art, depth
---


# Question
Title: Why aren't the Physics2D.Raycasts reliably colliding with the 2D Box Collider walls?
I've got this NPC walking around and I'm trying to create a cone to represent their line of sight, including how it would be blocked by buildings, similar to how Nicky Case has implemented it as described here: https://ncase.me/sight-and-light/

My main problem with this, right now, is that it seems like I'm not detecting collisions between my 2D box colliders and Physics2D.Raycast when I would expect to much of the time. The green rays in the image below are NOT colliding (this is fine on the corners, I don't really care, but when the rays are going straight through walls, that's a big problem for me). Red rays are colliding.

**Why aren't the Physics2D.Raycasts reliably colliding with the 2D Box Collider walls?**

I believe everything is in the same z-plane and has the correct collision matrix in place.

!\[ \]image of my NPC and raycasts from them at various points along their path

```
    List<UnityEngine.Vector2> endPoints = new List<UnityEngine.Vector2>();
    GameObject[] corners = GameObject.FindGameObjectsWithTag("verticies");
    //corners MUST BE WORLD-ORIENTED!

    for(int i = 0; i < corners.Length; i++) {
        UnityEngine.Vector2 corner = new UnityEngine.Vector2(corners[i].transform.position.x, corners[i].transform.position.y);
        RaycastHit2D endPoint = Physics2D.Raycast(this.transform.position, corner);
        if(endPoint.collider != null) {
            endPoints.Add(endPoint.point);
            Debug.DrawLine (this.transform.position, endPoint.point, Color.red);
        } else {
            Debug.DrawLine (this.transform.position, corner, Color.green);
        }
    }

```

# Answer
The problem is in line:

```
RaycastHit2D endPoint = Physics2D.Raycast(this.transform.position, corner);

```

In the docs it mentions that the second parameter of Physics2D.Raycast is the direction of the ray and not the target position.

So what you have to do is to subtract target position (corner) from player position and normalize the vector in order to get the direction of the ray.
> 2 votes

---
Tags: unity, collision-detection, raycasting
---


# Question
Title: unity addressables: built game throws InvalidKeyException on android platform while the game runs perfectly in editor
I've incorporated Unity's addressable package into my project, but the issue I have is the addressables do not get loaded when I'm testing on android. The problem persists for all my addressable that I have, but in this special case, I want to load map texture (which is a huge texture in term of size) when the player opens the map, and unload it when he/she close it.

here is the InitializeMap coroutine which makes sure all the core elements for map are available before I continue the flow:

```
 public IEnumerator InitializeMapReferences()
    {
       // find map reference and Initialize it
        _map = GameObject.FindGameObjectWithTag("MapCamera").GetComponent<MapManager>();
        yield return StartCoroutine(_map.Initialize());
    }

```

the map initialize coroutine is as follows:

```
public IEnumerator Initialize()
    {
        // load map texture instance
        var mapTextureInstanceLoad = m_mapTextureInstance.InstantiateAsync();
        yield return mapTextureInstanceLoad;
        m_mapTextureGameobject = mapTextureInstanceLoad.Result;
    }

```

here is my addressableAssetSettings Here is the log from adb's logcat:

```
    E/Unity   (16787): Exception encountered in operation UnityEngine.ResourceManagement.ResourceManager+CompletedOperation`1[UnityEngine.GameObject], result='', status='Failed': Exception of type 'UnityEngine.AddressableAssets.InvalidKeyException' was thrown., Key=035a9d5a8d41d8b42a738cf8b98c7781
E/Unity   (16787): UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption, String, Object)
E/Unity   (16787): UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
E/Unity   (16787): UnityEngine.Logger:LogFormat(LogType, String, Object[])
E/Unity   (16787): UnityEngine.Debug:LogErrorFormat(String, Object[])
E/Unity   (16787): UnityEngine.AddressableAssets.AddressablesImpl:LogException(AsyncOperationHandle, Exception) (at E:\mahmoud baghani\Payiz\Library\PackageCache\com.unity.addressables@1.5.0\Runtime\AddressablesImpl.cs:225)
E/Unity   (16787): UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:set_OperationException(Exception) (at E:\mahmoud baghani\Payiz\Library\PackageCache\com.unity.addressables@1.5.0\Runtime\ResourceManager\AsyncOperations\AsyncOperationBase.cs:286)
E/Unity   (16787): UnityEngine.ResourceManagement.AsyncO
E/Unity   (16787): Exception encountered in operation UnityEngine.AddressableAssets.Initialization.InitializationOperation, result='', status='Succeeded' - Chain<GameObject>: ChainOperation of Type: UnityEngine.GameObject failed because dependent operation failed
E/Unity   (16787): Exception of type 'UnityEngine.AddressableAssets.InvalidKeyException' was thrown., Key=035a9d5a8d41d8b42a738cf8b98c7781
E/Unity   (16787): UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption, String, Object)
E/Unity   (16787): UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
E/Unity   (16787): UnityEngine.Logger:LogFormat(LogType, String, Object[])
E/Unity   (16787): UnityEngine.Debug:LogErrorFormat(String, Object[])
E/Unity   (16787): UnityEngine.AddressableAssets.AddressablesImpl:LogException(AsyncOperationHandle, Exception) (at E:\mahmoud baghani\Payiz\Library\PackageCache\com.unity.addressables@1.5.0\Runtime\AddressablesImpl.cs:225)
E/Unity   (16787): UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:set_OperationException(Exception) (at E:\mahmoud baghani\Payiz\Library\PackageCache\com.unity.addressables@1.5.0\Runtime\Resourc
E/Unity   (16787): Exception encountered in operation UnityEngine.ResourceManagement.ResourceManager+CompletedOperation`1[UnityEngine.GameObject], result='', status='Failed': Exception of type 'UnityEngine.AddressableAssets.InvalidKeyException' was thrown., Key=adc44a52236cf704fab2efdb10c1c9e3
E/Unity   (16787): UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption, String, Object)
E/Unity   (16787): UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
E/Unity   (16787): UnityEngine.Logger:LogFormat(LogType, String, Object[])
E/Unity   (16787): UnityEngine.Debug:LogErrorFormat(String, Object[])
E/Unity   (16787): UnityEngine.AddressableAssets.AddressablesImpl:LogException(AsyncOperationHandle, Exception) (at E:\mahmoud baghani\Payiz\Library\PackageCache\com.unity.addressables@1.5.0\Runtime\AddressablesImpl.cs:225)
E/Unity   (16787): UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationBase`1:set_OperationException(Exception) (at E:\mahmoud baghani\Payiz\Library\PackageCache\com.unity.addressables@1.5.0\Runtime\ResourceManager\AsyncOperations\AsyncOperationBase.cs:286)
E/Unity   (16787): UnityEngine.ResourceManagement.AsyncO
E/Unity   (16787): NullReferenceException: Object reference not set to an instance of an object
E/Unity   (16787):   at MapManager+<Initialize>d__53.MoveNext () [0x00101] in E:\mahmoud baghani\Payiz\Assets\Code\MapManager.cs:125
E/Unity   (16787):   at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00020] in /Users/builduser/buildslave/unity/build/Runtime/Export/Scripting/Coroutines.cs:17
E/Unity   (16787):

```

As you can see, this exceptions results in null references (like the one I've included inside the log I have posted) and make the game unplayable as I am relying on addressables to load/unload some of my core stuff like map textures or big render textures. The problem does not reveal itself in the editor. I've tried cleaning and rebuilding the addressables with no success. How should I go about solving this problem?

# Answer
**UPDATE:**

I managed to fix the problem. Here is how I did it: The build script that is recommended by unity for builds is Packed mode. I had several asset groups, but the asset group that I used for the map textures, lacked a scheme. Adding a "content packing loading" scheme to my map asset group, and then "Build/new build/default build scrip" from addressables groups window solved the problem.
> 6 votes

---
Tags: unity, addressable
---


# Question
Title: How do I pause the game immediately when it starts?
I want my Unity game to start with Time.timeScale = 0f becuase it starts with a main menu that is in the same scene as the game. I tried to put Time.timeScale = 0f in Awake() but that did not work as expected. Putting it in Awake() paused it almost immediately but somehow the update funtions run at least once because some objects moved a little before the game paused. How do I pause it immediately when the game starts?

# Answer
> 1 votes
You can specify the setting on launch using the Time section of the project settings (Edit\>Project Settings\>Time).

https://docs.unity3d.com/Manual/class-TimeManager.html

# Answer
> -1 votes
Note that `Update` function is not affected by timeScale (Though it affects all measured delta times in the Time class, except for fixedDeltaTime). So, you should build some logic to tackle this. On the start of the `Update` body, add `if (Time.timeScale == 0f) return;`. This will effectively prevent `Update` from running while Time.timeScale is 0.

More info on Time.timeScale from the docs.

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


# Question
Title: How to FindGameObjectsWithTag then cast the array of GameObjects to an Array of Interfaces
I have a few GameObjects that implement a common Interface: IsTree. I need to call the function doTreeThing() on each of those IsTrees after getting a reference to each of them via FindGameObjectsWithTag("tree").

This line complains that it cannot implicitly convert from GameObject\[\] to IsTree\[\]

```
IsTree[] trees = GameObject.FindGameObjectsWithTag("tree");

```

So then I tried to leave the GameObject\[\] an iterate over it to convert each individual object inside to an IsTree.

```
GameObject[] trees = GameObject.FindGameObjectsWithTag("tree");
        foreach (GameObject tree in trees) {
            IsTree isTree = (IsTree)tree;
            isTree.doTreeThing();
        }

```

But this complains that it also cannot convert GameObject to IsTree.

Then I got a little desperate and tried to make my IsTree into a GameObject.

```
public class IsTree : GameObject {
    public System.DateTime getAge(){
        return null;
    }
}

```

GameObject is a sealed type. (I don't really know what that means besides that this does not work)

So how do I get this array of GameObjects into an array of SomeInterface?

# Answer
> 1 votes
GameObjects are not their components. They are containers *for* their components. So once you have the GameObject, you have to get the component from it, rather than just assume it *is* it.

```
GameObject[] trees = GameObject.FindGameObjectsWithTag("tree");
foreach (GameObject tree in trees) {
    IsTree isTree = tree.GetComponent<IsTree>();
    isTree.doTreeThing();
}

```

DMGregory’s suggestion should also work:

```
IsTree[] trees = GameObject.FindGameObjectsOfType<IsTree>();

```

---
Tags: unity
---


# Question
Title: How do you remove a tile from a scene in stencyl?
I have added tiles to a scene in stencyl. Now I have changed my mind and I can't seem to remove them! What do I click? I don't see the instructions in here.

# Answer
> 1 votes
If you are using stencyl3, you can directly make changes in tile API, if not then, change your mouse view from tile to pointer in cursor changer tab just above the scene.

**Change to normal mouse type and right-click on particular tiles to remove them , or use the eraser and delete multiple tiles.**

*Not sure if this doesnt work* and *scene attributes and tiles are small in number* you can always point the scene in game flow to NULL location and change flow with new scenes, although it is better to erase rather than adding new scenes each time USE Remove Tile At Row: (number) Col: (number) LayerID: (number) referrence : http://www.stencyl.com/help/viewArticle/47/

# Answer
> 0 votes
It's quite simple: click on the tile / select multiple tiles and hit the delete key. **Job done!**

# Answer
> 0 votes
Usually if I click on a tile and it does not get selected, either I have not chosen the select tool on the right side or I am not in the correct layer or the layer for that tile is locked. Layers are on the bottom right side. Look for a little lock icon next to the layers and unlock them one by one, clicking on your tile as you go, to see if it was part of that layer. Once it becomes clickable, delete it and remember to relock your layer.

---
Tags: stencyl
---


# Question
Title: Unity Tilemap's WorldToCell always return with (0, 0, 0)?
Based on a **Vector2** I want to know the **coordinate** of the tilemap at that position.

But for some reason, it always returns **(0, 0, 0)**. Why?

Why?

```
var position = new Vector2(1.5, -0.5);
for (int i = 0; i < 8; i++)
{
    position += new Vector2(1, 3);
    var coordinates = tilemap.WorldToCell(position);
    Debug.Log(position + ", result: " + coordinates);
}

```

# Answer
> 1 votes
It turns out, that if the **Tilemap's object is disabled**, **WorldToCell will always return (0, 0, 0)**

---
Tags: unity, tilemap
---


# Question
Title: Can't get basic example working with Bullet 3 (haxebullet port)
Example of my code:

```
var collisionConfiguration = new bullet.Bt.DefaultCollisionConfiguration();
var dispatcher = new bullet.Bt.CollisionDispatcher(collisionConfiguration);
var broadphase = new bullet.Bt.DbvtBroadphase();
var solver = new bullet.Bt.SequentialImpulseConstraintSolver();
var dynamicsWorld = new bullet.Bt.DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);

var groundShape = new bullet.Bt.StaticPlaneShape(new bullet.Bt.Vector3(0, 1, 0), 1);
var groundTransform = new bullet.Bt.Transform();
groundTransform.setIdentity();
groundTransform.setOrigin(new bullet.Bt.Vector3(0, -1, 0));
var centerOfMassOffsetTransform = new bullet.Bt.Transform();
centerOfMassOffsetTransform.setIdentity();
var groundMotionState = new bullet.Bt.DefaultMotionState(groundTransform, centerOfMassOffsetTransform);

var groundRigidBodyCI = new bullet.Bt.RigidBodyConstructionInfo(0.01, groundMotionState, cast groundShape, new bullet.Bt.Vector3(0, 0, 0));
var groundRigidBody = new bullet.Bt.RigidBody(groundRigidBodyCI);
dynamicsWorld.addRigidBody(groundRigidBody);

var fallShape = new bullet.Bt.SphereShape(1);
var fallTransform = new bullet.Bt.Transform();
fallTransform.setIdentity();
fallTransform.setOrigin(new bullet.Bt.Vector3(0, 50, 0));
var centerOfMassOffsetFallTransform = new bullet.Bt.Transform();
centerOfMassOffsetFallTransform.setIdentity();
var fallMotionState = new bullet.Bt.DefaultMotionState(fallTransform, centerOfMassOffsetFallTransform);

var fallInertia = new bullet.Bt.Vector3(0, 0, 0);
// fallShape.calculateLocalInertia(1, fallInertia);
var fallRigidBodyCI = new bullet.Bt.RigidBodyConstructionInfo(1, fallMotionState, fallShape, fallInertia);
var fallRigidBody = new bullet.Bt.RigidBody(fallRigidBodyCI);
dynamicsWorld.addRigidBody(fallRigidBody);

for (i in 0...3000) {
    dynamicsWorld.stepSimulation(1 / 60);

    var trans = new bullet.Bt.Transform();
    var m = fallRigidBody.getMotionState();
    m.getWorldTransform(trans);
    trace(trans.getOrigin().y());
    trans.delete();
}

```

It's a haxe port for Bullet3, but I think all components and the concept/logic remains the same as in c++. The idea is that the `fallShape` should bounce against the `groundShape`. But it doesn't. When printing the `trans.getOrigin().y()` it goes it to negative numbers. So what am I doing wrong?

# Answer
> 1 votes
Setting mass for static ground to 0

`var groundRigidBodyCI = new bullet.Bt.RigidBodyConstructionInfo(0.0, groundMotionState, cast groundShape, new bullet.Bt.Vector3(0, 0, 0));`

and enabling `fallShape.calculateLocalInertia(1, fallInertia);`

worked for me!

---
Tags: c++, bullet-physics, haxe
---


# Question
Title: How do idle games handle such large numbers?
Just wondering how games such as Tap titans and Cookie Clicker handle such large numbers.

I am trying to implement an idle game however the largest number format supported by C# is decimal.

I am looking to support up to 10^500; that needs to be floating point

How could I handle this?

P.S. it needs to be cross platform i.e. pc, mac, ios, android and compatible with Unity

# Answer
> 45 votes
If you just want to store massive numbers without complete accuracy, for example if you're going to show 12,567,000,000,000 as 12.567T (trillion), you could just use standard float/decimal values and show the first *x* significant figures, with a suitable suffix like this. When you're in the octillions, do you really need to care about each individual integer increment?

# Answer
> 23 votes
You could use something like BigInteger, which is only available in .net 4.0 if I am not mistaken (not supported by all unity build platforms).

There are some libraries that attempt to bring this functionality without the requirement of .net 4.0 however. For example here.

Alternatively, you can use smaller numbers to represent a larger one, by keeping track of the multiplier. For example:

```
double value = 9;
enum Multiplier {
   Hundred,
   Thousand,
   Million,
   Billion,
   Trillion
}

```

Now, even though you have a value of 9, if you couple it with your multiplier, you can effectively represent that 9 as 9 trillion (Either by putting in "trillion" or writing something that will append the zeros at the end of your value).

# Answer
> 14 votes
For handling big numbers, I'd look at what I think is a good example like Tower of Hero. Top left corner:

<sub>(source: mzstatic.com)</sub>

Without getting into gameplay, the way it handles numbers is relatively simple: You see two buckets of numbers. As you get higher in the tower, and make more "gold", the two buckets simply represent larger numbers.

```
120
120M320K - 120 Million
120B631M - 120 Billion
120T134B - 120 Trillion

```

Once the game passes T it moves into a, b, c... z, aa, ab, ...

```
56aa608z

```

Doing it this way, it still lets you know how much gold you've "earned"... while not bogging the game down in details.

Do you really care about Millions when your number is past Trillions?

Does it keep the number in Int, Big Int, Float, Double, Decimal, ...? Custom Array? When you are handling numbers in such a "fuzzy" way, I don't think it matters...

All that that likely matters are the most significant parts - in this case, the first 6... After that, MAYBE the next 3 or 6 - since earning a few hundred K can roll over into Millions - but there gets a point where earning a few hundred K isn't going to affect you when you hit T... much less aa and beyond.

Your mileage will vary (depending on what you want/need)... Just thought I'd put out my 2c on what I think is a good/simple example.

**Edit:**

Further thoughts on how I would implement the numbering system: I'd have a number with 3 significant parts: XXXX.YYY(...)xZZZ.

```
X is the most significant digits,
Y trailing
Z the multiplier (multiple of 3).

```

So 120.365x1 would be 120k365... 120.365x2 would be 120M365K... etc. Hit the 4 leading (1200.365x2), then just rotate the numbers 1.200365(...)x3. Bam. You have 1B200M.

X.Y would fit easily in a Decimal or Float... with Z sitting next to it as an int/unsigned int.

With a float, you'd be able to keep a sizable - but increasingly unimportant - number of digits after the dot.

Z would the easily represent an easily understandable block of numbers:

```
K = 1
M = 2
B = 3
T = 4
a = 5
...
z = 31 (I may be off on this)
aa = 32
...
az = 58
ba = 59
...
...

```

# Answer
> 12 votes
You'd likely need to write your own class for use in Unity, but it wouldn't be particularly hard.

Internally, it could be a list of integers (such as a `List<int>`), with each element in the list corresponding to a group of 9 digits. Each integer would have a range of 0 to 999 999 999. An integer can support a little over 2 billion, and double that if it's unsigned, but you'll want to have each "digit" overflow at `1 000 000 000`, because you'll also want to be able to easily convert your big-number into a string for display. It's easier to concatenate what are already decimal digits (`return group[i].ToString() + group[i-1].ToString() and so on`) than to figure out how to display the sum of groups that are outside of the range of any regular data type.

So, the first int in your list would represent 1s. The next would be the number of billions. The next, the number of quadrillions, and so on.

Addition and subtraction would work just like pen-and-paper addition and subtraction, where you have to watch for overflow and carry it over to the next "digit", but instead of digits with a range of 0-9, your digits range from 0 to 999 999 999.

# Answer
> 4 votes
Use break\_infinity.cs for unity: https://github.com/Razenpok/BreakInfinity.cs call using BreakInfinity; at the top of your script. If you want to save the variables (BigDouble), convert them to strings (`saveStringVariable = bigDoubleNum.ToString()`) and load the back, do `(bigDoubleNum = BigDouble.Parse(saveStringVariable))`

EDIT: It limits up to 1e(9e15), so yeah, you have a lot of room to work with. For people who are wondering, why? Check out Antimatter Dimensions (NG+3 especially) and https://lngi-incremental.glitch.me/, this one gets even bigger numbers than breakinfinity.cs

# Answer
> 3 votes
And easy way to handle large numbers is simply to have more than one INTEGER value then CARRY any overflow. If you have a 16-Bit INT value (0 to 65535) and you want to have more than that, use two 16-bit INT values in a row. Think of it like having a BYTE value (0 to 255) but only using it up to 99 digits of value. Once it hits 100, then roll it over to the next higher BYTE value for as many digits as you find useful. With today's GHZ computers, even sloppy coding like that is fine.

Of course, there is an alternative which is a bit faster.
If you're adding 18 repeatedly to a number, it is quicker to simply subtract 2 and add 20. 18, 36, 54, 72, 90, 108,... 18 = 20+(-2).
It works in Binary too. (Same decimal values in Binary) 10010, 100100, 110110, 1001000
DEC(18)=BIN(10010)
Except for easier Binary parsing, you need to think of 18 = 16+2
DEC(16 + 2)=BIN(10000 + 00010). If the value was 15, then think of it as adding 16 in binary and subtracting 1 (10000-00001).

In this way, you can keep the number chunks to manageable limits per value.
If you're using the sloppy coding method of limiting a basic 16-bit INT value (0 to 65535) to a 4-digit decimal limit (0 to 9999) then all you have to do is when the value exceeds the 9999 limit, subtract 9999 from it and carry it to the next value chunk (since you are doing basically "adds & subs" with numbers versus a real binary computation).

Ideally, you'd just use SYMBOLIC MATH that you learned in grade school. How does this work. If you have the decimal symbol of 1 and you add it to 1 then you get the decimal symbol of 2. The reason I call this a symbol is that you could use any symbol series with a lookup table of "IF symbol X(1) is added to symbol X(4) THEN output symbol X(5)". Symbol X(1) could be a picture of a cat and symbol X(4) could be the PERCENT sign, but it doesn't matter. You have your symbols, a basic rulebook of what happens then those symbols are combined (sort of like the multiplication tables you memorized as a kid) and what symbol must result as a part of that operation. With using Symbolic Math you can add an infinite number of digits while never really calling the numeric limits of your processor.

One way to do this in easy coding is to have each represented digit you wish to work with as a single unit in a large dimensioned array. If you want to represent 4096 decimal digits (not exceeding 2 digits per unit box), then you allocate 2 sets of 4096 BYTE array locations. Storing the value of 1098874 would utilize the array as (1)(0)(9)(8)(8)(7)(4). If you added the value of 7756 to it, you would convert it into (7)(7)(5)(6) and then add. The result would be (1)(0)(9)(15)(15)(12)(10) which you would then right-to-left subtract shift until all digit boxes were normalized to be the value of (0 to 9). The rightmost (10) value would have 10 subtracted and the resulting value would be zero (0) and that would carry the (1) value to the next-left box of (12) to make it (13) which then would have 10 subtracted to make it into (3). And so on until you had your result of (1)(1)(0)(6)(6)(3)(0) = 1106630.

# Answer
> 2 votes
What you do is have several variables combined, and then you control the addition and overflow between them yourself. You can have any number of digits that way. Combine 10,000 32-bit integers, and you have a number with 32,000 bits, if that is what you need. There is no limit in any programming language. The only limit is what you are able to figure out.

---
Tags: unity, mathematics
---


title: Sprites looks blurried on fullscreen

text:
# Question
Title: Sprites looks blurried on fullscreen
I'm trying to make a pixel art game and my resolution is 384 x 224, but when I change to fullscreen the sprites looks blurry and I don't know how I can disable bilinear filtering.

I tried `SamplerState.PointClamp` on spriteBatch.Begin but it didn't work, I also tried `this.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp` and disable PreferMultiSampling but nothing works. Someone told me that it can be fixed using renderTargets, and I tried that by myself, but that didn't work either.

I used `spriteBatch.GraphicsDevice.SetRenderTarget(renderTarget)` and null at draw method but it still looks blurry. How do I use renderTarget? does it replace my sprite? Does it needs to be window scale or sprite scale? Help please

PD: I'm using FNA, but it seems to monogame. Is a reimplementation of XNA

# Answer
What happens here is that your "screen" the game renders to is still the same resolution, and that is then crudely scaled to your physical screen.

You need to override the screen resize event and set your back buffer size to your actual screen dimensions.

This generally means creating an event handler such as this:

```
private void Window_ClientSizeChanged(object sender, System.EventArgs e)
{
    graphics.PreferredBackBufferWidth = Window.ClientBounds.Width;
    graphics.PreferredBackBufferHeight = Window.ClientBounds.Height;
    graphics.ApplyChanges();
}

```

and then putting `Window.ClientSizeChanged += Window_ClientSizeChanged;` in your Game class's Init method.

It will then instruct the graphics device to render to a bigger "panel" which then gets displayed on your screen.
> 2 votes

---
Tags: c#, xna, rendering, monogame, pixel-art
---


title: Make Render Texture distorted/blurry?

text:
# Question
Title: Make Render Texture distorted/blurry?
I have created a function that clicks images in real time and these images are copied to render texture that is created. I am looking for a way to blur/distort/half-fade-out the render textures. Is there a way to achieve this?

```
 Graphics.Blit(Texture2D, renderTexture);

```

# Answer
> 1 votes
No issues, I have found a shader and added an alpha channel to it. Here is the shader if anyone needs it. It has properties such as blur, distort and alpha channel.

```
Shader "Custom/Distort_Blur"{
    //show values to edit in inspector
    Properties{
        //_MainTex ("Texture", 2D) = "white" {}
        _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
        _Color ("Main Color", Color) = (1,1,1,1)
        _BlurSize("Blur Size", Range(0,0.5)) = 0
        [KeywordEnum(Low, Medium, High)] _Samples ("Sample amount", Float) = 0
        [Toggle(GAUSS)] _Gauss ("Gaussian Blur", float) = 0
        [PowerSlider(3)]_StandardDeviation("Standard Deviation (Gauss only)", Range(0.00, 0.3)) = 0.02
    }

    SubShader{
        // markers that specify that we don't need culling
        // or reading/writing to the depth buffer
        Cull Off
        ZWrite Off
        ZTest Always

         Tags {"RenderType"="Transparent" "Queue"="Transparent"}
         ColorMask 0

         Pass {
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask RGB
        Material {
            Diffuse [_Color]
            Ambient [_Color]
        }
        Lighting On
        SetTexture [_MainTex] {
            Combine texture * primary DOUBLE, texture * primary
            }
        }

        //Vertical Blur
        Pass{
            CGPROGRAM
            //include useful shader functions
            #include "UnityCG.cginc"

            //define vertex and fragment shader
            #pragma vertex vert
            #pragma fragment frag

            #pragma multi_compile _SAMPLES_LOW _SAMPLES_MEDIUM _SAMPLES_HIGH
            #pragma shader_feature GAUSS

            //texture and transforms of the texture
            sampler2D _MainTex;
            float _BlurSize;
            float _StandardDeviation;

            #define PI 3.14159265359
            #define E 2.71828182846

        #if _SAMPLES_LOW
            #define SAMPLES 10
        #elif _SAMPLES_MEDIUM
            #define SAMPLES 30
        #else
            #define SAMPLES 100
        #endif

            //the object data that's put into the vertex shader
            struct appdata{
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            //the data that's used to generate fragments and can be read by the fragment shader
            struct v2f{
                float4 position : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            //the vertex shader
            v2f vert(appdata v){
                v2f o;
                //convert the vertex positions from object space to clip space so they can be rendered
                o.position = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            //the fragment shader
            fixed4 frag(v2f i) : SV_TARGET{
            #if GAUSS
                //failsafe so we can use turn off the blur by setting the deviation to 0
                if(_StandardDeviation == 0)
                return tex2D(_MainTex, i.uv);
            #endif
                //init color variable
                float4 col = 0;
            #if GAUSS
                float sum = 0;
            #else
                float sum = SAMPLES;
            #endif
                //iterate over blur samples
                for(float index = 0; index < SAMPLES; index++){
                    //get the offset of the sample
                    float offset = (index/(SAMPLES-1) - 0.5) * _BlurSize;
                    //get uv coordinate of sample
                    float2 uv = i.uv + float2(0, offset);
                #if !GAUSS
                    //simply add the color if we don't have a gaussian blur (box)
                    col += tex2D(_MainTex, uv);
                #else
                    //calculate the result of the gaussian function
                    float stDevSquared = _StandardDeviation*_StandardDeviation;
                    float gauss = (1 / sqrt(2*PI*stDevSquared)) * pow(E, -((offset*offset)/(2*stDevSquared)));
                    //add result to sum
                    sum += gauss;
                    //multiply color with influence from gaussian function and add it to sum color
                    col += tex2D(_MainTex, uv) * gauss;
                #endif
                }
                //divide the sum of values by the amount of samples
                col = col / sum;
                return col;
            }

            ENDCG
        }

        //Horizontal Blur
        Pass{
            CGPROGRAM
            //include useful shader functions
            #include "UnityCG.cginc"

            #pragma multi_compile _SAMPLES_LOW _SAMPLES_MEDIUM _SAMPLES_HIGH
            #pragma shader_feature GAUSS

            //define vertex and fragment shader
            #pragma vertex vert
            #pragma fragment frag

            //texture and transforms of the texture
            sampler2D _MainTex;
            float _BlurSize;
            float _StandardDeviation;

            #define PI 3.14159265359
            #define E 2.71828182846

        #if _SAMPLES_LOW
            #define SAMPLES 10
        #elif _SAMPLES_MEDIUM
            #define SAMPLES 30
        #else
            #define SAMPLES 100
        #endif

            //the object data that's put into the vertex shader
            struct appdata{
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            //the data that's used to generate fragments and can be read by the fragment shader
            struct v2f{
                float4 position : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            //the vertex shader
            v2f vert(appdata v){
                v2f o;
                //convert the vertex positions from object space to clip space so they can be rendered
                o.position = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            //the fragment shader
            fixed4 frag(v2f i) : SV_TARGET{
            #if GAUSS
                //failsafe so we can use turn off the blur by setting the deviation to 0
                if(_StandardDeviation == 0)
                return tex2D(_MainTex, i.uv);
            #endif
                //calculate aspect ratio
                float invAspect = _ScreenParams.y / _ScreenParams.x;
                //init color variable
                float4 col = 0;
            #if GAUSS
                float sum = 0;
            #else
                float sum = SAMPLES;
            #endif
                //iterate over blur samples
                for(float index = 0; index < SAMPLES; index++){
                    //get the offset of the sample
                    float offset = (index/(SAMPLES-1) - 0.5) * _BlurSize * invAspect;
                    //get uv coordinate of sample
                    float2 uv = i.uv + float2(offset, 0);
                #if !GAUSS
                    //simply add the color if we don't have a gaussian blur (box)
                    col += tex2D(_MainTex, uv);
                #else
                    //calculate the result of the gaussian function
                    float stDevSquared = _StandardDeviation*_StandardDeviation;
                    float gauss = (1 / sqrt(2*PI*stDevSquared)) * pow(E, -((offset*offset)/(2*stDevSquared)));
                    //add result to sum
                    sum += gauss;
                    //multiply color with influence from gaussian function and add it to sum color
                    col += tex2D(_MainTex, uv) * gauss;
                #endif
                }
                //divide the sum of values by the amount of samples
                col = col / sum;
                return col;
            }

            ENDCG
        }
    }
}

```

# Answer
> 1 votes
Take a look at this repository on github named GaussianBlur

simpleBlit.cs uses a simple function to blit and set a texture2D which is desired by you as the source of the blit functionality

```
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    Graphics.Blit(_baseTexture, destination);
}

```

filterTest then creates a material at runtime and sets your custom shader on it (the project includes a shader that may suit your scenario).

```
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    if (_material == null)
    {
        _material = new Material(_shader);
        _material.hideFlags = HideFlags.HideAndDontSave;
    }

    RenderTexture rt1, rt2;

    if (_downSampleMode == DownSampleMode.Half)
    {
        rt1 = RenderTexture.GetTemporary(source.width / 2, source.height / 2);
        rt2 = RenderTexture.GetTemporary(source.width / 2, source.height / 2);
        Graphics.Blit(source, rt1);
    }
    else if (_downSampleMode == DownSampleMode.Quarter)
    {
        rt1 = RenderTexture.GetTemporary(source.width / 4, source.height / 4);
        rt2 = RenderTexture.GetTemporary(source.width / 4, source.height / 4);
        Graphics.Blit(source, rt1, _material, 0);
    }
    else
    {
        rt1 = RenderTexture.GetTemporary(source.width, source.height);
        rt2 = RenderTexture.GetTemporary(source.width, source.height);
        Graphics.Blit(source, rt1);
    }

    for (var i = 0; i < _iteration; i++)
    {
        Graphics.Blit(rt1, rt2, _material, 1);
        Graphics.Blit(rt2, rt1, _material, 2);
    }

    Graphics.Blit(rt1, destination);

    RenderTexture.ReleaseTemporary(rt1);
    RenderTexture.ReleaseTemporary(rt2);
}

```

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


# Question
Title: How to get the address of a nearby square on a chess board?
I'm making a chess game from scratch and I got stuck.

So far I have all my figures placed, I have the positions set, I've already done the collision detection and everything.

When I click the figure that is in position A1 for example, I want to make two green rectangles at positions A2 and A3, and they will be used to make the figure move.

Is there a method for to add 1 to the string "A1" to form the string "A2" or something? Because thats all I really need right now.

Also if there's a more clever way to make the positions please let me know.

As an example, here is how I currently look up my display positions using the A1, A2 etc. location codes:

```
let positions = {
        A1 : [10, 710],B1 : [110, 710],C1 : [210, 710],D1 : [310, 710],E1 : [410, 710],F1 : [510, 710],G1 : [610, 710],H1 : [710, 710],
        A2 : [10, 610],B2 : [110, 610],C2 : [210, 610],D2 : [310, 610],E2 : [410, 610],F2 : [510, 610],G2 : [610, 610],H2 : [710, 610],
        A3 : [10, 510],B3 : [110, 510],C3 : [210, 510],D3 : [310, 510],E3 : [410, 510],F3 : [510, 510],G3 : [610, 510],H3 : [710, 510],
        A4 : [10, 410],B4 : [110, 410],C4 : [210, 410],D4 : [310, 410],E4 : [410, 410],F4 : [510, 410],G4 : [610, 410],H4 : [710, 410],
        A5 : [10, 310],B5 : [110, 310],C5 : [210, 310],D5 : [310, 310],E5 : [410, 310],F5 : [510, 310],G5 : [610, 310],H5 : [710, 310],
        A6 : [10, 210],B6 : [110, 210],C6 : [210, 210],D6 : [310, 210],E6 : [410, 210],F6 : [510, 210],G6 : [610, 210],H6 : [710, 210],
        A7 : [10, 110],B7 : [110, 110],C7 : [210, 110],D7 : [310, 110],E7 : [410, 110],F7 : [510, 110],G7 : [610, 110],H7 : [710, 110],
        A8 : [10, 10], B8 : [110, 10], C8 : [210, 10], D8 : [310, 10], E8 : [410, 10], F8 : [510, 10], G8 : [610, 10], H8 : [710, 10],
    }

```

the \[0\] of the arrays is x and the \[1\] is y, and that's also how I placed the figures.

# Answer
It looks to me like what you really want is a 2D array for managing your board state, which in JavaScript you can accomplish with a nested array.

Your x & y coordinates stay as plain integers internally, so you can use them as indexes into the first/outer and second/inner dimensions of the array. This makes it easy to add and subtract coordinates, or compute other useful spatial patterns, like potential knight moves.

You then convert to "A1" style chess notation for display only, rather than using it as your underlying model. For example, using internal `x, y` indices in the range 0...7:

```
siteToLabel = function(x, y) {
    // 65 is the ASCII code for capital A, and the
    // rest of the alphabet proceeds sequentially.
    return String.fromCharCode(65 + x) + (y + 1).toString();
}

```

You can similarly compute your display coordinates this way, without the lookup table you're using now:

```
siteToDisplayCoords = function(x, y) {
    return [10 + 100 * x, 710 - 100 * y];
}

```

Once you're using integer indices internally, it's trivial to navigate to adjacent sites: just add/subtract one from your x or y index.
> 2 votes

---
Tags: javascript, html5, html-canvas, chess
---


# Question
Title: How are imaginary numbers useful in video game creation?
I learned about imaginary numbers in school and they seemed so impractical, so I asked my teacher what they were used for and he said "video game creation".

I just want to know if this is true and if so how is it used during the creation process.

# Answer
One place that imaginary numbers get a lot of use in video games is in the use of **quaternions to represent orientations and rotations of 3D objects**.

Like complex numbers \\$z = a + b \cdot i\\$, a quaternion consists of both a real part and an imaginary part. But instead of just one imaginary axis, quaternions have three!

\\$q = w + x\cdot i + y \cdot j + z \cdot k\\$

Each of these imaginary units \\$i, j, k\\$ has the property \\$i^2 = j^2 = k^2 = -1\\$, just like the \\$i\\$ you might be used to in complex numbers. But they also have special rules for how they multiply with each other:

$$\begin{matrix} \bf \times & \bf 1 & \bf i & \bf j & \bf k \\ \bf 1 & 1 & i & j & k\\ \bf i & i & -1 & k & -j\\ \bf j & j & -k & -1 & i\\ \bf k & k & j & -i & -1 \end{matrix}$$

Why would we work with such a torturous thing? It turns out this construction has a very useful isomorphism. Similar to how the multiplication of unit complex numbers is equivalent to 2D rotations in geometry, multiplication of unit quaternions is equivalent to 3D rotations!

Specifically, we can express a rotation around the unit vector \\$(x, y, z)\\$ by an angle \\$\theta\\$ as the unit quaternion:

$$q = \cos \frac \theta 2 + \sin \frac \theta 2 \cdot( xi + yj + zk)$$

This is huge. It turns out that manipulating rotations in this form has some major advantages over other ways we might try to represent them in 3D:

$$\begin{matrix} & \textbf{quaternion} & \textbf{rotation matrix} & \textbf{angle triplets}\\ \textbf{storage} & \text{4 floats} & \text{9 floats} & \text{3 floats}\\ \\ \textbf{interpolating} & \text{rotates cleanly} & \text{distorts scale} & \text{tumbles wildly}\\ \\ \textbf{composing} & \begin{array} .\text{16 multiplies} \\ \text{+ 12 adds}\end{array} & \begin{array} .\text{27 multiplies} \\ \text{+ 18 adds}\end{array} & \text{gimbal lock}\\ \\ \textbf{reversing} & \text {3 multiplies} & \text {6 swaps} & \text {trig nightmare} \end{matrix}$$

(For more info on the hazards of using the wrong rotation representation, see this case of compounding error, this example of interpolation, this example of orientation ranges, this issue with wraparounds, and gimbal lock)

So most often, 3D game software will use quaternions, with all their imaginary number guts, as the way to store and track rotations. Especially so in places where rotations need to be stacked on top of one another or blended - like in animating the orientation of all the bones in the hierarchical rig of an animated character.

We'll still usually convert these to matrices when it comes time to render our meshes, since those let us fold in scale, mirroring, skew, and translation into a single representation, but working with quaternions as the intermediate saves us a lot of headaches.

There are of course places where the simpler two-component complex numbers come up too, though they're often more niche. One example is when we need to **solve a high-order polynomial equation**, like in this answer about planning parabolic trajectories to hit an accelerating target \- something we'd need for an AI character to be able to accurately lob grenades in the path of a player. A quirky thing about cubic and higher-order polynomials is sometimes the fastest way to find the real-number solutions is to go via imaginary numbers along the way!

Imaginary numbers are also used in Fast Fourier Transforms for **manipulating audio signals** \- like applying DSP effects to sounds in the game, or speech recognition for voice control, or beat detection for music games, etc.
> 113 votes

# Answer
DMGregory already explained how Quaternions are often used for rotation in 3d space. But Quaternions are already 2 levels of understand above imaginary numbers.

When you want to go one level simpler, then you might find it interesting that you can use Complex numbers for rotation in 2d space.

When you want to rotate a set of 2d points by n degrees, then you need to use this algorithm:

```
xnew = xold * cos(angle) - yold * sin(angle)
ynew = yold * cos(angle) + xold * sin(angle)

```

But a rotation by n degrees can actually be encoded as a complex number. When you treat the coordinates as complex numbers too, then you can do a rotation by simply multiplying the point by the rotation.

```
rotation.real = cos(angle)
rotation.imaginary = sin(angle)
newPoint = oldPoint * rotation

```
> 19 votes

# Answer
Complex numbers have an enormous range of applications, but here we'll stick with those in game development.

Others have already noted how the "vanilla" 2-dimensional complex numbers \\$\Bbb C\\$ describe rotations in 2 dimensions, and the quaternions \\$\Bbb H\\$, a 4-dimensional "hypercomplex" system, describe rotations in 3 dimensions.

Another, less famous application of \\$\Bbb C\\$ is in representing the projections of 3-dimensional objects into a 2-dimensional plane identified with \\$\Bbb C\\$. (For example, Eq. (2) in the above paper notes that complex numbers \\$\alpha,\\,\beta,\\,\gamma\\$ are the projections into the plane of the vertices neighbouring 0, for some cube with a vertex projected to 0, iff \\$\alpha^2+\beta^2+\gamma^2=0\\$.) While such projections are obviously important in 3-dimensional games, which model a 3-dimensional world but ultimately have to display it in 2 dimensions on our devices' screens, I'm not sure whether games make use of this complex-number insight in practice.
> 5 votes

# Answer
Other authors have already discussed how important complex numbers can be for object rotation. Here I am adding a couple of other examples where we can see the use of complex/ imaginary numbers

* A really cool application of complex numbers is **Fractals** which is used in procedural generations in game development. Some of the popular fractals such as Mandlebrot set, Julia Set are basically built of iterations with complex numbers.
* Imaginary numbers are also used in procedural wave generation(using Fast Fourier Transforms). There are other methods of wave generation as well.
> 1 votes

---
Tags: mathematics
---


# Question
Title: Is it possible to detect a collision between a sprite and a UI image in Unity?
I have a stationary sprite with the tag "Player" with a Rigidbody2D (dynamic body type and discrete collision detection) and circle collider 2D.

I also have a moving UI image; also with a Rigidbody2D (dynamic body type and discrete collision detection) and circle collider 2D.

I want to detect when the moving UI Image collides with the sprite, however I'm not getting the print statement inside of the OnCollisionEnter2D() function below whenever I see them collide on the screen.

```
public class MeteorController : MonoBehaviour
{
    float xCoor;
    float yCoor;

    float newXCoor;
    float newYCoor;
    Vector3 newPos;

    float speed = 1.25f;

    // Start is called before the first frame update
    void Start()
    {
        xCoor = transform.localPosition.x;
        yCoor = transform.localPosition.y;

        newXCoor = xCoor * -1;
        newYCoor = yCoor * -1;
        newPos = new Vector3(newXCoor, newYCoor, 0);
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(newPos * Time.deltaTime * speed);
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Player")
        {
            SceneManager.LoadScene("PlanetSpawningTest");
            print("PLAYER");
        }
        else if (coll.gameObject.tag == "Planet")
        {
            print("PLANET");
        }
    }
}

```

# Answer
> 0 votes
I don't recommend doing it this way but just for the sake of your question.

Render the canvas to the world space. To detect the collision between the UI image and Sprite, based off of what you see on the game view rather than scene view.

However, this will displace all the objects in your canvas so it wont be shown on the game window anymore and you will have to re position the UI objects. So for this you can create a separate canvas just for the UI Images that have collision and render that canvas to world space.

# Answer
> 0 votes
There's probably a more elegant solution, but the way I would do this is to attach a script to the UI that needs to be collided with.

This script will calculate the screen-space to world space coordinates of the UI element. Then it will create a box collider with the dimensions of the UI element in world space, making its Z component very long so it overlaps your world. Then you can test collisions between this box collider and your player.

---
Tags: unity, 2d, collision-detection, sprites, rigidbody
---


# Question
Title: Throttling or adding delays between OnTriggerEnter2D calls
I have 2 game objects: `Explosion` and `Enemy`. At any given point, an enemy can collide with multiple `Explosion` game objects at the same exact time. This causes a few issues when I'm trying to destroy the `Enemy` game object.

This is the function that destroys the game object:

```
bool isDead = false;

public void KillCharacter () {
  if (!isDead) {
    isDead = true;
    Debug.Log ("kill enemy...");
  }
}

```

If I use `OnTriggerEnter2D` inside the `Enemy` script, like so:

```
void OnTriggerEnter2D (Collider2D other) {
  if (other.gameObject.tag == "Explosion") {
    KillCharacter();
  }
}

```

In case two explosions spawn on the position of the enemy, `Debug.Log` inside the `KillCharacter` function will fire twice, even though I set the `isDead` bool to true on the first run.

The only solution I found was to call `KillCharacter` from the `Explosion` script, like so:

```
void OnTriggerEnter2D (Collider2D other) {
  if (other.gameObject.tag == "Enemy") {
    other.gameObject.GetComponent<Enemy> ().KillCharacter ();
  }
}

```

Is there a way to run the `OnTriggerEnter2D` from the `Enemy` script, as I originally intended? Or is having the `KillCharacter` handle all the death logic and calling it from outside good enough?

# Answer
> 0 votes
Tested your question and code out as at first I thought it was regarding the 'Is Trigger' option on the collider. However, it's working as intended.

As shown here: https://i.stack.imgur.com/XBWfs.jpg.

> The script is on the Enemy tagged object. Tested with the 'Is Trigger' checked on one and both of the Objects "Enemy", "Explosion".

The only thing I changed from your code was set the `bool isDead` to `public` so that it shows on the inspector.

Most likely problem is that your bool `isDead` is being altered elsewhere.

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


title: How to create GUI or Menu for games?

text:
# Question
Title: How to create GUI or Menu for games?
I've advanced quite well in OpenGL and in graphics. However I lack a lot of experiences.

I have had this question in my mind since the beginning of my venture, how do I create UI or Menu for my game?

I imagine I will create a menu just like creating a 2D game in OpenGL.

# Answer
Option 1: turn back now and find and tweak a ready made solution, there are tons of GUI libraries for every language and framework.

Option 2: roll your own for the sake of rolling your own. Continue reading!

If you intend to have anything more complex than a health/score display, you will want to do it in multiple "layers".

Start with the bottom layer - the lowest level. Create some classes and routines that draw the various graphic elements (drawButton(X, Y, text, state)). Create the next layer - GUI elements themselves, which then use your drawing functions to draw themselves appropriately. Let these both have a common ancestor - a Control class which then handles things like passing mouse clicks through to its child Controls or firing actions when clicked. Create your Window class that also derives from Control, but has its own extra functionality like dragging and closing, if you need windows in your GUI.

Finally create the top layer, the Window/GUI manager. This will then take mouse and key input, keep track of what's in focus and what's where, draw windows in the right order, all the things, so that in the end you will perhaps end up with 2-3 methods that are actively used on game runtime, not counting initialisation and death.

By layering your abstraction like this you can make changes easily exactly where you need them - I made the mistake of having it all flat before and gave up after realising that now that I want buttons to highlight when mouse over I had to change like 30 places which each defined its own button.

As usual I will drop the most recent version of what I have, most of it is readily reusable but it is not really finished and probably MonoGame specific. The higher leve stuff, however, gives you a good idea of the layered principles:

https://github.com/htmlcoderexe/3DGame/tree/master/GUI

Here, I have two lower levels, one that deals with creating all the appropriate geometry that's later handed to the graphics card, and one that requests the creation of said geometry to actually render graphical elements.
> 1 votes

---
Tags: opengl, game-design, gui, menu
---


# Question
Title: Raycast check for Collisions across XZ coords without Y rotations / Unity C#
I'm really new to Unity/C# (I have a bit of experience in GML but far from professional) and I am currently building out my first prototype.

**I originally copied THIS script to get a cube that rotates face-to-face along one of its bottom edges.**

Currently, the state of the game is the cube "rolling" around on a 10x10 grid. The grid currently has a border of walls. I want the cube to shoot a rayCast in the direction the cube is moving towards, check if there is a wall, and decide whether the cube can move in that direction.

This is the way I had it set up previously:

```
Vector3 up = new Vector3(0, 0, 0.5f);
Vector3 right = new Vector3(.5f, 0, 0);
Vector3 down = new Vector3(0, 0, -0.5f);
Vector3 left = new Vector3(-.5f, 0, 0);
Vector3 currentDirection = Vector3.zero;

bool Valid()
{
    Ray myRay = new Ray(transform.position + currentDirection, transform.forward);
    RaycastHit hit;

    Debug.DrawRay(myRay.origin, myRay.direction, Color.red);
    if (Physics.Raycast(myRay, out hit, rayLength))
    {
        if (hit.collider.tag == "Wall")
        {
            return false;
        }
    }
    return true;
}

```

currentDirection is set to when movement keys "WASD" are pressed. I know one issue that I am running into is that transform.forward does not work because the Y-rotation of my cube never changes.

Gif format not supported so heres a link showcasing the problem: Movement & Clipping: https://i.imgur.com/XxlEx1G.gifv

Overall, I was wondering how to get the raycast to shoot in the appropriate direction based on movement.

Sorry if the answer is incredibly easy and I'm just missing it. Thanks for the help, Kalfin

# Answer
> 1 votes
As you mention, `transform.forward` can't be used like that for a rotating cube -- you need to pass one of four different directions:

```
bool DirectionIsFree(Vector3 direction)
{
    Ray ray = new Ray(transform.position, direction);
    Debug.DrawRay(ray.origin, ray.direction, Color.red);
    return !Physics.Raycast(ray, out RaycastHit hit, rayLength) ||
        hit.collider.tag != "Wall";
}

```

The direction would now be absolute as per your world view, not relative to the cube transform. For instance, you'd now call

```
Vector3 desiredDirection = Vector3.zero;
if (Input.GetKeyDown(KeyCode.W))
{
    desiredDirection = up;
}
else if (Input.GetKeyDown(KeyCode.A))
{
    desiredDirection = down;
}

if (desiredDirection != Vector3.zero)
{
    if (DirectionIsFree(desiredDirection))
    {
        MoveInDirection(desiredDirection);
    }
    else
    {
        PlayCannotDoSound();
    }
}

```

Good luck!

---
Tags: unity, c#, collision-detection, raycasting
---


# Question
Title: Back face as pure black with LWRP - Unity
I need to use LWRP in my current project, and I was looking for a way to render the back face as pure black, no lights, no shadows, nothing, just pure black while the normal face would should the textures and the maps.

I know how to do it using the regular shaders, but it is possible to do using the LWRP shaders?

# Answer
Well... I kind of figured a way to do it, I think that this isn't optimized at all, but it works flawlessly.

In the inspector I added a second material to the object and I created a new shader using the "Is Front Face" and the "Branch" node to set the normal faces transparent and the "back faces" to show the color I wanted
> 1 votes

---
Tags: unity, shaders
---


# Question
Title: Unity2D: Child class inheriting onCollisionEnter() methods
I may be an idiot for asking this but I can't seem to solve it myself, I have a GenericWeapon class which has a onCollisionEnter() method which I want applying to all child classes which inherit from it, here is the code:

```
public void onCollisionEnter(Collider target){
    Debug.Log("Collided with player!");
    if(target.GetComponent<Player>()){
        bc2d.enabled = false;
        rb2d.Sleep();
        equip(target.GetComponent<Player>());
    }
}

```

My child class is the following:

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

public class RangedWeapon : GenericWeapon
{
    // Start is called before the first frame update
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
    }
    public void attack(){
    }
}

```

and my in GameObject has the RangedWeapon class as a component however the GameObject does not seem to be picking up any collisions with the player. Could someone point out where I'm going wrong with this?

# Answer
> 1 votes
Use virtual keyword in your GenericWeapon class and make it public.

```
public class GenericWeapon: MonoBehaviour
{
    public **virtual** void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.name.Equals("Cube"))
            print("Parent Hit with cube");
    }
}

```

Then use Override in your Child Class. And Assign Child Class to the gameobject.

```
public class RangedWeapon : CollisionParent
{
    public override void OnCollisionEnter(Collision collision)
    {
        base.OnCollisionEnter(collision);
        print("Child hit with collider");
    }
}

```

This is the way how inheritance work.

Other than this you can use **Delegate**.

---
Tags: unity
---


# Question
Title: When setting Rigidbody.isKinematic true collider won't work anymore
I have a rigged 2D character and used Collider2D/Rigidbody2D/HingeJoint2D to body parts to implement ragdoll.

It works fine, but I needed to run ragdoll physics only when character is dead. So I made a script to easily control ragdoll related features called RagdollController:

```
using UnityEngine;
using UnityEngine.Experimental.U2D.IK;

public class RagdollController : MonoBehaviour {
    [SerializeField] private IKManager2D m_IKManager;
    [SerializeField] private Transform[] m_RagdollTransforms;
    private Rigidbody2D[] m_Rigidbodies;
    private HingeJoint2D[] m_Joints;

    void Setup() {
        m_Rigidbodies = new Rigidbody2D[m_RagdollTransforms.Length];
        m_Joints = new HingeJoint2D[m_RagdollTransforms.Length];

        for (int i = 0; i < m_RagdollTransforms.Length; i++) {
            m_Rigidbodies[i] = m_RagdollTransforms[i].GetComponent<Rigidbody2D>();
            m_Joints[i] = m_RagdollTransforms[i].GetComponent<HingeJoint2D>();
        }
    }

    public void Enable() {
        if (m_Rigidbodies == null) {
            Setup();
        }

        m_IKManager.enabled = false;

        foreach (Rigidbody2D rbody in m_Rigidbodies) {
            rbody.isKinematic = false;
            rbody.gravityScale = 1.0f;
        }

        foreach (HingeJoint2D joint in m_Joints) {
            joint.enabled = true;
        }
    }

    public void Disable() {
        if (m_Rigidbodies == null) {
            Setup();
        }

        m_IKManager.enabled = true;

        foreach (Rigidbody2D rbody in m_Rigidbodies) {
            rbody.isKinematic = true;
            rbody.gravityScale = 0.0f;
        }

        foreach (HingeJoint2D joint in m_Joints) {
            joint.enabled = false;
        }
    }
}

```

Important part is method named Disable:

```
public void Disable() {
    if (m_Rigidbodies == null) {
        Setup();
    }

    m_IKManager.enabled = true;

    foreach (Rigidbody2D rbody in m_Rigidbodies) {
        rbody.isKinematic = true;
        rbody.gravityScale = 0.0f;
    }

    foreach (HingeJoint2D joint in m_Joints) {
        joint.enabled = false;
    }
}

```

Method "Disasble" iterate internal rigidbodies and joints, and set isKinematic to true to prevent physics working, also turn off each hinge joint to prevent any joint physics.

However when I run the game and call Disable(), character just falling through the ground. Note that structure of character looks like this:

```
[Enemy] - Rigidbody2D and Scripts that controlling character
   └ [Mesh] - IKManager2D
       └ [Body] - SpriteRenderer/SpriteSkinEntity/SpriteSkin
       └ [Head] - SpriteRenderer/SpriteSkinEntity/SpriteSkin
       └ [LeftArm] - SpriteRenderer/SpriteSkinEntity/SpriteSkin
       └ [RightArm] - SpriteRenderer/SpriteSkinEntity/SpriteSkin
       └ [Root]
            └ [Stomach] - From here, every child has Collider2D/Rigidbody2D/HingeJoint2D
                 └ [Chest]
                      └ [Head]
                      └ [UpperArmL]
                             └ [LowerArmL]
                      └ [UpperArmR]
                             └ [LowerArmR]
                 └ [UpperLegL]
                        └ [LowerLegL]
                 └ [UpperLegR]
                        └ [LowerLegR]

```

Root of Enemy GameObject doesn't have collider, instead legs have it so by default character can stand on the ground.

However when I set rigidbody.isKinematic = true, colliders inside of legs and all other bones just not working and character just falling through.

I have no idea why disabling rigidbody affects to collider. I can temporarily fixed by adding simple box collider 2d near by character's foot and only activate it when character is still alive(means that deactivate when character is dead).

This way my character not falling through the ground so you might think the problem was solved, but there is huge problem, because unless set isKinematic = false, Raycast2D does not hitanything(It only hit the collider I just added to prevent falling through the ground, totally useless).

I want to keep my colliders in each body parts: head/stomach/chest/arms/legs to precise hit detection(I was used single capsule collider but hit detection was horrible). Am I doing wrong way, or is this glitch?

How do I make my colliders work even Rigidbody2D is turned off? Using Unity 2019.1.0f2 and 2D Animation Package@2.1.0, 2D IK Package@1.1.0.

# Answer
> 1 votes
When you set any object isKinematic, that means you are stopping motion related physics on that object.

For you, Initially set all the rigidbody to isKinematic and Enable them when your player Dead.

---
Tags: unity, 2d, physics, skeletal-animation, rigidbody
---


# Question
Title: Bullet Physics Step Simulation Crash when maxSubSteps is not 0
I am using Bullet physics along with Irrlicht. My program consistently crashes when `maxSubSteps` is not set to zero when calling `stepSimulation`. I believe it has something to do with the time between the stepSimulation calls because when I stopped Irrlicht from drawing the scene, Bullet worked perfectly fine. Here is my `stepSimulation` call:

```
dynamics_world->stepSimulation(frame_delta_time, 0);

```

The segfault crashing does not occur when the `maxSubSteps` is zero. I would like to find a better solution to this as I have read that disabling substepping is experimental. Does anyone know how to fix this?

The parameters I am using when calling bullet's `stepSimulation()` are:

```
const irr::u32 then = device->getTimer()->getTime();
...
const irr::u32 now = device->getTimer()->getTime();
const irr::f32 frame_delta_time = (irr::f32)(now-then)/1000.f;

```

The value of `frame_delta_time` when the program crashes is 0.009. `fixedTimeStep` is the default 1/60.

Values other than 0 I have set `maxSubSteps` to are 1 (the default), 10 and 100.

The gdb stack trace indicates the program is crashing at releasePredivtiveContacts():

```
Program received signal SIGSEGV, Segmentation fault.

#0  0x000055555557463b in btDiscreteDynamicsWorld::releasePredictiveContacts() ()
#1  0x00005555555746fc in btDiscreteDynamicsWorld::createPredictiveContacts(double) ()
#2  0x0000555555573c8f in btDiscreteDynamicsWorld::internalSingleStepSimulation(double) ()
#3  0x0000555555575335 in btDiscreteDynamicsWorld::stepSimulation(double, int, double) ()

```

**Edit:** The full code is on Github: https://github.com/morgenm/PMC-Game/tree/master/src

# Answer
> 0 votes
I fixed this by switching from the latest github code to the release code. When I posted this question I didn't realize I was using the latest github code.

---
Tags: c++, bullet-physics, irrlicht
---