# Question
Title: How to set the color of a game object as of the other?
I am 15 year old Indian student and I am creating my first 2D game in Unity. I have set the color of my player as Random and I have to set the color of my game object as of my player. But the color of the player changes Randomly. So I can't set a specific color to my game object. What I have tried:

public class SetColor : MonoBehaviour {

```
public GameObject player;
public SpriteRenderer sr;
void Start() {
     sr = GetComponent<SpriteRenderer>();
     sr.color = Color.player;
}

```

}

But this not worked. Please reply how to code it correctly?

# Answer
> 1 votes
The class `Color` has a couple predefined colors, but no color named "player". And the player itself doesn't have a color either. The player has a SpriteRenderer which has a color.

So what you need to do is obtain the SpriteRenderer component of the player and then the color from that SpriteRenderer.

```
 mySpriteRenderer = GetComponent<SpriteRenderer>();
 playerSpriteRenderer = player.GetComponent<SpriteRenderer>();
 mySpriteRenderer.color = playerSpriteRenderer.color;

```

Further, if you want the sprite to change color when the player changes color, then you shouldn't put the code into `Start`, you should put it into `Update`. This will update the color every frame. A more elegant and performance-friendly solution would only update the color when it actually changed, but that would make the above code a lot more complicated. So I would recommend to do it this way for now to get started.

---
Tags: unity, c#, sprites, gameobject, color
---


# Question
Title: Creating a 3d level from real world room
I'm doing a project simulating autonomous drone flights inside buildings and I was asked to provide a level which is modeled after one of the floors in our faculty building. I was given a pdf which contains 2d plans made with autocad 2014 and has layers. Unfortunately I don't have any knowledge on how to use those plans or read them. Is there some sort of way to model a real let's say corridor into unreal engine? preferably using photos or something like that but every method is fine as long as it works.

Thanks

# Answer
You have a couple of ways to create 3D models into (or to import into) Unreal:

* A very basic solution is to use the **BSP Brushes** in Unreal Engine, it’s actually a system designed to block out a level, for rapid prototyping, but it might suit your needs very well!
* A little more complex solution is the new **Mesh Tools** plugin that has been introduced in Unreal Engine, to let you model a Mesh in a more detailed way.
* For the most advanced solution you can make 3D models in **Blender**, a free full-fledged 3D Software, and use your PDF with Autocad plans to ensure the right proportions in Blender. After the modeling part is done, simply import it into Unreal Engine with the .FBX File Format. You can add or apply texture (photos) to your model as well.
* If you have or can extract your Autocad Plans and you would like to use them as references, then you can import them into **Blender** or Unreal Engine (with **DataSmith**)

Good luck with your project!
> 0 votes

---
Tags: unreal, level-design, 3d-modeling
---


# Question
Title: How can I expose material parameters in the Unreal level editor?
Is there a way to expose material parameters in Unreal 4 so that they are accessible from the level editor?

As far as I know, I can only do this through the Material Editor, but I wish to do it more fluently.

E.g. to edit a color for the currently selected object in a level:

# Answer
In order to properly display parameters from the Detail Panel in the Unreal Editor, you need to create a Blueprint and set a Dynamic Material Instance with multiple Set (Vector & Scalar) Parameters from the Construction Script. Here’s a step by step guide:

* **Mat-1**: Create a Material and add a **Constant3Vector** for the Base color, and **Constant1Vector** for the other Parameters (let’s say Roughness, Metallic and Specular for this guide).
* **Mat-2**: Left-click on each added **Constant** node (Base Color, Roughness, Metallic and Specular), and convert each one to a **Parameter** with a specific Name (this name will be used in the Blueprint).
* **BP-1**: Create a new Blueprint and add a **Static Mesh** Component to be able to change your Mesh directly from the Editor. The next steps are always done from the **Construction Script**.
* **BP-2**: Add a **Set Static Mesh** node and promote the **New Mesh** pin to a public variable (promote it to a variable and either click on the closed eye inside the *My Blueprint Tab* or check the *Instance Editable* parameter from the *Detail Panel*).
* **BP-3**: Add a **Create Dynamic Material Instance** node, and set the target to the **Static Mesh** component added earlier. You can also add multiple **Dynamic Material Instances** on the same Mesh, if it has multiple materials (each mat should have a different *Element Index*). Promote the **Source Material** pin to a public variable to select the material from the Editor. Promote also the **Return Value** pin to a variable (leave it private).
* **BP-4**: Add a **Set Vector Parameter Value**, but make sure it targets the Material Instance (the sentence *Target is Material Instance Dynamic* should be displayed under the title of the node). Set the **Parameter Name** to the Base Color Parameter name in the material created before.Promote the **Value** pin to a public variable to edit it from the Editor.
* **BP-5**: do the same with **Set Scalar Parameter Value** for Roughness, Metallic and Specular values.

Now you can add the Blueprint in the Editor, choose the right *Static Mesh* and the *Material* (you can have different materials but they should have the same Parameters nodes, so you can theoretically optimize each of them while still reuse the same Blueprint). Beware that the Blueprint will not check the name in the Set Scalar/ Vector Parameter Value, so if it’s not the exact same name, it will not work while not displaying any message whatsoever.

I’ve added two Pics (one for the Blueprint, the other for the Material) and pasted the Blueprint in BlueprintUE website. The last picture is the result.

How it looks in the end:
> 5 votes

---
Tags: unreal-4
---


title: Destroy player GameObject

text:
# Question
Title: Destroy player GameObject
I'm doing a game in Unity and I have a question regarding the destruction of my player object. Currently I'm destroying the player with

```
    public void Die()
{
    isDead = true;
    GetComponent<ScoreController>().SetEndLevelScore();
    GetComponent<ScoreController>().SetTotalScore();
    //ParticleSystem intantiatedParticle = Instantiate(deathParticle, transform.position, transform.rotation) as ParticleSystem;
    Debug.Log("Removing camera parent");
    Camera.main.transform.parent = null;
    sceneLoader.GetComponent<SceneLoad>().StartCoroutine("LoadScoreScreenAfterDelay");
    Debug.Log("Destroying player object");
    Destroy(gameObject);
    Debug.Log("Player object destroyed");
}

```

Now this works when I use it in the editor: the player is destroyed, the main camera shows the scene for a few seconds and then the scene changes to the score scene. As you can see:

However, this is not working as it should when I'm playing the game from the built version. In this case the player GameObject model is still there, as shown here:

This also happens if I use `gameObject.SetActive(false);` instead.

Anybody can tell me why it's not working on the built game but it is on the editor? Thanks!

P.S. : This is the log from the built version after health reaches 0:

```
Health <= 0
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
PlayerController:Update() (at Assets\03-Scripts\PlayerController.cs:333)

(Filename: Assets/03-Scripts/PlayerController.cs Line: 333)

Current level score setted in PlayerPrefs
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
ScoreController:SetEndLevelScore() (at Assets\03-Scripts\ScoreController.cs:131)
PlayerController:Die() (at Assets\03-Scripts\PlayerController.cs:371)
PlayerController:Update() (at Assets\03-Scripts\PlayerController.cs:334)

(Filename: Assets/03-Scripts/ScoreController.cs Line: 131)

Total score setted in PlayerPrefs
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
ScoreController:SetTotalScore() (at Assets\03-Scripts\ScoreController.cs:143)
PlayerController:Die() (at Assets\03-Scripts\PlayerController.cs:372)
PlayerController:Update() (at Assets\03-Scripts\PlayerController.cs:334)

(Filename: Assets/03-Scripts/ScoreController.cs Line: 143)

Removing camera parent
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
PlayerController:Die() (at Assets\03-Scripts\PlayerController.cs:374)
PlayerController:Update() (at Assets\03-Scripts\PlayerController.cs:334)

(Filename: Assets/03-Scripts/PlayerController.cs Line: 374)

Started wait time after death
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
<LoadScoreScreenAfterDelay>d__2:MoveNext() (at Assets\03-Scripts\SceneLoad.cs:16)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr) (at C:\buildslave\unity\build\Runtime\Export\Coroutines.cs:17)
UnityEngine.MonoBehaviour:StartCoroutineManaged(String, Object)
UnityEngine.MonoBehaviour:StartCoroutine(String, Object) (at C:\buildslave\unity\build\Runtime\Export\MonoBehaviour.bindings.cs:79)
UnityEngine.MonoBehaviour:StartCoroutine(String) (at C:\buildslave\unity\build\Runtime\Export\MonoBehaviour.bindings.cs:67)
PlayerController:Die() (at Assets\03-Scripts\PlayerController.cs:376)
PlayerController:Update() (at Assets\03-Scripts\PlayerController.cs:334)

(Filename: Assets/03-Scripts/SceneLoad.cs Line: 16)

Destroying player object
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
PlayerController:Die() (at Assets\03-Scripts\PlayerController.cs:377)
PlayerController:Update() (at Assets\03-Scripts\PlayerController.cs:334)

(Filename: Assets/03-Scripts/PlayerController.cs Line: 377)

Player object destroyed
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
PlayerController:Die() (at Assets\03-Scripts\PlayerController.cs:379)
PlayerController:Update() (at Assets\03-Scripts\PlayerController.cs:334)

(Filename: Assets/03-Scripts/PlayerController.cs Line: 379)

```

And this is the log in the built version:

