title: Using State Pattern with Unity

text:
# Question
Title: Using State Pattern with Unity
I am new to Game Development and Unity. I have written a component for Jumping and Running, `CharacterJumpAbility.cs` and `CharacterRunAbility.cs`.

I would like the Character to be able to Jump only if the Character is not moving. I came across a State Pattern but I can't understand how to apply it. For example if I want to Jump, first I must check if the Character is Running, but I have to do this in the `CharacterJumpAbility.cs` or in the `CharacterController.cs` (the component who handles inputs)?

If I define a state for example:

```
public enum CharacterState {
    Run,
    Jump
}

```

For example if the player is pressing the space bar, I have to set the Jump state, the code that sets `state = CharacterState.Jump` should be written in the `CharacterJumpAbility.cs` or in the component that handles inputs?

And if I want to set a new state for example Jump, while I am running, this is clearly not possible, how to handle situations like these?

# Answer
> 1 votes
for working with state pattern, first thing that comes to mind is enum and state. most problem is switch is not OO and most of the time its better to not to use switch-case. and you dont have much freedom to extend. its implemented like below: you can fill cases with any logic you want and you only have to change state variable to change running state.

```
 enum states {run, jum,shoot,etc }
    states state;
    private void Update()
    {
        switch (state)
        {
            case states.run:
                break;
            case states.jum:
                break;
            case states.shoot:
                break;
            case states.etc:
                break;
            default:
                break;
        }
    }

```

another approach that is much better is use of delegates like Action. one action runs in all times but you can change assigning function to it. you define it like below: you can change state like what happened in Start callback

```
  System.Action CurrentState;

    void Shoot() { }
    void Run() { }
    void Jump() { }

    private void Start()
    {
        CurrentState = Run;
    }

    private void Update()
    {
        CurrentState.Invoke();
    }

```

# Answer
> 1 votes
It depends on the complexity of your character. Enumerations are fine for simpler characters, but it can become very problematic when character's abilities get expanded.

Virtouso's answer is good, but I'd just like to add how I go about doing state machines a lot of the time.

You can create a base class along these lines:

```
public abstract class StateBase<T>
{
 public abstract void OnEnter(T owner);
 public abstract void Update(T owner);
 public abstract void OnExit(T owner);
}

```

Then have a state machine something like this:

```
public class StateMachine<T>
{
 private T owner;
 private StateBase<T> currentState;

 public void Update()
 {
  currentState.Update(owner);
 }

 public void GoToState(StateBase<T> state)
 {
  //...
 }
}

```

Obviously, this is very stripped down for an example, but you get the idea. Your running and jumping would inherit from StateBase. This state machine can then easily be re-used across different types.

I'm not a fan of the delegate method because you add a lot of functions, which I don't think is as clear as having classes that are easily found for each state.

I find this eBook very useful: https://gameprogrammingpatterns.com/state.html

# Answer
> -1 votes
Here is a good tutorial on the use of the state pattern in your game. If you set your animation controller up right, you can use the `OnStateEnter` and `onStateExit` methods of each state to set animator parameters. Hope this helps.

---
Tags: unity, design-patterns, state
---


title: Transparency in GLSurfaceView

text:
# Question
Title: Transparency in GLSurfaceView
I'm new in game development. I have a view using `GLSurfaceview` and call in `MainActivity`.

I want to make transparent that view. I have tried `setZOrderOnTop()` method in `MainActivity` and `glClearColor()` but both are not working.

```
public class RubikActivity extends Activity {

        cubeView cv;
        GLSurfaceView gv;

        @SuppressLint("NewApi")
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity);
        cv = (cubeView) findViewById(R.id.cubeView);
        cv.initialize(PreferenceManager.getDefaultSharedPreferences(this));
         cv.requestFocus();
            cv.setFocusableInTouchMode(true);
            cv.setEGLConfigChooser(8, 8, 8, 8, 8,0);
          //  cv.setRenderer( new CubeRenderer(getApplicationContext(), font, mWorld, rCube, mMenu, prefs);

            cv.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        cv.setZOrderOnTop(true);

        }

```

cubeView.java

```
public cubeView(Context context, AttributeSet attrs) {
super(context, attrs);
font = new TextureFont(getContext(), R.drawable.roboto_regular, "roboto_regular_dims.txt");
mWorld = new GLWorld();

}

public void initialize(SharedPreferences prefs) {
rCube = new Rubec(mWorld, prefs.getInt("dim", 3));
mMenu = new CubeMenu(rCube, font);
_renderer = new CubeRenderer(getContext(), font, mWorld, rCube, mMenu, prefs);
rCube.setRenderer(_renderer);
mWorld.setRubeCube(rCube);
setRenderer(_renderer);

getHolder().setFormat(PixelFormat.TRANSLUCENT);
setZOrderOnTop(true);
}

```

cubeRenderer.java

```
@Override
public void onDrawFrame(GL10 g) {
GL11 gl = (GL11)g;

surfaceSetup(gl);

gl.glClearColor(1.0f, 1.0f, 1.0f,0);
gl.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
gl.glDisable(GL11.GL_DEPTH_TEST);
gl.glMatrixMode(GL11.GL_MODELVIEW);
gl.glShadeModel(GL11.GL_SMOOTH);
    gl.glLoadIdentity();

GLU.gluLookAt(gl, 0f, 0f, 7f,
          0f, 0f, 0f,
          0f, 1f, 0f);
gl.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelViewMatrix, 0);
if(!worldBoundsSet) {
    getWorldBounds();
}
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glEnable(GL11.GL_DEPTH_TEST);
gl.glEnableClientState(GL11.GL_COLOR_ARRAY);
    gl.glEnableClientState(GL11.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
menu.draw(gl);
mWorld.draw(gl);
gl.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
/*gl.glDisableClientState(GL11.GL_COLOR_ARRAY);*/
gl.glDisableClientState(GL11.GL_VERTEX_ARRAY);

//gl.glFlush();
}

```

I want the white color to show as transparent background in my layout. I am already use `glClearColor(0,0,0,0)` which shows as a black color and already use in xml file:

```
 <com.rtpl.rubikgame.cubeView
  android:id="@+id/cubeView1"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_weight="1"
  android:background="#000000"
  android:windowIsTranslucent="true"/>
</LinearLayout>

```

but nothing happened; when we use `glClearColor(0,0,0,0)` it shows this:

# Answer
```
final GLSurfaceView glView = (GLSurfaceView) findViewById(R.id.myGlView);

glView.setZOrderOnTop(true);
glView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
glView.getHolder().setFormat(PixelFormat.RGBA_8888);

```

### What this does

Displays `GLSurfaceView` on top of other views, this is required.
Configures OpenGL and the surface to allow transparent drawing.

---

Source
> 2 votes

# Answer
had the same issue another day, found the solution: in your renderer onDrawFrame() method add very last (it's important) string like this:

```
gl.glClearColor(0, 0, 0, 0);

```

Hope it would help someone. Also, to get transparent background in layout put "#80" before color code. It doesn't seem to work for glSurfaceView although, cause default renderers usually redraw view background.

Better later than never =)
> 0 votes

---
Tags: android, glsl, opengl-es
---


# Question
Title: What am I suppose to use instead of Unity Resources if I have to load and unload sprites at runtime?
I recently read this guide posted in the Unity website about Resources. It is clear from the get-go that it is discouraged to use `Resources` unless you are prototyping something.

My game is like a 2D RPG, and it has over five thousand monster sprites (yes, a lot). As far as I'm concerned, it makes perfect sense to put all the sprites in the Resources folder, and just load the ones that I need (using their name) when a battle starts and then unload them.

The Unity article makes one point that might support my approach:

> Generally required throughout a project's lifetime

Well, I'm not so sure about it - in a single game session it's entirely possible that thousands of those sprites will not be used at all as the player simply doesn't encounter those monsters.

The article goes on to talk about why is it discouraged to use `Resources`:

> This operation is unskippable and occurs at application startup time while the initial non-interactive splash screen is displayed. Initializing a Resources system containing 10,000 assets has been observed to consume multiple seconds on low-end mobile devices, even though most of the Objects contained in Resources folders are rarely actually needed to load into an application's first scene.

And it is indeed true - my game does in fact take several seconds to load on some low-end devices, especially Android ones. It is also true that none of those sprites of mine need to be loaded at startup.

So I am willing to stop using `Resources` \- but I am at a loss now: the article doesn't mention a reasonable alternative to this.

Here are the (unreasonable) approaches that I have thought of:

> Create a component with a collection of all the sprites, that way they are all loaded without using Resources.

Yeah but I have five thousand sprites. This sounds extremely tedious.

> Same as the previous suggestion, but use Texture Packer or something similar to pack lots of sprites into different sheets - this way I have to do less work.

My sprites are large and packing them won't be a huge help - I'd still end up with a thousand or so sheets.

---

My point is, I just can't have 5000+ sprites preloaded. I need to load them at runtime via `Resources`, but Unity clearly discourages it. Is there a solution to this?

# Answer
> 8 votes
Well, there are currently two other ways(other than using Resources Folder) to maintain assets in unity.

1. Asset Bundle, like @Phillipp mentioned. (Get Started with AssetBundle Here)
2. Addressable: Its a new feature in **Unity 2018+**. You can simply grab the package through unity's package manager. One thing to note here is Addressables are now in beta. So, many people will not recommend it. However, I used it for one of my projects and it works fine.

When you install Addressables, your asset will have a new checkbox in the inspector to mark that as an addressable. You just mark all the assets you want to load on runtime. Then from the Addressable's window (Window-\> Asset Management-\>Addressable Assets), you can group assets, label them, and put the downloadable address for each group. (So you can either make 5000 assets as one group, make 10 groups (500 assets each) and then put the host address where you want to download it from runtime.

Here are a few links to getting started with Addressable.

1. Unity's Addressable Asset system for speed and performance - Unite LA

2. Addressables-Sample

3. Unite Melbourne- Hands on Session on Addressable Assets

# Answer
> 5 votes
If you want to load assets at runtime, then the solution suggested by Unity Technologies is to put those assets into asset bundle files which you can then load at runtime with `AssetBundle.LoadFromFile(filepath)`. When you don't need the sprite anymore, unload that asset bundle with `loadedAssetBundle.Unload()`.

Putting each sprite into its own asset bundle might be one posible solution. But I have never worked with a project with 5000 asset bundles before, so I am not sure if this solution is really that scalable. If you can, try to group your asset bundles into what you are going to need at the same time. For example, if you have a 1:n relationship between areas and monsters, try to put all the monsters for one area into one asset bundle. But now you do of course need some kind of directory system which tells you which monster is in which asset file (with each monster in its own file, you can just name the files after the technical identifiers of your monsters).

I am looking forward to defeating all the 5000+ monsters in your game.

