# Question
Title: Improving the look of a character with solid parts inside a translucent jello exterior
So my problem is a bit hard to explain. I have a character made out of a jello shell, with an internal skeleton. So let me introduce you to ma boi "Chonker McJello"

The problem is, that I want a rich green slightly transparent jello, without loosing too much details and "whiteness" on the internal skeleton. If I turn the transparency or saturation of the jello down, the jello looks ugly, if I put the jello as I want, the Skeleton looses too much details/turns green. I have thought of different approaches, but do not really know how to achieve the effect I want.

1. Single sided emission: Is there a way to make the jello glow internally and light the skeleton up? The emission should only come from the backfaces.
2. Doing something with the render layers, like rendering the skeleton with transparency on top of the jello again, to make it appear "less affected" by it's color

Everything I have in mind sounds easy but is propably pretty complicated and I don't have a lot of experience with shadergraphs and unity's hdrp. If you have any idea how to achieve the desired effect (maybe not in the way I thought) I would really appreciate your help!

Thanks a lot!

# Answer
> 1 votes
I'd render the jello twice.

Once: drawing only back faces, with high opacity, to get that rich green jello colour *behind* your skeleton. This pass could even be opaque if you like.

Then a second time: drawing only front faces, with low opacity, just to get a mild green tint over your bones, and catch the specular highlights and fresnel reflection.

You can set up two different materials for this - controlling the behaviour of each pass independently - and assign them both to your mesh to render them sequentially.

---
Tags: unity, shaders, unity-shader-graph, hdrp
---


# Question
Title: How to programmatically change sprite sheet sub-sprite name
I am trying to change the name of the sub-sprites of a sprite sheet. I have searched and tried everything I can think of and cannot get it to work, which makes me think it can't be done at this point in time.

Let's say I have a sprite sheet that has already been split up into individual sprites inside of Unity.

I am attempting to **change** the **sub-sprite names** programmatically.

I tried using

```
AssetDatabase.RenameAsset (...)

```

on the sprite sheet asset, which only changes the sprite sheet name and not sub-sprites.

I then thought to obtain a sub-sprite and attempt to change its name using the below code.

```
            if (AssetDatabase.IsSubAsset (subSprite))
            {
                AssetDatabase.RenameAsset (AssetDatabase.GetAssetPath (subSprite), "newSprite" + i.ToString ());
            }

```

However, this too only changes the sprite sheet name.

I'm not sure where else I can take this to achieve my desired outcome, apart from programmatically copying the original sprite sheet and using that to create a copy. But even then, I still am unable to alter the sub-sprite names.

I also tried changing subSprite.name, but this just changes the internal name and not the asset name.

Any ideas?

# Answer
Ok so based on @Rouze comment regarding the sprite slice renamer, I've managed to mock something up quickly that does the job.

Here is the quick mockup I did if anyone else is looking for a quick and dirty way to change the subsprite names. In my research for this subject, it appears I was referring to them as Sub-Sprites when the more known name is Sprite Slices... Probably why I couldn't find anything on this subject.

```
using UnityEngine;
using UnityEditor;
using System.Collections;

public class SubSpriteRenamer : MonoBehaviour
{
    public Texture2D texture2D;
    public string newName;

    private string path;
    private TextureImporter textureImporter;

    void Start ()
    {
        path = AssetDatabase.GetAssetPath (texture2D);
        textureImporter = AssetImporter.GetAtPath (path) as TextureImporter;
        SpriteMetaData[] sliceMetaData = textureImporter.spritesheet;

        int index = 0;
        foreach (SpriteMetaData individualSliceData in sliceMetaData)
        {
            sliceMetaData[index].name = string.Format (newName + "_{0}", index);
            print (sliceMetaData[index].name);

            index++;
        }

        textureImporter.spritesheet = sliceMetaData;
        EditorUtility.SetDirty (textureImporter);
        textureImporter.SaveAndReimport ();

        AssetDatabase.ImportAsset (path, ImportAssetOptions.ForceUpdate);
    }

    void Update ()
    {

    }
}

```
> 4 votes

# Answer
I had the same problem - a quick fix is to open the meta file in a good editor and do a find / replace on the name fragment. In my case I needed `AbilityIcon_0X` changed to `UpgradeNodeIcon_0X`. So I did these steps:

* `Find "AbilityIcon_"`
* `Replace all` with `"UpgradeNodeIcon_"`.

A scripted solution if there is a batch is always great. If you just need to do a handful this might be easiest
> 1 votes

# Answer
I found this sprite slice renamer online. It's the closest thing I could find but the source is provided and might be of some use.
> 0 votes

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


# Question
Title: Control the movement space for an object?
I want my object not cross the limit of "AiX\AiZ" values. When object cross this limit it faces like walls that block him but not stop him from movement.

```
public GameObject Player, middleObject;
public float high, upForce, speed;
public float PlayerDistance, AiX, AiZ, PlayerNum;
public Vector3 PlayerPlace,PrediactPlace;

void Update()
{

    Quaternion currentRotation = transform.rotation;
    Quaternion wantedRotation = Quaternion.Euler(0, 90, 0);
    transform.rotation = Quaternion.Lerp(currentRotation, wantedRotation, Time.deltaTime * 10);

    AiX = gameObject.transform.position.x - middleObject.transform.position.x;
    AiZ = gameObject.transform.position.z - middleObject.transform.position.z;

    if (PlayerNum == 0) // control it from inspector
    {
        Player = null;
    }
    else
    {

        Player = GameObject.FindGameObjectWithTag("GPlayer");
        PlayerDistance = Vector3.Distance(gameObject.transform.position, Player.transform.position);
        PrediactPlace = Player.GetComponent<PlayerCtrl>().Point.position;

        if (AiX <= 2 && AiZ >= -2 && AiZ <= 7 && AiZ >= -7)
        {
            transform.position = Vector3.Lerp(transform.position, PrediactPlace, Time.deltaTime * speed);
        }

    }

}

```

# Answer
> 1 votes
It looks like you want to clamp your destination position using Min/Max functions, then MoveTowards that location.

```
public PlayerCtrl player;
public Transform middleObject;
public float speed;
public float playerNum;

void Update()
{

    Quaternion currentRotation = transform.rotation;
    Quaternion wantedRotation = Quaternion.Euler(0, 90, 0);
    transform.rotation = Quaternion.RotateTowards(currentRotation, wantedRotation, Time.deltaTime * 180f);

    if (playerNum == 0) // control it from inspector
    {
        player = null;
    }
    else
    {
        Vector3 predictedPlace = player.Point.position;

        Vector3 offset = predictedPlace - middleObject.position;

        Vector3 halfExtents = new Vector3(2, 0, 7);
        Vector3 outer = middleObject.position + halfExtents;
        Vector3 inner = middleObject.position - halfExtents;

        Vector3 moveTarget = Vector3.Max(inner, Vector3.Min(predictedPlace, outer));

        transform.position = Vector3.MoveTowards(transform.position, moveTarget, Time.deltaTime * speed);
    }

}

```

---
Tags: unity
---


title: delaying enemy attacks

text:
# Question
Title: delaying enemy attacks
I have an enemy attack script that when a raycast hits the player it deals damage to the player, however the enemy attacks at multiple times per second and I wish for the enemy to have to wait 1 second after it attacks the player before it can attack again. The script is here, the main focal point is the `void update()`. Any help is appreciated, let me know if I've missed out any needed details. :)

```
public class DamagePlayer : MonoBehaviour
{
    int attackDamage = 10;

    [SerializeField]
    float agroRange;

    [SerializeField]
    Transform castPoint;

    Rigidbody2D rb2d;

    bool isFacingLeft;

    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();

    }

    bool CanSeePlayer(float distance)
    {
        bool val = false;
        float castDist = distance;

        if (isFacingLeft == true)
        {
            castDist = -distance;
        }

        Vector2 endPos = castPoint.position + Vector3.right * castDist;
        RaycastHit2D hit = Physics2D.Linecast(castPoint.position, endPos, 1 << LayerMask.NameToLayer("Action"));

        if (hit.collider != null)
        {
            if (hit.collider.gameObject.CompareTag("Player"))
            {
                val = true;

            }
            else
            {
                val = false;
            }

            Debug.DrawLine(castPoint.position, endPos, Color.red);
        }
        else
        {
            Debug.DrawLine(castPoint.position, endPos, Color.green);
        }

        return val;
    }

    // Update is called once per frame
    void Update()
    {
        if (CanSeePlayer(agroRange))
        {
            PlayerHealth.currentHealth -= attackDamage;
            //Debug.Log("can see player");
        }
        else
        {

        }
    }
}

```

# Answer
> 2 votes
1. Add a private variable to the script which represents the remaining cooldown time for the enemy attack.
2. Reduce that time in each `Update()` by `Time.deltaTime`
3. Only allow the enemy to attack when the cooldown is lower or equal than `0f`
4. When the enemy attacks, restore the value of that variable to the desired cooldown duration in seconds.

Example script:

```
public class DamagePlayer : MonoBehaviour
{
      public float attackCooldown; // Seconds between attacks
      private float attackCooldownLeft; // Seconds left until this object can attack again

      void Update() {
          attackCooldownLeft -= Time.deltaTime;
          if (attackCooldownLeft <= 0f && CanAttackPlayer()) {
               attackCooldownLeft = attackCooldown;
               DamagePlayer();
          }
      }

      private void CanAttackPlayer() {
         // Game-specific logic to determine if the mob should attack the player right now
      }

      private void AttackPlayer() {
         // Game-specific logic for performing one (1) attack on the player
      }
}

```

When your game has very high attack frequencies, then there might be occasions where the attack frequency is supposed to be higher than the current update frequency the user's device is capable of maintaining. In that case you should use the following code instead which allows multiple attacks in a single update. But note that it will enter an infinite loop if `attackCooldown` ever becomes 0 or negative for any reason (like you forgetting to set a value in the inspector), which means the game/editor will hang and needs to be killed via task manager, losing any progress since last time player/you saved the game/project:

```
      void Update() {
          attackCooldownLeft -= Time.deltaTime;
          while (attackCooldownLeft <= 0f && CanAttackPlayer()) {
               attackCooldownLeft += attackCooldown;
               AttackPlayer();
          }
      }

```

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


# Question
Title: How to customize player script with different abilities in each scene?
I'm making a game with Unity. I wanted the player script to not have some features in some scenes but couldn't remove them from the script because I needed them for other scenes.

So far, I just unpacked those player prefabs, created new scripts for each of them and removed the lines that I didn't want to have. I know this was not the best idea but I don't know any other way. One of its problems is that it makes managing the scripts hard and confusing.