```
Health <= 0
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
PlayerController:Update() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:333)

(Filename: C:/Users/Hector/GitHub/Shapeshifting Racing 3D/Shapeshifting Racing 3D/Assets/03-Scripts/PlayerController.cs Line: 333)

Current level score setted in PlayerPrefs
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
ScoreController:SetEndLevelScore() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\ScoreController.cs:131)
PlayerController:Die() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:371)
PlayerController:Update() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:334)

(Filename: C:/Users/Hector/GitHub/Shapeshifting Racing 3D/Shapeshifting Racing 3D/Assets/03-Scripts/ScoreController.cs Line: 131)

Total score setted in PlayerPrefs
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
ScoreController:SetTotalScore() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\ScoreController.cs:143)
PlayerController:Die() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:372)
PlayerController:Update() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:334)

(Filename: C:/Users/Hector/GitHub/Shapeshifting Racing 3D/Shapeshifting Racing 3D/Assets/03-Scripts/ScoreController.cs Line: 143)

Removing camera parent
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
PlayerController:Die() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:374)
PlayerController:Update() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:334)

(Filename: C:/Users/Hector/GitHub/Shapeshifting Racing 3D/Shapeshifting Racing 3D/Assets/03-Scripts/PlayerController.cs Line: 374)

Started wait time after death
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
<LoadScoreScreenAfterDelay>d__2:MoveNext() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\SceneLoad.cs:16)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
UnityEngine.MonoBehaviour:StartCoroutineManaged(String, Object)
UnityEngine.MonoBehaviour:StartCoroutine(String, Object)
UnityEngine.MonoBehaviour:StartCoroutine(String)
PlayerController:Die() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:376)
PlayerController:Update() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:334)

(Filename: C:/Users/Hector/GitHub/Shapeshifting Racing 3D/Shapeshifting Racing 3D/Assets/03-Scripts/SceneLoad.cs Line: 16)

Destroying player object
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
PlayerController:Die() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:377)
PlayerController:Update() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:334)

(Filename: C:/Users/Hector/GitHub/Shapeshifting Racing 3D/Shapeshifting Racing 3D/Assets/03-Scripts/PlayerController.cs Line: 377)

Player object destroyed
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
PlayerController:Die() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:379)
PlayerController:Update() (at C:\Users\Hector\GitHub\Shapeshifting Racing 3D\Shapeshifting Racing 3D\Assets\03-Scripts\PlayerController.cs:334)

(Filename: C:/Users/Hector/GitHub/Shapeshifting Racing 3D/Shapeshifting Racing 3D/Assets/03-Scripts/PlayerController.cs Line: 379)

```

# Answer
> 0 votes
In the end the issue was happening when changing the main camera parent to null. I have several cameras attached to the player but only one is active. Before, I was trying to get the camera in use and setting its parent to null before destroying the player GameObject, using `Camera.main.transform.parent = null;`.

Now I set all the cameras parents to null instead and works.

```
for (int i = 0; i < NUMCAMERAS; ++i)
{
    cameras[i].transform.parent = null;
}

```

Also works if I detach the cameras from the player and make them move with a script.

Still I find it a bit strange that `Camera.main.transform.parent = null;` worked in the editor but not on the built version.

---
Tags: unity
---


# Question
Title: Unreal: Get horizontal angle of velocity-looking direction
I want to calculate the relative angle of the speed in relation to the direction of view:

For this I do have the "Get Control Rotation" and the "Get Velocity" of the "Pawn"

I am stuck:

Yeah I stole the original image from: https://forums.unrealengine.com/development-discussion/blueprint-visual-scripting/74282-get-angle-offset-from-forward-vector-need-help

But it explains exactly how the "angle" should be.

Positive values if the velocity is "moving to the right" relative to the looking direction and negative values if "moving left".

**EDIT:**

Using arctan I can compute the negative and positive angle based on the horizontal components of the vector. As I am only interested in horizontal movement and the horizontal "direction" in which my pawn is facing.

As the "forward vector" of the rotator uses a "z" component when looking up/down I figured I could use the "right vector" and rotate it -90 degress (to the left or better say front) around the "z" axis, because it never get's a "z" value.

Unfortunetly if the velocity vector has a "z" value when moving sidewards up or down the hill the angle is +270 instead of -90 and reverse:

# Answer
> 0 votes
The problem with my solution was that whenever I do have a large angle (more than +/- 90 degrees) the calculation was not right so I added the following in between:

---
Tags: vector, unreal, angles, blueprints
---


title: UDK How To Make Class

text:
# Question
Title: UDK How To Make Class
I am currently using UDK because my PC has 32 bit CPU & doesn't support UE4,..

I Just Started Learning UDK From Yours Tutorial...

Que-\> I made 12 Tube light (mesh) in udk with there own point light Bulb,,,So I Want to Destroy Each Tube Light and There Own Blub...

With Plasma and beam Guns...

When The Health Of Tube light goes Specific Range Then It Destroy....But In Kismet How To Code That For Having All TubeLights Have There Own Health....In UE4 If We Write Script In Actor Class And Copy The Object Then It's Does But,In UDK How To Make The Class...For This TubeLight.

# Answer
Unfortunately, in UE3, Kismet was equivalent to Level Blueprints in UE4. There is no way to "create a class" using Kismet.

In UE3, you would either need to copy-paste the visual script for each light. You could possibly use a kismet function and pass in the tube light to eliminate some of the duplication.

To get the equivalent of blueprint classes in UE4, you'd have to utilize UE3's UnrealScript scripting language, and write out the functionality in script.