# Answer
> 0 votes
I'd also recommend Unity Addressables. I created an article that'll help you upgrade from hard references to soft references with Addressables. https://thegamedev.guru/unity-addressables-learn-workflows/

---
Tags: unity
---


title: C# NanoVG Transparency issue

text:
# Question
Title: C# NanoVG Transparency issue
Hi I'm trying to change from Cairo (2D Vector image library) to NanoVG. I'm using C#, openTK and Nano.VG.NET to make my game.

I'm having issues with alpha? Transparency/Blending is an issue…

Here is an output

Without NanoVG Overlay :

With NanoVG Overlay :

I think it has to do with blending or the nano shader….Not sure. Does anyone knows how to solve this?

My OpenGL Initialization :

```
GL.DrawBuffer (DrawBufferMode.Back);
GL.Disable (EnableCap.Lighting);
GL.Enable (EnableCap.Texture2D);
GL.Disable (EnableCap.Multisample);
GL.Disable (EnableCap.SampleAlphaToCoverage);
GL.Disable (EnableCap.AlphaTest);
GL.DepthFunc (DepthFunction.Lequal);
GL.Enable (EnableCap.DepthTest);
GL.Disable (EnableCap.ScissorTest);
GL.Enable ( EnableCap.TextureRectangle);

GL.Enable (EnableCap.Blend);
GL.BlendFunc (BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);

```

# Answer
Finally found a solution.

For Anyone Having this problem just Add GL.Enable (EnableCap.StencilTest);

```
internal static void InitializeOpenGL ()
{
GL.DrawBuffer (DrawBufferMode.Back);
GL.Disable (EnableCap.Lighting);
GL.Enable (EnableCap.Texture2D);
GL.Disable (EnableCap.Multisample);
GL.Disable (EnableCap.SampleAlphaToCoverage);
GL.Disable (EnableCap.AlphaTest);
GL.DepthFunc (DepthFunction.Lequal);
GL.Enable (EnableCap.DepthTest);
GL.Enable (EnableCap.StencilTest);
GL.Disable (EnableCap.ScissorTest);
GL.Enable ( EnableCap.TextureRectangle);

GL.Enable (EnableCap.Blend);
GL.BlendFunc (BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
}

```

And Call InitializeOpenGL before Sprite Rendering (or after drawing GUI).
> 1 votes

---
Tags: c#, opentk
---


# Question
Title: How to balance burst characters with dps characters in a competitive game?
Burst characters (common trope: mages) are distinguished by their peculiar pattern of fighting: they first unleash lots of damage, but then have to back off until their cooldows go down.

Dps characters (common trope: archers, fighters) do not have this pattern and are instead able to deal consistent damage over a long time.

The question is, how to balance the two classes of characters with respect to each other?

The interesting thing to note that in games like DOTA2 and League of Legends we have a consistent pattern of balancement: Namely, burst characters are typically good mid-game, but then fall off; dps characters, on the other hand, start very weak but get better and better and are the best class late game.

I am wondering when does this pattern come from (which problems may I run into if I ignore it) and how can this pattern be avoided nonetheless?