Is there a way that I can change them without creating new ones? Since I'm going to switch to the new Input system, I want to avoid the possible problems and headaches around these scripts. I also did this (creating a new script) for pause menu script as well. I provided two examples below to make the situation more clear.

**Example A)** The player can use a shotgun in one of the scenes and I chose to not let him to use the knife in there. So I created a new script for that player and copied and pasted the original script (which had the melee attack ability) and then removed those lines from the new script.

**Example B)** Pause menu can disable the health bar game object whenever the escape button is pressed. But for one of the levels, I don't want to use the health bar, so I pasted the code in a new pause menu script and removed the line that disables the bar.

# Answer
Instead of copying everything else it is better to do the opposite. Separate the optional part in a different MonoBehaviour and add it only in the scenes you want.

For example make a component that disables the healtbar when pause is active and don't use it in scenes that you want health to remain (or does not exist). In other words try to not mix what a single MonoBehaviour does - pause menu should deal with its own stuff and shouldn't have to care about healthbars. The same way you can separate your abilities in different MonoBehviours and add the ones you want per level.

Yes you will end with more components to manage but you will be able to easily combine them for different end results.
> 3 votes

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


title: How to detect collisions in Unity ECS?

text:
# Question
Title: How to detect collisions in Unity ECS?
I am creating a game using the new Data-Oriented Tech Stack (DOTS).

I am using Entities with the PhysicsShape and PhysicsBody authoring components of the new Physics package. Some of my PhysicsShape have "Collison Response: Collide Raise Collision Events" set. Unfortunately the documentation of the new Physics system doesn't say anything about how I can detect and handle these collision events, and information on the Internet regarding this is very sparse and disorganized. How can I detect when one PhysicsShape collides with another one sending collision messages and run some code in that case?

# Answer
> 2 votes
> **Update:** This answer was originally written based on Version 0.51 of the physics system. The documentation of version 1.0 of the physics system has a chapter on processing collision detection events that shows a solution applying some of the new idioms. That article might be more helpful than this answer.

You can do this with a `JobComponentSystem` which schedules a job implementing `ICollisionEventsJob`\*. You also need to set that job as a dependency for the `EndSimulationEntityCommandBufferSystem` using `AddJobHandleForProducer`. Here is an example script:

```
using Unity.Burst;
using Unity.Entities;
using Unity.Jobs;
using Unity.Physics;
using Unity.Physics.Systems;
using UnityEngine;

public class CollisionSystem : JobComponentSystem {

    [BurstCompile]
    private struct CollisionJob : ICollisionEventsJob {
        public void Execute(CollisionEvent collisionEvent) {
            Debug.Log($"Collision between entities { collisionEvent.EntityA.Index } and { collisionEvent.EntityB.Index }");
        }
    }

    private BuildPhysicsWorld buildPhysicsWorldSystem;
    private StepPhysicsWorld stepPhysicsWorldSystem;
    private EndSimulationEntityCommandBufferSystem commandBufferSystem;

    protected override void OnCreate() {
        base.OnCreate();
        buildPhysicsWorldSystem = World.GetExistingSystem<BuildPhysicsWorld>();
        stepPhysicsWorldSystem = World.GetExistingSystem<StepPhysicsWorld>();
        commandBufferSystem = World.GetExistingSystem<EndSimulationEntityCommandBufferSystem>();
    }

    protected override JobHandle OnUpdate(JobHandle inputDeps) {
        JobHandle jobHandle = new CollisionJob().Schedule(
            stepPhysicsWorldSystem.Simulation,
            ref buildPhysicsWorldSystem.PhysicsWorld,
            inputDeps);
        commandBufferSystem.AddJobHandleForProducer(jobHandle);
        return jobHandle;
    }
}

```

Note that the physics system will usually generate multiple collision events on what appears to be just a single collision to the player. There is some debate about whether that's a bug or a feature.

<sub>* Yes, I am aware how useless this documentation article is right now. Hopefully it will get more useful in future versions of the documentation.</sub>

---
Tags: unity, entity-component-system, unity-dots
---


# Question
Title: How to use a Rigidbody on a game object after animation in Unity?
How to use a Rigidbody on a game object after animation in Unity?

I want to play an animation fully controlling the positioning of the elements, i.e. ignoring physics. And after an animation plays till the end I want physics to resume affecting the element.

Right now to get the expected behavior I have to remove the **Animator** after an animation. I thought that maybe there is a neater way to do what I want, but I did not find it, so decided to ask here.

**UPDATE**

I just found a better way to achieve what I want. Instead of removing the **Animator** component I just disable it:

```
animator.enabled = false;

```

It feels better. But still I am hoping for a neater solution.

# Answer
> 0 votes
To make physics affect rigidbody after playing an animation we can disable an animator.

One way to do that is through the animation event which would call a script, which would disable the **Animator**:

```
//get an animator instance in any way
//e.g. through a property or through the .GetComponent<Animator>()
animator.enabled = false;

```

Another way is to disable an animator from animation itself. The **Animator** enablement checkbox seems to be an animatable property. But so far I was not able to do that.

---
Tags: unity, physics, animation
---


# Question
Title: Can a MonoBehaviour be a private inner class?
I want to use a private inner class `MonoBehaviour` as part of the internal implementation of a class (also a `MonoBehaviour`). Reduced to the essentials:

```
public class OuterClass : MonoBehaviour {
  public void SomeMethod(GameObject go) {
    go.AddComponent<InnerClass>();
  }

  private class InnerClass : MonoBehaviour {
  }
}

```

**This appears to be all working absolutely fine, with no errors or warnings.** But it also appears to violate the statement in the Unity documentation that:

> The class name and file name must be the same to enable the script component to be attached to a GameObject.

Is this a problematic violation of that rule? If so, what are the problems? I am aware that it means the script is not visible in the Editor, but that's exactly what I want: it should never be added by anything other than its enclosing class.

# Answer
> I am aware that it means the script is not visible in the Editor

That is the consequence that the Unity documentation is warning you about.

> but that's exactly what I want: it should never be added by anything other than its enclosing class.

> This appears to be all working absolutely fine, with no errors or warnings

Then it sounds like you've considered and tested the possible pros and cons of this approach and concluded that it serves your needs.
> 1 votes

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


# Question
Title: How can I rotate the two endpoints of a line around the line's center in 3d?
The object is a capsule. I have the position of the object vector3, and the orientation of the object, a quaternion. I want to construct a line which goes through the middle of the capsule with the two endpoints of the line being the top and bottom.

The capsule can be rotated in all 3 dimensions.

# Answer
Assuming your capsule is aligned along the y axis, it could look something like this:

```
top = centerPosition + orientation * (new Vector3(0, halfHeight, 0));
bottom = centerPosition + orientation * (new Vector3(0, -halfHeight, 0));

```

(Here I'm assuming `quaternion * vector` is evaluated as \\$q v q^{-1}\\$, rotating the vector by the quaternion)
> 1 votes

---
Tags: 3d, mathematics, rotation, quaternion
---


# Question
Title: How can I disable an Animator from the Animation in Unity?
How can I disable an **Animator** from the **Animation** in Unity?

The **Animator** enablement checkbox seems to be highlighted, which makes me believe that the enablement of the **Animator** is an animatable property itself. But whenever I try to animate it the enablement toggling just does not get recorded onto the animation line.

It feels like I am missing something here. If someone notices me doing something wrong, could you, please, point it out.

# Answer
When you use the animation time-line, Unity will automatically disable the animator component, even if you aren't trying to modify it. Try implementing the animation and then seeing if it will work.
> 1 votes

---
Tags: unity, animation, animator
---


# Question
Title: Adding physics to a Blueprint actor in UE4
I am trying to create a dice in ue4 and be able to read off what value it gives. I've made a mesh in Blender and created a texture, imported them and created a blueprint actor and added the static mesh to it.

When I start the game the dice just floats in the air and isn't affected by gravity. I have tried just using the static mesh and I can get that to be affected by gravity. However, I need to add scripts to the object so I can give it a random rotation and read its value, so I created a blueprint actor. I've looked online for a way to give this actor physics, nut nothing.

Does anyone know how I can add physics to a blueprint actor?

Also if anyone has any info on giving the actor a random rotation and reading the value of the dice that would be great.

# Answer
> 2 votes
What you're looking for is a checkbox titled 'Simulate Physics'. If you open up the blueprint for the actor you created and click on the static mesh component you will see it in the details panel. When this box is not selected your Actor is kinematic- meaning that it ignores physics and only moves when and where you tell it to, when you select this check box physics forces are applied to the Actor and it will no longer float in the air.

When you imported the object, if you didn't check the'auto-generate collision' box in the import options window you might not be able to check the 'Simulate Physics' box, in which case you would need to open up the static mesh editor and add a collider to it manually. I believe 'auto-generate collision' is enabled by default though so if you didn't change the setting you shouldn't have any problems.

Look into the SetActorRotation and GetActorRotation nodes, and the RandomIntFromRange node to supply a random rotation to the Actor.

# Answer
> 0 votes
Here's a supplemental answer for anyone looking to add "Simulate Physics" on the fly to an actor via a blueprint function, and perhaps the search results brought you here based on the title of this posting. There is a function called "Set Simulate Physics" which enables you to do exactly that.

---
Tags: physics, unreal-4, rigid-body-dynamics
---


# Question
Title: How do I access objects that are in the next scene I'm loading?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class HouseExit : MonoBehaviour
{
    public Transform player;

    public void Houseexit()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.CompareTag("Player"))
        {
            Houseexit();
            GameObject.Find("Wizard").transform.position = GameObject.Find("SpawnPos").transform.position;
        }
    }
}

```

This code belongs to the scene "Goblin House 1" and I'm trying to find the wizard and the spawn position both from level 1.

# Answer
> 1 votes
`LoadScene()` does not instantly load the new scene before the function returns.

It can't, not least because part of the work of loading the new scene, when you're not using additive scene loading (which you aren't, in this case), is *deleting everything from the previous scene*.

But your `HouseExit` script is still running its collision handler, so we can't delete it yet.

So when you call `LoadScene()` like this, what you're really doing is *requesting* the new scene to be loaded *at the end of this frame*, after the current scene has been unloaded.

Doing it that way, the `HouseExit` script is long gone before the wizard or spawn point exist. So trying to manipulate objects in the future from an object in the past just does not make sense.

Instead, you can think about saving a note for the newly loaded scripts to read when they load. Let's say we do something like this...

```
public class SpawnPointPicker : MonoBehaviour {

    static string _nextSpawnPointName;

    public static void SetSpawnPoint{string name} {
        _nextSpawnPointName = name;
    }