Specifically (it's been a while so I might be missing something in this process): \- Create a new package to hold your script files. \- Create a new script class and have it inherit from, at least Actor. \- Give it a StaticMeshComponent. (Alternatively, perhaps you could inherit from StaticMeshActor instead of Actor) \- Give it a PointLightComponent. \- Give it a health variable. \- Override TakeDamage() to handle reducing the health and destruction.

This is just a rough overview to get you started. Good luck!
> 0 votes

---
Tags: unreal, udk
---


# Question
Title: Call native code from Unity iOS build error
I created NativeCallProxy.cs in Unity

```
    public class NativeCallProxy: MonoBehaviour
    {
        [DllImport("__Internal")]
        public static extern void iOSUnloadUnityGame();

        public static void UnloadUnityGame()
        {
#if UNITY_IPHONE
            // Now we check that it's actually an iOS device/simulator, not the Unity Player. You only get plugins on the actual device or iOS Simulator.
            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                iOSUnloadUnityGame();
            }
#endif
        }
    }

```

and created two files in Assets/Plugin/iOS **NativeCallProxy.m**

```
#import <Foundation/Foundation.h>
#import "NativeCallProxy.h"

@implementation UnityBridgeAPI
id<UnityBridgeNativeCallsProtocol> api = NULL;
+ (void) registerAPIForNativeCalls:(id<UnityBridgeNativeCallsProtocol>)proxy {
    api = proxy;
}
@end

```

and **NativeCallProxy.h**

```
#ifndef NativeCallProxy_h
#define NativeCallProxy_h

@protocol UnityBridgeNativeCallsProtocol
@required
- (void)unloadUnityGame;
@end

__attribute__((visibility("default")))
@interface UnityBridgeAPI: NSObject
+ (void) registerAPIForNativeCalls:(id<UnityBridgeNativeCallsProtocol>)proxy;
@end

#endif /* NativeCallProxy_h */

```

and when I try to compile exported project I get an error in Xcode.

How can I figure out it?

# Answer
Just as the error says. You haven't defined "iOSUnloadUnityGame" that you have used in your NativeCallProxy class. You do have a method called "unloadUnityGame".
> 1 votes

---
Tags: unity, ios
---


# Question
Title: OpenGL - Multiple Render Target - write only to some targets, discard others
In OpenGL, is it possible to achieve behaviour like this:

```
out float out1
out vec4 out2;

//.....

out1 = /* write some value */
out2 = /* discard */

```

My output targets are R32F and RGBA.

# Answer
> 1 votes
From the official documentation (https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.30.pdf ; page 114-115 of 199) :-

> The discard keyword is only allowed within fragment shaders. It can be used within a fragment shader to abandon the operation on the current fragment. This keyword causes the fragment to be discarded and no updates to **any** buffers will occur ...

Thus, I believe it is impossible. (if anyone know the way, please add another answer)
You may workaround with e.g. :-

```
out1 = /* write some value */
out2 = vec4(0,0,0,0);   // if your blend mode is "add" or "transparent"

```

If your blend mode is currently `oblique`, just change it to `transparent` with `alpha=1`.

## **Discussion**

In the older version of OpenGl, the `ALPHA_TEST` checks only the first target and apply the same result to all the target, so this limitation have existed for a long time.

You can set blend mode for each target *individually* using glBlendFunci.

## **Reference**

---
Tags: opengl, glsl
---


title: Infinite world floor grid shader

text:
# Question
Title: Infinite world floor grid shader
I am trying to render an infinite world floor grid, similar to this question.

My project is using SceneKit with Metal Shading Language but the concepts are no doubt similar between GLSL/HLSL.

Here is an example project where I attempt to render a plane as a full screen quad with the grid lines drawn using a fragment shader.

Full shader code can be found here.

---

## Grid Rendering

A simple vertex shader sets the position and grid coordinate for the plane:

```
f.position = scn_node.modelViewProjectionTransform * float4(v.position, 1.0);
f.ij = v.position.xy;

```

The fragment shader then determines which color to render the grid or floor:

```
fragment half4 floor_fragment(FragmentIn f [[stage_in]]) {

    float2 fractional  = abs(fract(f.ij; + 0.5));
    float2 partial = fwidth(f.ij;);

    float2 point = smoothstep(-partial, partial, fractional);

    float saturation = 1.0 - saturate(point.x * point.y);

    return half4(mix(backgroundColor.rgb, gridColor.rgb, saturation), 1.0);
}

```

I then remove any MVP transforms and simply set the vertex position as is in clip space to fill the screen. This does have the intended effect of filling the screen but mangles the grid lines.

```
//inside floor_vertex()
f.position = float4(v.position, 1.0);
f.coordinate = v.position.xy;

```

---

## Ray Casting

As suggested in the comments, the fragment position should be projected into world space and intersected with the floor plane to find a new vector on the plane. I have an `intersect(plane:ray)` method returns a hit with a distance and a point on the plane or otherwise false if the ray is orthogonal to the plane.

It is my understanding that by multiplying the position in clip space with the `inverseViewProjectionTransform` the result will be in camera space. The plane is also converted to camera space with the `modelViewTransform` and I then test my ray against this which appears to work but with incorrect results.

```
fragment half4 floor_fragment(Fragment f [[stage_in]], constant SCNSceneBuffer& scn_frame [[buffer(0)]], constant NodeBuffer& scn_node [[buffer(1)]]) {

    //f.ij is in the vertex position in clip space (-1, -1) to (1, 1)

    //convert position into camera space
    float4 position = (scn_frame.inverseViewProjectionTransform * float4(f.ij.x, f.ij.y, 0.0, 1.0));

    //create ray from camera with direction
    Ray ray = Ray { .origin = float3(0.0), .direction = normalize(position.xyz) };

    //convert floor plane from world space to camera space
    float3 worldFloor = (scn_node.modelViewTransform * float4(float3(0.0, -5.0, 0.0), 1.0)).xyz;

    //hit test ray against floor plane
    Plane plane = Plane { .position = worldFloor, .normal = float3(0.0, 1.0, 0.0) };

    RayHitTest hitTest = intersect(plane, ray);

    if(!hitTest.hit) {

        return f.backgroundColor;
    }

    //grab xz values to determine floor fragment color
    float2 uv = hitTest.vector.xz;

    float2 fractional  = abs(fract(uv + 0.5));
    float2 partial = fwidth(uv);

    float2 point = smoothstep(-partial, partial, fractional);

    float saturation = 1.0 - saturate(point.x * point.y);

    return half4(mix(f.backgroundColor.rgb, f.gridColor.rgb, saturation), 1.0);
}

```

This video shows the final results where you can see that the grid is not correctly aligned with the world axis. The floor plane is positioned at `0.0, -5.0, 0.0` and the rectangle at `0.0, -4.5, 0.0` which should be aligned with each other but this is not the case. It looks to me that the perspective is off as the grid seems much larger than is should be.

Can anyone please point out the obvious mistake(s) I am making?

# Answer
> 1 votes
I used world space shader to draw Infinite grid

sorry I haven't enough time to convert this to glsl but I hope it will help you

first you should draw a square in shader:

then you can use fraction to repeat the square pattern to make a grid

it seems good but it isn't infinite!

to make it infinite you can use world space shader

nice!

you can make your own grid

here's simple glsl shader: you can tweak it in shadertoy

```
float size = 5.;

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord/iResolution.xy;
    vec2 tiledUV = fract(uv*size);
    vec2 square = abs(tiledUV*2.-1.);
    vec2 sharpSquare = step(0.8,square);
    float result = sharpSquare.x+sharpSquare.y;

    fragColor = vec4(1.0)*result;
}

```

---
Tags: shaders, fragment-shader, vertex-shader
---


# Question
Title: Sprites draw-order sorting for top-down 2D game with floors and bridges
I am working on custom 2D engine for a game.
I am having trouble figuring out a working system for sprite drawing-order sorting for this specific game.

**Game description:**

* 2D
* Top-down perspective
* Multiple floors
* Bridges

More details for clarity:

* Characters (Player characters, enemies, NPCs) can be positioned and move around any Floor and move between Floors.
* Objects (crates etc.) can be positioned on any Floor. (Not on Stairs.)
* Floors are traversed using Staircases.
Staircase is a "ramp" connecting 2 Floors.
Staircase can connect 2 Floors that can be any number of Floors apart.
* Characters and Objects cannot be positioned / move "behind" back-facing walls and behind Objects.
* Characters can be positioned / move behind other Characters and pass through each other.
* Characters and Objects can be positioned / move both on and under a Bridge.

Entities that need their sprites sorted are Characters, Objects, Bridges.
Visuals (tiles) that make rest of the game level, are rendered first (under everything else) in one pass, and don't need any kind of sorting.

**What I tried so far:**

**V0. Sorting by Y**
Obviously doesn't work because it can't solve verticality (Floors).

**V1. Sorting Characters into lists by Character current Floor, than sort each list by Character current Y**
Than drawing eg.
Floor 0 sorted Characters list
Floor 1 Bridges
Floor 1 sorted Characters list
...

Problem with this is approach, that Floor has to have a hard edge.
Each Character is at one point on one and only one Floor.
When two Characters are close enough together on Y axis to overlap, and each one is on a different Floor, this happens:

**V2. Sorting Characters and Bridges using "Painter's Algorithm" (average distance to camera of 3D rectangle vertices)**
Even though the graphic engine is 2D, I defined every Character and Bridge as 3D positioned rectangle, and defined virtual camera (view point) with 3D position.
Than calculated average 3D position of every entity and it's distance to camera. Than sorted by the distance.

Problem with this is approach is one of problems of Painter's Algorithm: the distance to camera is calculated from position of center point of the rectangle.
The bigger the rectangle, the more imprecise the calculation.
If the rectangle is big enough, it will start wrongly overlapping surrounding rectangles.
Characters on different heights (elevations) are often sorted wrongly.
Also if the Bridge is wide enough on Y axis, it will be wrongly sorted between Characters on and under the Bridge.

**V3. I can make the game fully 3D**
and use Z-Buffer, that is made to solve the problems mentioned above.
But before I make that leap, I would like to be sure I explored all other (2D) possibilities.

---

I searched the internet high nad low for any tutorial or article on this, and surprisingly didn't find a single one that would fit my case.

I will be very grateful for any advice.

# Answer
> -1 votes
Do you have a tile layer system? You could set it up where each layer is drawn in order. The transitions could be handled by a rectangle trigger and temporarily drawing a character/movable object twice, one for the exiting layer and once for the entering layer. Since they are being drawn on top of each other it should be invisible.

```
class Map {
    //...
    std::vector<Layer> layers;
};

class Layer {
    //...
    std::vector<Tile> tiles;
    Map* map;
};

class Tile {
    //...
    Layer* layer;
    Map* map;
};

class Entity {
    //...
    Layer* layer;
    Map* map;
    Tile* tile;
};

```

---
Tags: 2d, sprites, sorting
---


# Question
Title: Can't join to room through Unity's Matchmaking system on the Internet
It works perfectly when I try to connect **locally from my editor to my running build**.

But after I start the **server on my Android**, and try to connect to it **from my editor**, it **time outs**:

As you can see, it **finds the match**, and then **tries to join**, but it can't.

If I try to do it from a **build**, the log says the following:

```
Log: cannot connect after {10} attempt address {::ffff:127.0.0.1:7777}
ClientDisconnected due to error: Timeout

```

Why does it tries **localhost**, when I obviously **use the Matchmaking system**?

When I tried it on 2 Android devices, the same happened.

Ps.: I know that it's going to be depracated, I just want to use it during a short term gift.

Thanks in advance!

Starting Matchmaker in a **Start:**

```
networkManager.StartMatchMaker();
networkManager.matchMaker.baseUri = new System.Uri("https://eu1-mm.unet.unity3d.com");

```

When the **MatchScene ("Battle") is loaded:**

```
if (this.isHost)
{
    networkManager.StartHost();
}
else
{
    networkManager.StartClient();
}

```

And the **Play button's handle**: (still same component)

```
public void Play()
{
    networkManager.matchMaker.ListMatches(0, 1, string.Empty, true, 0, 0, OnMatchList);
}

void OnMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> matches)
{
    if (matches.Count == 0)
    {
        networkManager.matchMaker.CreateMatch("match", 2, true, string.Empty, string.Empty, string.Empty, 0, 0, OnMatchCreate);
    }
    else
    {
        networkManager.matchMaker.JoinMatch(matches[0].networkId, string.Empty, string.Empty, string.Empty, 0, 0, OnMatchJoined);
    }
}

void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
{
    this.isHost = true;
    this.networkId = matchInfo.networkId;
    SceneManager.LoadScene("Battle");
}

void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo)
{
    SceneManager.LoadScene("Battle");
}

```

# Answer
> 0 votes
Since I couldn't fix it under a day, I gave up and switched to **PUN**, which took me only like 5 hours.

And it was instantly working.

I used these sites:

https://blog.photonengine.com/dev-story-tanks-multiplayer/

https://doc.photonengine.com/en-us/pun/current/getting-started/pun-intro

---
Tags: unity, android, unity-networking, pc
---


# Question
Title: How to update different constant buffers for different vertices in vertex buffer?
Lets say I have vertices and indices for Box and Sphere and I put them into one vertex buffer. But if I want to use different constant buffers for each of the figures, how would I do that?

As I understand I need to somehow say in VertexShader "Do those calculations for those vertices, and these calculations for these". But to my understanding, shaders don't work that way? Also I can't have two input layouts for each figure (it doesn't even make sense). I've heard you are not suppose to do it that way these days, better to have different buffers for each figure, but still I want to try it.

# Answer
So, it's dead simple. object-\>SetConstBuffer(put here first thing); object-\>UpdateConstantBuffer(); object-\>DrawFirstOne();

object-\>SetConstBuffer(here goes second thing); object-\>UpdateConstantBuffer(exactly the same one, we overwriting); object-\>DrawSecondOne();

Update is where your Map/Unmap/updateSubresource happen. Nothing needs to be changed in vertex shader. The order is functions of important, you can end up reading from the same thing second time.
> 1 votes

---
Tags: c++, rendering, directx
---


# Question
Title: Move camera closer (Zoom In-Out) to object that is being followed
I have implemented a main camera that follows and orbits around an object (player). Now I would like to implement a Zoom In-Out mechanic. This functionality would allows the camera to approach the object that is being followed (lookAt()). Zooming in and out would be done by using the mouse scroll wheel. This is my code.

```
    public Transform PlayerTransform;
    private UnityEngine.Vector3 _cameraOffset;
    [Range(0.01f, 1.0f)]
    public float smoothFactor = 0.5f;

    void Start()
        {
            _cameraOffset = transform.position - PlayerTransform.position;
        }
    void Update()
        {
            UnityEngine.Vector3 newPos = PlayerTransform.position + _cameraOffset;
                    transform.position = UnityEngine.Vector3.Slerp(transform.position, newPos, smoothFactor);

            if (Input.GetMouseButton(0))
                        {
                            UnityEngine.Quaternion camTurnAngle =
                                Quaternion.AngleAxis(Input.GetAxis("Mouse X") * rotSpeed, Vector3.up);
                            _cameraOffset = camTurnAngle * _cameraOffset;
                            transform.LookAt(PlayerTransform);
                        }

        }

```

The code should also limit how close and far away from the player can the camera move. Thank you for considering my question.

# Answer
You can use Input.mouseScrollDelta to get which direction the mouse wheel is currently being scrolled and use that to offset the camerOffset Z value.

```
public Transform PlayerTransform;
private UnityEngine.Vector3 _cameraOffset;
[Range(0.01f, 1.0f)]
public float smoothFactor = 0.5f;
public float minZoomDistance = 0;
public float maxZoomDistance = 2f;
void Start()
{
    _cameraOffset = transform.position - PlayerTransform.position;
}
void Update()
{
    UnityEngine.Vector3 newPos = PlayerTransform.position + _cameraOffset;
    transform.position = UnityEngine.Vector3.Slerp(transform.position, newPos, smoothFactor);

    //offset the cameras forward Axis (Z) by whatever the current scroll wheel delta is, you can add a smoothing factor here to multiply by
    _cameraOffset.z += Input.mouseScrollDelta.y;

    //clamp the z value offset between min and max
    _cameraOffset.z = Mathf.Clamp(_cameraOffset.z, minZoomDistance, maxZoomDistance);
    if (Input.GetMouseButton(0))
    {
        UnityEngine.Quaternion camTurnAngle =
            Quaternion.AngleAxis(Input.GetAxis("Mouse X") * rotSpeed, Vector3.up);
        _cameraOffset = camTurnAngle * _cameraOffset;
        transform.LookAt(PlayerTransform);
    }

}

```

This is untested code but it should work!
> 1 votes

---
Tags: unity, c#, camera, transformation
---


# Question
Title: Why are these unity UI buttons only responding to the top half?
I'm instantiating UI objects with buttons on them into a scrollrect. For some reason, all of the buttons will ignore their bottom half with the exception of the last prefab instantiated. Below is a gif to show the problem. I have it set to turn red when the button is highlighted. When the mouse isn't in a highlight position clicking will do nothing so I know it's not just a highlighting issue.

Here is the code that I'm using to instantiate the scene.

```
    //Instantiate the parent UI
    MyLoadGUI = (GameObject)Instantiate(LoadGUI);

    //Get the RectTransform of the scroll rect so I can add each level to the right thing.
    RectTransform[] rt = MyLoadGUI.GetComponentsInChildren<RectTransform>();
    RectTransform myRt = new RectTransform();
    for (int i = 0; i < rt.Length; i++)
    {
        if (rt[i].name == "Scroll Panel")
        {
            myRt = rt[i];
            break;
        }

    }
    //We're going to make 6 fake levels
    int levelCount = 6;
    int levelSize = 88; //How tall the levels are

    int height = Mathf.Max(levelSize * levelCount, 252);

    myRt.sizeDelta = new Vector2(myRt.sizeDelta.x, height);
    myRt.anchoredPosition = new Vector2(myRt.anchoredPosition.x, -height);

    for (int i = 0; i < levelCount; i++)
    {
        GameObject lsl = (GameObject)Instantiate(LoadSingleGUI);
        RectTransform rect = lsl.GetComponent<RectTransform>();
        rect.SetParent(myRt, false);
        rect.anchoredPosition = new Vector2(0, -37 - (i * levelSize));

        //Fill in fake details.  Doesn't run anything related to the button.
        lsl.GetComponent<LoadLevelBar>().BuildRandom();
    }

```

So, nothing that should be affecting the button that I can see. I thought that the button was getting resized, but when checking in the scene the button is stretched all the way across the prefab. Any ideas why the button isn't working properly?

# Answer
> 1 votes
I have encountered this problem before. Its related to the anchor points. Like Sata suggested you should use a Layout Group when instantiating UI elements like this.

# Answer
> 0 votes
Been a long time since this one was asked. I just had a similar issue crop up and it was because an invisible portion of another text UI element was covering part of my button.

---
Tags: unity, gui
---


# Question
Title: 9-Slicing Sprite for UI Image still stretches corners
I am currently trying to slice a sprite for an Image component. It's a rectangle with rounded corners on the left side. Those rounded corners are supposed to stay the same even when the image is stretched while the rest of the rectangle is supposed to stretch dynamically horizontally and vertically. I will never stretch the image vertically, which is why that point can be ignored.

I setup 9-Slicing for the sprite like the documentation suggests, but the corners on the left side are still getting stretched. What am I doing wrong?

# Answer
It could be that you are trying to push the image smaller than the original. Zone D, E and F are used for resizing the image, but if you push it smaller than your buffer zones can provide, it has to resize the corners.

Your image looks like 512px height in the original and you try to display it at a new height of 100px
> 3 votes

---
Tags: sprites
---


title: Collision quadrant in godot appears

text:
# Question
Title: Collision quadrant in godot appears
I am learning to use godot following this video: Collisions with Autotiles

The problem is that when I create the collision for the cliffs using tilemap, it appears me a blue quadrant indicating the collision. What should I do for what these "quadrants" do not appear?

As you can see, all the cliffs are blue for indicate me the collision, but I have no idea about what to do for hide them.

# Answer
> 2 votes
This is the "Visible collision shapes" option from the Debug menu:

---
Tags: collision-detection, tilemap, godot
---


# Question
Title: Unity C# Scale 2d Object with Mouse Drag
So I have had a few attempts and posts about this but have still not been successful. The behaviour I want is this:

There is a circle (sphere) I want the player to be able to click and drag it outwards to make it larger, or drag inwards to make it smaller. Previously, I was scaling the object based on the inital dragging point, but this was giving me no way to scale the shape back down.. only make it larger. I figured I need to calculate whether we should be scaling up or down, based on the direction of the drag in relation to the centre of the shape. To figure this out, we need to check the position of the mouse, while dragging, compare it to the previous frame and decide whether we are closer or further away from the centre. If we are closer, then we are dragging inwards and we should scale the object down (make it smaller). Id we are further away, then we are moving outwards and should be scaling up (make it larger). I'm having a couple of problems. I don't seem to be able to get the circle to scale down at all. The detection for the direction of the drag seems to be flawed as it seems my bool for isDraggingOut is basically always true, I can't understand why. The other problem I'm having is that every time I click the circle, it snaps back to it's initial size.

I am trying to take the following steps in my code:

On Mouse drag: check where current position of the mouse is

check distance of previous position of the mouse

check distance of current position

determine whether player is dragging in or out. If current distance is more than the distance in the previous frame, we are dragging out

If this is true, then calculate the distance between the drag start point and the current position of the mouse, and scale accordingly

If the distance is less than the previous frame then we are dragging in

then calculate the distance between the drag start point and the current position of the mouse, and scale accordingly (here, i have tried to apply an inverse calculation of the upscaling calculation - this could be wrong)

The last thing I do in my code is make the current position equal to previousPosition variable, so that in the next frame it can be compared.

Any help would be appreciated as I am really struggling with this one.

---

```
using System.Collections.Generic;

using UnityEngine;

public class NewScalingScript : MonoBehaviour

{

public Vector3 temp;
public Vector3 dragStartingPoint;
public Vector3 centreOfShape;
public Vector3 currentDragPosition;
public Vector3 previousDragPosition;
public bool isDraggingOut;
public float previousDistance;
public float currentDistance;
public float amountDragged;
public float clampedAmountDragged;
private void Awake()

{

    centreOfShape = transform.position;

}

private void OnMouseDown()

{

    dragStartingPoint = Input.mousePosition;

}

private void OnMouseDrag()

{

//check where current position is

    currentDragPosition = (Input.mousePosition);

//check distance of previous position

    previousDistance = Vector3.Distance(previousDragPosition, centreOfShape);

//check distance of current position

    currentDistance = Vector3.Distance(currentDragPosition, centreOfShape);

//determine whether player is dragging in or out. If current distance is

// more than the distance in the previous frame, we are dragging out

if (currentDistance > previousDistance)

{

        isDraggingOut = true;

}

else

{

        isDraggingOut = false;

}

if (isDraggingOut == true)

{

       amountDragged = Vector3.Distance(currentDragPosition, dragStartingPoint);

// set minimum and maximum drag amount and store in clampedAmountDragged variable

        clampedAmountDragged = Mathf.Clamp(amountDragged, 100f, 300f);

// set amountDragged to clampedAmount to apply minimum and maximum

        amountDragged = clampedAmountDragged;

        temp = transform.localScale;

        temp.x = amountDragged / 100;

        temp.y = amountDragged / 100;

//make scale of object equal to temp variable

        transform.localScale = temp;

}

// else we are dragging in

else if (isDraggingOut == false)

{

        amountDragged = Vector3.Distance(currentDragPosition, dragStartingPoint);

// set minimum and maximum drag amount and store in clampedAmountDragged variable

        clampedAmountDragged = Mathf.Clamp(amountDragged, 100f, 300f);

// set amountDragged to clampedAmount to apply minimum and maximum

        amountDragged = clampedAmountDragged;

        amountDragged = amountDragged - 300;

        amountDragged = Mathf.Abs(amountDragged);

        temp = transform.localScale;

        temp.x = amountDragged / 100;

        temp.y = amountDragged / 100;

 //make scale of object equal to temp variable

        transform.localScale = temp;

}

   currentDragPosition = previousDragPosition;

}

}

```

# Answer
I think I can explain your problem.

When you let go of the mouse, that spot basically becomes "point a", and when you go back to the circle and click on it, it creates "point b". As the distance between those two points has a negative value (think of an x/y graph), the program is automatically shrinking the ball back down. It's less like the ball is snapping back to normal size and more like it's shrinking down in practically a millisecond.

At least, that's what I can gleam from this. I could very well be wrong about it.

EDIT: Actually, perhaps it's more like the program is setting "point b" as the new "point a", and since the distance between them is relatively small, that's what's making the ball shrink, because the distance between those two points is what dictates the size of the ball.
> 0 votes

# Answer
You are defining currentDragPosition and dragStartingPoint properly, but you have neglected to actually define previousDragPosition other than declaring it as a variable. At the very least in OnMouseDown() after you put

```
dragStartingPoint = Input.mousePosition;

```

add the line

```
previousDragPosition = dragStartingPoint;

```

to give previousDragPosition some sort of meaningful value.
> 0 votes

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


# Question
Title: Why do I have additional glBindBuffer() calls?
I have a OpenGL2/OpenGLES2 application and it among others renders a sphere using the following pseudocode:

1. Update vertices data on CPU
2. call glBufferSubData(GL\_ARRAY\_BUFFER, ...) to update them on GPU size
3. in a loop calls glDrawElements

Now I'm checking it under RenderDoc and see additional calls to glBindBuffer between glDrawElements:

1. glBindBuffer(GL\_ARRAY\_BUFFER, 0)
2. glBindBuffer(GL\_ARRAY\_BUFFER, my\_vbo\_id)
3. glDrawElements

Why I see those additional calls? Why GL driver (or GL library?) inserts them?

# Answer
> 1 votes
Actually, those call are inserted by RenderDoc. Here the response from RenderDoc creator:

> GLES has a legacy feature which allows you to specify vertex attribute pointers in CPU memory without using a vertex buffer at all
>
> (same with indices without an index buffer)
>
> renderdoc emulates that by checking when the drawcall happens if any such pointers exist, and quickly stuffing the data into a buffer, binding that buffer, and then restoring the state after the draw. That way most of the code only has to deal with vertex buffer handling from this century and not worry about CPU pointers
>
> most of the heavy lifting is skipped if you use a VAO because CPU pointers can't be used with a VAO, but if you're not using one then it has to do the slower path of checking each attribute. In your case you're not using a VAO so it goes down the slow path, but then each attribute is using a vertex buffer so it never \> actually has to do any emulation
>
> it still ends up doing a couple of redundant bind calls when it's "cleaning up" \> even if there's nothing to clean up

---
Tags: opengl, opengl-es, opengl-es2
---


# Question
Title: How to set up Easy Mobile Pro to work with assembly defintions?
I have a project with EMP imported, and now I would like to use assembly definitions to clean up my project a little bit. Everything works fine in the editor, but when I hit Build player script in my Addressables or just trying to Build I get a bunch of nasty error messages. When I switch to VS obviously there are no issues in the code editor. I have asmdef files in:

1. Core folder in my Scripts folder, these are scripts created by myself. -asmdef
2. EMP-Editor folder -\> this one references 3. -asmref
3. EMP-Scripts folder -asmdef

There are the kind of errormessages coming up(when trying to build only, there are 200 of them):

```
Assets\Plugins\EasyMobile\Editor\EM_BuiltinObjectCreator.cs(6,19): error CS0234: The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
Assets\Plugins\EasyMobile\Editor\EM_SettingsEditor_Privacy.cs(9,24): error CS0234: The type or namespace name 'SerializedProperty' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
Assets\Plugins\EasyMobile\Editor\EM_SettingsEditor_Privacy.cs(10,24): error CS0234: The type or namespace name 'EditorStyles' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)

```

I tried adding a refernece to the Unity.Editor dll in VS to the EMP assembly, but VS just doesn't do anything, no errors, no messages...Tried the same in asmdef file in Unity with no luck...

I got the inspiration from this video, and it was working ok...

Unity 2019.3
VS 2019
Android platform
EMP 2.5.2

Thanks

# Answer
> 0 votes
I just unchecked Android on my asmdef at the platforms section, as DMGregory suggested and voila. It works! Many thanks!

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


# Question
Title: Uploading APK build to Google Play Console error "You uploaded a debuggable APK or Android App Bundle"
I was trying to upload my andoid app apk build to my play console account and I keep getting this error:

```
You uploaded a debuggable APK or Android App Bundle. For security reasons you need to disable debugging before it can be published in Google Play.

```

In accordance with the informations given at

https://developer.android.com/studio/publish/preparing.html#publishing-configure

and

https://answers.unity.com/questions/1653647/you-uploaded-a-debuggable-apk-or-android-app-bundl.html

Here are what I have done so far:

1) I have gone to the root folder of my unity project, searched for **AndroidManifest.xml**, and I found multiple Manifest files, and changed the value of **"android:debuggable"** to false for each of these manifest files that were generated by unity(and I did not edit the google generated manifest files).

2) I have scanned every c# file on my project that contains the keyword *"Debug"* and I have either deleted or commented out the *Debug.log* lines except on the files generated by google(as a result of the integration of google play services into my game).