Because this seems counter-intuitive both plot-wise (bows&arrows better than a magic wand that soaks the battlefield in fire, really?) and gameplay-wise (it would seem that the gameplay would be richest if there were both mid-game and late-game bursts and both mid-game and late-game dps'ers).

I have my own hypothesis, but I have no idea if this is correct. I also have my own idea to avoid this pattern, but again I have no idea if this makes any sense.

Firstly: Why is this a thing?

People commonly say that this is just a power of mathematics. As the game progresses, burst characters scale with their burst damage (linearily) while dps characters scale with both damage (linearily) and attack speed (linearily) =\> they scale quadratically.

I have trouble with this reasoning because (a) asymptotics would only mean if the power was unbounded, which is practically not the case - otherwise gameplay designers' numbers are everything; (b) even despite the above this is incorrect. In Dota for example - where mages are supposed to scale even less than in LoL - we have Yasha&Kaya that increases spell damage by 12%, Orchid Malevolence which increases it (indirectly) by 30%, and refresher orb which (indirectly) increases it by a whopping 100% - this is 112%\*130%\*200% which as far as I know is exponential scaling!! (c) is unobservable IRL - a nuclear bomb, despite dealing "constant" damage will be more hurtful than an archer who can increase both their fireing speed and arrow damage through training.

Instead my hypothesis is that this stems from a conscious decision of the devs which MIGHT have been motivated by reasoning similar to this: *We have: DPS, burst, tanks. We need to balance them with respect to each other. Now if a burst can nuke down a tank then they can certainly also nuke a squishy dps = dps is useless in comparison to burst, so a burst will have to be countered by a tank. On the other hand to make burst not useless the burst will have to kill a dps, so we have rock paper scizzors: Tank beats burst beats dps beats tank. Now from this we already now we have to make dps late game, since they will have to scale hardly to keep and win the arms race with the scalings of the tanks. So we have to make burst mid game to balance this off. Ouch, it seems a burst might actually loose 1v1 with a dps late game? Well their power spike is over, its OK.*"

Am I correct with such an analysis? Because if I am than this sounds pretty solid - is there any escape from this pattern?

Well I do have scratch of an idea how to escape from this pattern... Would it make sense to reverse the rock-paper-scizzors? Burst beats tank bc of their immense damage. Tank beats dps because they can survive dps' weaker damage. Dps beats burst because... er because what?

Why not reverse the cooldowns mechanics with spell channeling mechanics? Dps beast burst because dps kills burst before burst can unleash their burst. Burst's spells are time consuming. Or to make this less boring: Burst can unleash their weak spells on a whim, but these do little more than allow them to survive and reduce the channeling time of powerful spells. Eg: Im a wind mage, uh-oh a guy with sword runs to me and wants to kill me! - I now cast a breeze that slows his movements, this makes wind blast accessible - I re-create the gap and only now I have bought myself enough time to summon a badass tornado that kills the sword guy.

This creates its own problems I guess - but does the idea make sense in principle?

# Answer
> 3 votes
There are many possible ways to make burst and dps characters both have useful roles at all stages of a match if that's what you want to do. Scaling the various statistics of characters with items and level ups can be complicated, but it is also very versatile. You can have an Agility stat that boosts attack speed for DPS characters but multiplies damage for Burst characters if that's what you want.

While the rock paper scissors of Burst beats DPS beats Tanks beats Burst makes sense, and could be reversed with some imagination, that's not even the only approach to counters you could have: say, what if burst attacks are kind of easy to avoid when you anticipate them, but can win the battle easily when you don't. Then Burst wins in ambushes and DPS wins in face to face confrontations, and you don't need a third type at all to have balance.

So there are indeed a lot of possible valid balances you can create depending on your preferences, and a lot of different tools at your disposal to create them. I'd like to cover your side questions but some of them can have pretty big answers on their own, maybe split those out.

---
Tags: balance
---


# Question
Title: Saving precomputed data about game objects in Unity3D
In my Unity3D game I have blocks of the environment that are placed by script into the scene. Each block has some bezier paths created with this asset. I can access all points of the paths when I place the block into the scene but I would like store start and end points of these paths somewhere and be able to retrieve this data before I place the blocks into the scene.

The only solution I can currently think of is creating a scene which would run a script that would place all these blocks into the scene, one after another, store the data in a file and this file would then be loaded before the game starts. However this solution feels kinda hacky.

Is there any better way to obtain and store this data in Unity? Is it even possible to create the file and load it when the game starts and also add it to the built game?

# Answer
> 0 votes
Assuming these two things:

* The asset exposes some API from which you can read the data you need
* Your "blocks" are saved as prefabs

Then you should be able to write an editor script to bake out the data into a format you can read at runtime without having to load the blocks.

### Getting each block's path data

It looks like you can use `PrefabUtility.LoadPrefabContents` to obtain the block data. This will give you the root `GameObject` in the prefab, upon which you can use the normal `Find`/`GetComponent` methods to get to the bezier curve data.

If that doesn't work, you can use `AssetDatabase.OpenAsset` and `PrefabStage` to obtain your data.

### Serializing the data

There's a couple of ways to do this. The easiest way is to save the data to a `ScriptableObject`. Simply create a subclass of `ScriptableObject` with serializable fields. At bake-time, create one of these assets, e.g. with the following code (from here):

```
        T asset = ScriptableObject.CreateInstance<T> ();

        string path = AssetDatabase.GetAssetPath (Selection.activeObject);
        if (path == "")
        {
            path = "Assets";
        }
        else if (Path.GetExtension (path) != "")
        {
            path = path.Replace (Path.GetFileName (AssetDatabase.GetAssetPath (Selection.activeObject)), "");
        }

        string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath (path + "/New " + typeof(T).ToString() + ".asset");

        AssetDatabase.CreateAsset (asset, assetPathAndName);

        AssetDatabase.SaveAssets ();
            AssetDatabase.Refresh();
        EditorUtility.FocusProjectWindow ();
        Selection.activeObject = asset;

```

Then you can modify the data contained inside. Make sure to use `EditorUtility.SetDirty` to mark it for saving after it's modified by your script.

At runtime, any objects which need that data can take a reference to that `ScriptableObject` (through inspector, `Resources.Load` or singleton pattern) and use the data accordingly.

Alternatively, if you don't like `ScriptableObject`s, you can always roll your own serialization using any of the various libraries out there. You can save the resulting file as a `TextAsset` and read it that way at runtime.

### How do I start the bake?

To run this code, I'd use a `MenuItem`. Alternatively, if you have a collection of these utilities, you can create your own `EditorWindow`.

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


title: Objects aren't rotating in sync

text:
# Question
Title: Objects aren't rotating in sync
This is a follow-up question to How to reapply force applied to one object to another object

> I want to make two objects move, react to collisions and other stuff as if they were one. For example, Objects A and B are entangled. When Object C rams into Object A and starts moving with it, Object B should start moving with it. When Object B hits a wall, Object A should act like it also hit a wall. I tried changing position/speed every frame, but this only works when done in one direction. Now, I want all forces applied to any of the objects to also apply to the other objects entangled to it.

Edit: This is the new code which only fails when multiple collisions happen at once

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

[RequireComponent(typeof(Rigidbody))]
public class EEScript : MonoBehaviour
{
    public List<EEScript> activeObjects;
    public new Rigidbody rigidbody;
    public Vector3 lastPosition;
    // Start is called before the first frame update
    void Start()
    {
        rigidbody = gameObject.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        lastPosition = transform.position;
    }

    private void OnCollisionEnter(Collision collision)
    {
        foreach (EEScript entangled in activeObjects)
        {
            if (entangled == this) continue;
            Rigidbody rb = entangled.rigidbody;
            if (rb is null) continue;
            rb.velocity = rigidbody.velocity;
            rb.angularVelocity = rigidbody.angularVelocity;
            entangled.transform.position = entangled.lastPosition + transform.position - lastPosition;
        }
    }
}

```

# Answer
Unfortunately, Unity's 3D collision structure doesn't contain all the information you need to compute angular effects from a collision unambiguously. We know the total linear impulse applied to the bodies but not the angular impulse.

But we can do our best to approximate this by keeping track of our previous angular velocity, and applying the difference to all our entangled partners.

```
[RequireComponent(typeof(Rigidbody))]
public class Entangled : MonoBehaviour {

    public Rigidbody[] entangledBodies;

    Rigidbody _body;
    Vector3 _lastKnownAngularVelocity;

    void Start() {
        _body = GetComponent<Rigidbody>();
        _lastKnownAngularVelocity = _body.angularVelocity;
    }

    void FixedUpdate() {
        _lastKnownAngularVelocity = _body.angularVelocity;
    }

    void ChangeAngularVelocity(Vector3 delta) {
        _body.angularVelocity += delta;
        _lastKnownAngularVelocity = _body.angularVelocity
    }

    void OnCollisionEnter(Collision collision) {
        // Unity sends the same impulse value to both participants in a collision,
        // even though one gets impulsed in the opposite direction. So which are we?
        Vector3 impulse = collision.impulse;
        if(Vector3.Dot(impulse, collision.GetContact(0).normal) < 0f)
            impulse *= -1f;

        Vector3 angularChange = _body.angularVelocity - _lastKnownAngularVelocity;

        // Transmit this impulse to all bodies entangled with this one.
        foreach(var entangled in entangledBodies) {
            entangled._body.AddForce(impulse, ForceMode.Impulse);
            entangled.ChangeAngularVelocity(angularChange);
        }
    }
}

```

Note that since we're only applying changes here, there are opportunities for differences to arise: from different initial conditions (if one body was already spinning at the time they became entangled), from different responses to changes (if one body has a different mass, pivot, moment of inertia, drag, or constraints), or from accumulation of small integration errors snowballing chaotically.

Instead of applying incremental pushes, you could instead set the linear & angular velocities of the entangled copies to those of the one most recently pushed by a collision (a role that could shift multiple times per frame when handling several collisions in a single physics tick). Or save an offset from a master object, and have all the entangled copies update their linear and angular velocities each frame to maintain that cached offset relative to the most recently pushed.
> 0 votes

# Answer
physics engine that unity3d uses is **non-deterministic**.

it means you cant predict exactly how it will move. so you best approach for you is to use **rigidBody** for one object and make **rigidBody** of another, **kinematic**. and just set rotation of first object to another using Transform and move second one as first one moves with some offset.
> 0 votes

---
Tags: unity, physics, rotation, physics-engine
---


# Question
Title: Instantiating, Inheritance, Objects and Children basics in Unity
First off, please understand I am horrendously confused with how to do things in Unity. I might not even be asking the right questions, I'll pose my problem and hope it shows my gap in knowledge.

For my game project (a clicker game), I have a several types of object for the player to interact with. Food, Training Dummies, Enemies etc. As per most games, I need objects of the similar type to have different parameters. eg. blue enemy does 1 damage, red enemy does 2. Unlike most games, I will only be showing one 'interactable' object per scene. once you defeat that enemy, it dies, you get experience and it respawns. once you've eaten the food, it vanishes and you get whatever bonus and then it restocks based on what you have in your inventory.

So, I'd made a base class Enemy (which is a unity script, right? which is just a c# class you can attach to a GameObject?)

Next step, adding my child game objects into the scene when I need them. I think this is where the confusion sets in.

So far I'd placed a GameObject in my scene, set it's layout etc and attached the enemy script to it. my respawn mechanic (for a single enemy object repeating itself) was to access the canvasgroup component and set the alpha & interactivity off and then back on, the 'new' enemy would also have it's health refilled, the total updated, all inside a single script using one class. I'm doing it in such a primitive way because I can't quite understand how to correctly create a new child object into my scene and interact with it.

if I make a c# script "BlueEnemyScript" inherit from script "EnemyScript", that's a "child object" in c#?

I create a GameObject (Blue\_Enemy) and attach all the components to it including BlueEnemyScript c# script, then drag it into prefabs.

I then have another GameObject called EnemyManage that will instantiate the prefab via a script.

When I instantiate this prefab (is that a Child in Unity?), it will have it's own unique instance of BlueEnemyScript?

If I were to instantiate the non child Enemy, but change it's parameters as part of the method to instantiate it, wouldn't it have the same effect since it has a unique instance of the script?

Do I even need multiple instances because I'll only have one of the same object type active at a time? should I just swap which method inside the object script is being accessed?

**Happy to have this question closed, I understand it's a mess.**

I read some old questions but they haven't made it much clearer:

# Answer
> 2 votes
> if I make a c# script "BlueEnemyScript" inherit from script "EnemyScript", that's a "child object" in c#?

No, when you define something like `public class BlueEnemyScript : EnemyScript`, that's a "derived class". The class `BlueEnemyScript` "derives" or "inherits" from the "base class" or "superclass" `EnemyScript`.

A "child object" is when you nest one object under another in the Unity hierarchy, as shown in this image from the Unity docs:

In code it looks like this:

```
 myGameObject.transform.parent = parentGameObject.transform;

```

A prefab *could* be a child object, if you instantiate it under a parent/container of some kind, eg.

```
myInstance = Instantiate(myPrefab, parentTransform);

```

A prefab can also contain its own child objects - you can have a whole hierarchy of parts making up one compound object.

> When I instantiate this prefab...it will have it's own unique instance of BlueEnemyScript?

Yes. Each copy you `Instantiate` or drag into your scene has its own instance of the script, and can have its own values of any of the script's member variables.

> If I were to instantiate the non child Enemy, but change it's parameters as part of the method to instantiate it, wouldn't it have the same effect since it has a unique instance of the script?

Yes, I'd strongly recommend not creating new scripts if all you want to do is change parameters.

You could make one `Enemy` script with gobs of prefabs mixing & matching different sets of parameters or other components, to define lots of different monsters without redundant code.

Or you can change the parameters of the object in your script when you instantiate it. The effect is the same. Some developers prefer to do everything in script like this, others prefer to keep this variation in the data like prefabs so it's easy to modularly add new types without code changes (which can help with a larger team where not everyone is a programmer)

> Do I even need multiple instances because I'll only have one of the same object type active at a time? should I just swap which method inside the object script is being accessed?

This is definitely an option too. You can even destroy or disable unneeded components and `AddComponent` or enable others to change up the behaviour without needing to implement multiple subclasses. This is the principle of composition over inheritance that Unity's component system banks on.

# Answer
> 0 votes
While I'm pretty novice I thought I would chime in too! (ofc i'm open to feedback too!) IMO it seems you're pretty close.

Rather than making multiple scripts to hold different enemies at this early phase, I agree with DMGregory's suggestion of using 1 prefab with different inputs.

After Instantiating the prefab enemy object I like to make a reference to the objects script in the EnemyManage object so i can call the different classes and assign values:

```
public GameObject EnemyPrefab;
public Enemy EnemyScript;
public void CreateBlueEnemy
{
    myInstance = Instantiate(myPrefab, parentTransform);
    EnemyScript = myInstance.GetComponent<Enemy>();
    EnemyScript.Damage = 1;
}

```

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


title: Canvas overlapped by scene objects

text:
# Question
Title: Canvas overlapped by scene objects
I am doing a space game and I have a little problem when doing the GUI.

As you can see here:  the objects from the scene overlap the text from the GUI.

From what I've seen on other topics, it seems that using Camera screen space any object closer than the Plane distance overlaps, but if I decrease the plane distance I can't see the canvas.

I've also tried setting the screen space to overlay, which should fix this, but then the GUI is not shown in the screen.

Anybody knows how to prevent the overlapping or at least what should I do for being able to use screen space overlay? Thanks!

# Answer
I think when you change **render mode** to **screen space overlay** then **target display** is not set to **Display 1**. So do the following I hope this will resolved the issue.

1. Change Canvas render mode to "screen space to overlay".
2. Change Target Display to "Display 1".
3. Make sure one or more UI object in the Canvas is enabled. i.e a button or txt.

"
> 1 votes

---
Tags: unity, gui
---


# Question
Title: Why is my A* algorithm is not taking future obstacles into consideration?
I am fairly new to programming, unity, and game design in general.
I am following an old A\* unity tutorial by Sebastian Lang and the algorithm he used doesn't seem to be completely accurate in terms of obstacles that aren't directly beside the path.

This is the current result of my code

So... not quite optimal. As you can see, going from bottom to top, it's trying to match the target's x-value, but the 1st block is in the way. As soon as the block ends, it successfully matches the target's x-value but then has to go around the 2nd block. Optimally, it would know that the only real obstacle is the 2nd block.

It's possible that he will come back later in another future video and fix this problem, as I am only 5/10 videos in; however, I'd rather practice thinking like a programmer instead of being told what to do exactly.

My guess for a fix would be to draw some sort of obstacle checking line from the start to the target and use the position data of the intersecting obstacles as a reference for the max distance the path needs to go in a specific axis. But even then, certain obstacle layouts wouldn't work, because an obstacle can obstruct the way without being exactly between the 2 points.

I'm not sure where to really go from here, so any advice would be helpful.

The main concepts are in pseudocode so those who don't know C# can also help.

**Pathfinding is calculated with the following pseudocode...**

```
h_cost = distance from start node
g_cost = distance from target node
f_cost = h_cost + g_cost

Get the start node position
Get the target node position

create an OPEN set for nodes that need to be evaluated
create a CLOSED set for nodes that have already been evaluated
add start node to OPEN

loop
     current = node with lowest f_cost
     move current from OPEN to CLOSED

     if current is the target node
          return

     for each neighbor of current (4 cardinal sides, and 4 diagonals)
          if unwalkable (an obstacle) OR in Closed
               continue

          if new path to neighbor is shorter OR neighbor is not in OPEN
               set f_cost of neighbor
               set parent of neighbor to current
               if neighbor is not in OPEN
                    add neighbor to OPEN

```

**Distance is calculated with the following pseudocode**

```
 Distance between start and target x-value = x
 Distance between start and target y-value = y

 If x > y, then 14 * y + 10 * (x - y)
 If x < y, then 14 * x + 10 * (y - x)

```

## Heap.cs

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

    public class Heap<T> where T : IHeapItem<T> {

        T[] items;
        int currentItemCount;

        public Heap(int maxHeapSize) {
            items = new T[maxHeapSize];
        }

        public void Add(T item) {
            item.HeapIndex = currentItemCount;
            items[currentItemCount] = item;
            SortUp(item);
            currentItemCount++;
        }

        public T RemoveFirst() {
            T firstItem = items[0];
            currentItemCount--;
            items[0] = items[currentItemCount];
            items[0].HeapIndex = 0;
            SortDown(items[0]);
            return firstItem;
        }

        public void UpdateItem(T item) {
            SortUp(item);
        }

        public int Count {
            get {
                return currentItemCount;
            }
        }

        public bool Contains(T item) {
            return Equals(items[item.HeapIndex], item);
        }

        void SortDown(T item) {
            while (true) {
                int childIndexLeft = item.HeapIndex * 2 + 1;
                int childIndexRight = item.HeapIndex * 2 + 2;
                int swapIndex = 0;

                if (childIndexLeft < currentItemCount) {
                    swapIndex = childIndexLeft;

                    if (childIndexRight < currentItemCount) {
                        if (items[childIndexLeft].CompareTo(items[childIndexRight]) < 0) {
                            swapIndex = childIndexRight;
                        }
                    }

                    if (item.CompareTo(items[swapIndex]) < 0) {
                        Swap(item, items[swapIndex]);
                    }
                    else {
                        return;
                    }
                }
                else {
                    return;
                }
            }
        }

        void SortUp(T item) {
            int parentIndex = (item.HeapIndex - 1) / 2;

            while (true) {
                T parentItem = items[parentIndex];
                if (item.CompareTo(parentItem) > 0) {
                    Swap(item, parentItem);
                }
                else {
                    break;
                }

                parentIndex = (item.HeapIndex - 1) / 2;
            }
        }

        void Swap(T itemA, T itemB) {
            items[itemA.HeapIndex] = itemB;
            items[itemB.HeapIndex] = itemA;
            int itemAIndex = itemA.HeapIndex;
            itemA.HeapIndex = itemB.HeapIndex;
            itemB.HeapIndex = itemAIndex;
        }

    }

    public interface IHeapItem<T> : IComparable<T> {
        int HeapIndex {
            get;
            set;
        }
    }

```

## Grid.cs

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

    public class Grid : MonoBehaviour {

        public bool onlyDisplayPathGizmos;
        public Transform player;
        public LayerMask unwalkableMask;
        public Vector2 gridWorldSize;
        public float nodeRadius;
        Node[,] grid;

        float nodeDiameter;
        int gridSizeX, gridSizeY;

        void Start() {
            nodeDiameter = nodeRadius * 2;
            gridSizeX = Mathf.RoundToInt(gridWorldSize.x / nodeDiameter);
            gridSizeY = Mathf.RoundToInt(gridWorldSize.y / nodeDiameter);
            CreateGrid();
        }

        public int MaxSize {
            get {
                return gridSizeX * gridSizeY;
            }
        }

        void CreateGrid() {
            grid = new Node[gridSizeX, gridSizeY];
            Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x / 2 - Vector3.forward * gridWorldSize.y / 2;

            for (int x = 0; x < gridSizeX; x++) {
                for (int y = 0; y < gridSizeY; y++) {
                    Vector3 worldPoint = worldBottomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.forward * (y * nodeDiameter + nodeRadius);
                    bool walkable = !(Physics.CheckSphere(worldPoint, nodeRadius, unwalkableMask));
                    grid[x, y] = new Node(walkable, worldPoint, x, y);
                }
            }
        }

        public List<Node> GetNeighbors(Node node) {
            List<Node> neighbors = new List<Node>();

            for (int x = -1; x <= 1; x++) {
                for (int y = -1; y <= 1; y++) {
                    if (x == 0 && y == 0)
                        continue;

                    int checkX = node.gridX + x;
                    int checkY = node.gridY + y;

                    if (checkX >= 0 && checkX < gridSizeX && checkY >= 0 && checkY < gridSizeY) {
                        neighbors.Add(grid[checkX, checkY]);
                    }
                }
            }

            return neighbors;
        }
        public Node NodeFromWorldPoint(Vector3 worldPosition) {
            float percentX = (worldPosition.x + gridWorldSize.x / 2) / gridWorldSize.x;
            float percentY = (worldPosition.z + gridWorldSize.y / 2) / gridWorldSize.y;
            percentX = Mathf.Clamp01(percentX);
            percentY = Mathf.Clamp01(percentY);

            int x = Mathf.RoundToInt((gridSizeX - 1) * percentX);
            int y = Mathf.RoundToInt((gridSizeY - 1) * percentY);
            return grid[x, y];
        }

        public List<Node> path;
        void OnDrawGizmos() {
            Gizmos.DrawWireCube(transform.position, new Vector3(gridWorldSize.x, 1, gridWorldSize.y));

            if (onlyDisplayPathGizmos) {
                if (path != null) {
                    foreach (Node n in path) {
                        Gizmos.color = Color.black;
                        Gizmos.DrawCube(n.worldPosition, Vector3.one * (nodeDiameter - .1f));
                    }
                }
            }
            else {
                if (grid != null) {
                    Node playerNode = NodeFromWorldPoint(player.position);
                    foreach (Node n in grid) {
                        Gizmos.color = (n.walkable) ? Color.white : Color.red;
                        if (path != null)
                            if (path.Contains(n))
                                Gizmos.color = Color.black;
                        Gizmos.DrawCube(n.worldPosition, Vector3.one * (nodeDiameter - .1f));
                    }
                }
            }
        }
    }

```

## Node.cs

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

    public class Node : IHeapItem<Node> {

        public bool walkable;
        public Vector3 worldPosition;
        public int gridX;
        public int gridY;

        public int gCost;
        public int hCost;
        public Node parent;
        int heapIndex;

        public Node(bool _walkable, Vector3 _worldPos, int _gridX, int _gridY) {
            walkable = _walkable;
            worldPosition = _worldPos;
            gridX = _gridX;
            gridY = _gridY;
        }

        public int fCost {
            get {
                return gCost = hCost;
            }
        }

        public int HeapIndex {
            get {
                return heapIndex;
            }
            set {
                heapIndex = value;
            }
        }

        public int CompareTo(Node nodeToCompare) {
            int compare = fCost.CompareTo(nodeToCompare.fCost);
            if (compare == 0) {
                compare = hCost.CompareTo(nodeToCompare.hCost);
            }
            return -compare;
        }

    }

```

## Pathfinding.cs

```
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System.Diagnostics;
    public class Pathfinding : MonoBehaviour {

        public Transform seeker, target;

        Grid grid;

        void Awake() {
            grid = GetComponent<Grid>();
        }

        void Update() {
            FindPath(seeker.position, target.position);
        }

        void FindPath(Vector3 startPos, Vector3 targetPos) {

            Stopwatch sw = new Stopwatch();
            sw.Start();

            Node startNode = grid.NodeFromWorldPoint(startPos);
            Node targetNode = grid.NodeFromWorldPoint(targetPos);

            Heap<Node> openSet = new Heap<Node>(grid.MaxSize);
            HashSet<Node> closedSet = new HashSet<Node>();
            openSet.Add(startNode);

            while (openSet.Count > 0) {
                Node currentNode = openSet.RemoveFirst();
                closedSet.Add(currentNode);

                if (currentNode == targetNode) {
                    sw.Stop();
                    print("Path found: " + sw.ElapsedMilliseconds + " ms");
                    RetracePath(startNode, targetNode);
                    return;
                }

                foreach (Node neighbor in grid.GetNeighbors(currentNode)) {
                    if (!neighbor.walkable || closedSet.Contains(neighbor)) {
                        continue;
                    }

                    int newMovementCostToNeighbor = currentNode.gCost + GetDistance(currentNode, neighbor);
                    if (newMovementCostToNeighbor < neighbor.gCost || !openSet.Contains(neighbor)) {
                        neighbor.gCost = newMovementCostToNeighbor;
                        neighbor.hCost = GetDistance(neighbor, targetNode);
                        neighbor.parent = currentNode;

                        if (!openSet.Contains(neighbor))
                            openSet.Add(neighbor);
                    }
                }
            }
        }

        void RetracePath(Node startNode, Node endNode) {
            List<Node> path = new List<Node>();
            Node currentNode = endNode;

            while (currentNode != startNode) {
                path.Add(currentNode);
                currentNode = currentNode.parent;
            }
            path.Reverse();

            grid.path = path;

        }

        int GetDistance(Node nodeA, Node nodeB) {
            int dstX = Mathf.Abs(nodeA.gridX - nodeB.gridX);
            int dstY = Mathf.Abs(nodeA.gridY - nodeB.gridY);

            if (dstX > dstY)
                return 14 * dstY + 10 * (dstX - dstY);
            return 14 * dstX + 10 * (dstY - dstX);

        }

    }

```

# Answer
> 5 votes
It looks to me like the problem is just a typo here in your node type:

```
public int fCost {
    get {
         return gCost = hCost;
      }
 }

```

This should be a `+`, not an `=`

This typo would result in your heuristic cost h alone being used when comparing items in the heap, so the algorithm would prefer nodes close to the target even if they have a larger total path distance to reach them, leading it to swerve inward between obstacles to minimize the heuristic instead of taking the shorter straight path.

This typo also pollutes your g cost, so g costs of its neighbours will come out wrong too.

---
Tags: unity, c#, 3d, path-finding
---


# Question
Title: My FollowPlayer script runs AWAY from the player?
With the script I'm using, it would make whatever model it was attached to, follow the player when they were close enough. Even though I have NOT updated to the newer version of Unity, the script isn't working how it used to.

While it does make the model face towards the player, it no longer follows/chases then and I have a suspicion that it may be because I am using rigidbody for the player controls instead of character controller (due to Character Controller no longer working after the latest Unity, which I did NOT update to)

Below is a copy of the script I'm using, which is super simple:

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

public class FollowPlayer : MonoBehaviour {

    //The target player
    public Transform Player;
    //At what distance will the enemy walk towards the player?
    public float walkingDistance = 10.0f;
    //In what time will the enemy complete the journey between its position and the players position
    public float smoothTime = 10.0f;
    //Vector3 used to store the velocity of the enemy
    private Vector3 smoothVelocity = Vector3.zero;

    //Call every frame
    void Update()
    {
        //Look at the player
        transform.LookAt(Player);

        //Calculate distance between player
        float distance = Vector3.Distance(transform.position, Player.position);

        //If the distance is smaller than the walkingDistance
        if (distance < walkingDistance)
        {
            //Move the enemy towards the player with smoothdamp
            transform.position = Vector3.SmoothDamp(
                transform.position,
                Player.position,
                ref smoothVelocity,
                smoothTime);
        }
    }
}

```

Any ideas why the model isn't chasing the player? I keep changing the settings to see if it's anything silly like that, but no matter what I put it, or what I do, the model just wants to stare but not follow or chase the player :/

Here's a screenshot of the hierarchy:

\[

And the player model does have the player tag. No matter what values I put into the inspector for the FollowPlayer script, the model with the attached script will not move towards the player.

**UPDATE:** I figured out it was because the model with the script attached didn't have a rigidbody component. The problem now is, the model runs *away* from the player.

# Answer
I figured out why they're running away. Because this model is so far away from the player, I made a duplicate player model and disabled the first one.

After deleting the duplicate and using the original, it stopped the model from running away from the player.
> 0 votes

# Answer
there are lots of thing that can make this happen. one thing i found in your code is that:

```
 float distance = Vector3.Distance(transform.position, Player.position);

        //If the distance is smaller than the walkingDistance
        if (distance < walkingDistance)
        {}

```

you calculate distance from player and say if its less than a threshold. if you want to stap in ha distance you have to change direction of `>` in that if condition.

standard way is to use `Vector3.MoveToward()` https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html

rigidBody is nonSense in your case as you are moving it using Transform. so you can simply remove rigidBody.
> 1 votes

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


title: Monobehavior functions list of unity

text:
# Question
Title: Monobehavior functions list of unity
I just started unity. Currently, I am familiar with Start() , Update(), Awake(), OnCollosionEnter(), OnTriggerEnter() and FixedUpdate(). Can you give me more functions like these

# Answer
The documentation of an API is generally a good place to go to if you want to find out the list of functions, types, et cetera in that API.

Unity's documentation for `MonoBehavior` can be found here. It includes a complete list of methods and members for `MonoBehavior`, which can be clicked on to get more details. If the documentation alone is insufficient for describing the purpose of or how to use something you are curious about, it should at least give you enough keywords to do a search on your favorite internet search engine for that topic.

If even that fails to turn up results that answer the questions you have, you can always ask another (more specific) question here.
> 2 votes

# Answer
you can simply search for unity **monobehavior** **callbacks**. you can find the, in link below:

https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
> 1 votes

---
Tags: unity
---


# Question
Title: Can I sample audio sources from others without asking?
As the title says, would it be considered legal if I take a part of an audio source (any media like music, dialog, video, etc.) to use in a project, whether it is for commercial or non-commercial purposes, without contacting the owner/creator of the asset?

As an example, Earthbound used this technique to create unique and memorable soundtracks.

# Answer
> 1 votes
Copyright law varies by jurisdiction. In the US, if you plan to distribute your music, samples must typically be cleared before use.

As described on nolo (note: the *italicized* emphasis is my own):

> Sample clearance is typically required only if you plan to make copies of your music and distribute the copies to the public. If you are just playing for your friends in a small group, you likely do not need to worry about copyright litigation from a large music studio.
>
> Sample clearance is ordinarily not required if:
>
> * You are just using the sampled music at home.
> * You are using the sample in live shows. This is because you are probably not making copies, and the owner of the venue pays the blanket license fees to performing rights organizations such as Broadcast Music Incorporated (BMI) or the American Society of Composers, Authors, and Publishers (ASCAP).
> * You plan to distribute copies to the public but meet one of the following: (1) an average listener would not notice the similarities between your end product and the sample, or (2) your use of the sample falls under the "fair use" doctrine. For more information on these, see "Defending a Lack of Sample Clearance," below. ...
>
> **Defending a Lack of Sample Clearance** If you decide to use samples without clearance, you might be in the clear in certain situations. Under U.S. copyright law, you do not have to obtain sample clearance if your sample is so altered that it does not infringe on the original, or your use is a fair one.
>
> **Ensuring Your Sample Use Does Not Infringe on Copyright** If you alter a sample so that an average listener cannot hear any substantial similarities between your work and the sample, there is no violation of the law. Often, musicians can be inspired by a tune, but make it so radically different from the original that the original artists (and the public) would not see the tunes as the same.
>
> **What Is Fair Use?** Fair use is the right to copy a portion of a copyrighted work without permission because your use is for a limited purpose, such as for educational use in a classroom or to comment upon, criticize, or parody the work being sampled.
>
> Factors in determining fair use. When reviewing fair use questions, courts primarily look for three factors:
>
> * You did not take a substantial amount of the original work (say, ten seconds of a song versus 60 seconds).
> * You transformed the material in some way (for instance, you added new base sounds to a melody).
> * You did not cause significant financial harm to the copyright owner (perhaps you are using a bit of classical music in your heavy metal rock song, which appeals to a different market).
>
> Do not believe the widespread myth that "less than two seconds is fair use." There is no "magic number" like this. Also, *some courts apply a fair use rule only to the musical composition copyright, not the sound recording copyright. For example, one judge ruled that any musical sampling violated the sound recording copyright*.
>
> You can use the above arguments to defend yourself against a lawsuit for sampling without permission. The problem: *You will not know for sure which way the judge will rule. And, most likely you will have to hire an attorney to represent you in court.*

Finally, even if the Earthbound soundtrack was sampling they likely legally cleared their samples first and even if they didn't, their prior actions aren't legal justification for anyone else.

# Answer
> 0 votes
IANAL, and this is not a legal advice site. You should consult with a lawyer.

---

No, you can't. This would be copyright infringement, and you cod be sued for it.

---
Tags: legal, audio
---


# Question
Title: How to Steer a Moving Object Away From Another Object(s)
I'm working with C# in Unity, and I'm making a top-down space shooter game in which there are many different AI-controlled ships flying around. The problem is that these ships often fly on top of one another in passing, and sometimes even will fly the same route on top of one another if given the same waypoint. I want to add a system to steer my AI ships away from each other as well as other obstacles so that instead of overlapping one another when flying the same path they will fly side-by-side, and will also try to avoid things that pass in front of them.

My current system essentially works like this: The AI looks at all of the current objectives, points of interests, etc, and decides where it wants to be on the map (a coordinate). The AI then sends an input direction to the ship, which then applies acceleration in that direction and changes the velocity. Therefore, any solution to alter my ship's pathing would need to alter this input direction somehow.

So my first idea was to check if there are any obstacles (ships, asteroids, structures, etc) within a radius of the ship, increasing this radius based on the ship's velocity (higher velocity = larger "view" radius):

```
Collider2D[] hits = Physics2D.OverlapCircleAll(transform.position, ship.velocity.magnitude);

```

If there is something nearby, calculate the direction to that collision, then calculate the opposite direction and scale it to the reciprocal, which also has the added effect of making the aversion stronger the shorter the distance to the collision is:

```
foreach (Collider2D hit in hits)
{

    if (hit.gameObject == gameObject) continue; // exclude self from the search

    Vector2 v = hit.ClosestPoint(transform.position) - (Vector2)transform.position;
    v = (1 / v.magnitude) * -v.normalized;

```

I would perform this for every nearby obstacle and add all of these together to get the avoidance vector:

```
    avoidanceVector += v;
    continue;
}

```

Then I add the total avoidance vector to the AI's input direction and normalize the result:

```
inputDirection += avoidanceVector;
inputDirection.Normalize();

```

However, when i add this avoidance vector to my input direction, my ships exhibit a strange behavior where sometimes they will simply stop moving completely. commenting out the line where i add them together stops this behavior.

I'm really not sure what could be going wrong here, but I think it has to do with my approach altogether. Can anyone help me figure out a clean, simple way to make my ships steer away from other objects?

# Answer
The problem with my code was with the way Unity's built-in function `Collider2D.ClosestPoint(Vector2 position)` works. The point returned by the function is not necessarily a point along the edge of the collider like I assumed it was - instead, if `position` is inside the collider, then it returns the same point. This creates a NaN when you divide by the magnitude of the distance between the two calculated points, which is zero.

Changing `hit.ClosestPoint(transform.position)` to `hit.transform.position` works well enough to steer them out of the area, but it does not take into account the *fastest* way to get out of the area.
> 1 votes

---
Tags: unity, c#, ai, path-finding, steering-behaviors
---


# Question
Title: Problems implementing shadow maps in directx
I am trying to implement shadow maps in my Dx11 rendering engine. I created a shadow map texture2d, a shader resource view, a depth stencil, a viewport, and a rasterizer state, as recommended by microsoft's guide. I used the Visual Studio graphics debugger and found out that the depth buffer is purely red. Does anyone have any suggestions on why this might be happening? Note-I am using a directional light to calculate the view and projection matrices.

This is my C++ code for creating all directx resources

```
D3D11_TEXTURE2D_DESC shadowMapDesc;
ZeroMemory(&shadowMapDesc, sizeof(D3D11_TEXTURE2D_DESC));
shadowMapDesc.Width = 1024;
shadowMapDesc.Height = 1024;
shadowMapDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
shadowMapDesc.Format = DXGI_FORMAT_R32_TYPELESS;
shadowMapDesc.ArraySize = 1;
shadowMapDesc.MipLevels = 1;
shadowMapDesc.CPUAccessFlags = 0;
shadowMapDesc.MiscFlags = 0;
shadowMapDesc.SampleDesc.Count = 1;
shadowMapDesc.SampleDesc.Quality = 0;
shadowMapDesc.Usage = D3D11_USAGE_DEFAULT;

//creating a texture
device->CreateTexture2D(&shadowMapDesc, nullptr, &shadowMapTexture);

//description for depth stencil view
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
ZeroMemory(&depthStencilViewDesc, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC));
depthStencilViewDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthStencilViewDesc.Texture2D.MipSlice = 0;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;