    void Start() {
        if (string.IsNullOrWhiteSpace(_nextSpawnPointName)) {
            Debug.Log("No spawn point set. Staying in default position.");
            return;
        }

        var spawnPoint = GameObject.Find(_nextSpawnPointName);

        if (spawnPoint == null) {
            Debug.LogWarning($"No spawn point found with name {_nextSpawnPointName}.");
            return;
        }

        transform.position = spawnPoint.transform.position!
    }
}

```

Your `HouseExit` script can now call `SpawnPointPicker.SetSpawnPoint()` to set the name of the point where the wizard should spawn *the next time it loads*.

Put an instance of this `SpawnPointPicker` component on your wizard. When it loads, it will look up this saved spawn point name and try to move itself to a corresponding object.

This way, we can use the `static` variable to retain information between scenes and send the information about where to spawn into the future where it will be needed, rather than trying to time travel from an object that was destroyed in the past.

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


# Question
Title: How to justify text that appears character-by-character
I'm currently using the latest version of phaser framework and I have a problem to which I haven't been able to figure out how to approach.

I need to have a block of text appear letter by letter and also be justified as a block. (I'm working on a text-based game project).

Text typed letter by letter is functional, but my issue is with justification: it has issues like some words first appearing on a line and then being removed and placed in the next line.

This is my code so far:

```
    addTextParagraph(text) {
    //  We check the current GAME STATE.
    //  During exploration (SCOUTING_STATE), text is in typewriter mode.
    if (gameState === SCOUTING_STATE) {
      this.typewriteText(text);
    }
  }

  typewriteText(text) {
    let delayedCallback;
    let length = text.length;
    let i = 0;

    this.time.addEvent({
      callback: () => {
        this.textParagraph.text += text[i]
          ++i
        // Callback after typewriter text is complete.
        // Delay before the choices appear in the screen (in ms)
        if (i >= length) {
          i = 0;
          delayedCallback = this.time.delayedCall(200, this.addChoiceArray, [], this);
        }
      },
      repeat: length - 1,
      delay: 40,
    })
  }

```

Thanks.

# Answer
I don't know what functionality Phaser offers, so this answer is abstract, but in general you *must* lay out the *full* text (or at least the entire next word for ragged-right and the entire next paragraph for full-justified text) to get consistent layout.

One way to approach this, if you're not managing layout and drawing yourself, is to treat this as **styled text**: all the text you don't want to show yet exists but is styled to be invisible (fully transparent, or color the same as the background).
> 2 votes

---
Tags: text, phaser
---


title: rendering transparent meshes in LibGDX

text:
# Question
Title: rendering transparent meshes in LibGDX
Building open this tutorial - https://code.google.com/p/libgdx/wiki/ProjectionViewportCamera I have constructed a class for generating polygon meshes. But i cannot figure out how to render semi transparency, even though the mesh in the tutorial takes a color object with an alpha channel.

I am rendering with `squareMesh.render(GL10.GL_TRIANGLE_STRIP, 0, 4);` This is the code used for initializing the mesh

```
if (squareMesh == null) {
    squareMesh = new Mesh(true, 4, 4,
                 new VertexAttribute(Usage.Position,    3, "a_position"),
                 new VertexAttribute(Usage.ColorPacked, 4, "a_color"));

    squareMesh.setVertices(new float[] {
        -0.5f, -0.5f, 0, Color.toFloatBits(128, 0, 0, 255),
         0.5f, -0.5f, 0, Color.toFloatBits(192, 0, 0, 255),
        -0.5f,  0.5f, 0, Color.toFloatBits(192, 0, 0, 255),
         0.5f,  0.5f, 0, Color.toFloatBits(255, 0, 0, 255) });
    squareMesh.setIndices(new short[] { 0, 1, 2, 3});
}

```

# Answer
> 1 votes
In Color.toFloatBits(128, 0, 0, 255), the "255" is the alpha channel (where 255 means completely opaque and 0 means completely transparent = invisible).
Make sure you've enabled transparency in OpenGL with

> Gdx.gl.glEnable(GL10.GL\_BLEND);
> Gdx.gl.glBlendFunc(GL10.GL\_SRC\_ALPHA, GL10.GL\_ONE\_MINUS\_SRC\_ALPHA);

to disable transparency again, simple use `Gdx.gl.glDisable(GL10.GL_BLEND);`

# Answer
> 0 votes
I found that ModelBatch.begin(...) will disable Blending by calling Gdx.gl.glDisable(GL20.GL\_BLEND). So make sure to enable blending AFTER calling ModelBatch.begin().

```
modelBatch.begin(camera); // resets Blending to false
// enable Blending
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
// draw mesh
mesh.render(shader, GL20.GL_TRIANGLES);
modelBatch.end();

```

---
Tags: java, opengl-es, libgdx, transparency
---


# Question
Title: How to orient hands(or spine) to always look at some target?
I am building an FPS game in Unity 3D everything was going cool but when I tried to implement aiming for the rifle everything just broke.

1): I have an IK setup which triggers when you equip weapon, this IK only calculate the hand position and orientation needed to hold the gun and after that the IK system disables itself, basically I am using IK for getting the proper hand position on different guns.

2): Once hands are positioned correctly on the gun then I rotate the hands(or spine, which will rotate hands and head with it) with the mouse to look up, down, right and left.

3): Handgun is very easy to handle, equip it and rotate the arms, arms are almost straight along the z-axis so I just rotate them on the y-axis to aim upward and downwards.

4): With the rifle, I can calculate the hand position and rotation to hold the rifle easily but (because static animation pose of holding he rifle is little oriented to make the player little realistic) when I rotate arms they rotate weirdly.

I checked in the editor by changing the y-axis of the rotation and found that only y-axis can't rotate the arm the way I want and to rotate it that way other axis must change their values. I searched a bit and found that it is a situation called as Gimbal Lock which is very common with euler rotations, I tried many things but still can't fix it.

Original Code:

```
        leftArm.transform.localEulerAngles = new Vector3(leftArm.transform.localEulerAngles.x,
        leftArm.transform.localEulerAngles.y + (currentCamRotX + offset),
        leftArm.transform.localEulerAngles.z);

        rightArm.transform.localEulerAngles = new Vector3(rightArmFPS.transform.localEulerAngles.x,
        rightArmFPS.transform.localEulerAngles.y + (currentCamRotX + offset),
        rightArmFPS.transform.localEulerAngles.z);

```

It works great with Handgun but not with Rifle.

I read about and tried following but in vain:

```
    //Method 1: Failed
    var target = camera.GetChild(0).GetChild(0);
    var direction = target.position - rightArmFPS.position;
    var toRotation = Quaternion.FromToRotation(rightArmFPS.up, direction);
    rightArmFPS.rotation = Quaternion.Lerp(rightArmFPS.rotation, toRotation, Time.deltaTime * 5);

    //Method 2: Failed
    var targetForward = target.position - spine.position;
    targetForward.Normalize();

    var rotAxis = Vector3.Cross(Vector3.forward, targetForward);
    var angle = Mathf.Acos(Vector3.Dot(Vector3.forward, targetForward)) * Mathf.Rad2Deg;

    spine.eulerAngles = rotAxis * angle;

