title: Can I create a "Multiple" Sprite in C#?

text:
# Question
Title: Can I create a "Multiple" Sprite in C#?
In the import settings for my sprite image I can select a dropdown box titled "Sprite Mode" and I can change it from Single to Multiple.

Is there any way to select "Multiple" if I'm creating a Sprite within a C# script with `Sprite.Create()`?

# Answer
"Multiple" as a mode doesn't really mean anything at game runtime. It makes sense in the editor for asset management purposes, being able to group sprites from the same source asset together in the project folder & inspectors.

At runtime though, you're only working with the individual sprites. So you'll have more than one sprite referencing the same source texture, but each of those sprites doesn't need to know about its neighbours. They're individually created the same as if they were the only sprite on that texture.

So, we can create as many Sprites as we want out of a single spritesheet texture using Sprite.Create:

> public static Sprite Create(Texture2D texture, Rect rect, Vector2pivot, float pixelsPerUnit = 100.0f, uint extrude = 0, SpriteMeshType meshType = SpriteMeshType.Tight, Vector4border = Vector4.zero);

Something like this:

```
public Sprite[] MakeMultiSprite(
                 Texture2D spritesheet,
                 float pixelsPerUnit,
                 params Rect[] regions)
{

    var sprites = new Sprite[regions.Length];

    for(int i = 0; i < output.Length; i++)
        sprites[i] = Sprite.Create(
                       spritesheet,
                       regions[i],
                       new Vector2(0.5, 0.5),
                       pixelsPerUnit);

     return sprites;
}

```

This generates any number of Sprites from a collection of rectangular regions on a single texture — effectively making that texture act like a "Multiple" mode sprite.
> 1 votes

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


# Question
Title: How can I replicate Quantum Break's distortion particle effect?
Quantum Break has this fantastic particle effect, it's a distortion effect like broken glass. I want know how I can replicate this effect? You can see it below, and a full video is available on YouTube:

# Answer
> 105 votes
# Pyramid Particle

Unity default particle's shape is quad. first you need to change this shape to pyramid by using pyramid object or turns quads to pyramids with a geometry shader.

# Refraction

To making broken glass effect(Refraction) you can use `GrabPass { "TextureName" }` that will grab screen contents into a texture.

> GrabPass is a special pass type - it grabs the contents of the screen where the object is about to be drawn into a texture. This texture can be used in subsequent passes to do advanced image based effects.
>
> https://docs.unity3d.com/Manual/SL-GrabPass.html

```
Shader "Smkgames/GlassRefraction"
{
    Properties{
        _Refraction("Refraction",Float) = 0.05
        _Alpha("Alpha",Range(0,1)) = 1
    }
    SubShader
    {
Tags {"Queue"="Transparent" "RenderType"="Transparent"}

        Blend SrcAlpha OneMinusSrcAlpha

        GrabPass
        {
            "_GrabTexture"
        }

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
            };

            struct v2f
            {
                float4 grabPos : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };
            sampler2D _MainTex;
            float _Alpha,_Refraction;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.grabPos = ComputeGrabScreenPos(o.vertex);
                return o;
            }

            sampler2D _GrabTexture;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2Dproj(_GrabTexture, i.grabPos+_Refraction);
                return float4(col.rgb,_Alpha);

            }
            ENDCG
        }
    }
}

```

# Using mesh normals

Let’s proceed with a shader that displays mesh normals in world space. I used it because I wanted to look three dimensional broken shape.

```
    Shader "Smkgames/BrokenGlass3D"
{
    Properties{
        _MainTex("MainTex",2D) = "white"{}
        _Alpha("Alpha",Float) = 1
    }
    SubShader
    {
Tags {"Queue"="Transparent" "RenderType"="Transparent"}
 Blend SrcAlpha OneMinusSrcAlpha

        GrabPass
        {
            "_GrabTexture"
        }

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 grabPos : TEXCOORD0;
                float3 normal :NORMAL;
            };

            struct v2f
            {
                float4 grabPos : TEXCOORD0;
                float4 vertex : SV_POSITION;
                half3 worldNormal :TEXCOORD1;

            };
            sampler2D _MainTex;
            float _Intensity,_Alpha;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.grabPos = ComputeGrabScreenPos(o.vertex);
                o.worldNormal = UnityObjectToWorldNormal(v.normal);
                return o;
            }

            sampler2D _GrabTexture;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 c = 0;
                c.rgb = i.worldNormal*0.5+0.5;
                float4 distortion = tex2D(_MainTex,i.grabPos)+_Intensity;
                fixed4 col = tex2Dproj(_GrabTexture, i.grabPos+c.r);
                return float4(col.rgb,_Alpha);
            }
            ENDCG
        }
    }
}

```

# Heat Distortion

To creating heat distortion you can use flow map

> A flow-map is a texture that stores 2d directional information in a texture. The color of the pixel determines what direction it is using the uv-coordinates texture as a base. The more color there is the faster the proportional speed. Example green tells it to go up-left, the center is neutral, and red will go down right. It’s a useful technique for liquid materials like water, and a useful alternative to just a panner node.

```
    Shader "Smkgames/HeatDistortion"
{
    Properties{
        _DistortionMap("DistortionMap",2D) = "white"{}
        _Intensity("Intensity",Float) = 50
        _Mask("Mask",2D) = "white"{}
        _Alpha("Alpha",Range(0,1)) = 1
    }
    SubShader
    {
Tags {"Queue"="Transparent" "RenderType"="Transparent"}

        GrabPass
        {
            "_GrabTexture"
        }

        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
            };

            struct v2f
            {
                float4 grabPos : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };
            sampler2D _Mask,_DistortionMap;
            float _Alpha,_Refraction;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.grabPos = ComputeGrabScreenPos(o.vertex);
                return o;
            }

            sampler2D _GrabTexture;
            float _Intensity;

            fixed4 frag (v2f i) : SV_Target
            {
                float mask = tex2D(_Mask,i.grabPos);
                mask = step(mask,0.5);
                //mask = smoothstep(mask,0,0.4);
                float4 distortion = tex2D(_DistortionMap,i.grabPos+_Time.y)+_Intensity;
                fixed4 col = tex2Dproj(_GrabTexture, i.grabPos*distortion);
                return float4(col.rgb,mask*_Alpha);

            }
            ENDCG
        }
    }
}

```

another example by using normal:

```
Shader "Smkgames/HeatDistortion2" {
Properties {
        _CutOut ("CutOut (A)", 2D) = "black" {}
        _BumpMap ("Normalmap", 2D) = "bump" {}
        _BumpAmt ("Distortion", Float) = 10
}

Category {

    Tags { "Queue"="Transparent"  "IgnoreProjector"="True"  "RenderType"="Opaque" }
    Blend SrcAlpha OneMinusSrcAlpha
    Cull Off
    Lighting Off
    ZWrite Off
    Fog { Mode Off}

    SubShader {
        GrabPass {
            "_GrabTexture"
        }
        Pass {

CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#pragma multi_compile_particles
#include "UnityCG.cginc"

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

struct v2f {
    float4 vertex : POSITION;
    float4 uvgrab : TEXCOORD0;
    float2 uvbump : TEXCOORD1;
    float2 uvcutout : TEXCOORD2;
};

sampler2D _BumpMap,_CutOut,_GrabTexture;
float _BumpAmt;
float4 _GrabTexture_TexelSize;
float4 _BumpMap_ST,_CutOut_ST;

v2f vert (appdata_t v)
{
    v2f o;
    o.vertex = UnityObjectToClipPos(v.vertex);
    o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*-1) + o.vertex.w) * 0.5;
    o.uvgrab.zw = o.vertex.zw;
    o.uvbump = TRANSFORM_TEX( v.texcoord, _BumpMap );
    o.uvcutout = TRANSFORM_TEX( v.texcoord, _CutOut );
    return o;
}

half4 frag( v2f i ) : COLOR
{
    half2 bump = UnpackNormal(tex2D( _BumpMap, i.uvbump )).rg;
    float2 offset = bump * _BumpAmt * _GrabTexture_TexelSize.xy;
    i.uvgrab.xy = offset * i.uvgrab.z + i.uvgrab.xy;

    half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
    fixed4 cut = tex2D(_CutOut, i.uvcutout);
    fixed4 emission = col;
    emission.a = (cut.a);
    return emission;
}
ENDCG
        }
    }

  }
}

```

# RGB Split

If you pay attention to your first gif you can see little RGB split.

```
Shader "Hidden/RgbSplit"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _NoiseTex1 ("Noise Texture A", 2D) = "white" {}
        _NoiseTex2 ("Noise Texture B", 2D) = "white" {}
    }
    SubShader
    {

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex,_NoiseTex1,_NoiseTex2;
            float3 colorSplit(float2 uv, float2 s)
{
    float3 color;
    color.r = tex2D(_MainTex, uv - s).r;
    color.g = tex2D(_MainTex, uv    ).g;
    color.b = tex2D(_MainTex, uv + s).b;
    return color;
}

float2 interlace(float2 uv, float s)
{
    uv.x += s * (4.0 * frac((uv.y) / 2.0) - 1.0);
    return uv;
}

    fixed4 frag (v2f i) : SV_Target
    {

    float t = _Time.y;

    float s = tex2D(_NoiseTex1, float2(t * 0.2, 0.5)).r;

    i.uv = interlace(i.uv, s * 0.005);
    float r = tex2D(_NoiseTex2, float2(t, 0.0)).x;

    float3 color = colorSplit(i.uv, float2(s * 0.02, 0.0));

    return float4(color, 1.0);

            }
            ENDCG
        }
    }
}

```