device->CreateDepthStencilView(shadowMapTexture, &depthStencilViewDesc, &shadowDepthStencil);

//creating a shader resource view
D3D11_SHADER_RESOURCE_VIEW_DESC shadowSRVDesc;
ZeroMemory(&shadowSRVDesc, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC));
shadowSRVDesc.Format = DXGI_FORMAT_R32_FLOAT;
shadowSRVDesc.Texture2D.MipLevels = 1;
shadowSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;

device->CreateShaderResourceView(shadowMapTexture, &shadowSRVDesc, &shadowSRV);

//setting up the shadow viewport
ZeroMemory(&shadowViewport, sizeof(D3D11_VIEWPORT));
shadowViewport.Width = 1024.0f;
shadowViewport.Height = 1024.0f;
shadowViewport.MinDepth = 0.0f;
shadowViewport.MaxDepth = 1.0f;
shadowViewport.TopLeftX = 0.0f;
shadowViewport.TopLeftY = 0.0f;

//rasterizer for pixel shader
D3D11_RASTERIZER_DESC shadowRasterizerDesc;
ZeroMemory(&shadowRasterizerDesc,sizeof(D3D11_RASTERIZER_DESC));
shadowRasterizerDesc.FillMode = D3D11_FILL_SOLID;
shadowRasterizerDesc.CullMode = D3D11_CULL_BACK;
shadowRasterizerDesc.DepthClipEnable = true;
shadowRasterizerDesc.FrontCounterClockwise = false;