```

What I am looking for now is if someone can point me what topic I should be looking in(because my poor maths skills are really getting me and I often use very poor workarounds for what could be solved easily with maths or physics), pseudo code to get me started or anything that might help me resolving this issue.

I know there are bunch of other ways to achieve what I am looking for and I have tried many of them like: using IK to position hands and then moving the guns up or down or having animations for each gun aiming up or down but honestly each method has it's own drawback(or its just me who is too noob for these things).

I followed this solution: Orienting a model to face a target

and many others, you might find it duplicate but none of the post on the internet has solved my problem(it is second day and I still can't figure this out).

Hope you understood the question and thanks for reading this:)

# Answer
is your code in LateUpdae, also have you thought of using a asset? I use FinalIK

I know it's expensive but I wouldn't be without it.

If you go to that link then in there you will find another link to the forum, great people there, helped me out loads ..
> 0 votes

# Answer
Perhaps transform.LookAt(othertransform) might be suitable. This orients the z-Forward axis to point at the other transform.

This doesn’t affect the position.

If your spine has a non z-forward axis, you might need to then rotate it immediately after that by some known amount. To offset this original rotation

Also if you only want to rotate about the y axis, you can always reset your X and z rotations back to their original values after doing the lookat.
> 0 votes

---
Tags: unity
---


# Question
Title: In today's video game industry, why isn't every game released on PC?
In this day and age, you absolutely must use a computer to make a video game; and, no, "users making their own content using our editor built into the game itself" doesn't count. I'm talking about the base game that you purchase to use that editor.

Given that you *made* the game using a computer and special hardware is required to test/run it on anything else (PS4/5 Dev machines, etc). Why do games come out on, say, *just* a console? The basic testing prior to copying files over to a console for specific-issue testing is performed on a computer, programming is done on a computer, *compiling* is done on a computer, etc.

You actually have to do **more** work to release something exclusive to a console.

So, to re-iterate, why aren't games always released for home computers?

# Answer
> 4 votes
Consoles have their advantages. You know exactly what hardware and software environment your game is going to run in. No targeting a huge array of combinations of GPUs (which might or might not have up-to-date drivers), CPUs and amount of memory players might have, no testing on different operating systems or versions of the same operating system, no supporting different screen resolutions (the boon of every UI designer), no weird programs running in the background which might interfere with your game, you even know exactly what controller the player is going to use. That makes a lot of things a lot simpler.

But that being said, it's quite frequent that console manufacturers make deals with game developers so they release the game specifically on their console. Especially when that console is new, and they need a couple high-profile exclusive titles as system sellers. A console is only as good as its game library. A very hyped game being available on only one console can convince a lot of people to buy that console just so they can play that game.

# Answer
> 0 votes
Consoles are made specifically for gaming and as such it's tied to user experience. Since every single PC is different it's hard to predict or control that aspect and the games title will suffer as a result. I've always wondered why Sony never made a PC compatible CD drive and that's largely due to market share.

Expanding on the user experience any serious PC gamer can tell you that you constantly have to do upgrades and with consoles there are no technical attachments and even some portability to a degree

---
Tags: game-industry, pc, release
---


title: How to handle objects on 2D Map

text:
# Question
Title: How to handle objects on 2D Map
I am making a 2D RPG game in Monogame XNA. For the moment I have 2 kinds of data in my game: sprites objects and tiles.

All the sprites are contained in a array list. I iterate over the sprites ArrayList to update and draw each sprites. Sprites objects are sort by their Y positions before each draw. This way, my character and other enemies can walk behind sprites. Sprites can be anything that require player interaction for example: chest, tree, enemy, player…

Tiles represent inanimate objects(2D array) (object that you cannot interact with) and only used for collision data and have a basic animation system.

However, for sprites collision checking I have to iterate over every sprites to do a bounding box overlap check.

My system works well, but I want to simplify things. What if I store static objects in my 2D tile array? I could just do `getTile(x,y)` to get the object stored in that position instead of going through my array list.

In the future I would like to have several types of objects, weapons, projectiles, and I want a consistent way to organize this.

# Answer
Since your question is a bit vague, I'll reply with an anecdote.

In the early 2000s, there were some graphics libraries but not that many game engines, so we hobby game devs wrote that stuff ourselves. With tile-based maps and sprites/objects on top, a common hint was to store the objects as part of the tile map to limit what needs to be drawn on screen. After all, it's simple to compute the visible portion of the 2D tile map on screen as `minX/Y` and `maxX/Y` of the tile map when you multiply the `scrollOffsetX/tileSize` and `screenWidth/tileSize`.

Now imagine that NPC positions are tile-based and each map tile knows which NPC stands on it; then you can draw the visible part of the tile map as a backdrop and then all visible NPCs on top. What's not on screen is skipped.

Having this information means you can also limit the collision checks. Player moves left? Peek at the tile position left of the player and see if there's an NPC blocking the space, or a collision 'flag' set, e.g. for walls.

So all in all, relying on the tile map and storing more information for each tile than which imge needs to be painted is totally viable.

This also works when you make characters move "in between tiles". It can work with the same base approach, but needs tweaking to position sprites at `tileX/tileY` plus an offset relative to the tile on screen.

Example: your tiles are 16x16 pixels. Your player character starts at the tile coordinates X=10, Y=20. On the screen, that means `playerX=tileX*tileSize=10*16=160` and `playerY=tileY*tileSize=20*16=320`. Now the player moves 8px to the right. Then you store the `8` as an offset relative to the tile origin and factor this in. `playerX=tileX*tileSize+offsetX=10*16+8=168`.

If the player moves 16 instead of 8 pixels, check for `offsetX >= tileSize`, and if true, advance one tile `tileX += 1` and reset the offset `offsetX = offsetX % tileSize`.

So yes, it works to store everything as tile info, and it can also help keeping the logic simple.
> 0 votes

---
Tags: xna, tilemap, rpg
---


# Question
Title: Simulation step size in a physics engine
I am trying to integrate a physics engine (Bullet) into my game engine, but I immediately found that I do not know how big should I make the simulation step. I think of 2 options:

1. Use a fixed step size of 1/60. This way I have consistent simulation. Bullet allows making multiple steps when this time is exceeded. I think this is good for consistent simulation but I think it has a big flaw and that is that position of objects will not update when my framerate is higher than 60FPS. Right now I have around 1000 FPS but it will drop significantly to around 150 I expect because I use simple materials and not many objects plus the simulation time is not included yet. Is it possible to interpolate between steps so that 2 frames are always different but check for collisions only when 1/60 of a second passed?
2. Update physics every frame but when frame time is longer than 1/60 then use substeps. This way I should be able to get more precision but it would lower framerate because the step is performed more than 60 times per second. I definitely get the new position of the object in every frame.

Which is a better approach and why? Is there a standardized way to go about it?

I know that when slow-motion footage of CSGO is taken in every frame the position of the object change but the tick rate is just 64. Which would not update the position in every one of the 240 frames monitors can handle and duplicate frames would be created. I know that animation can be sampled at any point in time but not the position of the objects. How is that achieved?

# Answer
> 1 votes
To close this question I will take what Vaillancourt said in the comment. This article perfectly describes how to handle physics steps.

And to clarify my other question whether we interpolate between actual and previous physic state then yes we do. It is nicely explained in this post.

Edit:
Because those links can expire I will summarize the most important information here. First, how big should the steps be? They should always be the same size. You can choose whatever number you want but the smaller the more precise it will be in exchange for computing time. But the trick is that you do not want to match frames with steps. I think this code is quite explanatory:

```
double t = 0.0;
const double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

while ( !quit )
{
    double newTime = hires_time_in_seconds();
    double frameTime = newTime - currentTime;
    currentTime = newTime;

    accumulator += frameTime;

    while ( accumulator >= dt )
    {
        integrate( state, t, dt );
        accumulator -= dt;
        t += dt;
    }

    render( state );
}

```

We do as many steps as we can until we would exceed the current time. Which is easy to implement.

The second link explains how to have objects moving even between steps. We cannot extrapolate the movement because we could experience stutter when a collision accures. That is why we have to interpolate between actual physics state and the last physics state using linear interpolation. This allows for smooth motion in exchange for 1 step delay. But because steps are usually 1/60 of second long we do not percieve it much.

---
Tags: physics-engine, bullet-physics, timestep
---


title: Why does my object rotate too fast?

text:
# Question
Title: Why does my object rotate too fast?
```
IEnumerator MoveBack()
{
    yield return new WaitForSeconds(3f);

    float t = 0;
    float duration = 30f;
    while (t < duration)
    {
        t += Time.deltaTime;
        player.rotation = Quaternion.Slerp(player.rotation,
           Quaternion.Euler(player.rotation.x, player.rotation.y + 90f, player.rotation.z),
           t / duration);
        yield return null;
    }
}

```

If I set the `duration` to 0.1f, it will rotate too fast to see.

But also if I set `duration` to 30 it's still not rotating that slow.

Should a lower `duration` value rotate more slowly, or more quickly?

30 seems almost fine, but is it sensible to set the value so high to make it rotate a bit slower?

# Answer
This becomes obvious if we walk through the loop step by step. Let's say your duration is 1 second, we're running at 30 FPS, and the object starts with Euler angles (0, 0, 0):

* On the first loop, we blend between (0, 0, 0) and (0, 90, 0) by a factor of 1/30. 0 + (90-0)\*1/30 = 0 + 90/30 = 0 + 3, so that brings us to the angles (0, 3, 0)
* On the second loop, we blend between (0, 3, 0) and (0, 93, 0), by a factor of 2/30 (your starting and ending points are both re-calculated from where we are now, and your `t` value accumulates every loop). 3 + (93 - 3)\*2/30 = 3 + 90/15 = 3 + 6 = 9, so that brings us to the angles (0, 9, 0)
* On the third loop, we blend between (0, 9, 0) and (0, 99, 0) by a factor of 3/30, bringing us to (0, 18, 0)
* On the fourth loop, we blend between (0, 18, 0) and (0, 117, 0) by a factor of 4/30, bringing us to (0, 30, 0)

And so on. Our step size grows linearly with time, because we're changing both the blend factor and the endpoints we're blending between.

It looks like you meant to write something more like this:

```
Quaternion start = player.rotation;
Quaternion end = Quaternion.Euler(0, 90, 0) * player.rotation;

for (float t = 0; t < 1f; t += Time.deltaTime/duration) {
    player.rotation = Quaternion.Slerp(start, end, t);
    yield return null;
}
player.rotation = end;

```

Note that we cache our starting and ending points up-front, so they stay fixed in place, and only `t` changes as it blends us from 0 (all the way at `start`) to 1 (all the way at `end`).
> 2 votes

---
Tags: unity, c#, rotation, lerp
---


# Question
Title: What's a code-efficient way to go about DB objects, DTO objects and actual objects?
Currently I have 3 different classes for the same type of entity. One is the main class that contains logic and everything the entity needs. Then I have a DB object, that has the same structure as the entity inside the database. The third is a data transfer object (DTO) that only contains the values the client is supposed to know about.
Now whenever I add a variable, I have to add the variable in all 3 classes and copy the DTO class over to the client too. Also, I have to add the variable to each converter method, that creates the DTO and DB objects from the main object and need to add a check to the DTO converter, so that I can differentiate which variables actually need to be updated to lessen the network usage. It's a huge mess and the bigger those classes become, the more I hate my current approach.
What's a smarter approach to this? Maybe there is a way to use C# attributes, but before I try to learn about how to make my own and implement it, I'd love to know if it's even a good choice.

**edit 1**:

following method checks which values have been updated and not sent to the client yet and returns a new DTO object to send, if the client is not up-to-date. The DTO object is serialized to json and sent as a string. Then its deserialized on the client and the client checks for valid values to know which one to update:

```
public CharacterDTO GetNetworkDTOValues()
{
    bool shouldUpdate = false;
    CharacterDTO returnDTO = new CharacterDTO();

    if (_clientInstance == null)
    {
       _clientInstance = new CharacterDTO();
    }
    if (_clientInstance.Level != Level)
    {
       returnDTO.Level = Level;
       shouldUpdate = true;
    }
    if (_clientInstance.Experience != Experience)
    {
       returnDTO.Experience = Experience;
       shouldUpdate = true;
    }
    if (_clientInstance.Life != Life)
    {
       returnDTO.Life = Life;
       shouldUpdate = true;
    }

    [...] (there are around 30 more variables)

    if (shouldUpdate)
    {
       _clientInstance = CreateDTO(this);
       return returnDTO;
    }

    return null;
}

```

# Answer
Using DTO solely to convert to and from JSON means given DTO defines a JSON *shema*. Good news is that JSON can work without (explicitly defined) schema just fine and JSON does not care what class to serialize from / deserialize to — which allows to **map JSON to a dictionary** (and back).

It means you can get rid of a DTO entirely. Moreover, if de/serialization is as straightforward as simply copying selected fields, you can entrust serialization to JSON framework: just annotate fields that you want to be skipped. For more complex conversions you can define custom converters.

Mapping database entities directly into game objects certainly has a code smell to it, because it pokes a leak in a neat onion architecture. Just remember that you are taking technical debt here.

As for diffing, try diffing serialized JSON. Would it prove being too slow, try double-buffering next: maintain a second copy of a DB object, do a CLR diff and propagate it to a JSON dump.
> 1 votes

# Answer
It looks to me like you could accomplish a lot of this by re-using a common struct between the client instance, the on-the-wire data, and the server instance.

```
public class Character {

    // Data that needs replication over the network.
    public struct DTO {
        public int level;
        public int experience;
        public int life;
        // ...etc.
    }

    DTO _replicated;

    // Client-only data;
    int _localIndex;
    // ...etc.
}

```

When you need to add a new variable to `Character`, if it's one that needs to be replicated, you add it (once) to the `Chatacter.DTO` struct, and access it via `_replicated.newVariableName`.

When you need to send something over the wire, you can grab the whole `_replicated` struct as a unit, rather than fishing out one variable at a time.

Then on your server, you can do something like this...

```
public class ServerCharacter {
    // Data to replicate.
    Character.DTO _clientSnapshot;
    Character.DTO _liveData;

    // Private server data.
    uint _databaseID;
    // ...etc.