And yet, I still have the same problem when I try to upload my apk to play console. What else am I missing? Should I also remove the *Debug.log* lines from google generated c# script files?

# Answer
I'm not sure of what happened exactly, but I uploaded successfully after disabling "Enable built-in Ads extension" on Unity's Services window to fix the Unity Ad duplicate errors that I was getting in the console after a build.
> 0 votes

# Answer
1- Firstly you have to disable the development build in your Android Build settings uncheck the development build 2- Second in your code try to find out where you have written debugging=true third look into your android manifest file
> 1 votes

# Answer
Go to build settings:

1. Select IL2CPP
2. Verify the C++ Compiler Configuration is set to Release
3. Check all Android manifests for `android:debuggable`.

It should be `<application android:debuggable=false>`
> 1 votes

---
Tags: unity, c#, google-play, google-play-services
---


# Question
Title: NullReferenceException in save game function
I was making save system to save position of player.

I get an exception:

> NullReferenceException: Object reference not set to an instance of an object

It comes from this line: `FloatPos[0] = DataG.transform.position.x;`

Here is my Save Manager:

```
[System.Serializable]
public class SaveManger
{
    public float[] Player, Top, Ground, ET, ED;
    public int PN, PCN;

    public SaveManger(SaveGame SaveGame)
    {
        PosMath(Player, SaveGame.PlayerPos);
        PosMath(Top, SaveGame.TopPos);
        PosMath(Ground, SaveGame.GroundPos);
        PosMath(ET, SaveGame.EfTop);
        PosMath(ED, SaveGame.EFDown);

        PN = SaveGame.TransformMover.GetComponent<TransformMover>().PuzzleNumper;
        PCN = SaveGame.TopPos.GetComponent<PuzzleSetUp>().PuzzleCloneNumper;
    }

    public void PosMath(float[] FloatPos, GameObject DataG)
    {
        FloatPos[0] = DataG.transform.position.x;
        FloatPos[1] = DataG.transform.position.y;
        FloatPos[2] = DataG.transform.position.z;
    }
}

```