//creating this rasterizer
device->CreateRasterizerState(&shadowRasterizerDesc, &shadowRasterizerState);

//sampler for the shadow texture
D3D11_SAMPLER_DESC shadowSamplerDesc;
memset(&shadowSamplerDesc, 0, sizeof(shadowSamplerDesc));
shadowSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER;
shadowSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER;
shadowSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER;
shadowSamplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
shadowSamplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
shadowSamplerDesc.BorderColor[0] = 1.0f;
shadowSamplerDesc.BorderColor[1] = 1.0f;
shadowSamplerDesc.BorderColor[2] = 1.0f;
shadowSamplerDesc.BorderColor[3] = 1.0f;
shadowSamplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR;
shadowSamplerDesc.ComparisonFunc = D3D11_COMPARISON_LESS;

device->CreateSamplerState(&shadowSamplerDesc, &shadowSamplerState);

```

This is how I am rendering everything to the buffer

```
    UINT stride = sizeof(Vertex);
UINT offset = 0;

//set depth stencil view to render everything to the shadow depth buffer
//context->ClearRenderTargetView(backBufferRTV, color);
context->ClearDepthStencilView(shadowDepthStencil, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
context->OMSetRenderTargets(0, nullptr, shadowDepthStencil);

context->RSSetViewports(1, &shadowViewport);
context->RSSetState(shadowRasterizerState);

XMFLOAT3 directionLightPosition;
XMFLOAT3 center(0.0f, 0.0f, 0.0f);
XMFLOAT3 up(0.0f, 1.0f, 0.0f);

//taking the center of the camera and backing up from the direction of the light
//this is the position of the light
XMStoreFloat3(&directionLightPosition, XMLoadFloat3(&center) + XMLoadFloat3(&directionalLight.direction) * 1000.f);
//creating the camera look to matrix
auto tempLightView = XMMatrixLookToLH(XMLoadFloat3(&directionLightPosition),
    XMLoadFloat3(&directionalLight.direction), XMLoadFloat3(&up));

//storing the light view matrix
XMFLOAT4X4 lightView;
XMStoreFloat4x4(&lightView, XMMatrixTranspose(tempLightView));

//calculating projection matrix
XMFLOAT4X4 lightProjection;
XMMATRIX tempLightProjection = XMMatrixOrthographicLH((float)shadowViewport.Width,(float)shadowViewport.Height,
    0.0f,10000.0f);
XMStoreFloat4x4(&lightProjection, XMMatrixTranspose(tempLightProjection));

shadowVertexShader->SetShader();
context->PSSetShader(nullptr, nullptr, 0);

for (size_t i = 0; i < entities.size(); i++)
{
    auto tempVertexBuffer = entities[i]->GetMesh()->GetVertexBuffer();
    shadowVertexShader->SetMatrix4x4("view", lightView);
    shadowVertexShader->SetMatrix4x4("projection", lightProjection);
    shadowVertexShader->SetMatrix4x4("worldMatrix", entities[i]->GetModelMatrix());
    shadowVertexShader->CopyAllBufferData();
    context->IASetVertexBuffers(0, 1, &tempVertexBuffer, &stride, &offset);
    context->IASetIndexBuffer(entities[i]->GetMesh()->GetIndexBuffer(), DXGI_FORMAT_R32_UINT, 0);

    //drawing the entity
    context->DrawIndexed(entities[i]->GetMesh()->GetIndexCount(), 0, 0);
}

```

This is my pixel shader for creating the shadow map

```
float4 main(VertexShaderInput input): SV_POSITION
{

    matrix worldViewProj = mul(mul(worldMatrix,view),projection);

    //transforming the point
    float4 outpos = mul(float4(input.position,1.0f),worldViewProj);

    return outpos; //returning the position

}

```

# Answer
> 2 votes
When rendering a shadow map, you are rendering the scene geometry from the perspective of the light and the only thing you are trying to get from it is the depth of the scene.

Your pixel shader is set up like a vertex shader. Make your "pixel shader" be a vertex shader, and then you can either set your pixel shader to NULL or you can make a void pixel shader if you want to check something on the pixel before adding it. For example, a texture might have a low alpha channel indicating it is see through, so clipping it will make it not show up in the depth buffer.

A void pixel shader looks like this:

```
void SHADOW_PS (VertexShaderOutput input)
{
    //bHasTexture is a Constant Buffer value set per model section
    if (bHasTexture > 0)
    {
        //ObjTexture is a Texture2D, ObjSamplerState is a Sampler State
        float4 texColor = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

        //if alpha of texture is too low, clip it
        clip(texColor.a - 0.2f);
    }
//note there is no return statement as there is no output
}

```

The improper setup of the vertex/pixel shaders is the most likely cause in your case of why you aren't getting anything. One other important thing to note is that you can't have the Shader Resource View (SRV) for a texture and a Render Target View (RTV)/Depth Stencil View (DSV) for the same texture bound to the graphics pipeline at the same time. After rendering the shadow map, you need to unbind the shadow DSV before binding the shadow SRV. Then, next frame, you need to unbind the shadow SRV before binding the shadow DSV again.

If you create your directx device with the debug flag enabled, in Visual Studios' debug output window (view-\>output), if there are any issues occurring with the graphics pipeline, messages detailing the issue will pop up there. It is an invaluable tool for debugging.

---
Tags: c++, directx11, hlsl, shadow-mapping
---


# Question
Title: Shader / Reconstructing position from DEPTH in VR through Projection Matrix
In Unity you can access the Depth-Buffer in the Pixel Shader. With that Depth-Buffer and the Nearplane, Farplane, CamToWorldMatrix and FOV you can calculate every pixel position of the objects the camera is seeing.

in VR though I get the wrong positions - because a VR frustum is slightly skewed. (http://doc-ok.org/?p=77)

So now we dont use the variables above to determine the Position - Now should be using the Projection Matrix.

Unitys "OnRenderImage()" is rendering alternately left and right eye of the VR device. So we "take" the projection matrix from each different eye. Also the FOV , Near and Far Planes, should be correct. We have also the screen Resolution. - which is exactly "540x600"

The Big Question here:

How to get that pixel Position with the help of those values.?

This is working for non-VR for those who need this in a computeshader:

Script:

```
        computeShader.SetTexture(_Kernel, "_DepthTexture", depthRenderTexture);
        computeShader.SetFloat("_CamFOV", camFOV);
        computeShader.SetFloat("_CamAspect", camAspect);
        computeShader.SetFloat("_CamNear", camNear);
        computeShader.SetFloat("_CamFar", camFar);
        computeShader.SetFloat("_ScreenWidth", Camera.main.pixelWidth);
        computeShader.SetFloat("_ScreenHeight", Camera.main.pixelHeight);
        computeShader.SetVector("_CamWorldMatrix0", camWorldMatrix.GetRow(0));
        computeShader.SetVector("_CamWorldMatrix1", camWorldMatrix.GetRow(1));
        computeShader.SetVector("_CamWorldMatrix2", camWorldMatrix.GetRow(2));
        computeShader.SetVector("_CamWorldMatrix3", camWorldMatrix.GetRow(3));
        computeShader.Dispatch(_Kernel, (int)(Camera.main.pixelWidth*Camera.main.pixelHeight)/128, 1, 1);

```

---

ComputeShader:

```
    [numthreads(128, 1, 1)]
    void CSMain(uint3 id : SV_DispatchThreadID)
    {
        if (id.x >= (uint)(_ScreenWidth*_ScreenHeight))
        return;

        int y = id.x / int(_ScreenWidth);
        int x = id.x % int(_ScreenWidth);
        float4 depthInfo = _DepthTexture[uint2(x, y)];

        float depthValue = depthInfo.z * _CamFar;
        // world X and Y components of our target vector
        float tanFov = tan(radians(_CamFOV / 2));
        float screenDimY = tanFov * _CamNear;
        float screenDimX = screenDimY * _CamAspect;
        // normalize screenpos from range 0..1 to range -1..1
        float4 normPos = depthInfo * 2 - 1;
        float screenPosX = screenDimX * normPos.x;
        float screenPosY = screenDimY * normPos.y;
        float screenPosZ = -_CamNear;
        float4 objInEyeSpaceVector;
        objInEyeSpaceVector.xyz = float3(screenPosX, screenPosY, screenPosZ) * depthValue / _CamNear;
        objInEyeSpaceVector.w = 1;
        float4x4 camWorldMat = float4x4(_CamWorldMatrix0, _CamWorldMatrix1, _CamWorldMatrix2, _CamWorldMatrix3);
        float4 objInWorldSpace =  mul(camWorldMat, objInEyeSpaceVector);

}

```

^ but this has to work now in VR too.

There are already the answers for a unity-shader. But i Need that as a computeshader

I dont have a v2f vert (appdata v) and a fixed4 frag (v2f i) : SV\_Target in the compute shader. In the end of the day, i would like ... Input: Matrixes, floats, everything i Need incl. depth. I have already the current X and Y coordinate of the Screen-Pixel which gets rendered. So... the last line of Code should be: float4 pixelPositionWorld; Just like in the first example i had.

# Answer
The approach we'll take depends on whether we're rendering an object in the world (like a screenspace decal volume) or a full-screen blit pass (like a post effect).

## Object in World

```
struct v2f
{
    float2 uv : TEXCOORD0;
    float3 worldDirection : TEXCOORD1;
    float4 screenPosition : TEXCOORD2;
    float4 vertex : SV_POSITION;
};

sampler2D _CameraDepthTexture;

v2f vert (appdata v)
{
    v2f o;

    // Subtract camera position from vertex position in world
    // to get a ray pointing from the camera to this vertex.
    o.worldDirection = mul(unity_ObjectToWorld, v.vertex).xyz - _WorldSpaceCameraPos;

    // Typical boilerplate.
    o.vertex = UnityObjectToClipPos(v.vertex);
    o.uv = v.uv;

    // Save the clip space position so we can use it later.
    // (There are more efficient ways to do this in SM 3.0+,
    // but here I'm aiming for the simplest version I can.
    // Optimized versions welcome in additional answers!)
    o.screenPosition = o.vertex;

    // Done.
    return o;
}

fixed4 frag (v2f i) : SV_Target
{
    // Compute projective scaling factor...
    float perspectiveDivide = 1.0f / i.screenPosition.w;

    // Scale our view ray to unit depth.
    float3 direction = i.worldDirection * perspectiveDivide;

    // Calculate our UV within the screen (for reading depth buffer)
    float2 screenUV = (i.screenPosition.xy * perspectiveDivide) * 0.5f + 0.5f;

    // Read depth, linearizing into worldspace units.
    float depth = LinearEyeDepth(UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, screenUV)));

    // Advance by depth along our view ray from the camera position.
    // This is the worldspace coordinate of the corresponding fragment
    // we retrieved from the depth buffer.
    float3 worldspace = direction * depth + _WorldSpaceCameraPos;

    // Draw a worldspace tartan pattern over the scene to demonstrate.
    return float4(frac((worldspace)), 1.0f);
}