    public bool ShouldSendDTO(ref Character.DTO dataToSend) {
        if (_clientSnapshot == _liveData)
            return false;

        _clientSnapshot = _liveData;
        dataToSend = _liveData;
        return true;
    }
}

```

As long as your struct is set up correctly, no references or padding, the default comparison operator will do a fast memory compare of the two instances' bits, without you having to check and assign each variable one by one.

You could likely even implement this generically with an `unmanaged` type constraint to both enforce the no-references rule and save you some repeated code.
> 0 votes

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


# Question
Title: Button onClick in a menu prefab doesn't work
I don't seem to be able to make a reference to a Button inside a menu prefab.

My menu prefab consists of a panel and the panel has 4 buttons.

I added

```
public GameObject prefabMenu;

```

in my code and drag and dropped the prefab in the Unity Editor to it.

When my scene is starting (`Start()` method) I instantiate this prefab into a GameObject like this:

```
panelMenu = Instantiate(prefabMenu, canvas.transform);

```

after that I try to refer one of the buttons with this line and set an `onClick` listener:

```
btnResume = panelMenu.transform.Find("BtnResume").GetComponent<Button>();
btnResume.onClick.AddListener(() => Log.I("Working"));

```

The log method however doesn't not get called when I click on the button (I checked and the `btnResume` is not null).

I appreciate any help on this. Thank you.

# Answer
1- first check is your event system object present in the Hierarchy if yes then create a button check its working or not if working fine then its your button problem either it can be due Raycast or some other UI object over that button.

2- second try is that assign a function from editor to that button if its working then your event subscribing (onclick event) is in problem..
> 0 votes

# Answer
To have click events in a prefab try to use `IPointerClickHandler` interface.
> -1 votes

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


# Question
Title: How can I create a musical sheet using sprites?(Ocarina of time )
I am looking to make a musical sheet similar to the image below:

I want to:

* use sprites prefabs
* have each sprite correspond to a different line
* Move down notes are more are being played
* have tail end notes disappear or go outside of text view (like when you type past a search bar)

I am unsure if there is a UI asset in Unity that can perform what I just mentioned. I was thinking could just instantiate the prefabs in the right positions, shift them down, then delete the tail end prefabs as more are being played. Outside of that, I'm lost.

# Answer
> 0 votes
Decided to forego the UI approach and instead used a game object with four empty children used positions. I use 1 sprite to make up the display and have others spawn on the display. Then I just set two colliders at the end of each end of the display to push back notes and despawn others.

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


# Question
Title: Help finding bug in seperating axis theroem code
My collision detection is inconsistent. I am testing between 2 rectangles. When they are un-rotated, it says they are intersecting way before they touch, but when I rotate one, it works properly. I do not understand why.

When rect1 is rotated 0 or 180 degrees it starts saying collision detected about one rect width apart, but when its rotated at a non 90 degree angle, it works properly.

        // storing rotated points in lists for easy looping to avoid duplicate code
        FixedList512<float2> points1 = new FixedList512<float2>();
        points1.Add( bl_r );
        points1.Add( br_r );
        points1.Add( tl_r );
        points1.Add( tr_r );

        FixedList512<float2> points2 = new FixedList512<float2>();
        points2.Add( bl_r2 );
        points2.Add( br_r2 );
        points2.Add( tl_r2 );
        points2.Add( tr_r2 );

        bool intersects = true;

        for ( int shape = 0; shape < 2; shape++ )
        {
            if ( shape == 1 )
            {
                var temp = new FixedList512<float2>();
                temp.Add( bl_r );
                temp.Add( br_r );
                temp.Add( tl_r );
                temp.Add( tr_r );

                points1 = points2;
                points2 = temp;
            }

            for ( int a = 0; a < points1.Length; a++ )
            {
                int b = ( a + 1 ) % points1.Length;
                float2 axisProjection = new float2( -( points1[ b ].y - points1[ a ].y ) , points1[ b ].x - points1[ a ].x ); // invert points for normal to line segement

                float minR1 = float.MaxValue;
                float maxR1 = -float.MaxValue;

                for ( int p = 0; p < points1.Length; p++ )
                {
                    float q = points1[ p ].x * axisProjection.x + points1[ p ].y * axisProjection.y; // dot product of current point and axis of projection
                    minR1 = math.min( minR1 , q );
                    maxR1 = math.max( maxR1 , q );
                }

                float minR2 = float.MaxValue;
                float maxR2 = -float.MaxValue;

                for ( int p = 0; p < points2.Length; p++ )
                {
                    float q = points2[ p ].x * axisProjection.x + points2[ p ].y * axisProjection.y; // dot product of current point and axis of projection
                    minR2 = math.min( minR2 , q );
                    maxR2 = math.max( maxR2 , q );
                }

                if ( !( maxR2 >= minR1 && maxR1 >= minR2 ) ) // break if points dont overlap as we dont have a collision
                {
                    intersects = false;
                    break;
                }
            }
        }

        if ( intersects )
        {
            Debug.Log( "Intersects" );
        }
```
</code></pre>

# Answer
I ended up fixing the problem. Here is my implementation if anyone is interested. As dmgregory pointed out, I was ordering my vertices in z order fashion, silly mistake.

<pre><code>    private void PolygonPolygonSAT( List<float2> verts1 , List<float2> verts2 )
    {
        List<float2> axes = new List<float2>();
        float smallestOverlap = float.MaxValue;
        float2 MTVAxis = float2.zero;

        for ( int i = 0; i < verts1.Count; i++ ) // collect the axes to project points on, these axes are the normals to each edge of each polygon
        {
            float2 v1 = verts1[ i ];
            float2 v2 = verts1[ i + 1 == verts1.Count ? 0 : i + 1 ];

            float2 projectionAxis = new float2( -( v2.y - v1.y ) , v2.x - v1.x ); // get the normal of the edge
            axes.Add( projectionAxis );
        }

        for ( int i = 0; i < verts2.Count; i++ ) // repeat for polygon 2
        {
            float2 v1 = verts2[ i ];
            float2 v2 = verts2[ i + 1 == verts2.Count ? 0 : i + 1 ];

            float2 projectionAxis = new float2( -( v2.y - v1.y ) , v2.x - v1.x );
            axes.Add( projectionAxis );
        }

        for ( int i = 0; i < axes.Count; i++ ) // now, loop through all projection axes and project each edge onto it
        {
            float2 axis = axes[ i ];

            float min1 = float.MaxValue; // keep track of the minumum and maximum projected points
            float max1 = float.MinValue;

            for ( int p = 0; p < verts1.Count; p++ )
            {
                float q = verts1[ p ].x * axis.x + verts1[ p ].y * axis.y; // the projection is the dot product of the edge and the projection axis

                min1 = math.min( min1 , q );
                max1 = math.max( max1 , q );
            }

            float min2 = float.MaxValue;
            float max2 = float.MinValue;

            for ( int p = 0; p < verts2.Count; p++ )
            {
                float q = verts2[ p ].x * axis.x + verts2[ p ].y * axis.y;

                min2 = math.min( min2 , q );
                max2 = math.max( max2 , q );
            }

            float overlap = LineOverlap( min1 , min2 , max1 , max2 ); // return the amount of overlap

            if ( overlap <= 0 ) // if there is no overlap then we know no intersection and break
                return;

            if ( overlap < smallestOverlap )
            {
                smallestOverlap = overlap;
                MTVAxis = axis;
            }
        }

        // now we get the direction of the MTV and multiply it my the overlap/2 to get the displacement for both shapes
        float2 dir = new float2( polyPos2.x , polyPos2.z ) - new float2( polyPos1.x , polyPos1.z );
        if ( math.dot( MTVAxis , dir ) <= 0 )
            MTVAxis *= -1;

        MTVAxis = math.normalize( MTVAxis );

        float2 displacement1 = -( MTVAxis * smallestOverlap ) / 2;
        float2 displacement2 = ( MTVAxis * smallestOverlap ) / 2;

        polyPos1 = new float3( polyPos1.x + displacement1.x , polyPos1.y , polyPos1.z + displacement1.y );
        polyPos2 = new float3( polyPos2.x + displacement2.x , polyPos2.y , polyPos2.z + displacement2.y );

        Debug.Log( "Intersects" );

    }
    private float LineOverlap( float min1 , float min2 , float max1 , float max2 )
    {
        float _min1 = math.min( max1 , max2 );
        float _max1 = math.max( min1 , min2 );
        float diff = _min1 - _max1;

        return math.max( 0 , diff );
    }