# Useful Links

https://www.fxguide.com/featured/time-for-destruction-the-tech-of-quantum-break/

Source On Github

---
Tags: unity, shaders, graphic-effects
---


# Question
Title: How do I access a variable from my code in Godot's editor?
In Godot, I have a node with a variable that I often need to tweak for balancing purposes. It would be a lot easier to manage if I could modify it inside the editor instead of the code.

How would I go about doing this?

# Answer
This can be done with the `export` keyword.

```
export var my_var = 5

# No default value
export(int) var my_int

```

The result of this code in the editor is this:

It is possible to use pretty much any type used in the engine as can be seen in the documentation. This means that you could set a scene resource to be instanced from the editor instead of hard-coding it in.
> 11 votes

---
Tags: godot
---


title: How to push an object?

text:
# Question
Title: How to push an object?
I would like to "push" an object using a raycast. With the following code, the problem is that depending of player rotation, i don't push the object but i pull it.

What am i wrong ?

```
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast (RayCastSpawnOut.transform.position, fwd, out hit, 5)) {
                if (hit.transform.tag == "MyObjectTag") {
                    GameObject myobj = hit.transform.gameObject;
                    Rigidbody myobj_rb = myobj.GetComponent<Rigidbody> ();
                    Vector3 dir = transform.position - myobj_rb.transform.position;
                    dir.Normalize(); //Normalize to get the correct direction
                    myobj_rb.AddRelativeForce (dir * 0.5f, ForceMode.Impulse);
                }
            }

```

# Answer
# Lets look at the math:

We'll assume that the universe is 1 dimesnional and your player object exists at `5` while the object you want to push exists at `6`.

You fire a ray, it hits the object, we get the rigidbody and then we perform this calculation:

```
dir = transform.position - myobj_rb.transform.position

```

What is the value of `dir` in our one dimensional universe? Why, -1:

`5` minus `6` is `-1`

We then normalize (no change) and then apply that force to the object:

```
myobj_rb.AddRelativeForce (dir * 0.5f, ForceMode.Impulse);

```

But the force is negative, pulling it towards the player!
> 1 votes

---
Tags: unity, physics
---


title: Time limit on puzzle games: yea or nay?

text:
# Question
Title: Time limit on puzzle games: yea or nay?
Of course, it goes without saying that this can only work when the puzzle is randomly generated (say, something like minesweeper/bejeweled) and not hand-designed levels (such as trainyard, theseus & the minotaur etc).

I am currently thinking that this can instill a sense of urgency to the player and make them feel more challenged. Along with increasing the actual puzzle difficulty, a time restriction could be another way to increase difficulty, and the combination of both can be used as a way to give a sense of progress.

Also possibly, incremental time increases when solving parts of the puzzle (like time extensions in racing games) could be used for these games.

What I'm wondering about is, what's the accepted thought about using time limits? Would they work as I'm currently thinking or am I missing anything?

# Answer
> 7 votes
Some thoughts about puzzle time limits:

1. You can have soft time-limits. With this, the game will not allow you to move to the next level because you didn't solve the puzzle in time, but you can still continue playing just to learn strategies, etc.
2. Many people play puzzle based games for relaxation purposes, so it might not make sense in certain scenarios.
3. A tiered reward system (5 stars for \< 1 min, 4 stars for \< 1:30) might make sense. This allows those who want to get the highest score, get the highest score, and those who don't care will still be able to progress.
4. Some non-random puzzle games still have time limits. There is a graph coloring game for iOS (whose name I can't think of) that has pre-made levels whose main goal is to beat under the time limit. The actual puzzle is easy, but the time limit is the main cause of difficulty

# Answer
> 3 votes
I'm not sure why you say that time limits can't work on hand-designed levels. I'd say that they're more reasonable on hand-designed levels, because you can test and work out what the minimum time necessary is and what a reasonable extension is for the limit.

However, a hard time limit (out of time =\> lose the level) is more appropriate for the arcadey early days of video game design. If you're not getting paid per play, it's a good idea to tone down the frustration of being half a second too slow - and, while you're at it, make the game playable by people which physical limitations which make them slower than the average player - by using soft time limits. In other words, out of time means no time bonus, but you can still complete the level. (As an example, see my game The Track Controller). Then you can get into achievements for completing X levels with time bonus, etc. (Not sure why I didn't think of that back then).

# Answer
> 2 votes
I'd say, the harder it is in the first place the less need for a time limit. Bejeweled wouldn't work very well without some sort of time control, in more complicated games the limit may just be annoying.

You could make multiple different game modes with different timing systems, try out what works and give the player some options.

# Answer
> 0 votes
Tetris and Doctor Mario have time limits in the sense that you have to act on every brick within a given time, and the time allocated becomes more scarce as the game becomes faster.

Doctor Mario for example, has a specific puzzle to solve with bricks that fall fast like tetris, and after a given time limit the game becomes impossible to play due to the speed of play.

It's a very popular game system which gives a constant and increasing sense of pace and anticipation, of continual time pressure on the player.

Given the sales figures of those to games, You can say that suspense inducing, continuous rather than final time constraints and fast thinking can be a very challenging and interesting attribute for a game.

---
Tags: game-design, puzzle
---


# Question
Title: Establishing if a tile is available to move into
I'm working on a grid-based game as a hobby project. Think of an ANSI game like ZZT. The grid is represented by a two-dimensional array of objects which contain both the UI element which takes care of displaying the sprite image and also the data accompanying whatever is in that position on the grid. I'm having trouble working out the mechanics of elements on the game grid determining whether they are able to move into a neighbouring cell.

Determining whether there is something in any given grid position is straightforward, as each instance of the class representing a cell on the grid has a property representing the sprite in occupation of the cell. Checking if this property is nil works fine in establishing if something static is there, but it becomes problematic if there are many objects moving from one grid position to another. The problems I'm having are:

1. Objects in grid cells will attempt to push objects out of their destination cell; this is intended behaviour, so that the player or NPCs can move objects around. The object which is pushed will check if it is capable of moving in that direction, and if the cell into which it is being asked to move already contains another object. If it does, it will attempt to push that object, and so on and so on until an object either agrees to be pushed (into an empty spot), or refuses (because there is nowhere for it to move or because it cannot move in that direction). The return values for the attempt to push will then cascade back up to the originating object and the sprites all move (or not). This causes a problem, however, if there are several sprites moving in a straight line in the same direction. Rather than all moving forwards together (which they should), the last object in the line thinks that the next cell is occupied so tries to push the object in that cell, which is unnecessary, because that object will be moving anyway. This causes the objects to spread out with gaps between them, which is abnormal.
2. Due to this, I considered having the objects check if the destination cell is occupied, and if so, check if the object in that cell will be moving out, and if anything else will be moving in. However, I'm concerned this could result in a condition where several objects may refuse to move because of each other's presence.

I have considered looking at source code for a similar game, but I don't want to copy another implementation, rather I'm looking for guidance on how I can solve the problem. Thanks in advance!

# Answer
It looks like you can resolve this like so:

1. For each dynamic object in your grid....
2. If that dynamic object has already had its movement updated this cycle, continue to the next one

(this is important because we have some out-of-order updates coming)
3. If that dynamic object needs its movement updated, check to see if the cell it's moving into is free

* if so, move it, and mark it as having already updated its movement this cycle
4. If the cell it's moving into is not free, check if it contains a dynamic object whose movement has not yet been updated

* if so, recursively resolve its movement starting from to step 3
5. If the cell it's moving into is not free and does not contain a dynamic object that might yet move, check if it's a pushable object

* if so, recursively resolve the push starting from step 3
6. If we still haven't been able to move the object, we've exhausted our options, and the object cannot move this cycle

* mark it as having already updated its movement this cycle, and continue to the next...

So for your example of a line of objects all moving in the same direction, this scheme will lead us to recurse all the way down to the lead object, move it (if able), then move its first follower, and so on, back until we reach the object we started with in the chain. Because we skipped around the normal iteration order to move the leader first, we mark it as done for this cycle, so that we don't accidentally move it a second time when we resume our normal iteration.

If you manage to recurse all the way back to the same object again, then you have a tautology "this object can move, if the chain of objects ahead of it can move, if this object can move." So all moves in that loop can complete successfully, you'll just need to use a little caution executing them to make sure you don't overwrite anybody since the moves no longer have a "front-to-back" order but happen simultaneously.

---

This basic version remains sensitive to the order in which your original iteration over the dynamic objects runs: if two objects are positioned like so:

```
 A--->[  ]
        ^
        |
        B

```

Then the result depends on whether A updates first, then B pushes it, or B updates first, then is pushed by A:

```
A first           B first
  A
[ B ]              [ A ] B

```