```

## Blit / Post Effect

Unfortunately, when rendering a post effect as with `Graphics.Blit` it appears that the scene camera view & projection matrices aren't populated correctly, so we'll need to compute the needed parameters in a script and pass them to the shader as a property.

**Script**

```
void LateUpdate() {
   // To investigate: do we need to use non-jittered version for antialiasing effects?
   var p = _camera.projectionMatrix;
   // Undo some of the weird projection-y things so it's more intuitive to work with.
   p[2, 3] = p[3, 2] = 0.0f;
   p[3, 3] = 1.0f;

   // I'll confess I don't understand entirely why this is right,
   // I just kept fiddling with numbers until it worked.
   p = Matrix4x4.Inverse(p * _camera.worldToCameraMatrix)
      * Matrix4x4.TRS(new Vector3(0, 0, -p[2,2]), Quaternion.identity, Vector3.one);

   _material.SetMatrix("_ClipToWorld", p);
}

```

**Shader**

```
sampler2D _CameraDepthTexture;
float4x4 _ClipToWorld;

v2f vert (appdata v)
{
    v2f o;

    // No need for a matrix multiply here when a FMADD will do.
    o.vertex = v.vertex * float4(2, 2, 1, 1) - float4(1, 1, 0, 0);

    // Construct a vector on the Z = 0 plane corresponding to our screenspace location.
    float4 clip = float4((v.uv.xy * 2.0f - 1.0f) * float2(1, -1), 0.0f, 1.0f);
    // Use matrix computed in script to convert to worldspace.
    o.worldDirection = mul(_ClipToWorld, clip) -_WorldSpaceCameraPos;

    // UV passthrough.
    // Flipped Y may be a platform-specific difference - check OpenGL version.
    o.uv = v.uv;
    o.uv.y = 1.0f - o.uv.y;

    return o;
}