```

> 0 votes

---
Tags: collision-detection, separating-axis-theorem
---


title: Puzzle design in Adventure games

text:
# Question
Title: Puzzle design in Adventure games
Creating interesting, original, logical, thoughtful puzzles is an art.

What techniques and methods do you use to create good puzzles?

Do you write storyline before designing puzzles or combine these 2 processes?

# Answer
Some general inspiring approaches to create puzzles:

1. One possible inspiring method is to use puzzle classifications.
Adventure UML (Visual representation)
Adventure UML (Source article)
Mark Newheiser's classification
"Making Better Puzzles" by Stephen Granade

All these classifications can be used to stimulate your creativity and brainstorming.
2. TRIZ - "a problem-solving, analysis and forecasting tool derived from the study of patterns of invention in the global patent literature". It was developed by Soviet engineer and researcher Genrich Altshuller and his colleagues, beginning in 1946. In English the name is typically rendered as "the theory of inventive problem solving", and occasionally goes by the English acronym "TIPS".

TRIZ is variously described as a methodology, tool set, knowledge base, and model-based technology for generating new ideas and solutions for problem solving. It is intended for application in problem formulation, system analysis, failure analysis, and patterns of system evolution. Splits have occurred within TRIZ advocacy, and interpretation of its findings and applications are disputed. TRIZ (wiki)
3. Edward de Bono's methods of creative thinking. Edward de Bono (wiki)
> 16 votes

# Answer
I prefer to design a situation, model it as accurately as I can, and allow as many standard manipulations as I can, and let problems and solutions emerge intrinsically and appropriately.

Early examples included Infocom's *Suspended* and FTL's *Dungeon Master*, though they were a mix of scripted puzzle logic and semi-realistic game systems.
> 3 votes

# Answer
An interesting way to design puzzles is through abstraction - look at objects around your home or elsewhere and think about how they interact with each other, how they can be manipulated and how they could benefit a goal or aim.

Don't forget to think in three dimensions, as this will help with the design of the puzzle space.

Puzzles can be about a whole variety of things applicable to simple day-to-day living. Some examples: shape, colour, memory, logic, primitive maths (addition, subtraction, multiplication and division), sound, depth, light, interaction of lifeforms.

Be sure to tie your puzzles in with the game world and the immersion of the game itself and you will have some thoroughly engaging mind-bogglers.
> 3 votes

# Answer
Experiment. Think about puzzle games you have played that come packaged with a level editor. How would you create a new puzzle using their tool?

Usually by experimenting you can find interesting interactions between puzzle elements.

Working backwards is also a very intuitive way to create puzzles of any sort. I would imagine this is the most common technique. When you know the answer it is easy to build complexity on top of it.

Think of IQ puzzle designers. If I give you a sequence 1,9,25,49,*_* and ask you what is next you have to use logic to determine what is going on. Where as from the designers point of view it is just matter of making something up that takes no logic at all: ((n\*2)-1)^2

So, I would suggest building a tool to edit levels / elements / etc in your game. Experiment yourself, and allow other designers to experiment. You will see interesting patterns emerge.
> 3 votes

# Answer
Adventure games rely heavily on the same motivations as readers or viewers of books or film. For this reason I'd recommend taking a look at the chapters on the section on the inciting incident and the principle of closing the action-expectation gap in Robert McKee's book Story: http://www.amazon.co.uk/Story-Substance-Structure-Principles-Screenwriting/dp/0413715604

The basic premise is that there is something (the story that you probably want to tell) that sets up a disparity between the expected outcome of an action of the hero, and the actual outcome of that action. This is the gap that needs to be closed by the hero during his adventure. This applies to Adventure game puzzle design by being the technique by which you reveal the new puzzles to be solved: If you know you need A, then you first need to find A, or find someone that can tell you where A is, and when you know that you might need to know how to get there, or how to get A once you get to it. Each thing you need to do to acquire A could be an action, or another item to find/use on another item to create another item/action/opportunity to find another step towards A. Even when you have A/get to A, the final outcome should be that A was not quite what you wanted, but took you someway towards getting what A originally represented as its outcome.

Now, i'll give you an example. You are a cook, and you have broken your frying pan. the story is the cook that has to cook food for your slave driving master. To mend the pan, you just need to get a new handle, the helper recommends using the broken broom in the corner, but it needs cutting, where to find a saw to cut it? Outside, maybe by taking the milk from the fridge to swap for a few moments with a saw... pan fixed, you cook, but the original solution of making breakfast has now been made harder as the time it took to fix the pan has caused the fire to go out...

The expectation of the player should be teased out so they almost always only feel a few clicks away from completing their task, but at the same time allowing the opportunity for a really long list of actions to complete in order to finish the game.

An important part of any long sequence of actions is that the player should know when they are about to finish the game, make sure it's obvious that they are, otherwise the game will feel like they're being short changed at the end, and there's nothing worse than an experience ending badly.
> 3 votes

# Answer
As an adventure game developer (Eternally Us, McCarthy Chronicles) I've found that adventure gamers are generally split into 2 camps. Those who play for puzzles and those who play for interaction and story. Of course there is some overlap but it might be a good idea to establish your audience before thinking about puzzle design.

Those who play for story generally prefer 'puzzles', in a broad sense, with a heavy grounding in reality. This include the more modern post-adventure games like Heavy Rain and Dreamfall. The key with games like this is not to break the immersion and to consider your 'puzzles' as 'challenges' instead.

On the flip side, the old school adventure gamers tend to want hardcore puzzles like they saw in maniac mansion. The best way to design puzzles like this is to start at the solution and work backwards. This allows you to create multi-faceted solutions like those seen in Day of the Tentacle and the other classic Lucas Arts games. These puzzles start with a concept and build the puzzle around it. These games are generally easier to design puzzles for because its acceptable for puzzles to get ridiculous and unintuitive because it is, after all, a 'puzzle. Think of how stupid some of the puzzles with the crystals were in The Dig.

The biggest advice I can give is to play a lot of adventure games. All puzzles generally fall within 1 of several specific categories with well established tropes. Just observe and imitate, then try to branch your puzzles into something new.
> 2 votes

# Answer
If we are talking about adventure games, then there are some things you can do in puzzles there that you can’t do with puzzles in other games. However, puzzles in games have a lot in common. Personally, I find it best to brainstorm, and come up with a unique setup or interaction with npcs or item such, and figure out the best way to make the interaction feel natural. Even though some puzzles in adventure games make no sense at all, that doesn’t mean you should make puzzles that make no sense.

A puzzle should be designed in a way that if you were to look up the solution, you would think that that totally makes sense within the rules of the universe you’ve created, and that you could have actually figured it out without just brute-forcing it and using every item on every thing, or just walking around spamming the interact button.

Let’s create an imaginary scenario. There are three guys you have to get past. One of them always tells the truth, one of them always lies, and one tells the truth 50% of the time. You have to figure out which one is which to move on. They can only respond with Beck, or Reck, and you don’t know which is yes or no. First, we need to find the random guy, as he could throw us off. The solution to finding him is simple. Just ask each one the same question over and over, and if one of them doesn’t give the same answer to the same question every time, then he is the random guy.

Then, we must figure out what they are actually saying. To figure that out, the player would have to ask if Beck means yes. If they say Reck, then that means no. Is they say Beck, than it means yes. You could do the same thing with Reck, but the concept is the same. Then, you could, with your new knowledge, ask an objectively true or false question, such as whether Pluto is a planet or not. If they say whatever is false, then they are the lying one, and by process of elimination, you have found the one who tells the truth.

However, they don’t always have to be this complex. Especially earlier on, you could have simpler puzzles that could potentially be just as hard, just with not as many steps.
> 0 votes

---
Tags: game-design, adventure-games
---


title: Spawning a customized sprite with text

text:
# Question
Title: Spawning a customized sprite with text
I'm making a game where I have circles filed with words or pictures drop from the top of the screen to the bottom. they should spawn right above and then drop. I just started using unity a couple days ago and I managed to do this with a simple sprite, but I couldn't fill it with the info I wanted and from searching online it seems like it can't be done.

So I decided to try with buttons instead, since those can be given text and images(I think) but i'm not sure how to do so.

with the circles I passed an object of them to the script and then used `newCircle = Instantiate(Circle, temp, Quaternion.identity);` but with buttons everything seems to work weird because there's also the need for the canvas and the units are different so I'm not sure how to do it

# Answer
You can make a simple script to put on your sprite prefab that looks a bit like this:

```
using UnityEngine;
using TMP;

public class WordSprite : MonoBehavíour {
    public Sprite sprite;
    public TextMeshPro word;

    public void Setup(string text) {
        word.text = text;
    }
}

```

Now you can add the text as a child object, and assign a reference to both the sprite and the text in the inspector.

Now your spawner can expose an inspector field:

```
public WordSprite prefab;

```

Then you can instantiate and populate it just like you did with the regular sprite before:

```
var wordSprite = Instantiate(prefab, spawnPosition, Quaternion.identity);
wordSprite.Setup(putYourChosenWordHere);

```

> from searching online it seems like it can't be done.

Don't give up so easily, especially on something this simple.
> 0 votes

# Answer
I found a great guide on YouTube, I'm not sure if it's ok to post a link here so please tell me if its not. https://www.youtube.com/watch?v=bJ5tyiW\_L24.

The idea is we make a Canvas with a Text into a child of the object and we simply resize both the canvas and the text to fit the sprite object. we need to change the canvas into world space and also change the pixels per unit since it's going to be much much smaller (changing to 100 worked well for me). with the Text make sure to mark the "Best Fit" box otherwise the letters will likely be too big for your sprite.
> 0 votes

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


# Question
Title: Unity method/framework for handling different input modes
I'm a very new Unity developer who's looking for a best practice or framework for handling different input modes. I'm working in `C#`. Here's a contrived example:

# Sample Map Application

### Control Scheme 1:

* `W/A/S/D` keys move map up/right/down/left.
* `Escape` key closes application

**`Spacebar` opens menu and switches to Control Scheme 2**

### Control Scheme 2:

* `W/A/S/D` moves menu selection up/down/into submenu/back to parent menu.
* `Escape` key closes menu and switches to Control Scheme 1

I realize this is a silly contrived example, but it demonstrates the point. When we are in a menu we don't want the W/A/S/D keys to also move the map while we are trying to navigate the menu. This *could* be done with a bunch of `if` statements such as

```
if(moveMode)
   // read keypresses and move map
else if(menuMode)
   // read keypresses and menu navigation

```

But you can see how this would get messy very quickly if we had lots of modes. We could also end up with a lot of nested `if` statements if we have sub-modes for controls.

Surely there's a cleaner way to do this? Any best practices for this? Any frameworks?

# Answer
The new input system makes this very easy.

Just create an input actions asset with a different action map for each input mode.

If you prefer to work with the auto-generated mapping classes for each input asset, then you can just enable and disable those input actions separately. This can look like this (assuming your input action assets is named "My Input Actions" and you enabled "Generate C# Class" on it):

```
private void Awake() {
    myInputActions = new myInputActions();

    myInputActions.Scheme1.SwitchToScheme2.performed += ((InputAction.CallbackContext ctx) => {
         myInputActions.Scheme1.enabled = false;
         myInputActions.Scheme2.enabled = true;
    }
    // other event handlers for myInputActions.Scheme1

    myInputActions.Scheme2.SwitchToScheme1.performed += ((InputAction.CallbackContext ctx) => {
         myInputActions.Scheme1.enabled = true;
         myInputActions.Scheme2.enabled = false;
    }
    // other event handlers for myInputActions.Scheme2

    myInputActions.Enable();
}

```

When you prefer to use the Player Input component, you can use the method SwitchCurrentActionMap:

```
private void OnSwitchToScheme1() {
    GetComponent<PlayerInput>().SwitchCurrentActionMap("Scheme1");
}

private void OnSwitchToScheme2() {
    GetComponent<PlayerInput>().SwitchCurrentActionMap("Scheme2");
}

```
> 1 votes

# Answer
**Event handlers.**

When your map is open or gains focus, it subscribes to key events.

```
InputManager.OnKeyPressed += HandleKeyPress;

```

When your map closes or loses focus, it unsubscribes from key events.

```
InputManager.OnKeyPressed -= HandleKeyPress;

```

Here's a Unity example and video about it.
> 0 votes

# Answer
You could just use the Unity Input System. It is designed to handle contextual mappings, remappings, and support for multiple input methods.

https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/QuickStartGuide.html
> -1 votes

---
Tags: unity, input
---


# Question
Title: Optimizing the economy of a resource management game
I am an amateur game designer. I am designing a resource management game involving real money. This is my first time designing such a game. I explain the design and mechanics below. I need feedback from experienced game designers regarding:

i) The sustainability of the core economic loop of this game,

ii) Concrete suggestions to de-risk or fine-tune it (if you can think of any)

---

My game is about digging up treasure. Treasure is real $$$ players can cash out. The objective of the game is to make as much money as possible.