One common strategy to approach this is to split your movement resolution into two phases: in the first phase, every object tries to reserve the cell it wants to move into - propagating pushes as above, but not moving anything yet, just noting an *intention* to move. If any cells get reserved more than once, record a list of all the objects trying to reserve that cell. Then proceed with all uncontested moves.

Next you move on to your lists of contested moves, and check if they're still contested (an object might have gotten pushed so it no longer wants to enter a contested cell). Perform any moves that are now uncontested, then check this lists again...

Once you have only contested moves left, perform an order-independent resolution on each of those contested lists (eg. "nobody gets to move" or "a randomly selected object gets to move" or "the object with the highest speed value gets to move, with ties broken by...." are all examples of resolution rules you could use).

Now at last you can move everything. Just watch out for cyclic dependencies and make sure you don't chase an infinite loop! ;)
> 2 votes

# Answer
I want to thank @DMGregory again for the great explanation in his answer above. I'm leaving his answer as the accepted answer, but wanted to also post a snippet of code which I wrote using his explanation as a guide.

This is in Objective-C, and quite a specific situation. Each `Actor` object can have idle `Response`s added to it which are carried out one at a time per tick. They can also emit `Stimulus` objects which are detected by other `Actor`s and elicit further `Response`s from them. In this way, the various `Actor`s can be configured to interact with each other (and the player) in ways which do not need to be pre-programmed.

The example below interacts with this system when checking if the `Actor` which is blocking the way will move. Its `idleActions` are checked to see if its `Response` for the current tick will result in it moving, and if so, whether it is able to do so. I'm using Objective-C block-based coding for this, and it's so deeply embedded in my (now very large) project that there was no way I was changing it all to get a return value from the block back to the main function. So I cheated by putting in the infinite loop, which is broken by the completion block when the return value is ready.

I hope this helps others who might be trying to solve the same problem, as long as it's not too specific a case to apply to others.

**EDIT** I've added code to the sample below to handle a deadlock situation where two `Actor`s want to move to each other's positions on the grid (which is impossible in my case). In this situation, the one with the lowest UUID (and thus created first) will take priority and try to find a route around the other. This whole solution is possibly overkill for my needs, but it's been fascinating to see this puzzle through from start to finish. And here's gif showing the result of the below code in context. The two characters have not had their movements programmed beyond their start and end points. The path they have chosen, the re-routing, waiting for the other actor to wait, continuing the path and evaluating arrival is all handled dynamically.

```
- (BOOL)canMoveToGridElement:(GridElement*)gridElement direction:(GridDirection)direction {
    self.moveTestGridElement = gridElement;

    //Only move once per tick (reset by the GameController each tick)
    if (self.hasMovedThisTick) {
        return [self finishCanMoveToGridElementCanMove:NO];
    }

    //Prevent moving out of bounds (should never happen, but just in case)
    if (!gridElement) {
        return [self finishCanMoveToGridElementCanMove:NO];
    }

    //If the destination is emppty, move there
    if (!gridElement.object) {
        return [self finishCanMoveToGridElementCanMove:YES];
    }

    //If there's something in the destination which isn't an Actor, don't move there
    if (![gridElement.object isKindOfClass:[Actor class]]) {
        return [self finishCanMoveToGridElementCanMove:NO];
    }

    //Get the Actor which is blocking the way
    Actor *blockingActor = (Actor*)gridElement.object;

    //We're in a deadlock situation, where two Actors are adjacent and want to move to each other's position
    if (blockingActor.moveTestGridElement == self.gridElement || self.moveTestGridElement == blockingActor.gridElement) {
        //The Actor with the highest UUID (created most recently) takes priority and will try to re-route
        if (self.UUID.integerValue < blockingActor.UUID.integerValue) {
            GridDirection alternativeDirection = GridDirectionNone;

            if (direction == GridDirectionUp || direction == GridDirectionDown) {
                if ([self canMoveInDirection:GridDirectionLeft]) {
                    alternativeDirection = GridDirectionLeft;
                }
                else if ([self canMoveInDirection:GridDirectionRight]) {
                    alternativeDirection = GridDirectionRight;
                }
            }
            else if (direction == GridDirectionLeft || direction == GridDirectionRight) {
                if ([self canMoveInDirection:GridDirectionUp]) {
                    alternativeDirection = GridDirectionUp;
                }
                else if ([self canMoveInDirection:GridDirectionDown]) {
                    alternativeDirection = GridDirectionDown;
                }
            }

            if (alternativeDirection != GridDirectionNone) {
                blockingActor.waitForBlockingActorToMove = YES;
                [self moveInDirection:alternativeDirection];
            }

            return [self finishCanMoveToGridElementCanMove:NO];
        }

        return [self finishCanMoveToGridElementCanMove:NO];
    }

    //If the blocking actor has idle actions pending
    if (blockingActor.idleActions.count > 0) {
        //Get the first Response in the blocking Actor's idle array
        Response *firstResponse = blockingActor.idleActions.firstObject;

        //If the first Response is of movement type
        if ([firstResponse isKindOfClass:[ResponseMovement class]]) {
            //Set by the blocking Actor's movement Response completion block
            BOOL __block blockingActorDidMove;
            //Keep the current thread in an infinite loop until the blocking Actor's movement completion block has finished
            BOOL __block waitForBlockingActor = YES;

            //Perform the blocking actor's movement Response
            [firstResponse performWithCompletion:^(ResponseReturnCode returnCode) {
                if (returnCode == ResponseReturnCodeFailure && firstResponse.breakResponse) {
                    Response *breakResponse = firstResponse.breakResponse;

                    [blockingActor clearIdleActions];

                    [breakResponse performWithCompletion:^(ResponseReturnCode returnCode) {
                        //Set flags for the main function
                        blockingActorDidMove = (returnCode == ResponseReturnCodeSuccess);
                        waitForBlockingActor = NO;
                    }];
                }
                else {
                    //Set flags for the main function
                    blockingActorDidMove = (returnCode == ResponseReturnCodeSuccess);// success;
                    waitForBlockingActor = NO;
                }
            }];

            //Wait for the blocking Actor's completion block to finish
            while (waitForBlockingActor) {

            }

            //If the blocking actor moved, we'll take its place
            if (blockingActorDidMove) {
                return [self finishCanMoveToGridElementCanMove:YES];
            }
        }
    }

    //If we've reached this point, the blocking actor either had no pending move-type idle action this tick, or was unable to move itself. Try to push it out of the way
    if ([blockingActor pushInDirection:direction]) {
        return [self finishCanMoveToGridElementCanMove:YES];
    }

    //Give up
    return [self finishCanMoveToGridElementCanMove:NO];
}

```
> 1 votes

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


# Question
Title: In Unity (2017) is there a way to set the buttons used by Input.GetAxis() programatically?
The buttons used for keyboard axis inputs can be set manually via Negative and Positive Button fields for the axis at Edit \> Project Settings \> Input Manager. However I'd like to make this a user configurable option which I think means needing to set the button values from a script.

I've been looking for a method along the lines of:

`Input.SetAxis("Vertical").positveButton`

But so far I'm striking out. Is there a way to do this?

# Answer
# No it is not possible.

I recommend getting the Rewired asset instead. There may be other assets that also work, but I know Rewired is already set up to allow rebinding for both mouse/keyboard and controllers.
> 1 votes

---
Tags: unity, input, ui-design
---


title: Normals on a sphere

text:
# Question
Title: Normals on a sphere
I am generating vertices for a sphere by normalizing the vertices of a cube. The coordinates of the vertices are mapped to \[-1; 1\].

.

I want to get the normal vector of each vertex.

My question is do I need to compute the normals, or can I just use the positions of the sphere by just normalizing them? Also, which is more GPU friendly: pre-computing the normals and passing them as an attribute or just calculating them on the go?

```
out_normal = normalize(in_position);

```

# Answer
For normalising on the GPU, it depends on what you want to do. If you want to do real time transformation (say animate), then yes, go ahead and calculate on the fly in the GPU. But if it's a once off, just precalc, its better since if you add lots of balls it does add up.

The final thing is just to remember to multiply the 3x3 component of your matrix for your normals once you start rotating or scaling. But that's the usual.
> 2 votes

---
Tags: glsl, graphics-programming
---