fixed4 frag (v2f i) : SV_Target
{
    // Read depth, linearizing into worldspace units.
    float depth = LinearEyeDepth(UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, i.uv)));

    // Multiply by worldspace direction (no perspective divide needed).
    float3 worldspace = i.worldDirection * depth + _WorldSpaceCameraPos;

    // Draw a worldspace tartan pattern over the scene to demonstrate.
    return float4(frac((worldspace)) + float3(0, 0, 0.1), 1.0f);
}

```
> 10 votes

# Answer
I wanted to drop a note here since I referred to this thread multiple times during my process of solving this issue. Linked is my Unity Forum post about this. My implementation differs quite a bit from @DMGregory to circumvent the issues unique to being in Single-Pass Stereo (SPS) VR.

In short there are a couple of issues that needed to be worked around:

1. CommandBuffer.Blit (and possibly Graphics.Blit?) have weird UVs in SPS
2. The Unity CBuffer values are wrong. You need to calculate your own.
3. The Clip-To-View math needs to be done a very particular way to correctly reverse the projection.
4. The Unity API Stereo Projection Matrix is wrong and needs to be slightly modified. I verified this by using RenderDoc and peeking at Unity's CBuffer during the FowardOpaque queue.

I'll recap the code from my forum post:

**In your C#**

```
    private void OnPreRender() // This is just a Later-Than-LateUpdate
    {

        if (cam.stereoEnabled)
        {
            // Left and Right Eye inverse View Matrices
            leftToWorld = cam.GetStereoViewMatrix(Camera.StereoscopicEye.Left).inverse;
            rightToWorld = cam.GetStereoViewMatrix(Camera.StereoscopicEye.Right).inverse;
            mat.SetMatrix("_LeftEyeToWorld", leftToWorld);
            mat.SetMatrix("_RightEyeToWorld", rightToWorld);

            leftEye = cam.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left);
            rightEye = cam.GetStereoProjectionMatrix(Camera.StereoscopicEye.Right);

            // Compensate for RenderTexture...
            leftEye = GL.GetGPUProjectionMatrix(leftEye, true).inverse;
            rightEye = GL.GetGPUProjectionMatrix(rightEye,true).inverse;
            // Negate [1,1] to reflect Unity's CBuffer state
            leftEye[1, 1] *= -1;
            rightEye[1, 1] *= -1;

            mat.SetMatrix("_LeftEyeProjection", leftEye);
            mat.SetMatrix("_RightEyeProjection", rightEye);
        }
    }

```

**In your Shader**

```
fixed4 frag (v2f i) : SV_Target
{
    float d = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uv); // non-linear Z
    float2 uv = i.uv;

    float4x4 proj, eyeToWorld;

    if (uv.x < .5) // Left Eye
    {
        uv.x = saturate(uv.x * 2); // 0..1 for left side of buffer
        proj = _LeftEyeProjection;
        eyeToWorld = _LeftEyeToWorld;
    }
    else // Right Eye
    {
        uv.x = saturate((uv.x - 0.5) * 2); // 0..1 for right side of buffer
        proj = _RightEyeProjection;
        eyeToWorld = _RightEyeToWorld;
    }

    float2 uvClip = uv * 2.0 - 1.0;
    float4 clipPos = float4(uvClip, d, 1.0);
    float4 viewPos = mul(proj, clipPos); // inverse projection by clip position
    viewPos /= viewPos.w; // perspective division
    float3 worldPos = mul(eyeToWorld, viewPos).xyz;

    fixed3 color = pow(abs(cos(worldPos * UNITY_PI * 4)), 20); // visualize grid
    return fixed4(color, 1);
}

```

**And the result should be something like:**

Cheers!
> 4 votes

# Answer
I'd like to provide an updated version of @colourmath's solution for ***single pass stereo*** since unity has changed since then and you can use `unity_StereoEyeIndex` to your advantage. And since this thread is the easiest thing to find when searching for VR world position in post effect shader, I figured it would be good to help anyone searching for a solution. I should note this is a solution for a post processing shader and not an object shader.

**C# Script:**

```
Matrix4x4[] matrices = new Matrix4x4[4];
void SetMatrix() {

    //cache matrices so they can be used in render image step
    if (mainCam.stereoEnabled) {
        // Both stereo eye inverse view matrices
        matrices[0] = mainCam.GetStereoViewMatrix(Camera.StereoscopicEye.Left).inverse;
        matrices[2] = mainCam.GetStereoViewMatrix(Camera.StereoscopicEye.Right).inverse;

        // Both stereo eye inverse projection matrices, plumbed through GetGPUProjectionMatrix to compensate for render texture
        matrices[1] = GL.GetGPUProjectionMatrix(mainCam.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left), true).inverse;
        matrices[3] = GL.GetGPUProjectionMatrix(mainCam.GetStereoProjectionMatrix(Camera.StereoscopicEye.Right), true).inverse;

        // Negate [1,1] to reflect Unity's CBuffer state
        matrices[1][1, 1] *= -1;
        matrices[3][1, 1] *= -1;

    } else {
        // Main eye inverse view matrix
        matrices[0] = mainCam.cameraToWorldMatrix;

        // Inverse projection matrices, plumbed through GetGPUProjectionMatrix to compensate for render texture
        matrices[1] = GL.GetGPUProjectionMatrix(mainCam.projectionMatrix, true).inverse;

        // Negate [1,1] to reflect Unity's CBuffer state
        matrices[1][1, 1] *= -1;
    }

    renderMat.SetMatrixArray("stereoMatrices", matrices);
}

```

**Shader:**

```
float4x4 stereoMatrices[4];

#define IVIEW_MATRIX stereoMatrices[unity_StereoEyeIndex * 2]
#define IPROJ_MATRIX stereoMatrices[unity_StereoEyeIndex * 2 + 1]

v2f vert(appdata v) {
    v2f o;

    o.pos = v.vertex * float4(2, 2, 1, 1) - float4(1, 1, 0, 0);
    o.uv = UnityStereoScreenSpaceUVAdjust(v.uv, _MainTex_ST);

    //_ProjectionParams.y is camera near plane
    float4 viewPos = mul(IPROJ_MATRIX, float4(v.uv * 2.0 - 1.0, _ProjectionParams.y, 1));
    viewPos /= viewPos.w;
    float3 wPos = mul(IVIEW_MATRIX, viewPos).xyz;

    o.ray = wPos - _WorldSpaceCameraPos;

    return o;
}

fixed4 frag(v2f i) : SV_Target {

    float zdepth = DECODE_EYEDEPTH(UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, i.uv)));
    float3 wPos = i.ray * zdepth + _WorldSpaceCameraPos;

    ...

}

```
> 4 votes

# Answer
A version that does't require additional script.

Based on Unity built in shader "Particle Add.shader".

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

struct appdata
{
    float4 vertex : POSITION;
};
struct v2f
{
    float4 vertex : SV_POSITION;
    float4 projPos : TEXCOORD0;
    float3 ray : TEXCOORD1;
};

UNITY_DECLARE_DEPTH_TEXTURE(_CameraDepthTexture);

v2f vert (appdata v)
{
    v2f o;
    float4 worldPos = mul(UNITY_MATRIX_M, v.vertex);
    o.ray = worldPos.xyz - _WorldSpaceCameraPos;
    o.vertex = mul(UNITY_MATRIX_VP, worldPos);
    o.projPos = ComputeScreenPos (o.vertex);
    o.projPos.z = -mul(UNITY_MATRIX_V, worldPos).z;
    return o;
}

float4 frag (v2f i) : SV_Target
{
    float sceneDepth = LinearEyeDepth (SAMPLE_DEPTH_TEXTURE_PROJ(_CameraDepthTexture, UNITY_PROJ_COORD(i.projPos)));
    float3 worldPosition = sceneDepth * i.ray / i.projPos.z + _WorldSpaceCameraPos;

    // Draw a worldspace tartan pattern over the scene to demonstrate.
    return float4(frac(worldPosition), 1.0f);
}

```
> 1 votes

---
Tags: unity, shaders, virtual-reality
---


title: Game engine animation management

text:
# Question
Title: Game engine animation management
Usually in a game scene there might be tens of animations going on at the same time, each being in its own state. I wonder usually how is this managed in game engines? Do they just stack a variable indicating the state of the animation on entity? Or do they use a separate animation system to keep all states?

# Answer
In unity it is handled with a node system. each node is an animation you made earlier, and you connect them in the order you want them to be played. You can also control when they are played by scripts, and then the node system gets more complicated with transitions. you can set a transition to occur when a boolean is true, or false, or when an integer is equal to 0 or 1 or less than or greater than etc.
> 1 votes

---
Tags: animation
---


# Question
Title: How to get the actor to follow the mouse while clicking and holding?
I am trying to do the top down project from scratch.

**I can already get the actor to move toward the mouse click:**

Only I need to keep clicking several times to change its path and keep walking indefinitely.

I would like to know how to keep it moving while I hold the mouse button.

**In the previous version (4.21) this code below fit perfectly, so I managed to do that (the condition was a variable that only became false when I released the mouse button):**

But now I can't make this connection (4.22).

I searched for some functions and even searched the new documentation for this loop (While Loop), but nothing worked.

**Link (While Loop BP UE4):**

https://docs.unrealengine.com/en-US/Engine/Blueprints/UserGuide/FlowControl/index.html#whileloop

---

**Player Blueprint:**

---

**As I could do this before, you can see in the answer to this question:**