Players utilize digging machines (excavators) to unearth treasure. The attributes of these digging machines are:

* **Digging prowess:** Most machines are mediocre diggers. I.e. they unearth small treasure. A few rare machines can dig up really big treasure. And then there are other types in between these two extremes.
* **Scarcity:** Only a finite number of machines are available in this game world.
* **Transparency:** Machines' visual design varies in accordance to their digging prowess. I.e. players can easily spot which machine is better than the rest.

---

**Main mechanics:**

When a new player joins this game, they utilize real $$$ to buy one or multiple such machines. Once bought, each machine can either be:

* Stored away (unused), or
* Put to work. Note that when a machine accumulates 1 hour of digging time, it unearths treasure. The amount unearthed is always proportional to the machine's digging prowess.

Putting machines to work has an upside and a downside:

* **Upside:** Machines that are put to work unearth treasure (actual $$$ players can claim).
* **Downside:** Working machines can be *forcefully bought* by another player (for the machine's current value + 5% profit). No permission is needed. This permanently increases the value of the machine. Which means, if you want to snatch it back, you pay a further 5% increment on top of everything.

Storing machines away has an upside and a downside:

* **Upside:** Nobody can forcefully buy them from the player.
* **Downside:** They don't help the player earn anything.

---

**How do we finance the treasure-finds?**

There is a pool of money in the back-end that finances each and every treasure-finding. We finance this pool in two ways:

* The first time a digging machine is bought, 90% of the proceeds are routed to this pool (10% are pocketed by the game developer).
* I earlier mentioned that whenever a machine is forcefully bought, a 5% profit is paid by the buyer to the unwitting seller. We route 10% of that profit to the treasure pool, 10% to the game developer, and 80% to the unwitting seller of the machine.

---

It would be great to get feedback from experienced game designers regarding the economic viability of the game's core loop. How do we:

1. Make it sustainable?
2. What are the economic risks?
3. How can they be quantified?
4. Are there any risk-minimization tactics we can bake in?

# Answer
Using the revised explanation of the mechanics from a comment:

> You're thinking the player gets 80% of 105% the base value. That wasn't my intention. The player actually gets 80% of the 5% profit above the base value (and of course they get the base value too)

We can analyze this a different way (check the edit history if you want to see the previous analysis under a different interpretation of the rules).

We'll look at the player's expected hourly earning from fielding a machine with value \\$v\\$ that accrues \\$a\\$ treasure per hour and might get purchased with probability \\$p\\$ in that hour:

$$\begin{align} E\_\text{player} &= p (0.8 \times 0.05 v + v) + (1-p)a\\ &= 1.04 p v + a - p a\\ \end{align}$$

By construction, this is always positive. So that seems to suggest that this is always a profitable investment for all parties and we can make free money off it endlessly! But we know to be suspicious of perpetual motion machines, so let's look closer.

The exponential growth of the machine prices is the trick. Even with a small growth factor like 5%, these values get *huge*. A machine purchased for $1 originally costs $10 after 48 trades, $100 after 95 trades, $10 00 after 142 trades, and $10 000 after 189 trades.

As we get into these higher prices, whatever rate of return per hour \\$a\\$ the original $1 machine gave me in treasure earnings is pretty much negligible compared to what I had to pay to buy it. I could get a better return by putting that same money into a savings account or GIC instead. So now as a machine-holder I'm relying solely on other players buying the machine off me to make a profit.

But as we go up and up in price, the pool of potential customers willing to shell out that kind of money for this "game" gets thinner and thinner.

If we model the probability of a machine getting purchased in a given hour as inversely proportional to its price, then my expected earnings per hour approach a constant, while the price to stay in the game (by buying a new machine anytime one of mine gets bought) continues growing exponentially.

$$\begin{align} E\_\text{player} &= p (0.8 \times 0.05 v + v) + (1-p)a\\ &= 1.04 p v + a - p a\\ &= 1.04 \frac {p^\*} v v + a - \frac {p^\*} v a\\ &= 1.04 p^\* + a - \frac {p^\* a} v \end{align}$$

So there will always come a point where this bounded earning rate drops below what the player can be earning through alternative investments. So they stop buying new machines, cash out their treasure, and put that money into an investment that scales with their investment instead.

That leaves you with a pool of machines that are no longer trading hands (so you make no new profit), and an obligation to continue paying their hourly treasure earnings indefinitely.

So neither the endless exponential growth nor perpetual payment obligation are sustainable.
> 5 votes

# Answer
The problem with this ponzi scheme (not calling it a game, because it **is** a ponzi scheme) is that the payout to the members from "digging treasures" is financed by new members joining the scheme and putting in money. As with every ponzi scheme, this is sustainable as long as there are new members, but becomes unsustainable as soon as no members join anymore. And in this particular scheme, that point is actually hardcoded into this system, because the number of available digging machines is finite.

Digging machines already in the scheme get more expensive by forceful buying, but not more useful. Which means their expected return of investment will go down over time. That makes them less attractive the more often they change hands.

When the digging machines are no longer reasonably priced, they will stick with their current owners. At that point all the digging machines will keep accumulating cash prices for their current owners, but there won't be any stream of new cash to finance those cash prices. The price pool will dry up, and a lot of people who invested a lot of money into the scheme will get very angry.

At which point the developer might want to take what money they earned and leave to some exotic country which doesn't extradite them or seize their bank accounts.

But how can we extend the time until that happens? By occasionally adding new digging machines over the running time of the scheme for new members to buy. That way the scheme stays able to attract new and old members willing to put in more cash. It will stay sustainable as long as there is a target demographic to get new members from, or the existing demographic can be convinced that throwing in more money will benefit them in the long run (it doesn't, because as is in the nature with ponzi schemes, it can't pay out more money than it takes). This will increase the time it will take for the scheme to collapse.

Another option to save this scheme from collapse would be to not finance the cash prices from what the players put into the game, but rather use the system to distribute a cash flow from an entirely different source of income.
> 4 votes

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


title: Checkerboard using Shadergraph

text:
# Question
Title: Checkerboard using Shadergraph
In Unity Shadergraph, how can I create a checkerboard pattern that works independently of the size of the quad that it is applied to?

Here's what I got so far. Since I have set the Frequency to 10x6, this will work for a quad that has a scale of 20x12. However, if I increase the scale of the quad, the checkerboard will get stretched to fit. But instead, I would like it to "add more squares" to fit the new size.

Is there a way to get it to somehow use the size of the quad instead of manually specifying the frequency?

# Answer
Pipe a worldspace position value into the checkerboard's UV input, instead of the default texture coordinate:

This assumes you want your quad to sit in the XY plane. If you want it in XZ, you'll want to swizzle the vector first to move Z into the Y slot.

Here are two ways to do that swizzle:
> 1 votes

---
Tags: unity, shaders, unity-shader-graph
---


title: Depth to World Space Position problem

text:
# Question
Title: Depth to World Space Position problem
I am having a problem with turning depth to world space position. I am using GLSL.

What could go wrong?

Here is the code:

```
float x = (uv.x * 2.0) - 1.0;
float y = (uv.y * 2.0) - 1.0;
float z = (depth * 2.0) - 1.0;

vec4 pos_clip = vec4(x, y, z 1.0);

vec4 inverse_pos_view = InvCamProjMatrix * pos_clip;
inverse_pos_view.xyz /= inverse_pos_view.w;

vec4 pos_ws = InvCamViewMatrix * inverse_pos_view;

return pos_ws.xyz;

```

Thanks.

# Answer
> 1 votes
I found an answer.

```
vec4 pos_ws = InvCamViewMatrix * InvCamProjMatrix * pos_clip;
pos_ws.xyz /= pos_ws.w;

```

---
Tags: opengl, glsl
---


# Question
Title: Chess engine stock fish process for mobile
I am making the chess interface I designed for a game. I am using the process to get answers from a stock fish binary:

```
stockfish = new Process {
                StartInfo = new ProcessStartInfo {
                    FileName = System.IO.Directory.GetCurrentDirectory () + "\\Assets\\Scripts\\Stockfish\\stockfish.exe",
                    Arguments = "",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardInput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }

            };

```

The problem I face is it worked for my Windows build but for mobile package build it won't work with the executable. Is there a way around it?

# Answer
> 2 votes
I have managed to make this work like this. You need to update the package name in the file path.

```
using System.Diagnostics;
using System.IO;
using UnityEngine;

namespace Assets.Scripts
{
    public class EngineCommunicator
    {
        public static Process mProcess;
        public static string fileName = "stockfish.android.armv7";
        public static void Communicate()
        {
#if UNITY_EDITOR
            string filepath = "E:\\Personal\\Unity\\Chess2d\\Assets\\Plugins\\Windows\\stockfish_13_win_x64";
#elif UNITY_ANDROID
            string filepath = "/data/data/com.tiringbring.Chess2d/lib/stockfish.android.armv7.so";
            UI.Instance.AddJob(() =>
            {
                UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text = filepath;
            });

            if (!File.Exists(filepath))
            {
                UI.Instance.AddJob(() =>
                {
                    UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text =UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text +" "+ "file not found";
                });
            }else{
                UI.Instance.AddJob(() =>
                {
                    UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text =UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text +" "+ "file found";
                });
            }
#else
        string filepath = Application.streamingAssetsPath+ "/" + "stockfish_13_x64.exe";
#endif
            // creating the process and communicating with the engine
            mProcess = new Process();
            ProcessStartInfo si = new ProcessStartInfo()
            {
                FileName = filepath,
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardError = true,
                RedirectStandardInput = true,
                RedirectStandardOutput = true
            };
            mProcess.StartInfo = si;
            mProcess.OutputDataReceived += new DataReceivedEventHandler(MProcess_OutputDataReceived);
            mProcess.Start();
            mProcess.BeginErrorReadLine();
            mProcess.BeginOutputReadLine();

            SendLine("uci");
            SendLine("isready");
            SendLine("ucinewgame");
            SendLine("position startpos");
            SendLine("go infinite searchmoves e2e4 d2d4");

        }

        private static void SendLine(string command)
        {
            mProcess.StandardInput.WriteLine(command);
            mProcess.StandardInput.Flush();
        }

        private static void MProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            string text = e.Data;
            UI.Instance.AddJob(() =>
            {
                UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text = UI.Instance.TestText.GetComponent<TMPro.TextMeshProUGUI>().text +" "+ text;
            });

            UnityEngine.Debug.Log(text);
        }
    }
}

```

Put the file in Assets/Android directory with .so extension.

It will be copied automatically in lib folder on android mobile

# Answer
> 2 votes
This line should only ever work in Windows version (or for versions that your VS supports):

```
FileName = System.IO.Directory.GetCurrentDirectory () + "\\Assets\\Scripts\\Stockfish\\stockfish.exe",

```

For Unity's builder, you need to use Application.dataPath or Application.persistentDataPath. I've had success with using both, the former for accessing the game folder and the latter for saving or loading files.

---
Tags: unity, chess
---


# Question
Title: Splitting up HLSL code into separate functions causes the number of needed temporary registers to increase
**EDIT**

Per request I've provided a simple compute shader that reproduces the problem. The compute shader below is kind of a contrived example meant to compute the rolling average over an input structured buffer.

By defining "USE\_FUNCTION" certain parts of the algorithm will be split up into a separate function. This results in additional temporary registers being used by the compiled code as described in the original question.

The Unity version used to compile the compute shader is 2020.3.0f1 Personal.

```
#pragma kernel ComputeRollingAverage

// Comment out "USE_FUNCTION" define to inline code manually.
#define USE_FUNCTION
#define SAMPLE_COUNT 10
#define CODE \
count = 0; \
 \
for (uint offset = 0; offset < SAMPLE_COUNT; offset++) \
{ \
    if (index + offset >= size) \
    { \
        break; \
    } \
    samples[count++] += input[index + offset]; \
}

uint size;

StructuredBuffer<float> input;
RWStructuredBuffer<float> output;

void InitializeSamples(out float samples[SAMPLE_COUNT])
{
    for (int iterator = 0; iterator < SAMPLE_COUNT; iterator++)
    {
        samples[iterator] = 0.0;
    }
}

void SampleInput(uint index, inout float samples[SAMPLE_COUNT], out uint count)
{
    CODE
}

[numthreads(64, 1, 1)]
void ComputeRollingAverage(uint3 id : SV_DispatchThreadID)
{
    uint index = id.x;
    float samples[SAMPLE_COUNT];
    uint count;
    InitializeSamples(samples);

#ifdef USE_FUNCTION
    SampleInput(index, samples, count);
#else
    CODE
#endif

    float rollingAverage = 0.0f;

    for (uint iterator = 0; iterator < count; iterator++)
    {
        rollingAverage += samples[iterator];
    }
    output[id.x] = rollingAverage / count;
}

```

**Original Question Below**

I'm currently working on a compute shader in Unity (implementing Cubical Marching Squares) and noticed that splitting up certain parts of the algorithm into separate functions causes the number of needed temporary registers (in below's case `dcl_indexableTemp` registers) to increase.