# Question
Title: Fresh Unity/Visual Studio 2017 install error
Installed Unity 5.6.3p2 (my projects's current version) on a new machine. When I opened the project in Visual Studio 2017 I got a prompt to update the .NET framework from 3.5 to (I think) 4.2.x. I confirmed the upgrade for all projects in the solution but now all I get is this

If I close and reopen visual studio I no longer get the upgrade prompt. I tried downloading .NET 3.5 to no avail. Any information is appreciated.

# Answer
Just had to right click on each project in the solution and select Reload Project. It took a few tries on some of them for some reason.
> 1 votes

---
Tags: unity, c#, visual-studio
---


# Question
Title: RenderTexture.Create failed in Unity. please help me
RenderTexture.Create failed: width & height must be larger than 0 UnityEngine.RenderTexture:Create() Prime31.SpriteLightKit:updateTexture(Boolean) (at Assets/SpriteLightKit/SpriteLightKit-master/Assets/SpriteLightKit/SpriteLightKit.cs:177) Prime31.SpriteLightKit:OnEnable() (at Assets/SpriteLightKit/SpriteLightKit-master/Assets/SpriteLightKit/SpriteLightKit.cs:75)

# Answer
> 1 votes
You are trying to create a texture with 0 size (apparently). You shoud pass with and height of the texture. If you don't know, try to use a square creation (256x256 for example).

From Unity documentation:

```
public class ExampleClass : MonoBehaviour {
    public RenderTexture rt;
    void Start() {
        rt = new RenderTexture(256, 256, 16, RenderTextureFormat.ARGB32);
        rt.Create();
    }
}

```

---
Tags: unity, game-design, sprites
---


# Question
Title: Why the rotation switching mode is not working right when using bools?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Objects : MonoBehaviour
{
    public float maxScale = 10.0f;
    public float minScale = 2.0f;
    public float shrinkSpeed = 1.0f;
    public float rotatingSpeed = 3f;
    public bool automaticScale = false;
    public bool rotateOnMouseMove = false;
    public bool rotateOnMouseDrag = true;

    private float targetScale;
    private Vector3 v3Scale;

    void Start()
    {
        v3Scale = transform.localScale;
    }

    void Update()
    {
        RaycastHit hit;
        Ray ray;

        if (Input.GetMouseButton(1))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit) && hit.transform == transform)
            {
                targetScale = minScale;
                v3Scale = new Vector3(targetScale, targetScale, targetScale);
            }

            if (automaticScale == false)
                transform.localScale = Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime * shrinkSpeed);
        }

        if (Input.GetMouseButton(0))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit) && hit.transform == transform)
            {
                targetScale = maxScale;
                v3Scale = new Vector3(targetScale, targetScale, targetScale);
            }

            if (automaticScale == false)
                transform.localScale = Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime * shrinkSpeed);
        }

        if (automaticScale == true)
        {
            transform.localScale = Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime * shrinkSpeed);
        }

        if (rotateOnMouseMove == true)
        {
            transform.Rotate(Input.GetAxis("Mouse Y") * rotatingSpeed, -Input.GetAxis("Mouse X") * rotatingSpeed, 0, Space.World);
        }

        if (rotateOnMouseMove == true)
        {
            rotateOnMouseDrag = false;
        }

        if (rotateOnMouseDrag == true)
        {
            rotateOnMouseMove = false;
        }
    }

    private void OnMouseDrag()
    {
        if (rotateOnMouseDrag == true)
        {
            transform.Rotate(Input.GetAxis("Mouse Y") * rotatingSpeed, -Input.GetAxis("Mouse X") * rotatingSpeed, 0, Space.World);
        }
    }
}

```

The problem is at the bottom:

```
if (rotateOnMouseMove == true)
            {
                rotateOnMouseDrag = false;
            }

            if (rotateOnMouseDrag == true)
            {
                rotateOnMouseMove = false;
            }

```

Once I'm starting the game by default the rotateOnMouseDrag is set to true. When I click on the check box of rotateOnMoseMove it's switching between them the rotateOnMouseDrag is false and rotateOnMouseMove is true.

The problem is when then I click again on the check box of rotateOnMouseDrag but it's never switching between them again it keep staying true on the rotateOnMouseMove.

I want it to act like a switch each time one of them is true the other should be false.

# Answer
Its a little gross to use bools in conditionals in that way, because it can become very difficult to follow the control flow. It would be easy to fix in several different ways, for example, exposing your property setters for your two bools to make sure they are always opposite (whenever you set a bool, it sets it's opposite bool too). Howwwever, I think the best thing to do here is to use an enum! It is easy to read, and it will be trivial to implement more rotation styles in the future. Also, don't forget about switch statements!

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

public class Objects : MonoBehaviour
{
    public float maxScale = 10.0f;
    public float minScale = 2.0f;
    public float shrinkSpeed = 1.0f;
    public float rotatingSpeed = 3f;
    public bool automaticScale = false;

    [System.Serializable]
    public enum RotationStyle{
        MOUSE_MOVE,
        MOUSE_DRAG
    }
    [SerializeField] private RotationStyle _rotationStyle;

    private float targetScale;
    private Vector3 v3Scale;

    void Start()
    {
        v3Scale = transform.localScale;
    }

    void Update()
    {
        RaycastHit hit;
        Ray ray;

        if (Input.GetMouseButton(1))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit) && hit.transform == transform)
            {
                targetScale = minScale;
                v3Scale = new Vector3(targetScale, targetScale, targetScale);
            }

            if (automaticScale == false)
                transform.localScale = Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime * shrinkSpeed);
        }

        if (Input.GetMouseButton(0))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit) && hit.transform == transform)
            {
                targetScale = maxScale;
                v3Scale = new Vector3(targetScale, targetScale, targetScale);
            }

            if (automaticScale == false)
                transform.localScale = Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime * shrinkSpeed);
        }

        if (automaticScale == true)
        {
            transform.localScale = Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime * shrinkSpeed);
        }

        if (_rotationStyle == RotationStyle.MOUSE_MOVE){
            transform.Rotate(Input.GetAxis("Mouse Y") * rotatingSpeed, -Input.GetAxis("Mouse X") * rotatingSpeed, 0, Space.World);
        }

    }

    private void OnMouseDrag()
    {
        if (_rotationStyle == RotationStyle.MOUSE_DRAG)
        {
            transform.Rotate(Input.GetAxis("Mouse Y") * rotatingSpeed, -Input.GetAxis("Mouse X") * rotatingSpeed, 0, Space.World);
        }
    }

    public void SetRotationStyle(RotationStyle style){
        _rotationStyle = style;
    }
}

```

In this example, if you want to set the rotationStyle via script, you'd just do something like

```
object.SetRotationStyle(Objects.RotationStyle.MOUSE_DRAG);

```
> 1 votes

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


title: Unity 5.5 Android scaling

text:
# Question
Title: Unity 5.5 Android scaling
The questions I've seen are outdated, explained, not to my liking, or just don't work.

**Problem:** I want to be able to create a game that can scale on all mobile devices with ease and with no pixelation.

*Extra Info:*

* I'm very new to unity and tackling the the software with all my might I'm sorry for being a noob.
* I already paired unity with my phone and set the build to android (Nexus 5).
* Aspect ratio is 10:16, The game is going to be portrait.
* I have no scripts or anything, Its legit a blank game with a camera that has a blue background.

I have some pictures, if you need anything else for my assistance don't hesitate I'm here to learn and take, GULP, Constructive Criticism.

**PC**

**Android**

# Answer
> 1 votes
Based on the comment I'm typing this just to provide an answer.

Unity remote DOES NOT BUILD I repeat DOES NOT BUILD to the target device. What it does is send a compressed video stream to the device. It is mainly used to test touch inputs and gyro stuff and so on because it can send the device input back to the editor. The quality is always bad when using Unity remote.

# Answer
> 1 votes
scaling to screen size is very easy in unity. you can use canvas scaler and give it a reference resolution (try to give it as higher as possible).

Here is the step to use UI Canvas

1. GameObject \> UI \> Canvas
2. Select Canvas \> GameObject \> UI \> Image
3. In Image Component's Source Image \> Add your Image
4. Go Back to Canvas Find Canvas Scaler which looks like the image i attached and try to play with the value if you don't find a proper solution.

I hope this solves your problem. Cheers!

# Answer
> -1 votes
EDIT :
If you don't understand code , UI / Canvas is your last option

what i suggest that is your main idea is to make your picture / game object look in same position and look same big as if at other resolution , i have the script ( i tell you how to install it at the bottom of the page ) for it but unfortunally , i can't make it automatically scale all your game object ( one by one ) , the script still scale at aspect ratio but you can't use the script if you build the game using aspect ratio resolution ( must be fixed resolution , because the script itself , explained later) .

this is the script for 2D version ( because your game is 2D ) :

```
using UnityEngine;
using System.Collections;
public class calculateresolution : MonoBehaviour {

void CalculateResolution(string theobjectm , float resolutionwidthyouusetobuild , float resolutionheightyouusetobuild ) {

GameObject objecttocalculate = GameObject.Find(theobjectm);
float desiredscreenheight = resolutionheightyouusetobuild;
float desiredscreenwidth = resolutionwidthyouusetobuild;
float desiredaspectratio = desiredscreenwidth / desiredscreenheight;
float desiredaspectratioheight = desiredscreenheight / desiredscreenwidth;
float screenheight = Screen.height;
float screenwidth = Screen.width;
float aspectratioheight = screenheight / screenwidth;
float aspectratiowidth = screenwidth / screenheight;
float objectsizex = objecttocalculate.transform.localScale.x;
float objectsizey = objecttocalculate.transform.localScale.y;
float objectsizez = objecttocalculate.transform.localScale.z;
float objectcoordx = objecttocalculate.transform.localPosition.x;
float objectcoordy = objecttocalculate.transform.localPosition.y;
float objectcoordz = objecttocalculate.transform.localPosition.z;
float newobjectsizex = aspectratiowidth / desiredaspectratiowidth * objectsizex;
float newobjectsizey = objectsizey;
float newobjectsizez = objectsizez;
float newobjectcoordx = aspectratiowidth / desiredaspectratiowidth * objectcoordx;
float newobjectcoordy = aspectratioheight / desiredaspectratioheight * objectcoordy;
float newobjectcoordz = objectcoordz;
objecttocalculate.transform.localScale = new Vector3(newobjectsizex,newobjectsizey,newobjectsizez);
objecttocalculate.transform.localPosition = new Vector3(newobjectcoordx,newobjectcoordy,newobjectcoordz);
}
void Start() {

// Example i build my game at fixed resolution 1366 x 768
// 1366 is resolution width , and 768 is resolution height
// and i have GameObject ( such as picture , ect ) named pictureone in the hierarcy
// put this magical command inside Start() { }
// if you don't know where is the inside , just remove the 2 backslash and change the pictureone into your object name
// don't forget to change 1366 and 768 with your screen width and screen height !
// \/ the magical command \/
// CalculateResolution("pictureone",1366f,768f);
// /\ the magical command /\
}
void Update() {

}
}

```