How to make my character walk by clicking and holding the mouse button?

# Answer
Why dont you do it in Tick ?

You still can set the boolean variable on input action - and then use EventTick with conjunction of delay and send the player to the mouse location.
> 0 votes

---
Tags: movement, unreal-4, mouse
---


# Question
Title: Enemy sprite moving to a specific way depending on how it spawns
So I have a code where the sprite spawn outside the window and I want it to move on a specific straight line depending on where it spawn say if the sprite spawn at the top it goes at the bottom and vise versa if the sprite then spawn to the left it will go right and vise versa. Game1.cs code:

```
 public class Game1 : Game
 {
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Player player;
    List<Enemy> enemies = new List<Enemy>();

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {

        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        //player
        Texture2D playertexture = Content.Load<Texture2D>("Player");
        player = new Player(new Vector2(350, 175), playertexture);

        //enemy
        Texture2D enemytexture = Content.Load<Texture2D>("Enemy");
        Random random = new Random();
        var width = GraphicsDevice.Viewport.Width;
        var height = GraphicsDevice.Viewport.Height;

        for (int i = 0; i < 20; i++)
        {

            enemies.Add(new Enemy(new Vector2(random.Next(width, width + 100), random.Next(0, height)), enemytexture));
            enemies.Add(new Enemy(new Vector2(random.Next(0 - 100, 0), random.Next(0, height)), enemytexture));
            enemies.Add(new Enemy(new Vector2(random.Next(0, width), random.Next(-100, 0)), enemytexture));
            enemies.Add(new Enemy(new Vector2(random.Next(0, width), random.Next(height, height + 100)), enemytexture));
        }

    }

    protected override void UnloadContent()
    {

    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();
        foreach (Enemy enemy in enemies)
        {
            enemy.Update(gameTime);
        }
        player.Update(gameTime);

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        foreach (Enemy enemy in enemies)
        {
            enemy.Draw(spriteBatch);
        }
        player.Draw(spriteBatch);

        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

Enemy.cs

```
class Enemy
{
    Texture2D enemytexture;
    Vector2 enemyposition;

    public Enemy(Vector2 enemyposition, Texture2D enemytexture)
    {
        this.enemyposition = enemyposition;
        this.enemytexture = enemytexture;

    }

    public void Update(GameTime gametime)
    {
        enemyposition.X++;
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(enemytexture, enemyposition, Color.White);
    }
}

```

I wonder if I can do this in a way?

```
enemies.Add(new Enemy(new Vector2(random.Next(width, width + 100), random.Next(0, height)), enemytexture, enemyposition.X++));

```

# Answer
It sounds like you're on the right track with your thinking but the code you posted isn't quite right.

It looks like what you're really trying to do is give the enemy a *direction* when it spawns. So let's start at the `Enemy` class and see how that might look:

```
class Enemy
{
    Texture2D enemytexture;
    Vector2 enemyposition;
    Vector2 enemydirection;

    public Enemy(Vector2 enemyposition, Texture2D enemytexture, Vector2 enemydirection)
    {
        this.enemyposition = enemyposition;
        this.enemytexture = enemytexture;
        this.enemydirection = enemydirection;
    }

    public void Update(GameTime gametime)
    {
        enemyposition += enemydirection;
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(enemytexture, enemyposition, Color.White);
    }
}

```

Now, when you spawn an enemy you just need to pass in another `Vector2` that defines the direction like so:

```
enemies.Add(new Enemy(new Vector2(random.Next(width, width + 100), random.Next(0, height)), enemytexture, new Vector2(-1, 0));

```
> 1 votes

---
Tags: c#, monogame
---


title: How to give the effect on the obstacle?

text:
# Question
Title: How to give the effect on the obstacle?
I want to the obstacle Scale-In and Scale-Out using Dotween PlugIn? means some effect??

See this link: https://www.youtube.com/watch?v=\_Tq4t0gx49g&t=569s

Image:

I want to give a effect on the obstacle?

script:

Obstacle.cs

void Update()
{
        goTopToDown();
}

void goTopToDown()
{

  foreach (Transform item in GetComponentsInChildren<Transform>())
  {
      if (item.tag == "obstacleobject") //some obtsacle slow
      {
          item.localPosition += Vector3.down * speed * Time.deltaTime;                   //move top to down object
      }
      if (item.tag == "movefastobject") //some obstacle fast
      {
           item.localPosition += Vector3.down * movefastobjectspeed * Time.deltaTime;     //move fast object
       }
  }
```
</code></pre>

# Answer
Its quit simple, Here the code which will do the job:

```
    public void ScaleINOutAnimation(Transform objectTransform, float scaleIn, float scaleOut, float duration)
    {
        objectTransform.DOScale(scaleIn, duration).OnComplete(() =>
        {
            Debug.Log("Scale In done.");
            objectTransform.DOScale(scaleOut, duration).OnComplete(() =>
            {
                ScaleINOutAnimation(objectTransform, scaleIn, scaleOut, duration);
            });
        });
    }

```

As in the function parameter I used "Transform" to scale in and out Object if you are using "RectTransform" then just convert "Transform" to "RectTransform" and it will do the job.

**How to use this function:**

* **objectTransform:** The object you want to animate.
* **scaleIn**: The object scale you want for scale in.
* **scaleOut**: The object scale you want for scale Out.
* **duration**: Duration for "Scale In" animation or Duration for "Scale Out".

so the call will some thing like this:

```
ScaleINOutAnimation(this.GetComponent<Transform>(), 0.9f, 10.0f, 0.1f);

```

or

```
ScaleINOutAnimation(object, 0.9f, 10.0f, 0.1f);

```

I hope this help, Let me know if you need any help with this.
> 0 votes

---
Tags: unity
---


# Question
Title: How to create a map array with multiple layers?
I’m trying to create a map array without using JSON because I want to dynamically generate the map:

```
const map = [
      [
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1]
      ],
      [
        [3, 3, 3, 3, 0, 3, 3, 3],
        [3, 3, 3, 3, 7, 3, 3, 3],
        [4, 5, 5, -1, -1, -1, 5, 6],
        [11, -1, -1, -1, -1, -1, -1, 13],
        [11, -1, -1, -1, -1, -1, -1, 13],
        [11, -1, -1, -1, -1, -1, -1, 13],
        [11, -1, -1, -1, -1, -1, -1, 13],
        [18, 19, 19, 19, 19, 19, 19, 20]
      ],
      [
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15]
      ]

    ]
    const map = this.make.tilemap({data: map, tileWidth: 32, tileHeight: 32});
    const tileset = map.addTilesetImage("spritesheet", "tiles");
    const layer = map.createStaticLayer(0, tileset, 0, 0);
    const layer1 = map.createStaticLayer(1, tileset, 0, 0);
    const layer2 = map.createStaticLayer(2, tileset, 0, 0);

```

But it does not work, I did take a look at the documentation:

https://photonstorm.github.io/phaser3-docs/Phaser.Tilemaps.Tilemap.html

```
createStaticLayer(layerID, tileset [, x] [, y])

```

and “createStaticLayer” is asking for the layerID as I am passing, is it wrong the way I was creating the array for a 3 layers?

# Answer
> 1 votes
I just ran into this same issue, except I'm using dynamic layers instead of static layers. I was able to get it working by switching from the `createDynamicLayer` function to the `createBlankDynamicLayer` function.

I modified your code to reflect what worked for me, try it out:

```
const map = this.make.tilemap({ width: 8, height: 8, tileWidth: 32, tileHeight: 32 }),
    tileset = map.addTilesetImage("spritesheet", "tiles"),
    layer1 = map.createBlankDynamicLayer('layer1', tileset, 0, 0, 8, 8, 32, 32),
    layer2 = map.createBlankDynamicLayer('layer2', tileset, 0, 0, 8, 8, 32, 32),
    layer3 = map.createBlankDynamicLayer('layer3', tileset, 0, 0, 8, 8, 32, 32);

const layer1Data = [
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1],
        [-1, -1, -1, -1, -1, -1, -1, -1]
    ],
    layer2Data = [
        [3, 3, 3, 3, 0, 3, 3, 3],
        [3, 3, 3, 3, 7, 3, 3, 3],
        [4, 5, 5, -1, -1, -1, 5, 6],
        [11, -1, -1, -1, -1, -1, -1, 13],
        [11, -1, -1, -1, -1, -1, -1, 13],
        [11, -1, -1, -1, -1, -1, -1, 13],
        [11, -1, -1, -1, -1, -1, -1, 13],
        [18, 19, 19, 19, 19, 19, 19, 20]
    ],
    layer3Data = [
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15],
        [15, 15, 15, 15, 15, 15, 15, 15]
    ];

layer1.putTilesAt(layer1Data, 0, 0);
layer2.putTilesAt(layer2Data, 0, 0);
layer3.putTilesAt(layer3Data, 0, 0);

```

Instead of an existing layerID or layer name from Tiled, the first parameter for `createBlankDynamicLayer` is a name to give your new layer.

According to the docs, the last 4 parameters should be optional in this case (width, height, tileWidth, tileHeight), but it didn't work for me unless I included them.

Unfortunately, I don't see an equivalent "createBlank" function for static layers in the docs, so you'd need to switch to dynamic layers to do it this way. I'm guessing that's because you can't change static layers (like I do with the `putTilesAt` function at the end of the code above), so a new blank one would forever stay blank. As far as I know the only difference between static and dynamic layers is that you can do more with dynamic layers at the expense of slower rendering speed. (Personally, I haven't noticed a difference in rendering speed between the two, so you might be fine switching to dynamic.)

# Answer
> -1 votes
I am not sure it works like this https://jsfiddle.net/nazimboudeffa/y830g9u6/ (you have to notice that the layed ID is the Index of it in the array) but the correct way is doing it this way with one layer

```
var config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    width: 800,
    height: 600,    loader: {
      baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/',
      crossOrigin: 'anonymous'
    },
    scene: {
        preload: preload,
        create: create
    },
    physics: {
        default: 'arcade'
    }
};

var game = new Phaser.Game(config);
var m =
      [
        [0, 1, 2, 3, 4, 5, 6, 7, 8],
        [8, 8, 8, 8, 8, 8, 8, 8, 8],
        [0, 0, 0, 0, 0, 3, 3, 0, 0]
      ];

function preload ()
{
    this.load.image('tiles', 'maps/super-pixel-platformer-set/tileset.png');
}

function create ()
{
    this.map = this.make.tilemap({data: m, tileWidth: 16, tileHeight: 16});
    this.tileset = this.map.addTilesetImage("spritesheet", "tiles");
    this.layer = this.map.createStaticLayer(0, this.tileset, 0, 0);

}
```

```
<script src="//cdn.jsdelivr.net/npm/phaser@3.18.1/dist/phaser.min.js"></script>
```

---
Tags: javascript, tilemap, phaser
---