Here is my saved game component:

```
public class SaveGame : MonoBehaviour
{

    public GameObject PlayerPos,TopPos,GroundPos,EfTop,EFDown,TransformMover;

    public void Start()
    {
        string path = Application.persistentDataPath + "/GSave.GSF";
        if(File.Exists(path))
        {
            LoadButton();
        }
        else
        {

        }
    }

    public void SaveButton()
    {
        SAVESYSTEM.VoidSaver(this);

    }

    public void LoadButton()
    {
        SaveManger Data = SAVESYSTEM.LoadSave();

        TransformMover.GetComponent<TransformMover>().PuzzleNumper = Data.PN;
        TopPos.GetComponent<PuzzleSetUp>().PuzzleCloneNumper = Data.PCN;
    }
}

```

# Answer
> 1 votes
You never initialize your `float[] Player` array, so it holds an initial value of `null`.

When you then try to set `FloatPos[0] = DataG.transform.position.x;`, with `FloatPos` pointing to `Player` which is still `null`, that means `null[0] = ...` \- but `null` doesn't have a 0th element to assign! It's just nothing.

So, initialize your arrays!

```
public SaveManger(SaveGame SaveGame)
{
    Player = new float[3];
    PosMath(Player, SaveGame.PlayerPos);

    Top = new float[3];
    PosMath(Top, SaveGame.TopPos);

    Ground = new float[3];
    PosMath(Ground, SaveGame.GroundPos);

    // ...

```