The only workaround I found is manually inlining everything, basically going back to one single, giant kernel function. That works, but the code gets harder to read and maintain.

Below I've provided a small snippet of my code (with parts omitted) illustrating the problem. At the beginning I create a local array of Segment structs of size 12:

```
[numthreads(4, 4, 4)]
void GenerateMesh(uint3 id : SV_DispatchThreadID)
{
    if (IsOutOfVoxelBounds(id))
    {
        return;
    }

    Segment segments[12];
    uint segmentsCount = 0;

    for (uint faceIndex = 0; faceIndex < 6; faceIndex++)
    {
        // >>> Calculate face segments.
        uint4 faceSampleIndices = voxelFaceSampleIndices[faceIndex];
        uint segmentsIndex = 0;

        for (uint sampleIndex = 0; sampleIndex < 4; sampleIndex++)
        {
            uint3 position = voxelStride * (id + voxelCorners[faceSampleIndices[sampleIndex]]);
            HermiteData sample = hermiteVolume[CalculateHermiteIndex(position)];
            segmentsIndex |= (GetHermiteDataDensity(sample) < 0.0) << sampleIndex;
        }

        uint4 voxelFace = voxelFaces[faceIndex];
        uint4 faceSegments = marchingSquaresSegments[segmentsIndex];

        for (uint faceSegmentsIndex = 0; faceSegmentsIndex < 4; faceSegmentsIndex += 2)
        {
            if (faceSegments[faceSegmentsIndex] == -1)
            {
                break;
            }

            Segment segment;
            InitializeSegment(segment, 0, 0, 0, 0, 0);
            segments[segmentsCount++] = segment;
        }
        // <<<
    }

    if (segmentsCount == 0)
    {
        return;
    }

    // additional code omitted
}

```

A single Segment struct uses up two 4-component registers. So the whole local array uses up `2 * 12 = 24` 4-component registers. When looking at the compiled code through Unity (snippet below) the local array shows up as `dcl_indexableTemp x0[24], 4` as expected. Everything fine so far.

```
dcl_uav_structured u0, 16
dcl_uav_structured_opc u1, 24
dcl_uav_structured u2, 12
dcl_input vThreadID.xyz
dcl_temps 22
dcl_indexableTemp x0[24], 4
dcl_indexableTemp x1[8], 4
dcl_indexableTemp x2[2], 4
dcl_indexableTemp x3[8], 4
dcl_thread_group 4, 4, 4

```

I now put the parts between `// >>> Calculate face segments.` and `// <<<` into a separate function and call it from the kernel like so:

```
void GenerateSegments(uint3 id, uint faceIndex, inout Segment segments[12], inout uint segmentsCount)
{
    uint4 faceSampleIndices = voxelFaceSampleIndices[faceIndex];
    uint segmentsIndex = 0;

    for (uint sampleIndex = 0; sampleIndex < 4; sampleIndex++)
    {
        uint3 position = voxelStride * (id + voxelCorners[faceSampleIndices[sampleIndex]]);
        HermiteData sample = hermiteVolume[CalculateHermiteIndex(position)];
        segmentsIndex |= (GetHermiteDataDensity(sample) < 0.0) << sampleIndex;
    }

    uint4 voxelFace = voxelFaces[faceIndex];
    uint4 faceSegments = marchingSquaresSegments[segmentsIndex];

    for (uint faceSegmentsIndex = 0; faceSegmentsIndex < 4; faceSegmentsIndex += 2)
    {
        if (faceSegments[faceSegmentsIndex] == -1)
        {
            break;
        }

        Segment segment;
        InitializeSegment(segment, 0, 0, 0, 0, 0);
        segments[segmentsCount++] = segment;
    }
}

[numthreads(4, 4, 4)]
void GenerateMesh(uint3 id : SV_DispatchThreadID)
{
    if (IsOutOfVoxelBounds(id))
    {
        return;
    }

    Segment segments[12];
    uint segmentsCount = 0;

    for (uint faceIndex = 0; faceIndex < 6; faceIndex++)
    {
        GenerateSegments(id, faceIndex, segments, segmentsCount);
    }

    if (segmentsCount == 0)
    {
        return;
    }

    // additional code omitted
}

```

Again, looking at the compiled code through Unity (snippet below), an **additional** `dcl_indexableTemp` register is used just because of the function call that should be inlined regardless.

```
dcl_uav_structured u0, 16
dcl_uav_structured_opc u1, 24
dcl_uav_structured u2, 12
dcl_input vThreadID.xyz
dcl_temps 22
dcl_indexableTemp x0[24], 4
dcl_indexableTemp x1[24], 4
dcl_indexableTemp x2[8], 4
dcl_indexableTemp x3[2], 4
dcl_indexableTemp x4[8], 4
dcl_thread_group 4, 4, 4

```

My understanding is that using the input modifier `inout` copies the function argument in before and out after the function call. So in that sense the additional `dcl_indexableTemp` register makes sense. But shouldn't the compiler notice that this copying can be omitted in aboves case and save up on those temporary registers?

Am I forced to manually inline everything or is there another way (in Unity) which would actually allow for the usage of functions to split up the larger algorithm?

# Answer
I found a way to get the compiler to do the right thing while using functions. It's not ideal, but better than inlining everything manually.

What I did was use static global variables instead of inout parameters. You may want to do some more experimentation to find out exactly which things need to be global variables instead of parameters.

Here's a modified version of your example shader that compiles to exactly the same assembly regardless of the `USE_FUNCTION` define being set or not:

```
#pragma kernel ComputeRollingAverage

// Comment out "USE_FUNCTION" define to inline code manually.
#define USE_FUNCTION
#define SAMPLE_COUNT 10
#define CODE \
count = 0; \
 \
for (uint offset = 0; offset < SAMPLE_COUNT; offset++) \
{ \
    if (index + offset >= size) \
    { \
        break; \
    } \
    samples[count++] += input[index + offset]; \
}

uint size;

StructuredBuffer<float> input;
RWStructuredBuffer<float> output;

static float samples[SAMPLE_COUNT];

void InitializeSamples()
{
    for (int iterator = 0; iterator < SAMPLE_COUNT; iterator++)
    {
        samples[iterator] = 0.0;
    }
}

void SampleInput(uint index, out uint count)
{
    CODE
}

[numthreads(64, 1, 1)]
void ComputeRollingAverage(uint3 id : SV_DispatchThreadID)
{
    uint index = id.x;
    uint count;
    InitializeSamples();

#ifdef USE_FUNCTION
    SampleInput(index, count);
#else
    CODE
#endif

    float rollingAverage = 0.0f;

    for (uint iterator = 0; iterator < count; iterator++)
    {
        rollingAverage += samples[iterator];
    }
    output[id.x] = rollingAverage / count;
}

```

Note that I tested this by compiling with fxc.exe directly, and not using Unity, but I'd expect the results to be the same.

Using fxc.exe directly allowed me to compile it twice, and pass `/D USE_FUNCTION` on the command line for one compilation, output the results to a file with `/Fc`, and then diff the two results with `fc`. For reference, this is what the batch file I used looked like:

```
fxc.exe /E ComputeRollingAverage /T cs_5_0 ComputeShader.txt /Fc inline.txt
fxc.exe /E ComputeRollingAverage /T cs_5_0 ComputeShader.txt /Fc function.txt /D USE_FUNCTION
fc function.txt inline.txt > diff.txt
pause

```

Note that you may need to specify the full path to `fxc.exe`.
> 0 votes

---
Tags: unity, hlsl, compute-shader
---


# Question
Title: Trouble with Raylib install on Arch Linux
I am learning Raylib game library, but in the "First Person Maze" example the images cannot be found, for example:

```
`Image imMap = LoadImage("cubicmap.png");`

```

returns a File not Found by the compiler/linker, it´s the same with the other image. I am using CodeLite IDE, but I don't know how to add assets, right now I have them in a virtual folder named "resources".

Any help would be nice, I have googled the problem but I can't find anything. But now I don't know what's wrong because I have compiled the library with make and make install and also added Raylib package from Arch Linux and I can't even run the *My first window* example from the site.

# Answer
As Vaillancourt said, in CodeLite IDE when you create a virtual folder it's really virtual, you have to make sure your files are actually in a folder in your project, otherwise your files won't be loaded.
> 1 votes

---
Tags: c++, raylib
---