The how-to-use the script is explained inside function Start() , now :

Installation :
1. Create any object ( or just put another picture if you don't understand how to create object ) 2. Create new C# script by Assets menu at top part ( beside GameObject and Edit ) , Create \> , C# Script , and then name the script with name calculateresolution . 3. add the script component ( not working yet ) to object , if you don't understand , drag the script into the object you created at step one from hierarchy .
4. Open and edit the script
5. Copy all the script above
6. paste the code to the editor
7. then test it ( without modifying it ) , if its give error , then you have done wrong in previous step , go back and take a look where you are wrong .
8. If the script give no error , then edit the script as i explained in the Start() .
9. If you don't understand code , UI / Canvas is your last option .
10 . Do not lie to script about what resolution you are using , else it will do wrong .

This script only scale when you run the game first time ( did not change if you change the resolution in-game ) , also did not run if you didn't run the game .

Also this not fix your second problem , if player use resolution that is higher than resolution you use to make the game , the picture / sprite still get blurry a little .

If you still don't understand , contact me jaydhani.43@gmail.com

EDITED !

---
Tags: unity, 2d, android, camera, scale
---


# Question
Title: How can I use the Kinect as a microphone in Linux?
I am using Ubuntu 14.04 LTS, and the Kinect camera has type `Microsoft_Xbox_NUI_Sensor_043367545147-02-Sensor`.

I can access the Kinect's camera from a Linux program that I'm writing, but I'd also like to use its microphone for voice communication. How can I do that?

# Answer
Based on what others have said in the comments and some research I have done, here are my suggestions.

HARK-KINCET should do the job, though it does require installation. There is a possibility you could bundle installation in your game, though you will probably require permission from the developers. \[Based on Theraot's answer\]

The other option presented here is using the libraries here and code a program that connects to those libraries. \[Based on McLovin's answer\]

A solution that will only work for you would be to use the code posted here and then set that up in your kernel. You may want to check what the site said about some microphones having a bug that prevents full setup; if so use this setup command:

```
sudo kinect_upload_fw /lib/firmware/kinect/UACFirmware.C9C6E852_35A3_41DC_A57D_BDDEB43DFD04

```

If you have this bug, you will get this error:

```
libusbx: error [op_set_configuration] failed, error -1 errno 110
  About to send: 09 20 02 06 01 00 00 00 60 00 00 00 00 00 00 00 15 00 00 00 00 00 00 00
  libusbx: error [submit_bulk_transfer] submiturb failed error -1 errno=2
  Error: res: -1    transferred: 0 (expected 24)

```

From what I have read, this is probably the problem you are having. You can fix it by downloading the source and editing it, then fetching the firmware.

```
cd ~/Downloads
wget https://launchpad.net/ubuntu/+archive/primary/+files/kinect-audio-
setup_0.3.orig.tar.gz

```

From here you should follow the steps presented in the link, as my explanations may get slightly confusing. If you wish to continue with my explanation, edit the file called “kinect\_upload\_fw.c” so that it reads as:

```
index b2188d6..e3b72db 100644 (file)
b/kinect_upload_fw/kinect_upload_fw.c
@@ -155,9 +155,19 @@ int main(int argc, char** argv) {
            goto fail_libusb_open;
    }

   int current_configuration = 0;
   libusb_get_configuration(dev, &current_configuration);
   if (current_configuration != 1)
           libusb_set_configuration(dev, 1);

   libusb_claim_interface(dev, 0);

   libusb_get_configuration(dev, &current_configuration);
   if (current_configuration != 1) {
           res = -ENODEV;
           goto cleanup;
   }

    seq = 1;

    bootloader_command cmd;

```

Save the changes and then build and install it. This should fix the problem.
> 1 votes

---
Tags: linux, kinect, voice
---


# Question
Title: How should I structure a design document?
Should the design document be a continuous line of text, with real sentences, more like a description of the entire game, or should I structure it in simple points? What are the benefits, and are there more ways of structuring it?

# Answer
> 30 votes
There are no rules or industry standards; structure the document in the way that will be most useful to the people who will *consume* that document, keeping in mind what the purpose of your document is.

Personally I would expect there to be portions of the document that are better suited to using "real sentences" to convey your idea, as well as portions that are better suited to being written as a bullet-point list of features.

Who is your audience? If it's just you, if this is just supposed to help you focus your thoughts, do whatever works for you. If you are working with others, ask them how they'd prefer to see the document broken down and how they would expect to use it.

I would expect to see a prose description of the salient points of the game: it's main concept, style and feeling. I would then expect to see a section for each major feature of the game.

Do not go overboard with detail and statistics, remember that a design document is typically something that will evolve over the lifetime of the game as you build and iterate. It's impractical to think that you'll write it once, up front, and it will be perfect, so focus on what you need the document to convey *now* and how you can best convey that to the specific consumers of that document.

It doesn't matter what other people do, you want to do what works best for your team.

# Answer
> 24 votes
In addition to what Josh has said in his answer, several people have shared their idea of what should go in a game design doc, which may help you decide what aspects are going to be useful in your own docs. Remember that these are professional designers, and what worked for them in the context of the traditional games industry is not necessarily right for you, so it's useful to try and work out why they use certain approaches and pick the ones that will help you the most.

# Answer
> 5 votes
There is one piece of information that I'd like to add: when documenting the actual design of the game (ie: the rules), provide clear explanations for *why* you're making a particular rule design choice.

One of the things you're more likely to forget when you go about implementing something is the exact reason why you added a particular rule. Also, one of the things you're very likely to do is to add rules and game elements just because other games have them, not because your game *needs* them.

By adding a section on exactly why a game element exists, it forces you to justify the use of that element in terms of the overall game design. And later on, it allows you to effectively evaluate whether a particular element is actually serving the needs you intended it to. If it's not, then you can remove it and replace it with something else that does serve those needs.

Even better, if you find the game isn't working out, and you want to replace multiple elements to make the game more fun, you can look back at your design document and understand why you choose those elements and what new elements need to accomplish. If the needs of your game design change, then you can update your list of what the game elements are supposed to do.

# Answer
> 1 votes
I like the way Level Up author uses to write his game design documents with drawing many cute shapes, characters and etc.

I highly recommend you take a look at this book Level Up!: The Guide to Great Video Game Design

With adding little drawings to your documents the others will pay attention to you more and you can be sure they will read your design documents

# Answer
> 0 votes
The structure of your game design document is completely up to you, but one I create tends to include (note that this works better for RPGs or other story-driven games):

*Table of Contents* \- Very important, as once you have more complex games you will need to include an organization method

*Description of the Game* \- A brief description of the game, giving some descriptions of game-play, along with platform and other important details

*Story overview* \- Give an overview of your plot

*Controls* \- List the controls you will be using in your game

*Tech requirements* \- You can go into more detail about platform here

*Game Flowchart* \- Show how your game's screens connect

*Presentation* \- Give details about camera type, HUD, and other info the player will see

*Player Character* \- Give information about your player, such as what they look like, backstory, and tools/weapons they may use

*Combat* \- Describe how combat works (if applicable)

*Game Levels* \- Give some examples of levels

*Enemies* \- Give details about your enemies (attacks, looks)

*Bosses* \- Information about specific bosses

*NPCs* \- Describe AIs that don't attack your character

*Music/SFX* \- What music and SFX need to be produced

*Appendices* \- Place long lists here along with scripts and any other information

You may also want to create a more concise version of your game design document which is about one page, containing the following things:

*Title and Concept Overview* \- Give a brief overview of what the game is like and what players will do

*Platform* \- List the platform the game will be published on

*Main Points* \- Give the very basic info about your game, such as it being an FPS, an MMO, and having a single-player mode

*Summary* \- Summarize your plot, if any

*Characters* \- Give some info about your characters

---
Tags: game-design
---


# Question
Title: Procedural Dungeon Generation Connect Rooms With Passageways
I've been working on a simple procedural generation class which currently places rooms on a x, y grid and selects a starting room. Each room needs to be connected with passageways so the player will be able to access them. The part that I am having issues with is how to actually connect the rooms.

There's a number of algorithms I've seen online, but I am unsure how to implement most of them.

As for my implementation of placing the rooms, the code tries placing them randomly on the grid until I get the desired density of rooms. After each room is placed, it is added to a list which stores the dimensions of the room. A room is them randomly selected to be the starting room.

**Edit**

Here's an example of the generated dungeons (the room with the "S" is the starting room):

Preferably, the rooms should be connected with their nearest neighbor. I'm not sure what the best way to go about this is.

# Answer
I would make it little different, i would make a procedural path builder and then spawn floor tiles randomly all over the map, so the rooms will be more "natural created" and them will be linked at least for 1 tile, i can't code in java but i'll code the example in javascript, i think it's clear enough.

```
var c = document.getElementsByTagName("canvas")[0];
c.width = 600;
c.height = 600;
var ctx = c.getContext("2d");

//We gonna format a map of 300x300 tiles with 2px each
var mapSize = 300;
var tileSize = 2;
var _map = new Int8Array(mapSize*mapSize).fill(0);

var pathLength = 20000;

//Here we draw our path with a length of 20000 tiles randomly from the entry point [150,150]

var currentPos = [150,150];
_map[currentPos[0]+(currentPos[1]*mapSize)] = 1;

for(var p = 0; p < pathLength; p++){
 var dir = [
   Math.floor(Math.random()*3)-1,
    Math.floor(Math.random()*3)-1
  ]

  currentPos[0] += dir[0];
  currentPos[1] += dir[1];

  if(currentPos[0] >= mapSize) currentPos[0]--;
  if(currentPos[0] < 0) currentPos[0]++;
  if(currentPos[1] >= mapSize) currentPos[1]--;
  if(currentPos[1] < 0) currentPos[1]--;

 _map[currentPos[0]+(currentPos[1]*300)] = 1;
}

//We now has an array of 0 and 1 that makes paths and rooms randomly

//We gonna draw our map
var r = 0;
var c = 0;
for(var t of _map){
 if(r == mapSize){
   c++;
    r=0;
  };

  ctx.save();
  switch(t){
   case 0:
     ctx.fillStyle = "black";
   break;
    case 1:
     ctx.fillStyle = "grey";
    break;
  }
  ctx.fillRect(c*tileSize,r*tileSize,tileSize,tileSize);
  ctx.restore();
  r++;
}
```

```
<canvas style="border: 1px solid grey"></canvas>
```
> 4 votes

# Answer
I'm going to drop this alternative into the mix. Its one that I really liked and used myself, with some changes.

https://www.reddit.com/r/gamedev/comments/1dlwc4/procedural\_dungeon\_generation\_algorithm\_explained/

Roughly speaking the steps are:

1. Generate a bunch of squares of various sizes, save them to an array (you probably want a class for these objects: x, y, width, height, doesOverlap(other), etc).
2. Loop through the set of rooms and jiggle them around until they "lay flat" (that is, they no longer overlap). This will be a tricky part to get right, to avoid edge-case infinite loop problems. The simple solution is that if two rooms overlap, randomly pick between them and move the selected room away from the other in the direction that will make it not-overlap the most quickly (so if the overlap size is 2 along X and 5 along Y, then shift it 1 along X away from the other room's center (this may be negative!)).
3. Perform a Delaunay Triangulation on the room's centers. Finding some code that does this is pretty easy, although you may have to do some translation into Java. Try to use native types where possible.
4. Categorize rooms into "small" and "large." Large rooms are like what you have now. Small ones will not be added until step 6.
5. Find the triangulation's MST. This will create a minimally connected map. Add a few more edges (say 15% of the remainder, although personally I looked for connections that would create interesting loops, ignoring any edge that would make a triangle). Draw dog-leg hallways for these edges, drawing along one axis first, then turning to draw along the other. I choose a random point within the room to start drawing from, and a random target point within the destination to connect to. I also check that this path will not cross other hallways or rooms, but depending on your needs you may be OK with this.
6. Any *small rooms* that a hallway passes through are added to the map, any that aren't are ignored. This gives the hallways some definition and quirks.

It might also be worth making your cell data structure hold informational values, such as "this is a room, this is the wall around a room, this is dead space, this is a hallway, here's a corner, there's where a hallway meets a room (e.g. "door") so that these features can be easily located later, even if functionally a "hallway" cell and a "room" cell are the same thing.
> 4 votes

# Answer
It´s hard without seeing the code, but I think I can give you an asnwer.

* You can check which rooms are next to which rooms using the rows and columns of the file you created.
* The pathfinding is a bit harder, once you have your current room and the objetive room (the one next to the current room, I guess), all you need to do is define exact point for "doors" in each room.

(You can do this by selecting a random point of the wall of each room, for example).

Once you have the two points you want to connect, run a pathfinding algorithm.

I have a very basic implementation of A\* (or AStar) algorithm in java, you can use it as a waypoint.

```
import java.util.*;

public class AStar {

  public static class PriorityList extends LinkedList {

    public void add(Comparable object) {
      for (int i=0; i<size(); i++) {
        if (object.compareTo(get(i)) <= 0) {
          add(i, object);
          return;
        }
      }
      addLast(object);
    }
  }

  protected List constructPath(AStarNode node) {
    LinkedList path = new LinkedList();
    while (node.pathParent != null) {
      path.addFirst(node);
      node = node.pathParent;
    }
    return path;
  }

  public List findPath(AStarNode startNode, AStarNode goalNode) {

    PriorityList openList = new PriorityList();
    LinkedList closedList = new LinkedList();

    startNode.costFromStart = 0;
    startNode.estimatedCostToGoal =
      startNode.getEstimatedCost(goalNode);
    startNode.pathParent = null;
    openList.add(startNode);

    while (!openList.isEmpty()) {
      AStarNode node = (AStarNode)openList.removeFirst();
      if (node == goalNode) {
        // construct the path from start to goal
        return constructPath(goalNode);
      }

      List neighbors = node.getNeighbors();
      for (int i=0; i<neighbors.size(); i++) {
        AStarNode neighborNode =
          (AStarNode)neighbors.get(i);
        boolean isOpen = openList.contains(neighborNode);
        boolean isClosed =
          closedList.contains(neighborNode);
        float costFromStart = node.costFromStart +
          node.getCost(neighborNode);

        // check if the neighbor node has not been
        // traversed or if a shorter path to this
        // neighbor node is found.
        if ((!isOpen && !isClosed) ||
          costFromStart < neighborNode.costFromStart)
        {
          neighborNode.pathParent = node;
          neighborNode.costFromStart = costFromStart;
          neighborNode.estimatedCostToGoal =
            neighborNode.getEstimatedCost(goalNode);
          if (isClosed) {
            closedList.remove(neighborNode);
          }
          if (!isOpen) {
            openList.add(neighborNode);
          }
        }
      }
      closedList.add(node);
    }

    return null;
  }

}

```

Please, ask if you have any question.
> 1 votes

# Answer
A very neat technique I stumbled upon a long time ago for mapping shortest path for an enemy to take was for an invisible block to be copied along in all directions, not including walls, until it hit your base (This technique was used in a tower-defense game).

To implement this in your game, you could create another character, say &, that would be copied throughout the map from all points on your room. It would be copied such that it would go off into different paths at each point that there was more than one way for it to go. In your case, it will be able to spread however it wants until it hits another room.

Those path would be tracked, and whichever path encountered a room first would thus be the path you use.

If you do end up using this method (highly doubtful considering how long ago this was, but for future readers), make sure that paths do not take all routes possible. Overall this is just food for thought, as it is a highly impractical technique to code on a larger scale, but could work quite well in a smaller game.
> 0 votes

---
Tags: java, procedural-generation, roguelikes
---


# Question
Title: How to change fps character's movement speed and mouse sensitivity in UE4?
As the title says, I'm using the default fps template from UE4 (blueprint template) and the movement speed is very high, also I want to adjust the mouse sensitivity, but I don't know where are those values, nor the variables, and my other question is... Where are those values/variables?

# Answer
> 0 votes
The player has a max speed which I've found useful for lowering speed when a player runs out of stamina. To set it up to lower the speed from the beginning, use connect the following to your BeginPlay:

If my memory is correct, the default walking speed is 600 so adjust yours accordingly until the speed is what you want.

With the mouse sensitivity issue, this is just a guess because I've never done it myself but in the Input Settings (Project Settings-\>Engine-\>Input) the default scales for InputAxis-\>Turn are 1.0 and -1.0. I would presume that if you adjust these to lower values, the mouse would move slower.

---
Tags: game-mechanics, unreal-4, first-person-shooter, blueprints
---


# Question
Title: A shader that casts shadows, doesn't receive shadows and doesn't render any textures/models at all?
Bit of a strange one but I'm in the situation where i need a shader to essentially render nothing and cast a shadow!

I found this though some googling but sadly that casts shadows onto itself which is undesirable.

# Answer
> 1 votes
As mentioned in the comment by DMGregory, there is an option in the renderer to do this...

---
Tags: unity, shaders, rendering, shadows
---


# Question
Title: Let both clients know of complete game-state in turn-based game?
I'm writing a simple turn-based game for mobile, just to test the waters and I'm having doubts about the approach.

Each player has 5 cards on hand.

I want for both players to be able to replay exactly what the other player did. Would it be okay (from a security perspective (and in what degree?)) for both clients to know in-memory what the other player has on hand?

Example: Game Start \> Server sends encrypted data\* to both clients \> Clients decrypts data in memory

Server sends user action \> Client replay action

\*where data is Client1's cards and Client2's cards.

The reason for not having the server sending "need to know" stuff, is for code-simplicity and responsiveness.

# Answer
> 2 votes
This is not safe.

As soon as you let client know something, consider the player knows it too. Even if the information is hidden from players view in GUI, it can be more or less easily extracted from memory and/or network data exchange.

---
Tags: multiplayer, turn-based, security, memory, game-state
---


# Question
Title: How to project textures onto an animated model?
I'm trying to figure out exactly how to project textures onto an animated model. I've taken a look at L4D2's wound's white paper. But their method doesn't exactly explain how they went about this.

I've tried using the old school method to create a mesh and attach it to the object... But that would require the GPU to store that data for a long period of time, and recall it correctly for the animated model. On top of that there's the Z-fighting problem with it.

I've tried the Deferred shading method. But I can't get that to work correctly either. My set up requires some form of filter in order to prevent the decal from projecting onto other models. And then should a moving body part cross over the volume, it gets rendered onto that as well, which is not as desired.

# Answer
> 1 votes
What i do is store an object ID in a uint16 rendertarget when i build my G-Buffer then in the decal pass i just convert the decal box vertex positions to screen space and then read back the object ID buffer and see if the returned ID is the target ID of the decal.

I have my decal shader setup so i can pass in an array of object ID's that way you if you want your decal to hit say the player and the terrain you just up load the payer object ID and the terrain object ID and away the shader goes.

The object ID buffer is also used in my lighting pass to set up the material properties.

# Answer
> 1 votes
One of the simplest methods I've seen is to project into the model's texture map itself. Then it tracks & animates with the model just as the rest of the model's skin does, at no additional geometry/blending cost each frame.

This does have some restrictions:

* models that can be decalled must be unwrapped uniquely, without mirroring/parts of the texture re-used in different places around the model
* each decalled instance requires a unique copy of its texture, and (unless you're atlassing them) a separate draw call from other models using the undecalled version of that texture
* decals away from UV seams are easiest to process. Decals crossing UV seams can be accomplished using a projection method. Though this has a similar "overspray" possibility mentioned for the deferred case, it's usually more manageable because the projection math happens just once, rather than animating continuously with a moving limb. If the projection is performed in the model's T-pose the risk of undesired splash is much lower. Non-projection methods can work too, but generally require some non-trivial mesh-walking to find the correct alignments.

The technique of layering an additional geometry "skin" over the decal area works too, inheriting the skinning weights from the original mesh so it animates together with it seamlessly. To avoid z-fighting, it usually suffices to render the decal second, and apply a slope-sensitive z-bias. Since the decal skin closely follows the source mesh, it's not quite as fiddly to tune as arbitrary z-fighting cases. ;)

---
Tags: graphics, projection, decal-system
---


# Question
Title: How can I port my Gear VR app (Java, OpenGL ES) to Unity?
I want to port my Gear VR app (created in Java using the official framework) to Unity, so I can also support Microsoft's new-ish VR headsets (not talking about the Hololens!).

In my current app I'm using OpenGL ES to draw everything I need (the app reads coordinates and additional information about what it has to draw from a .txt file), which is:

1. GL\_LINE\_STRIP: The .txt file gives it a bunch of coordinate triples (x, y and z, so single vertices), it then has to automatically connects them (usually without loops)
2. Kind of plane: Either display a rectangular plane with a texture (using the Gear VR framework's "GVRSceneObject") OR create an outline (usually first point = last point) that then gets filled in a specific color (GL\_TRIANGLE\_FAN) AND that is a little bit transparent - if it includes concave areas, it's using GL\_TRIANGLES and the .txt file has coordinates for single triangles that have to be displayed at the same time and filled (it's still a single object/mesh!)

What I need Unity to do (with 1. and 2.):

* Display a couple of 1. (could be up to 50 or more) and 1 of 2. at the same time (there'll never be more than 1 of type 2.!)
* Remove all of 1. (that are displayed at the same time) or 2. from the scene and/or replace them with a couple of different 1. or another 2.
* Group a couple of 1. together, so you can remove them at the same time (which would make stuff a lot easier)
* Read .obj files (including their texture) from internal storage (Android) or the HDD (Windows) and display it/them instead of 2. (the .txt file includes the path to the file and texture)

Everything has to happen at runtime, since the app doesn't come with any .txt files or pre-imported .obj scenes/objects!

My question is:

How can I do this with Unity, targeting Windows and Android?

# Answer
Using native OpenGL functionality in Unity is going to be tricky. You might be able to get this to work on *one* platform with some dirty hacking, but I doubt you will manage to do it in a portable way.

You can generate procedural meshes in Unity. So you just need to write some code which takes your coordinates and uses them to build a `Mesh` component. You can then assign these meshes to game objects, set the right material on their renderer and you should be good to go.

Reading .obj files at runtime is a problem. The Unity Editor can import .obj 3d models, but it converts them into the Unity-specific 3d model format, which is the only format you can load at runtime. So when you want to load 3rd party content at runtime, that content must be in the Unity AssetBundle format. Unless, of course, you load it as a binary file and then build your mesh and texture using your own code.

Everything else you describe should be possible in Unity. But you are describing some very high-level concepts here. It will be very unlikely that you will be able to convert any of your Java code 1:1 into Unity code. You won't get around developing everything from scratch. I would recommend you to do some basic Unity tutorials to get a feeling for how the engine works and then recreate your game the Unity way.
> 2 votes

---
Tags: unity, android, opengl-es, windows
---


title: Applying Perlin Noise to Tiles

text:
# Question
Title: Applying Perlin Noise to Tiles
Playing with some Documentation about Perlin Noise I managed to create this map:

Nothing different from other Procedural Generated Maps. It is a HeightMap with colours at given heights.

The problem I am having with it is that this Colour Map it's in a single plane.

**QUESTION**

**¿How can I draw the Perlin Noise Map in a plane made by a set of individual tiles?**

The idea behind that question is that each tile will have a set of values such as population, water levels, soil quality, temperature and etc. I want to store things which can not be done on a simple single plane (according to my knowledge in this matter).

**EDIT:** Ok, after some more planning and research in the matter I did the next thing:

I have created a new class type named MapData.cs, this class will hold information about the heights, temperature, wetness and etc form the map as show below

**MapData class**

```
    public class MapData{

    //The MapData class will hold different types of Data
    //Temperature, Rainfall, etc.

    public float[,] Data;
    public float Min { get; set; }
    public float Max { get; set; }

    public MapData(int width, int height)
    {
        Data = new float[width, height];
        Min = float.MinValue;
        Max = float.MaxValue;
    }

}

```

Then i will use that MapData class to put data into the tiles as show below:

**Load Tiles function inside the Generator Class**

```
void LoadTiles()
{
    for (int x = 0; x < mapWidth; x++)
    {
        for (int y = 0; y < mapHeight; y++)
        {
            Tiles t = new Tiles();
            t.X = x;
            t.Y = y;

            float heightValue = HeightData.Data[x, y];
            heightValue = (heightValue - HeightData.Min) / (HeightData.Max - HeightData.Min);
            t.HeightValue = heightValue;

            if (heightValue < DeepWater)
            {
                t.HeightValue = DeepWater;
            }
            else if (heightValue < ShallowWater)
            {
                t.HeightValue = ShallowWater;
            }
            else if (heightValue < Sand)
            {
                t.HeightValue = Sand;
            }
            else if (heightValue < Grass)
            {
                t.HeightValue = Grass;
            }
            else if (heightValue < Forest)
            {
                t.HeightValue = Forest;
            }
            else if (heightValue < Mountain)
            {
                t.HeightValue = Mountain;
            }
            else { t.HeightValue = Snow; }
        }
    }

```

My actual problem here is that i am still confused with the Texture Generator as how do i apply this new concept into it. I am still learning and I do not want to mess up my progress.

**Texture Generator**

```
    public class TextureGenerator{

    //Height Colours
    private static Color DeepColor = new Color(15 / 255f, 30 / 255f, 80 / 255f, 1);
    private static Color ShallowColor = new Color(15 / 255f, 40 / 255f, 90 / 255f, 1);
    private static Color RiverColor = new Color(30 / 255f, 120 / 255f, 200 / 255f, 1);
    private static Color SandColor = new Color(198 / 255f, 190 / 255f, 31 / 255f, 1);
    private static Color GrassColor = new Color(50 / 255f, 220 / 255f, 20 / 255f, 1);
    private static Color ForestColor = new Color(16 / 255f, 160 / 255f, 0, 1);
    private static Color RockColor = new Color(0.5f, 0.5f, 0.5f, 1);
    private static Color SnowColor = new Color(1, 1, 1, 1);

    //This class will receive the colorMap array we set up before along with width and height

    public static Texture2D TextureFromColourMap(Color[] colourMap, int width, int height)
    {
        //New texture object and apply that color code.
        Texture2D texture = new Texture2D(width, height);
        texture.filterMode = FilterMode.Point;
        texture.wrapMode = TextureWrapMode.Clamp;
        texture.SetPixels(colourMap);
        texture.Apply();

        return texture;
    }

    public static Texture2D TextureFromHeightMap (float[,] heightMap)
    {
        int width = heightMap.GetLength(0);//Grab the x from the heightMap array
        int height = heightMap.GetLength(1);//Grabt the y from the heightMap array

        Texture2D texture = new Texture2D(width, height);//New texture object

        Color[] colourMap = new Color[width * height];//New colourMap object
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                //Gray scale colours for the NoiseMap
                colourMap[y * width + x] = Color.Lerp(Color.black, Color.white, heightMap[x, y]);//Explained before in Noise Script
            }
        }

        return TextureFromColourMap(colourMap, width, height);//Using the gray scale, coloursMap has colours in it!
    }
}

```

I had inside the texture Generator some colour code for my initial tests for coloring the Perlin Noise over a plane. As you can see up in the image.

# Answer
**EUREKA!**

**Introduction**

My initial question was about **"How to Tiling with Perlin Noise"**

I had in mind creating a plane with tiles (kind of a grid) \[width * height\] and on those tiles i will paint different textures. (*That was kind of a brain fuck for me*)

Initially i started with a plane and a texture material applied on it. It worked perfectly but i wanted some kind of way/ability to divide the map somehow in squares for purposes out of this question.

The result is the photo at the head of the question.

**How i solved my problem?**

Thanks to DMGregory and his infinite wisdom i started doing research and found out i could create multiple textures and apply them into the plane terrain AND i could access values the same way i access pixels to paint them.

**Solution**

I created a Data\[,\] container to store the random values generated,

```
MapData HeightData

```

then i "Tilled" them. **How?**

```
public void LoadTiles(MapData HeightData)

```

This load container which will help me display information gathered in the previous container into a texture using:

`public static Texture2D GetHeightMapTexture(int width, int height, Tiles[,] tile)`

And this is the result:

It is the same height map as i did before but this one code i remade helps me being more organized and it is expandable *(easy to add more code without lose yourself and suffer depression)*
> 1 votes

---
Tags: tiles, data-structure, perlin-noise, heightmap
---


# Question
Title: Opengl - Cascading Shadow Maps Implementation
after reading about CSM, I have a few questions about the implementation that I can't find the answer to.

1. According to the wiki, an FBO can only take 1 depth attachment, so in order to render cascaded shadowmaps in one pass, I would have to use TEXTURE\_2D\_ARRAY or TEXTURE\_3D, correct?
2. This would force me to use a geometry shader. Would this have a performance hit vs. an alternative method?
3. The other problem is that I have to define gl\_Layer per primative. Could it be possible that a primitive is not fully covered by any single ortho projection? e.g. the camera fov is subdivided, then an ortho projection from the sun is created for each subdivision. If the camera normal is aligned with the sun normal, then the projections' bounds would barely overlap. If a primitive isn't fully covered by either projection, then I can't calculate the depth for that primitive using gl\_Layer.

# Answer
Answer for anyone who want to know...

1. In order to render to multiple depth layers in one pass, a 2d texture array or 3d texture is needed.
2. Geometry shader is needed. It slows down performance, but it is needed anyway for multiple ortho projections and to duplicate geometry that falls within the bounds of 2 layers.
3. Per #2.. if primitive is in multiple boundaries, then duplicate it and set gl\_Layer separately for both.

If there is a more optimal way to do it, then please let me know!
> 0 votes

---
Tags: opengl, 3d, textures, deferred-rendering, fbo
---


# Question
Title: How can I achieve long-distance rendering of static terrain and props in an open-world context?
How can I perform seamless rendering of long-distance vistas in a fashion suitable for an open-world game (e.g., where the player is relatively unconstrained in how they traverse the world)?

For the purposes of this question, I'm only concerned with rendering of static objects: terrain and large props, as my game world is relative devoid of dynamic actors outside of the player.

The PS4 remake of Shadow of The Colossus™ illustrates the kind of effect I'm going for:

# Answer
> 2 votes
There are a few techniques that go into most LOD terrain. More than that, alot of what you see in the distance is more a prop than actual terrain. The same goes with static models.

Alot of the time, the occulusion game engine framework will include considerations into distance as well. Basically most of what you see is a LOD, but things that quite practically are too small to be seen at a distance will obvioulsy be culled (or faded out at distance).

What really is a challenge is to rapidly remove items that are not in the view of the player. Most of the work on the game engine (especially in an open world) is to ensure the minimum draw set needed for the scene. After that, Level of Detail can be applied. The onus is then on the artists to a degree to ensure that the transition in LOD of all objects is smooth (multiple LOD of the model).

As DMGregory said above, if your question is structured slightly differently, say as how a certain look was achieved (which is sort of your thrust of your original post). If your question was, how did they achieve such smoothness of framerate on such an open world? That would be just as pertinent.

# Answer
> 2 votes
Since I don't know what language you're using, I'm going to answer purely based on what I can tell you about scaling objects/background objects.

If you haven't already started, I'd recommend using Unity's Level of Detail feature.

If you have started and aren't using Unity, I would recommend creating a program that scales your objects, or manually scaling them using a graphic editor and removing some details. You could also implement an object such as fog that would remove some details and prevent your program from trying to render too much at once, as otherwise system restrictions may cause your game to run slowly.

# Answer
> 0 votes
Terrain LOD rendering is what you're looking for. It can be done on the GPU by utilizing the tesselation shader to subdivide triangles.

---
Tags: rendering
---


# Question
Title: How do I add an object to the node tree at a specific position
I'm making a skiing game, and a part of that is programmatically adding snow to the scene in a specific place. It will all be the child of a single node.

I was looking through the Flappy Bird code but when it instances a scene, it only uses the function `add_child()`. There doesn't seem to be a way to set its position.

Here is the project on github.

# Answer
So first I would create a scene called "flag\_scene". In that scene, have your code for making the flags do what you want. Every time the script I posted below is ran (and if it's put in main scene), it creates a copy of the flag scene, sets it in whatever position you want, and does the actions you assigned it to do in the script (attached to flag\_scene.tscn)

```
onready var flag_scene = load("location of flag.tscn")

var timer_raw = 0
var timer

func _procces(delta):
    timer_raw += delta
    timer = round(timer_raw)

    if timer > 4:
        spawn_flag() #call every 4 seconds
        timer_raw = 0

func spawn_flag():
    flag = flag_scene.instance()
    flag.set_pos([where you want the flag])
    # If you use Godot 3.0:
    # flag.position = [where you want the flag]
    add_child(flag)

```
> 1 votes

# Answer
As you already noticed, when you call `add_child()`, there isn't a way to input the position at the same time.

To change the position, you modify the position variable on the instanced node.

```
scene_instance.position = Vector2(x, y)

```

The structure that this gives instancing/placing code looks something like this.

```
scene_instance = scene_being_instanced.instance()

# All modification you want to happen *before* the node(s) are added
scene_instance.position = Vector2(x, y)

self.add_child(scene_instance)

# All modifications you want to happen *after* the node(s) have been added

```

For more information, I recommend taking a look at the Node documentation.
> 0 votes

---
Tags: godot
---


# Question
Title: What is the term for how much a game's code is coupled to its engine?
Essentially, what is a word or phrase I might use/search for to describe how much the choice of an engine dictates the structure of your code, such as the language it is written in or the way objects much be structured, as well as aspects of what design patterns can be used or how assets are formatted?

For instance, Unity has a high amount of this coupling because, while it allows the use of C# (which runs on many platforms), it requires many object interconnections to be exposed as concrete classes and public member variables. GameMaker Studio is almost completely coupled in this way because it has its own proprietary scripting language and asset format.

# Answer
I don't think there's a widely-used term for high coupling against game engines, yet. It is however analogous to **Framework Coupling** \- search that term and you'll find a few blog posts discussing that topic, its pros and cons.

I suppose you could call it **(Game) Engine Coupling**, and most people should know what you're talking about. It's a less common problem for game developers, because compared to general software, there are fewer games that are ported across engines, or have code extracted from them, since few games last long enough to warrant that sort of thing.
> 3 votes

# Answer
I'm not sure there is a unique and easily-searchable term unfortunately; if there is, I haven't heard it regularly.

In my experience, people tend to anthropomorphize the code to arrive at a way to talk about this concept. That is, they will refer to the engine's "expectations" about data, "opinions" about inter-system communication, "design guidelines" about object modelling, and so on.

Typically these terms are referring to things you do not, strictly speaking, *have* to do (those would just be "requirements") but rather things that you should do, or things that if you do them will make your experience less painful.

You may also hear references to "best practices" within the engine; the concepts are closely related and possibly even overlap. If you're looking for a way to search online about how this concept applies to various potential engines or tools, "best practices" is probably the search term most likely to get you the results you want.

For example, the popular build system tool CMake *expects* you to list all your source files explicitly in its input files. While it has mechanisms that allow you to automatically glob a collection of source files, its *opinion* is that you shouldn't do that, and it works better when you don't (it correctly automatically regenerates projects when new files are added).
> 2 votes

---
Tags: architecture, terminology
---