(You might have fallen out of the habit of doing this because in Unity `MonoBehaviour` or `ScriptableObject` scripts, public arrays or lists of serializable types are initialized to an empty array by default by Unity's serialization systems)

This is a basic programming problem that does not require game development specific expertise to solve, so please remember to search on StackOverflow first \- you'll find lots of existing answers that explain this in depth. Ask here when your problem is unique to games.

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


title: Algorithm for chase by multiple enemies

text:
# Question
Title: Algorithm for chase by multiple enemies
If I have one enemy that should chase the player, I can use a path-finding algorithm such as BFS to find the shortest path from the enemy to the player (taking into account obstacles along the way), and advance the enemy along the path.

But if there are two enemies, this is not necessarily the most efficient strategy. For example, if there is a large obstacle, instead of both enemies chasing the player from the east, it may be more efficient for tnem to cooperate, one of them should go chase the player from the east while the other blocks the player's escape route from the west.

My question is: what is an algorithm for efficiently coordinating the chase behavior of two enemies?

# Answer
"Algorithm efficiency" is a very broad expression. If I understand correctly, you want an heuristic to predict the path of enemy AI's so they can trap the player. There are multiple ways to handle this and the best solution also depends on the victory condition.

Does the player has an objective to go somewhere in the map, or is he just trying to survive for the longest time?

Considering the player just has to survive for the longest time, one suggestion of an algorithm I can make is:

1. Compute the sum of distances of all the paths the player can go without going into any enemy range.
2. Compare which combination of directions of movement each AI can take and choose the combination that mostly minimizes the sum computed in step 1.
> 1 votes

---
Tags: algorithm, ai
---


# Question
Title: How to change between camera angles in Unity
I need to change camera angles in Unity by hitting a key.

For example,

* I want to look down on the battle, so I hit 1.
* Then I want to see it from the side, so I hit 2, etc.

How do I write a script to do this change of perspective?

I have 3 cameras set up, each of them outputting to a different display. I want to switch between those cameras/displays to get a different viewing angle for the players. As an example, in the Unity editor, in the upper left corner, you have a tab that says Display 1. Clicking that will show you other displays.

Also, when setting up a camera, you have to connect it to a display. (I know you already know this, I just wanted to make sure you guys knew what I was talking about)

# Answer
> 1 votes
Displays on cameras are only used to target different monitors on a PC. If that's what you're going for, you can modify those values. If not, always set it to the first display.

Assuming you're using one monitor, All you need to do is make sure that you have those 3 cameras in the place you want them in the scene, but only have one active at a time.

So an example function could look like this:

```
void SetActiveCamera(int _whichCamera)
{
   for(int i = 0; i < cameras.Length; i++)
   {
       if(i == _whichCamera)
           cameras[i].SetActive(true);
       else
           cameras[i].SetActive(false);
   }
}

```

`cameras` is an array of game objects - your camera game objects. You can assign this in the Inspector.

This function will turn on the camera you choose, and turn off all the others.

If you want a multi-monitor set up, all you need to do is have the proper Display configured for the camera and have them all enabled. But I don't think that's what you're going for.

# Answer
> 0 votes
in unity we have scenes. you have to implement you game in different scenes and change scenes using code below: using UnityEngine; using UnityEngine.SceneManagement;

```
public class ExampleClass : MonoBehaviour
{
    void Start()
    {
        // Only specifying the sceneName or sceneBuildIndex will load the Scene with the Single mode
        SceneManager.LoadScene("OtherSceneName", LoadSceneMode.Additive);
    }
}

```

scenes are files in assets. look at this link https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html

another approach to puth some gameObjects in a scene.then make camera show those scenes. this is my example:

list objList;

```
Update()
{

    if(Input>GetKeyDown(KeyCode.Q))
    {
    Camera.main.transform.position= new Vector3(objList[0].transform.position.x,
    objList[0].transform.position.y,
    Camera.main.transform.position.z);
    }

}

```

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


# Question
Title: How to compress repetitive information when uploading mesh data?
I want to avoid sending repetitive information when drawing a mesh.

If I use a single point for each face and two vectors as additional attributes that represent the travel of each vertex, I can use that information in a Geometry Shader to produce the normal and the two points followed by any additional attributes for that face.

Is the computation cost worth the saved data needing to be transferred? Or is there a better way to optimize the pipeline for sending over a mesh to draw?

Edit: In particular this is a case where the mesh has attributes unique to the face and not the vertex, so if it were done the regular way each vertex would be multiplied by the number of faces used by it.

# Answer
> 1 votes
For simplicity, let's assume you're working with an endless grid of 2-triangle quads, with normals/texture coordinates shared at each vertex. This is similar to what you'd use for a terrain mesh, and character meshes will have similar local properties away from the sites of topology changes and texture seams.

If we "compress" this as you propose for the geometry shader approach, then for each quad we need:

* 2 faces, each containing:
    + face point (3 floats = 12 bytes)
        - vertex 1 travel (3 floats = 12 bytes)
        - vertex 2 travel (3 floats = 12 bytes)
    + face texture coordinate (2 floats = 8 bytes)
        - vertex 1 texture coordinate travel (2 floats = 8 bytes)
        - vertex 2 texture coordinate travel (2 floats = 8 bytes)

So that's **120 bytes per quad** of mesh. Seems... kind of heavy. Let's say we reduce the storage for all our travel offsets, assuming our triangles are small so we don't need the full range and precision of a 32-bit float to get from one side to the other. If we half their storage, that brings us down to **80 bytes per quad**. If we get really aggressive and quarter it (so only 256 distinct values possible), we're down to **60 bytes per quad**.

Now let's compare that to traditional indexed rendering:

* 4 vertices per quad, each shared between 4 quads, means 1 vertex per quad on average. Each vertex contains:

+ position (3 floats = 12 bytes)
    + texture coordinate (2 floats = 8 bytes)
    + normal (3 floats = 12 bytes)
* 6 indices per quad (6 shorts = 12 bytes)

For a total of **44 bytes per quad** of mesh.

So your "compression" strategy actually *increases* your upload bandwidth requirements by about 36%, even if we're maximally aggressive in compressing our local offsets. It also adds an extra programmable stage to the rendering pipeline, increasing our latency. And it costs you the use of the GPU's vertex cache, which can often save us from re-running the vertex shader on shared vertices, making this solution even more costly.

---

If instead you're dealing with attributes that are largely not shared between adjacent faces, then you can do this more simply using a constant buffer, and indexing into it with vertex ID in the vertex shader (divided by 3).

Per triangle, that's then:

* 3 unique vertices, each containing:

+ position (3 floats = 12 bytes)
    + texture coordinate (2 floats = 8 bytes)
* 1 entry in your constant buffer, containing:

+ face normal (3 floats = 12 bytes)
    + (other shared triangle attributes, as needed)

For a total of 72 bytes per triangle, not significantly more than the compressed version uses for the same precision. And we still don't need to add an extra pipeline stage or break the vertex cache to do it.

---

Moral of the story: check that it's really a problem before you attempt to "solve" it with something more complex.

---
Tags: opengl, geometry-shader
---


# Question
Title: Drawing object lines in the Tiled map editor
Suppose I have this picture:

I have a map like this created in Tiled already. I would like to draw collision lines (the green ones in the picture) without having to make it a polygon. As far as I know, Tiled does not support drawing a line as a collision object, so I would appreciate ideas on how to make this work.

I also tried drawing a quadrilateral and calculating the diagonal in code (LibGDX), but that's a bit clunky and can go wrong easily.

# Answer
> 4 votes
Tiled *does* support drawing lines as collision objects. To do this, you should just not close the polygon (right-click once you're done with the polyline).

In the past these have been separate tools, but in Tiled 1.2 they have been unified into a single tool. Probably the UI needs to be more clear that the tool can be used to create both polygons and polylines.

---
Tags: java, libgdx, tiled
---


# Question
Title: How do I debug OpenGL apps written in python?
How do I debug OpenGL apps written in python? I tried but I was unable to use standard tools like nvidia nsight or glsl-debugger or renderDoc on python code.

# Answer
It's hard to tell without knowing more about the python code you are trying to debug and with what library. All the tools you listed will be able to capture OpenGL calls in python the same way it would in C++, C#, rust etc.

They work by intercepting the underlying library calls to the library (.dll, .so, etc) which happen no matter what language you are using.

Some common issues on RenderDoc you can avoid are:

* Bad executable path: The executable you enter has to be the interpreter python. It cannot be the script, this has to go in the command-line arguments section:
    + Executable path: `/usr/bin/python`
    + Command-line Arguments: `/tmp/hello_world.py`
* Your script could be quitting due to some error during runtime. Check the log in this case.
* The library you are using could be rendering in a forked process. Check "Capture Child Process" in RenderDoc or the equivalent option in NSight or glsl-debugger. Make sure you try capturing all the child processes.
* If your application is a static image, it's possible that you cannot capture because that image was submitted to OpenGL only once. For example, pyglet will only draw once unless it is given an update function with `pyglet.clock.schedule`. If that's the case, you tell RenderDoc to capture the first frame with Actions: Queue Capture Frame 0.
* Finally, make sure your library is using a compatible OpenGL profile. RenderDoc will warn you if a profile is too old. If that's the case, either find a way to use at least 3.2 profile or you can use apitrace.

For example, here are the safest options you can have in RenderDoc. Capture Child Process is enabled in case it forks, Queue Capture is enabled in case only one frame is submitted and python is set as the executable.

And this is the code

```
import pyglet

window = pyglet.window.Window()
label = pyglet.text.Label('Hello, world!',
                          font_name='Arial',
                          font_size=36,
                          x=window.width // 2,
                          y=window.height // 2,
                          anchor_x='center',
                          anchor_y='center')

@window.event
def on_draw():
    window.clear()
    label.draw()

def update(dt):
    pass

# Update function to make sure pyglet re-draws periodically
pyglet.clock.schedule(update)
pyglet.app.run()

```
> 2 votes

---
Tags: opengl, glsl, python, debugging
---


# Question
Title: Unity3d texture size different than original png image
While selecting a png image as a texture for a material in Unity, it shows different size (bigger) than the actual file size, why is this so? how can I reduce its effective size to make it perform better without loosing much detail.

Size in windows explorer (825 kb)

and this is same image in Unity texture select window (1.3 MB)

# Answer
> 0 votes
Take a look at your import settings for the texture. Setting a different value in the Max Size field will have an effect on the disk space it will take up in a build.

---
Tags: unity, android, textures, materials
---


title: Effectors in 3D

text:
# Question
Title: Effectors in 3D
I see that, in the Unity editor, there are only Effector2D components, but no Effector components. Are there other components that can be used with the 3D physics engine, that function like effectors? Or should I write my own custom components for this?

# Answer
> 2 votes
The Unity 2d and 3d physics engines are completely separated from each other and work in very different ways. So you can not expect to see every feature being mirrored 1 to 1 between 2d and 3d. The effectors happen to be among the features exclusive to the 2d engine.

But if you want to simulate them, then that's often not difficult to do.

Create a game object with a collider set to "Is Trigger" enabled. The shape and size of the collider represent the area of effect. Then add a MonoBehaviour which implements `OnTriggerStay(Collider other)` to apply the physics forces to the `Rigidbody` of anything within the trigger.

---
Tags: unity, physics
---


# Question
Title: UI Sprite in Unity3D is badly drawn? (Possibly anti-aliasing problem)
I move a

* **28x42 Image**,
* in a **11x17 RectTransform**
* in **Update**,
* with **anti-aliasing on**,
* **without compression**,
* with **point filtering**.

But sadly its visuals aren't smooth, it's **flickery**, even in a standalone build with **1440p** resolution.

**I move it like this:**

```
Arrow.anchoredPosition = new Vector2(newX, Arrow.anchoredPosition.y);

```

**I've already tried:**

* Changing the RectTransform's size to 28x42.
* Turning off anti-aliasing.
* Changing filtering modes.
* Moving it in FixedUpdate.

I tried it with a 110x170 and 280x420 RectTransform, but it's still wrong: (110x170 shown below)

Why?

# Answer
> 3 votes
This occurs because you're displaying your sprite at a size on screen such that there's a non-integer ratio between the number of screen pixels it occupies, and the number of source texels in the sprite.

That means that somewhere, some source texels need to be displayed more times than others to fill the space, and which ones get repeated/skipped depends on rounding as your sprite moves, creating a shimmery/rippling effect that rolls over the image as you see here.

Some common ways to fix this, in approximately increasing order of complexity:

1. Use bilinear filtering on your sprite, instead of nearest neighbour / point filtering.

Point filtering is great for crisp pixel art, but it requires exacting attention to your display-pixels-per-texel ratio, which might not be what you want here.

By using bilinear filtering, the GPU is able to blend between adjacent texels when there's a mismatch between the display pixel grid and the source asset, minimizing any apparent ripple or shimmer, especially on high-resolution displays. There can be a slight loss of crispness this way, if your source art isn't sized correctly for your display size, but the degradation is gradual rather than so glaring, so small mismatches are often tolerable enough in this form.
2. Configure your assets and display settings so that your sprites are always displayed at an integer ratio of display pixels per source texel.

For some projects, this can be as simple as setting "Constant Pixel Size" on your canvas and keeping your pixels per unit / reference pixels per unit values consistent. The downside is that on low-res displays your UI widgets might look too big/clunky, and on very high-res displays they might look too small to read/use comfortably.

You can compensate by scaling up your assets by integer factors, to keep them a similar apparent size on all display resolutions you choose to support, within the limits of rounding. Or by swapping to an alternative asset set depending on the resolution to ensure you get pixel-perfect crispness on every supported resolution.
3. For simple elements like the slider thumb, that need crisp edges at any resolution but lack internal detail, you can ditch conventional sprites and instead render them with signed distance fields, so you can get a pixel-perfect antialiased stroke of controllable thickness over a wide range of display sizes.

---
Tags: unity, rendering, gui, antialiasing
---


# Question
Title: How to create a component that is a child of another component?
I have several objects in my game that all have an `customEvent` component. I have three different types of `customEvent`, `customEventA, customEventB, customEventC`. At some point, I want to enable this `customEvent` component, but I don't know if its type `A, B, or C`.

What I want to do is just reference `GetComponent<customEvent>().enabled = true` and then it will automatically enable whatever type is actually attached to the GameObject.

What I am trying to do is similar to how `Collider` component works. You can have a `BoxCollider, SphereCollider, PolyCollider, etc.` and can refernce it by saying `GetComponent<Collider>()`.

How can I achieve this?

# Answer
> 3 votes
I can't see how you have your scripts, but each event A, B and C needs to extend from a common base class.

Assuming your CustomEvent class looks like this

```
 //base class
public class CustomEvent : MonoBehaviour
{
   //whatever you have in here
}

```

You would make your A, B and C events inherit from this class

```
//extends base
public class CustomEventA : CustomEvent
{
   //whatever you have in here
}

```

Then when you call GetComponent\<*CustomEvent*\>() it doesn't matter which it is (A, B or C) as they all extend the same base class.

You can also use interfaces for this (with the caveat that they require extra checks if you are using GetComponent to retrieve the interface), but without knowing more I can't recommend an option.

You have to be careful that you don't try to call a function that doesn't exist, keep all functionality common to each CustomEvent A,B,C etc in the CustomEvent Base Class and they will inherit it from the Base Class.

For example if CustomEventA has a function named OnEventTrigger() but CustomEventB doesn't you will run into problems, if you are treating an object as a base class, it will only have access to the methods in the base class unless you cast it specifically to whatever type it is.

---
Tags: unity
---


# Question
Title: How to get/set specific properties of a video texture in pixi.js?
I managed to get a video to play in Pixi using the following line:

```
    this._texture = PIXI.Texture.from(require("Images/video.mp4"));

```

The problem is that I can't find any properties to do things such as pausing it, forwarding/backwarding, adjusting volume, adjusting playing-speed etc.

Neither the PIXI.Texture or PIXI.Sprite seem to have any properties for this. Is this legitimately all the control PIXI gives you or am I missing something?

# Answer
> 2 votes
Taking a tour through the docs, it looks like you should be able to access the HTMLVideoElement that's playing your video via:

```
this._texture.baseTexture.resource.source

```

And then use members it inherits from HTMLMediaElement like `.pause()`, `.fastSeek()`, `.volume`, `.playbackRate`, etc.

---
Tags: video, pixi.js
---


# Question
Title: How do I randomly position objects without overlap?
I'm studying a little about procedurally generating levels and decided to start with a vertical scrolling game.

I would like to position some platforms vertically in my scene. So far, I've used a basic method: Random positions, with some maximum `y`-distance between them. However, that means platforms at the same height can still overlap. I would like to be able to have more than one platform at each height:

I thought about using sets of platforms including unique platforms, combined platforms (2 or 3 per `y`, and so on), and randomly position those sets. However, this would not prevent the overlapping and I really would like to do it properly procedurally.

Even so, I cannot guarantee that each platform is accessible by the player character from the previous one.

How can I proceed?

# Answer
I'd try something like this:

* Go from the start to the end and place the platforms at semi-random positions.
* Ensure this basic level is solvable, i.e. the end may be reached.
* Once that's done, use additional iterations to add more optional platforms. When placing those, you can verify that they're not too close or don't overlap for example.

As an alternative:

* Rather than placing random platforms, create "screens" with fixed platform layouts (or possibly optional platforms).
* Instead of placing platforms randomly, you now pick the order of screens randomly.
* You can add constants identifying the left/right border setup to ensure levels may be solved (e.g. a very low platform can't transition to a very high platform unless there's some kind of ladder or catapult).
> 3 votes

# Answer
Before randomly placing the platforms you need to take into consideration some important values:

1. Character's height
2. Character's width
3. Jump's maximum height
4. Jump's maximum distance
5. Minimum distance to run for optimal jump between platforms at the same level

With that in mind you craft your platform generator floor by floor, starting by the ground floor and taking it as a platform.

**Basic rules**

* Character's height \< vertical distance \< jump's maximum height
* Character's width \< horizontal distance \< jump's maximum distance
* Character's width \< platform width \< (max horizontal space - character's width)

**Advanced rules**

* If maximum horizontal distance in same floor \> threshold, ensure one of the platforms complies with the minimum distance to run for taking that optimal jump
* If maximum horizontal distance in previous floor \> threshold, don't place a platform above the gap in order to avoid a jump collision that disables the player to properly jump that gap

There would be more rules and considerations (e.g. placing spikes), but those are what comes to mind right now for starters.

**Note:** I'm not taking into account the height of the platforms just to make the rules cleaner.

Take into consideration that depending on the approach rules addition, this could be a complex problem in terms of computational theory, making it CPU-intensive. In that case, it could be seen as a CSP problem, but this first approach look suitable because the computations are bond to same-level platform and two floors at the same time (current and previous).

---

Just like Mario said, the approach of making hand-crafted platform blocks is less CPU-intensive and making it easier to place random platforms in real time. However, the trade-off would be to invest time creating and tuning those platform blocks (considering the rules above).
> 2 votes

# Answer
If you use a tile-based level layout where a grid cell either contains a platform or not, then you implicitly solve the problem of preventing overlap. Indeed, it can happen in two ways:

1. Additive approach: Start with all cells empty, then set "cell\[x\]\[y\] = platform\_tile" for each platform you add. Setting a given cell to platform twice won't matter as its value will be unchanged from the first time it was set. Does need a routine to check if you've sealed off the path if the platforms aren't the jump-through type, though.
2. Subtractive approach: Start with all cells solid, then pick where to put the empty space the player can move through. Avoids the need for the check that you haven't sealed off the player's path. Might make generating background art for supports a little harder, though.

Either way, you will need some sort of reachability check, which other posters have already covered.
> 1 votes

# Answer
A crude but pretty common solution is to try random positions until you get a valid one. However, if there are very few or even no valid positions, then this algorithm can end up in an infinite loop. To prevent that there is usually a limit of how many tries the algorithm has before giving up and just not spawning the object at all.

Pseudocode:

```
tries = 0
max_tries = 10  // (or whatever is a good balance between reliability and performance)

do
    generate random position
    add 1 to tries
while (position is invalid AND tries <= max_tries)

if (tries <= max_tries)
     spawn object at position

```

This is simple to implement, adapts if your criteria for valid positions change over the course of your development and is often a "good enough" solution. Unfortunately it can become insufficient if you want to use it for objects which simply **must** exist in your outcome. For example, if you use this to generate procedural levels in a top-down shooter, you can perhaps tolerate if there are only 11 instead of 12 enemies in the level, but it is not acceptable when there is no player start position. How can you handle this problem?

* Create high-priority objects first to ensure they have a very high chance to find valid positions
* Pick a location and **make** it valid by removing or repositioning any objects which are in the way
* Discard the whole level as invalid and start generating a new one from scratch
> 0 votes

---
Tags: procedural-generation, platformer, side-scroller
---


title: Check if point is inside convex hull

text:
# Question
Title: Check if point is inside convex hull
I first tried with a simple axis aligned bounding box to test my algorithm (later shape will be different but always convex 6 faces), but even this case did not work, it always tells me that the point is not inside:

```
                BoundingBox bb = new BoundingBox(-new Vector3(.5f), new Vector3(.5f));

                var corners = bb.GetCorners();

                bool liesInside = true;
                for (int cornerIndex = 0; cornerIndex < 6; cornerIndex++)
                {
                    Plane plane = new Plane(corners[cornerIndex], corners[cornerIndex + 1], corners[cornerIndex + 2]);
                    if (plane.DotCoordinate(rayPos) > 0)
                    {
                        liesInside = false;
                        break;
                    }
                }

```

# Answer
> 1 votes
Some basics on convex hull tests for folks that might read this later:

A convex hull is a volume defined by a number of planes (at least 4, but it could be much more). Testing to see which side of a plane a given point is on is trivial (computationally speaking), it's just a dot-product. Go look up "dot product" if you don't know what that is. Do it now. It's important.

Back? Okay, so in a working convex hull test, all the planes would be facing inward or all facing outward. In other words, for a point to be inside, all the dot products would be positive (which is what codymanix is using above), or all negative. You'll need to pick one in advance and stick to it, and all your data defining your hulls needs to stick with it too.

Codymanix is starting with a box, which is defined, as far as we're concerned, by six planes. If all six planes are "facing inward" then we're fine, but what happens when 2 or more of those planes are "facing outward"? All of a sudden, no point in our coordinate system will ever satisfy the positive dot product check on all six planes defining the hull.

To visualize this, lets imagine a square in 2d. The top is labeled "top" and the bottom is labeled "bottom". To be inside this square, a point must be below top and above bottom. With me so far? Okay, not lets move the top until it is below bottom... and we'll keep the tests the same. Now there is no point that is above the top and below the bottom. We've turned our square "inside out" and nothing can be inside it.

I suspect that condymanix's hull has been turned "inside out".

Okay, that's the problem, so how do we fix it?

IIRC, the "front" and "back" of a given triangle are defined by a "winding rule". "Wind" as in "wind your watch" not "wind is blowing". There are two different winding rules, called "left handed" and "right handed". Make a thumbs up gesture, fingers curled into a fist, thumb sticking straight up. The way your fingers curl is the order in which the points on a triangle are ordered to define the "front" of that triangle, the direction your thumb is pointing. Right hand: counter clockwise, left hand: clockwise.

Codymanix, I'm guessing you're mixing left and right handed winding. You need to define your hulls such that the thumbs are all pointed in the same direction. It would be nice if you use the same winding rule as your meshes just for consistency's sake. It will probably also make generating hulls from your meshes easier.

---
Tags: xna, collision-detection, mathematics, linear-algebra
---


# Question
Title: Efficiently rendering lots of the same mesh in Unity3D, but with different colors?
I'm working on a tile based game, where grass is spreading from tile to tile, so soon lots of grass appear on the board.

Instancing is on, so the FPS is kind of good, even with 300k triangles (1 grass leaf consists of 90 triangles).

**BUT:** Tiles can be wet and dry on **floating scale**, which makes the grass leaves turn from **green to yellow**.

Currently I implemented this simply as such:

```
var r = originalColor.r + 0.27f * (1f - (ground.Status / 100));
renderer.material.color = new Color(r, originalColor.g, originalColor.b);

```

Which creates a **new material** for every grass...

Obviously I can't change the sharedMaterial's color, because that would change all other grass' colors as well.

**So how could I efficiently render grass on a big spectrum from yellow to green?**

One thing I came up with is that I create only like **100 materials, with 1 percent steps.**

* = first material is 100% yellow, and the last one is 100% green.

And when a grass turns a bit more green, it **doesn't have to create a whole new material** with 3.47% green, but instead **can use the already created** 3% green material.

Any better ideas?

Thanks!

# Answer
**MaterialPropertyBlocks** are perfect for this situtation.

I followed a quick tutorial, and managed to boost the performance by a lot.

The behaviour below always passes the Color stored in its **MaterialColor** property to the GPU via a **MaterialPropertyBlock**, thus letting **instanced meshes** have **different i.e. colors**.

```
public class ColorPropertySetter : MonoBehaviour
{
    //The color of the object
    public Color MaterialColor;

    //The material property block we pass to the GPU
    private MaterialPropertyBlock propertyBlock;

    private Renderer renderer;

    void Start()
    {
        //create propertyblock
        propertyBlock = new MaterialPropertyBlock();
        //Get a renderer component either of the own gameobject or of a child
        renderer = GetComponent<Renderer>();
        //set the color property
        propertyBlock.SetColor("_Color", MaterialColor);
        //apply propertyBlock to renderer
        renderer.SetPropertyBlock(propertyBlock);
    }

    void Update()
    {
        //create propertyblock
        propertyBlock = new MaterialPropertyBlock();
        //set the color property
        propertyBlock.SetColor("_Color", MaterialColor);
        //apply propertyBlock to renderer
        renderer.SetPropertyBlock(propertyBlock);
    }
}

```

The shader below uses the given MaterialPropertyBlock and also instancing.

```
Shader "Tutorial/048_Instancing" {
//show values to edit in inspector
Properties{
    [PerRendererData] _Color ("Color", Color) = (0, 0, 0, 1)
}

SubShader{
    //the material is completely non-transparent and is rendered at the same time as the other opaque geometry
    Tags{ "RenderType"="Opaque" "Queue"="Geometry"}

    Pass{
        CGPROGRAM
        //allow instancing
        #pragma multi_compile_instancing

        //shader functions
        #pragma vertex vert
        #pragma fragment frag

        //use unity shader library
        #include "UnityCG.cginc"

        //per vertex data that comes from the model/parameters
        struct appdata{
            float4 vertex : POSITION;
            UNITY_VERTEX_INPUT_INSTANCE_ID
        };

        //per vertex data that gets passed from the vertex to the fragment function
        struct v2f{
            float4 position : SV_POSITION;
            UNITY_VERTEX_INPUT_INSTANCE_ID
        };

        UNITY_INSTANCING_BUFFER_START(Props)
            UNITY_DEFINE_INSTANCED_PROP(float4, _Color)
        UNITY_INSTANCING_BUFFER_END(Props)

        v2f vert(appdata v){
            v2f o;

            //setup instance id
            UNITY_SETUP_INSTANCE_ID(v);
            UNITY_TRANSFER_INSTANCE_ID(v, o);

            //calculate the position in clip space to render the object
            o.position = UnityObjectToClipPos(v.vertex);
            return o;
        }

        fixed4 frag(v2f i) : SV_TARGET{
            //setup instance id
            UNITY_SETUP_INSTANCE_ID(i);
            //get _Color Property from buffer
            fixed4 color = UNITY_ACCESS_INSTANCED_PROP(Props, _Color);
            //Return the color the Object is rendered in
            return color;
        }

        ENDCG
    }
}

```

Source: https://www.ronja-tutorials.com/2020/02/11/material-property-blocks.html
> 0 votes

---
Tags: unity, rendering, materials, instancing
---


title: Octagon border algorithm

text:
# Question
Title: Octagon border algorithm
I'm working on an open source game for 2 years but I'm very bad at math. The game permits moving a character on an octagonal basis. When the character reaches the border coordinate (colored in yellow), I permit him to travel to another octagon:

The map is a simple 2d array of x, y coordinates. The goal is to know if an x, y tile coordinate is on a "yellow" tile, and which direction it represents (north, northeast, east etc.) depending on map width and height.

I wrote this algorithm many times and in two different language, example with Rust:

```
pub fn get_corner(width: i16, height: i16, new_row_i: i16, new_col_i: i16) -> Option<CornerEnum> {
    let left_col_i_end = width / 3;
    let right_col_i_start = (width / 3) * 2;
    let top_row_i_end = height / 3;
    let bottom_row_i_start = (height / 3) * 2;
    let mut more = if new_row_i >= 0 { new_row_i } else { 0 };
    #[allow(unused_assignments)]
    let mut right_col_i = 0;
    #[allow(unused_assignments)]
    let mut left_col_i = 0;

    if new_row_i < top_row_i_end {
        right_col_i = right_col_i_start + more;
        left_col_i = left_col_i_end - more;
    } else {
        if new_row_i >= bottom_row_i_start {
            more = (height / 3) - (new_row_i - bottom_row_i_start + 1);
            more = if more >= 0 { more } else { 0 };
            right_col_i = right_col_i_start + more;
            left_col_i = left_col_i_end - more;
        } else {
            left_col_i = left_col_i_end;
            right_col_i = right_col_i_start;
        }
    }

    if new_col_i < left_col_i && new_row_i < top_row_i_end {
        return Some(CornerEnum::TopLeft);
    }
    if new_row_i < 0 && left_col_i <= new_col_i {
        return Some(CornerEnum::Top);
    }
    if new_col_i >= right_col_i && new_row_i < top_row_i_end {
        return Some(CornerEnum::TopRight);
    }
    if new_col_i > width - 1 && top_row_i_end <= new_row_i {
        return Some(CornerEnum::Right);
    }
    if new_col_i >= right_col_i && new_row_i >= bottom_row_i_start {
        return Some(CornerEnum::BottomRight);
    }
    if new_row_i > height - 1 && left_col_i_end <= new_col_i {
        return Some(CornerEnum::Bottom);
    }
    if new_col_i < left_col_i && new_row_i >= bottom_row_i_start {
        return Some(CornerEnum::BottomLeft);
    }
    if new_col_i < 0 && top_row_i_end <= new_row_i {
        return Some(CornerEnum::Left);
    }

    None
}

```

But it is not working too well: it works only for some borders, but not for others, apparently depending on width/height odd/even... I curse my math. I'm sure it's not that complicated but I've failed for two years. So, I'm here to ask for a solution... which would be greatly appreciated!

# Answer
> 1 votes
I assume you are storing map information in some kind of 2D array or something similar where you can easily check neighboring tile information. Any border tile will be missing at least 1 neighbor. You can then tell what direction based on which neighbors are missing, for example if you are missing neighbor tiles to the south and west you know it is the south-west border. If you are missing a neighbor to the north only then it is the north border, etc. This should work for an octagon no matter what size. Hope this helps.

Edit: The corner tiles between directions may require special edge case logic because you could classify them in two directions potentially (as pointed out by Zibelas below). Depends on how you would classify those, but you can see any corner tile always has two missing neighbors. So any tile with two missing neighbors you should check to see if it has a neighboring border tile and if so use that tile's direction instead.

Also when I say neighbor, I mean only to the west/east/north/south, not diagonally.

---
Tags: mathematics, tiles
---


# Question
Title: Animator State does not switch immediately through code, even tho all transitions have "Has Exit Time" checked off
first of all, this is my code, I'm prototyping a state machine using Unity Animator (First Time) and I'm stuck coding a simple burst of speed.

```
using UnityEngine;
using UnityEngine.AI;

[CreateAssetMenu(fileName = "Dash", menuName = "States/Dash")]
class Dash : State
{
    NavMeshAgent agent;
    [SerializeField] float Speed = 50;
    [SerializeField] float Distance = 1;
    float oldSpeed,counter, duration;

    public override void onStart(Animator animator, AnimatorStateInfo stateInfo)
    {
        agent = animator.GetComponent<NavMeshAgent>();
        duration = Distance / Speed;
        oldSpeed = agent.speed;
        agent.speed = Speed;
        counter = 0;
    }

    public override void onUpdate(Animator animator, AnimatorStateInfo stateInfo)
    {
        counter += Time.deltaTime;
        Debug.Log(counter + " of " + duration);
        if(counter > duration)
        {
            Debug.LogError("Dash is finished");
            agent.speed = oldSpeed;
            animator.SetBool("isDashing", false);
        }
    }

    public override void onExit(Animator animator, AnimatorStateInfo stateInfo)
    {

    }

}

```

The issue is that the player standstill for few second after dashing. So I've added some debug.log and this is the result.

As you can see, the state keeps updating even tho the timer has ran up. It even keeps updating after switching to "Idle" state, tho this ends at some point. I've made sure that all transitions have "Has Exit Time" checked off and the Interruption Source = "Current State".

Note: this is just a prototype and the states have no animations still.

# Answer
As @DMGregory pointed out, the Issue was that Transition Duration of 0.25 seconds which forced the state to hold until a quarter of a second passes.

Making the Transition duration zero solved the problem and now the state switches immediately.
> 1 votes

---
Tags: unity, state, animator, animation-states
---