# Question
Title: What is the difference between Quaternion.Euler and transform.Rotate?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateObjects : MonoBehaviour
{
    public GameObject[] objectsToRotate;
    public Transform to;
    public float speed = 0.1f;
    public Vector3 spinDirection;
    public bool useMouse = false;
    public bool useQuaternion = false;
    public bool nonstopSpin = false;

    float x;

    // Use this for initialization
    void Start()
    {
        if (objectsToRotate.Length > 0)
        {
            if (useQuaternion == true)
            {
                for (int i = 0; i < objectsToRotate.Length; i++)
                {
                    objectsToRotate[i].transform.rotation = Quaternion.Lerp(objectsToRotate[i].transform.rotation, to.rotation, Time.time * speed);
                }
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (objectsToRotate.Length > 0)
        {
            for (int i = 0; i < objectsToRotate.Length; i++)
            {
                x += Time.deltaTime * speed;
                objectsToRotate[i].transform.rotation = Quaternion.Euler(x, 0, 0);

                if (useMouse == true)
                {
                    if (Input.GetMouseButton(0))
                    {
                        Rotate(i);
                    }
                }
                else
                {
                    Rotate(i);
                }
            }
        }
    }

    private void Rotate(int i)
    {
        if (useQuaternion == true)
        {
            objectsToRotate[i].transform.rotation = Quaternion.Lerp(objectsToRotate[i].transform.rotation, to.rotation, Time.time * speed);
        }

        if (nonstopSpin == true)
        {
            objectsToRotate[i].transform.Rotate(0, 1, 0);
        }
    }
}

```

In the Update for testing I'm using Quaternion.Euler to spin the object. In the bottom I'm using transform.Rotate.

In both cases I'm getting the same results the object is spinning around it self.

Then what is the difference between them and what should I choose when I want to spin an object ? And maybe there are more way to make an object to spin around it self. But I wonder what is the difference.

# Answer
> 2 votes
`Quaternion.Euler` generates a Quaternion that represents the orientation or relative rotation specified by the Euler/Tait-Bryan angles you provide as inputs.

`Transform.Rotate` rotates a transform by an incremental amount, specified by the Euler/Tait-Bryan angles you provide as inputs.

Internally, `Transform.Rotate` might call `Quaternion.Euler` or something like it to compute the rotation from the angles. For instance, it might look like this:

```
public void Rotate(float x, float y, float z, Space relativeTo = Space.Self) {
    Quaternion increment = Quaternion.Euler(x, y, z);

    if(relativeTo == Space.Self)
        this.rotation = this.rotation * increment;
    else
        this.rotation = increment * this.rotation;
}

```

So when you just want to rotate an object, you can use either one interchangeably.

`Transform.Rotate` provides a little convenience for doing this all in one line, with a handy `Space` selection so you don't have to remember which multiplication order corresponds to local vs world.

But sometimes you don't want to rotate an object right away. Sometimes you just want to transform some vectors. Or you want to cache a rotation rather than apply it to an object immediately. Or you want to do some math to compare, combine & blend orientations before applying them. For those cases, it's handy to be able to create a free-floating `Quaternion` to work with the rotation, rather than spawn a bunch of dummy objects to rotate whenever you want to do some rotation math. That's where things like `Quaternion.Euler` or `.AngleAxis` come in handy.

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


# Question
Title: Unintended stuttering when moving camera
I am using opengl and GLFW to make a rendering engine.

Things work per se, but there is some weird flickering happening when I move the camera.

Due the nature of the problem I need to link a youtube video:

https://www.youtube.com/watch?v=XhFrXadnWbs&feature=youtu.be

If you pay attention you will see the stuttering happening as I move the camera.

I beleive this problem occurs due to how I have implemented my camera movement, which is:

GLFW key callback:

```
#define CAM_SPEED 0.2f
void static key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if(key == GLFW_KEY_W)
    {
        c.translateForward(CAM_SPEED);
    }
    if(key == GLFW_KEY_S)
    {
        c.translateForward(-CAM_SPEED);
    }
    if(key == GLFW_KEY_A)
    {
        c.translateSideways(-CAM_SPEED);
    }
    if(key == GLFW_KEY_D)
    {
        c.translateSideways(CAM_SPEED);
    }
}

```

Camera code:

```
    void inline translateForward(float speed)
    {
        glm::vec3 hForward = forward;
        hForward.y = 0;
        hForward = normalize(hForward);

        position += hForward*speed;
    }

    void inline translateSideways(float speed)
    {
        position += side*speed;
    }

```

# Answer
The problem is caused by a delay in the frequency of poll calls to the GLFW key callback function.

Changing the code so that the callback function updates some global booleans

Like this:

```
    if(key == GLFW_KEY_W)
    {
        if(action==GLFW_PRESS)
            E_W=true;
        if(action==GLFW_RELEASE)
            E_W=false;
    }
    if(key == GLFW_KEY_S)
    {
        if(action==GLFW_PRESS)
            E_S=true;
        if(action==GLFW_RELEASE)
            E_S=false;
    }
    if(key == GLFW_KEY_A)
    {
        if(action==GLFW_PRESS)
            E_A=true;
        if(action==GLFW_RELEASE)
            E_A=false;
    }
    if(key == GLFW_KEY_D)
    {
        if(action==GLFW_PRESS)
            E_D=true;
        if(action==GLFW_RELEASE)
            E_D=false;
    }
    if(key == GLFW_KEY_SPACE)
    {
        if(action==GLFW_PRESS)
            E_SPACE=true;
        if(action==GLFW_RELEASE)
            E_SPACE=false;
    }
    if(key == GLFW_KEY_LEFT_SHIFT)
    {
        if(action==GLFW_PRESS)
            E_SHIFT=true;
        if(action==GLFW_RELEASE)
            E_SHIFT=false;
    }

```

And then making the update happen inside of the render loop as follows:

```
if(E_W)
    c.translateForward(CAM_SPEED);
if(E_S)
    c.translateForward(-CAM_SPEED);
if(E_A)
    c.translateSideways(-CAM_SPEED);
if(E_D)
    c.translateSideways(CAM_SPEED);
if(E_SHIFT)
    c.translate(vec3(0,-1,0)*CAM_SPEED);
if(E_SPACE)
    c.translate(vec3(0,1,0)*CAM_SPEED);

```

Eliminates the stuttering.

Or simply put, the update was moved from the callback function to the render function
> 2 votes

---
Tags: opengl, c++, camera, glfw
---


# Question
Title: What am I missing for this flycam to work correctly?
Through reverse engineering, I've found an instruction to inject on which allows me to obtain the XYZ coordinates of the camera, as well as pitch and yaw. Thus, I have the following:

> * camX (Plane) -- Value is a float ranging from negative to positive
> * camY (Plane) -- Value is a float ranging from negative to positive
> * camZ (Up/Down) -- Value is a float ranging from negative to positive
> * camH (Horizontal/Yaw) -- Value is a float in degrees from +180 to -180
> * camV (Vertical/Pitch) -- Value is a float in degrees clamped to +89 to -89

I've written a script in Lua which allows me to bind directions (forward, backward, left, right, up, and down) to keys (W, A, S, D, Q, and E); however, those simply add/subtract to/from XYZ values along with a speed modifier, meaning if I'm facing forward and moving forward, everything is fine. Turning 180 degress with the mouse, though, effectively means back is forward, left is right, etc.

What I'm looking to achieve is having those directional keys apply to wherever I'm aiming the mouse pointer. So, forward is always where I'm facing, etc.

I've been piecing together the necessity of sin/cos for calculations related to this; however, I'm apparently in over my head with understanding everything I'm reading/watching. I've found a number of calculations for this based on degrees, radians, converting degrees to radians, etc., but I'm just completely lost as nothing I've tried has panned out (even though I *think* I understand what I'm reading).

I've ascertained that, where applicable, respective games have sin/cos values stored somewhere in memory which I could use in lieu of calculating those values myself, but I'm honestly not sure what those values look like to seek out in the first place...or exactly what I need to do to make the calculations myself. They're probably staring me right in the face in nearby memory or on the stack as I trace through code, but I simply don't know.

Are there multiple ways to calculate the appropriate angles via sin/cos? Can I use some combination of the 5 values I listed above, along with a speed modifier and Lua's math.\* methods (math.rad, math.sin, math.cos), to get this flycam to work properly?

Thank you for any guidance you can provide!

# Answer
> 1 votes
Let's assume your Y axis points forward (Yaw = 0), your X axis points right (Yaw = -90 degrees), and your Z axis pints up (a right-handed coordinate system).

Then you can construct a unit vector in spherical coordinates that points in the direction your camera is looking:

```
x = -sin(yaw) * cos(pitch)
y =  cos(yaw) * cos(pitch)
z =  sin(pitch)

```

Multiply this vector by your desired speed (and delta time step) to get the displacement to move your camera forward.

Run the same formulas with `yaw - 90` to get the camera's right vector.

---
Tags: camera, coordinates, lua
---


# Question
Title: How to locate assets on different computers? JavaFX
i've programmed a little game in javafx in Eclipse. It uses 3 file-path url's to locate the images, sounds and savefile folders. My problem is that those url's have been hardcoded and therefor obviously only work on my computer. Like this:

```
    public static String imageDir = "FILE:///D:/Users/tlins/eclipse-workspace/SpaceWars3.0/src/images/";

```

I want to export my game in a jar file and then the programm should figure out for itself where the assets are located. I originally assumed that it would start looking in the same folder as the main class, and that i could just type

```
public static String imageDir = "images/";

```

But it gave me an exception error "url not found" regardless.

So im just here to ask how you people normally do this? This can't be an uncommon thing right?

Should i somehow let the program figure out the EXACT path like shown (far) above? Or is there a way to inform it that it should start looking from the folder of main class?

# Answer
> 0 votes
In order for your assets to be able to load from the same directory on any computer you have to use relative folder structure. Create an assets folder called res and make sure its part of your build path.

https://stackoverflow.com/questions/3718201/how-to-add-resources-to-classpath

Inside that folder you can place your assets in sub folders. Ex: res/images/player.png

Now to load the following assets you need to use the getResources() function. However if you want this to also work inside a .jar file this is the best solution:

```
URL assetLocation = Assets.class.getClassLoader().getResources("images/player.png")

```

Then you can use that URL as you please.

Link to Java Docs:

https://www.tutorialspoint.com/java/lang/class\_getclassloader.htm https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

# Answer
> 0 votes
i have been using getResource, this works even if you are running theyourgame.jar.

1.- i created a res folder and i put there all my images, 2.- i loaded all those images with ImageIO.read(this.getClass().getResource( "/demo1/xpace/ene1.png" ) )

image path its: res/demo1/xpace/ene1.png

---
Tags: java, assets, javafx
---


title: RayCast seems to ignore some objects?

text:
# Question
Title: RayCast seems to ignore some objects?
I'm currently using a Raycast both for my movement check aswell as a focus-setting check, both checks use pretty much the same code. The problem i'm having is that the Raycast goes through some objects and targets the background no matter what i've tried to far. As you can see in this screenshot, I first clicked on the black sphere (Just a 3D Sphere in my 2D world with a default Sphere Collider) and the Log shows so aswell, however when i click on the white box which the second Debug Log is supposed to be, it just ignores the box collider and goes straight to the Background (the green sprite). The same problem with the Interactable check, code works completely fine with the Sphere but not with the box. Here's the Code i currently use:

```
    //Movement
    if (Input.GetKeyDown(KeyCode.Mouse0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 100))
        {
            Debug.Log("We hit " + hit.collider.name + " " + hit.point);
            RemoveFocus();
            targetPosition = hit.point;
        }
    }
    if(targetPosition != (Vector2)transform.position)
        transform.position = Vector3.MoveTowards(transform.position, targetPosition, maxSpeed * Time.deltaTime);

    //Check for Interactable, pretty much same code...
    if (Input.GetKeyDown(KeyCode.Mouse1))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 200))
        {
            Interactable interactable = hit.collider.GetComponent<Interactable>();
            if(interactable != null)
            {
                SetFocus(interactable);
            }
        }
    }

```

# Answer
Few things:

* It can be because your gameObject is on Ignore Raycast layer, so it automatically ignores the raycast.
* Maybe the size of your collider is too small, so you thought you clicked on it, but you actually didn't.
* If you only check the result by debugging to console, I notice there is no Debug.Log () line under Input.GetKeyDown(KeyCode.Mouse1)
* You used 2DCollider, in which you need to use RaycastHit2D instead of RaycastHit. Or just just change the 2D collider to 3D collider.
* The MaxDistance of your raycast is 100 and 200, but maybe your gameObject is farther away.
* The collider might be too big that the camera ended up inside the collider, and because the raycast comes from camera, the collider never picked it up.
* You might be trying to raycast UI with ScreenPointToRay.
* If you're using sprites, the sprite that you want to raycast might be behind the background, it just seems it's infront of it because the layer order is higher.
> 2 votes

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


# Question
Title: Can I give a player money for completing my game?
As it says in the title, can I give a player that completes my game (which might be hard to complete) money?

# Answer
> 2 votes
Yes you can; nothing is stopping you from giving other people your money. The question is do you want to?

This reminds me of the "aardwolf" secret in Wolfenstein 3D. The game was released with a secret message, "Call Apogee and say Aardwolf". This was planned as a contest; the first player to follow those instructions would win a prize. However Apogee (the publisher) backed out after realising that with the release of cheat programs and game editors, the prize would probably be won via illegitimate means.

That was 1991; now with the Internet, free game guides, Let's Plays, anyone can easily finish any game if they had the slightest motivation. This would defeat the purpose of offering a cash prize, which is presumably to encourage people to complete your game via actually playing it.

Instead, consider offering a token that has no monetary cost to you, like an achievement.

---
Tags: real-money-transactions
---


title: Depth Intersection Shader

text:
# Question
Title: Depth Intersection Shader
I am trying to create a shader in Unity that shows where intersections occur between objects.

Most of the shader I have so far is based off of this youtube tutorial. However, I have made some slight modifications to it. The main one being that it is only using a camera's depth texture instead of the depthnormal texture.

```
Shader "Intersection/Unlit"
{
    Properties
    {
        _Color("Color", Color) = (0,0,0,0)
        _GlowColor("Glow Color", Color) = (1, 1, 1, 1)
        _FadeLength("Fade Length", Range(0, 2)) = 0.15
    }
    SubShader
    {
        Blend SrcAlpha OneMinusSrcAlpha
        ZWrite On

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

        Pass
        {
            CGPROGRAM
            #pragma target 3.0
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float2 screenuv : TEXCOORD1;
                float4 vertex : SV_POSITION;
                float depth : DEPTH;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert(appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);

                o.screenuv = ((o.vertex.xy / o.vertex.w) + 1) / 2;
                o.screenuv.y = 1 - o.screenuv.y;
                o.depth = -UnityObjectToViewPos(v.vertex).z *_ProjectionParams.w;

                return o;
            }

            sampler2D _CameraDepthTexture;
            fixed4 _Color;
            fixed3 _GlowColor;
            float _FadeLength;

            fixed4 frag (v2f i) : SV_Target
            {
                float screenDepth = Linear01Depth(tex2D(_CameraDepthTexture, i.screenuv));
                float diff = screenDepth - i.depth;
                float intersect = 0;

                if(diff > 0)
                    intersect = 1 - smoothstep(0, _ProjectionParams.w * _FadeLength, diff);

                fixed4 glowColor = fixed4(lerp(_Color.rgb, _GlowColor, pow(intersect, 4)), 1);

                fixed4 col = _Color * _Color.a + glowColor;
                col.a = _Color.a;
                return col;
            }
            ENDCG
        }
    }
}

```

This shader produces a result that looks like this.

However, this is a problem as there are large areas of the object that remain the initial blue colour. What I was expecting was something that looked like this.

I think the issue is caused when calculating screen depth from `i.screenuv`

```
float screenDepth = Linear01Depth(tex2D(_CameraDepthTexture, i.screenuv));

```

I have tried removing the difference check, this initially appeared to work. Although, when I placed an object in front of the object with this shader, the shader behaved as if there was a collision when there was not. As you can see below.

I would appreciate any help in resolving the issue

# Answer
This issue exists with the original shader as well, but is less apparent with the sphere mesh.

Notice how it looks alright when the model's vertices are close to the intersecting object.

But as they move further away we start to see the problem.

And with a little rotation it becomes really bad.

When things look alright near the vertices but get wonky further away, it almost always means that something is being done in the vertex shader when it should be done in the fragment shader. In this case it's the depth calculation. So how do we move the depth calculation to the fragment shader?

In Unity the answer is:

> **Screen space pixel position: VPOS**
>
> A fragment shader can receive position of the pixel being rendered as a special VPOS semantic. This feature only exists starting with shader model 3.0, so the shader needs to have the #pragma target 3.0 compilation directive.
>
> On different platforms the underlying type of the screen space position input varies, so for maximum portability use the UNITY\_VPOS\_TYPE type for it (it will be float4 on most platforms, and float2 on Direct3D 9).
>
> Additionally, using the pixel position semantic makes it hard to have both the clip space position (SV\_POSITION) and VPOS in the same vertex-to-fragment structure. So the vertex shader should output the clip space position as a separate “out” variable.

(See https://docs.unity3d.com/Manual/SL-ShaderSemantics.html)

Applying that to your shader gives you something like:

```
Shader "Intersection/Unlit"
{
    Properties
    {
        _Color("Color", Color) = (0,0,0,0)
        _GlowColor("Glow Color", Color) = (1, 1, 1, 1)
        _FadeLength("Fade Length", Range(0, 2)) = 0.15
    }
    SubShader
    {
        Blend SrcAlpha OneMinusSrcAlpha
        ZWrite On

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

        Pass
        {
            CGPROGRAM
            #pragma target 3.0
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert(appdata v, out float4 vertex : SV_POSITION)
            {
                v2f o;
                vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);

                return o;
            }

            sampler2D _CameraDepthTexture;
            fixed4 _Color;
            fixed3 _GlowColor;
            float _FadeLength;

            fixed4 frag (v2f i, UNITY_VPOS_TYPE vpos : VPOS) : SV_Target
            {
                float2 screenuv = vpos.xy / _ScreenParams.xy;
                float screenDepth = Linear01Depth(tex2D(_CameraDepthTexture, screenuv));
                float diff = screenDepth - Linear01Depth(vpos.z);
                float intersect = 0;

                if(diff > 0)
                    intersect = 1 - smoothstep(0, _ProjectionParams.w * _FadeLength, diff);

                fixed4 glowColor = fixed4(lerp(_Color.rgb, _GlowColor, pow(intersect, 4)), 1);

                fixed4 col = _Color * _Color.a + glowColor;
                col.a = _Color.a;
                return col;
            }
            ENDCG
        }
    }
}

```

It's mostly self explanatory once you know about VPOS, but there's at least one thing worth noting: the uv of the depth texture also had to be calculated in the fragment shader, and since vpos.xy is in screen pixel coordinates, we have to divide by the screen resolution (\_ScreenParams.xy) to get texture coordinates.

And now we get the intended effect no matter where the vertices are.
> 4 votes

---
Tags: unity, shaders, graphics, fragment-shader, cg
---


# Question
Title: OpenGL Bind all objects at once or single objects at a time
So if I have a bunch of objects, I do:

```
glBegin(); renderThing1(); glEnd();
glBegin(); renderThing2(); glEnd();
glBegin(); renderThing3(); glEnd();

```

Is this more or less efficient than:

```
glBegin(); renderThing1(); renderThing2(); renderThing3(); glEnd();

```

Not using unity, using LWJGL and java.

# Answer
> 0 votes
It's more efficient to have fewer glBegin/glEnd pairs, but it shouldn't make too much of a difference unless you have lots of very small things--this type of rendering (immediate mode) is incredibly inefficient no matter what. If you want decent performance from OpenGL then you need to use the modern API (https://learnopengl.com would be a good place to start).

---
Tags: opengl, java, lwjgl
---


# Question
Title: detecting if a chess move is valid for a given pawn , preferably using Linear algebra
I'm making a chess game, where you simply drag and drop a pawn on the board with respect to each player's turn. when it comes to dropping a pawn we need to validate weather the move is allowed. for some reason my very first instinct was to use linear algebra, particularly finding out if the new position is within the span of a given pawn.

now each pawn is given :

1- a set of vector movements e.g a queen's movement =(0,1),(1,0),(1,1);

2- a magnitude of movement e.g a queen can only move a single block a turn i.e magnitude =1

3- a direction i.e if a pawn can move back and forth then direction=-1 else direction =1;

using Gauss elimination we can check weather or not the new position is reachable given the pawn's set of movements but it disregards it's current position. e.g using Gauss elimination the position (4,5) is reachable by a queen pawn given it's set of movements. BUT only if the queen is 1 block away.

how to take the current position of a pawn while checking for the new positions validity using linear algebra and Gauss elimination?

# Answer
> 0 votes
Why don't you simply separate each piece's logic, then every time the user attempts a move, do something like `IsValidMovement(from, to)`. When it comes to the Rook, if `from` and `to` have the same X or the same Y, it's a valid move (but then you have to check for other pieces obscuring the way). Assuming that you use a language that supports OOP, you can do that in a form of subclass.

Using vectors is not wrong, but it becomes cumbersome and could potentially require too much manual work, the bishop's movement can be automated, you don't have to save all individual blocks that it can move to. Also the knight can jump over pieces, while others cannot. The pawn also has special behaviour when near enemy pieces.

Here's an example in pseudocode:

```
class BaseClass {

    // Data that all pieces have

    bool abstract IsValidMovement(Vector2 from, Vector2 to);

}

// Subclass for the Rook piece
class Rook : BaseClass {
    bool IsValidMovement(Vector2 from, Vector2 to);
}

// The user made a movement starting from `from` and ending at `to`
bool Rook::IsValidMovement(Vector2 from, Vector2 to) {
    /* The rook can only move either horizontally or vertically
     * as many squares as it likes (without obstacles)
     */
    if ((from.x == to.x) || (from.y == to.y)) {
        // The rook made a movement which is valid
        return true;
    }

    // The target square is not in reach
    return false;
}

```

Now when you create the pieces, you can do something like `Rook rookLeft = new Rook();` and when the user makes a movement, once they place the piece on the board you can do `rookLeft.IsValidMovement(originalPosition, endPosition);`. If it returns true, the piece can move there, if it returns false, the piece cannot move there.

If you want to check for obstacles, like a piece being in between, you can also add one more argument (maybe an array of pieces?) and include that in your logic. In the example of Rook, if the end position is three squares to the right of the rook, it's a valid movement, but if there's another piece one square to the right, then it's not.

---
Tags: movement, linear-algebra, chess
---


# Question
Title: Loading encounters and collisions questions within 2D
I had three basic questions regarding the creation of a 2D sandbox/openworld game much like Terreria.

Only looking for a general overview/opinion, nothing too detailed. Any links to literature that would help answer the questions below would also be helpful.

First off - Keeping track of the map using regions/chunks, lets say 512 x 512 chunks. Is it recommended to pre-load the surrounding chunks of the 'chunk in focus', so if the character enters either one there is no load time? ~Or do you simply load smaller slices of the chunk next door, in the direction of movement?

Secondly. Do I need to add a collision box to every tile that is preloaded so any NPCs that are off screen but 'next-door' can interact with the environment? Or is this going to be massively CPU intensive ? (512 x 512 x 9 tiles alone)

Third and last question. Off screen RANDOMDLY GENERATED NPCs/monsters I assume dont load and render as they enter the viewable area on the active chunk but are loaded and activated sometime before they are seen. What are the general strategies use to handle this?

For Reference: Using c# with Unity, no third party frameworks/plugins.

Many thanks John

# Answer
**Preloading**

Preloading is a touchy subject. It allows for simulation and fast loading but is subjected to the user's memory availability. If you use Minecraft for example, the preloaded area is the active chunks surrounding the player. The catch of preloading is that if the chunk is not loaded into memory, its not simulated.

Preloading can me summarized into a balance of the following items

* The need to simulate
* The availability of memory
* The requirement of continuity (whether the player have to pause and load the next chunk)

Ill talk about these 3 points briefly.

---

**Simulation**

This depends on the accuracy of the world you are creating. Whether the world need to "continue" when you are not watching it. Most tile based games have a set area that confines the player to avoid this issue. The only area it needs to simulate is the only area the player can play in. But if you need to have a large/open world there is two solutions I have seen before.

* Discard continuity and only simulate the area you are playing in
    + Examples of this is Minecraft. Where crops dont grow unless theres a player in the area.
* Discard accuracy and simulate in a lower resolution
    + I cant give an example of this but in a project I previously worked in, open world AI is simulated in a lower resolution. They have no colliders, no physics and path finds in a limited fashion. The only issue with this is that you need to resolve any issues that happens during the limited simulation when they are loaded into real simulation. ie. whether they morphed into a wall when they have no collision.
    + Check out this question for a more detailed explanation for your second question
    Good way to handle offscreen AI?

For your third question, since your design of the world is chunk based, your reference would probably be the entire chunk. Load your AI together with the chunk so that the AI can interact with the chunk. Apply the lower resolution simulation if necessary for AI outside the current chunk.

---

**Rendering**

On the subject of rendering stuff outside the screen, A simple positional calculation would serve the purpose with the least computation requirement. Simply not render any object that is X distance away from the center of your screen (Assuming it is a top down orthogonal view). For 3D solutions id recommend frustum culling as a solution.

Generally speaking Unity does a great job of doing this automatically. You can keep sprites and objects active and they wont render unless they are within view of the camera.

---

**Afterthought**

Do note that you are dealing with an optimization issue. While this is good, as Donald Knuth would say, *Premature optimization is the root of all evil*

Unless your AI is highly complex, most games are able to simulate a significantly large area at 3-5 times speed with no issues. Consider other solutions like multithreading if your AI is too compute intensive. One interesting strategy I have seen in an old game is to slow down the game when its really busy.

Most games suffer from not properly using the available CPU cores than actually have issues with simulation.
> 2 votes

# Answer
I am not sure about first and second question, but for third question, you can fix a position for event trigger on x so when your character enter the region, the NPCs/Monsters will be loaded and rendered.
> -1 votes

---
Tags: unity, 2d, open-world
---


# Question
Title: How to make a player have to destroy squares in a specific order?
I create a simple 2D Unity ( C#) animation, which is a tutorial for me.

I have a PLAYER.

1) My player moves with the mouse (he follows mouse).

2) After colliding with a square, he destroys it.

I don't have a problem with it, everything works ok.

**However, I would like the player to destroy the squares in the right order(in right sequence): 1-2-3-4.**

**If he destroys them in the wrong order(wrong sequence) , for example 1-3 (first collid with number 1 and then number 3), animation end.**

I know how to end animations when I touch an wrong thing, but I do not know how to make it in the right order (specific sequence).

**How to make a player have to destroy squares in a specific order?**

PS. Sorry for my English. If someone doesn't understand something, I'll try to write it simpler :)

Until now, with the help of tutorials, I did something like that:

```
 // this script is on the empty game object; just one of these, and it keeps track of which game object is the right one to be destroyed next.
int index = 0;

[SerializeField]
GameObject [] gamePieces;

public void GotDestroyed(GameObject go) {
   if(gamePieces[index] == go) {
      // correct one was destroyed.
      ++index; // if index >= gamePieces.Length, it's game over.. all done.

  }
    else {
       // if we're here, the one destroyed was not the next in the list
    }
 }

```

But how to further transform this code to solve the problem?

# Answer
> 1 votes
There are lots and lots of different ways to achieve this. There is no best solution, just the solution which fits best into the software architecture of your game.

One solution you could use is to add a variable `public Square previous` to your Square behaviour. Use the Inspector to assign to each square the previous square in order. Leave it `null` for the first square.

In your code which handles the square collisions, check if `previous == null`. Destroyed objects are considered equal to null by Unity, so this condition will return true if the previous square was destroyed or never assigned in the first place.

Another approach would be to have a `Square[] squares` in your Player behaviour and an `int nextSquare` which says which entry in the array is the one which needs to be visited next. When the player collides with a square, check if `squares[nextSquare] == collidedSquare`.

---
Tags: unity, c#, 2d
---


# Question
Title: How to create a puzzle where the player needs to rotate hexagons to connect to the neighbors?
I was researching different puzzle ideas and came across a game called Warframe that requires the player to hack a console to progress further into the level.

The player has to spin around the hexagons (randomly generated, and get more difficult later on) to link up the connections to other hexagon neighbors. It's simple for the player to do, but also quite fun from my research.

How can I create something similar to this?

Edit: To be more specific; I would like to know how to generate a puzzle like below and how to check for successful connections. The graphics, animations, and player input I can handle. I suppose it's more about the algorithms to create the puzzle and then check the conditions.

I couldn't figure out good search terms to find something similar. So even if someone can point me in the right direction, that would be helpful.

I will be doing this in Unity / C#.

Example of doing a puzzle.

# Answer
> 1 votes
One common strategy that's used to generate puzzles like this is to start from a solved state, then work backwards to scramble it. So...

1. Create your initial arrangement of hexes, initially all blank. This could be pulled from a list of pre-set arrangements, or you could place hexes one at a time so that they touch at least one other hex.

List all the places where two hexes share an edge.
2. Select and remove a shared edge from your list at random, and mark the hex on each side with a line pointing to that edge.

Repeat until you have as many connections as you want. (There's probably a sweet spot in ratio to the number of hexes in the puzzle, where the number of connections per tile is high enough to provide some choices, but not so high that everything connects to everything else)
3. Pick a hex at random and rotate it ±60° randomly.

Repeat `n` times, based on how scrambled you want the puzzle to be.

Verify that the puzzle hasn't accidentally been scrambled back into a solved state before terminating. If so, do a few more rotations.

This method:

* guarantees the puzzle is solvable
* guarantees the solution is reachable in `n` valid moves or fewer (since you used only `n` reversible moves to scramble it from a solved state)
* has tunable parameters to control the difficulty:

+ number of tiles
    + density of connections
    + scramble count `n`

Arriving at work now but I can give some implementation notes later. The main idea being store each hex as an array of 6 `bool`s representing connections, and an integer offset you can use to rotate your lookups into that array, modulo/barrel-shift style.

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


# Question
Title: Should I be caching the assets in my asset manager, or will the browser handle it?
I use the asset manager class below in my game to download all the game data at launch. It's about 5000 files. Each file is retrieved like so:

```
const image = AssetsManager.getImage("rooms.lounge.floor");

```

Will the browser cache these itself or should I add a caching layer myself?

```
import {
    ASSET_URL
} from 'src/AssetsManager';

export default class AssetsManager {

    static resolveUrl(path)
    {
        path = path.split('.').join('/');

        return ASSET_URL + path;
    }

    static async getJSON(path)
    {
        const url = AssetsManager.resolveUrl(path) + '/.json';

        return fetch(url)
            .then(response => response.json())
    }

    static async getImage(path)
    {
        const image = new Image();
        const url   = AssetsManager.resolveUrl(path) + '/.png';

        image.onload = () => {
            if (image.complete) Promise.resolve(image);
            Promise.reject();
        }
        image.src = url;
    }

```

# Answer
`fetch(url)` will always reload the resource from the web. So when you request the resource several times and you don't think it changed in the meantime, then you should really consider to add a caching layer.

When you load an image with `image.src = url;`, then the browser will usually load that image from cache if it is cached. But keep in mind that the browser might discard the image from memory if it isn't used and its caching settings don't require it to stay cached.

Loading 5000 files at game start might result in a quite long startup loading time. This is quite problematic for web games, because the average attention span of users on the web is rather short. Every second of startup delay will cause more people to just close the website. You might want to consider some strategy which allows you to load most assets while the game is already running... or at least create a very promising looking preload animation.

Also, you should be aware of that you are using several Javascript features which are very new. It might not work on some user's web browsers.
> 1 votes

---
Tags: javascript
---


# Question
Title: Pushing an object left and right (gravitation towards center of a circle)
So this is the problem:

I have an object pulled towards the center of a circle and I am unable to figure out how to move the object left and right depending on its rotation around the circle.

I basically need to know in which "angle" to push the object if the left or right key was pressed.

Thank you

# Answer
> 0 votes
This should be solveable by simple trigonometry.

Have a look at the following unit circle:

So basically, depending on detected key presses, you'd increase or decrease θ. Then, when with the center of your circle, just calculate any position by doing something like the following:

```
posX = centerX + cos(θ)*radius;
posY = centerY + sin(θ)*radius;

```

You also mentioned gravity. It can be simulated by slowly decreasing the radius of the circle.

Hope that helps.

Cheers

# Answer
> 0 votes
The solution depends on your implementation. If the object that is pulled towards the centre is not rotated, but only translated towards the circle, then the best solution would be to find the `tan` of that object, based on the circle. Ignatiamus's answer can probably help with that.

If however, your object is rotated based on the circle (if for example it represents a character that is walking on a planet), there is a more lazy way to do it. Simply Translate the character based on its local coordinates. If the character's face if facing the +X axis for example, if you do a translation towards the X axis with a positive value, the object will move towards it, based on it's local rotation. Once you do that, you should probably re-calculate the objects rotation, so that its placed properly towards the circle.

Some pseudocode:

```
void Start() { // Runs once in the beginning

    object.LookAt(circle); // Makes the object face the circle

}

void Update() { // Runs once a frame

    object.translate(1.0f, 0); // Move 1 unit towards the +X axis in 2D
    object.LookAt(circle); // Makes the object look at the circle again

}

```

This code will cause the object to constantly rotate around the circle and translate properly. Please note that based on your implementation you may need to change some parameters, like which axis your object you want it to point to etc.

---
Tags: mathematics, movement
---


# Question
Title: Javascript/HTML5 canvas: Integrate scrolling tilemap with map server
I am playing around adapting the example code at Mozilla Dev Network: Square tilemaps implementation: Scrolling maps to fit with a server I wrote myself. There's a link to the original source code at the bottom of the page.

Instead of hard-coding the map (and its layers) into the js page, I can have a server call deliver the map data in a similar format (a 1-dimensional sequence of numbers up to 256). The way the server (and the js interface) is constructed, I first need to get the map Id from the game that is stored on the server and use that id to get (a section of) the map.

This is the function for doing the data fetch:

```
function LoadGame(gameid) {
$.getJSON('/api/game/' + gameid)
    .done(function (game) {
        if (game !== null) {
            mapid = game.MapId;
            map = AssetLoader.LoadMapSection(mapid, 0);
        }
        else
            console.log("Could not load game with id: " + gameid);
    })
    .fail(function (jqXHR, status, error) {
        console.log(error);
    });
}

```

The LoadMapSection function looks like this:

```
AssetLoader.LoadMapSection = function (mapid, pos) {
    if (!(mapid in this.maps)) {
        this.status = statusEnum.LOADING;
        console.log("Loading map section: " + mapid + " at: " + pos);
        $.getJSON('/api/map/section/' + mapid + '/' + pos + '/32/24')
            .done(function (map) {
                AssetLoader.maps[mapid] = map;
                this.status = statusEnum.DONE;
                console.log("Loaded section of map: " + mapid);
            }).fail(function (jqXHR, status, error) {
                console.log(error);
                this.status = statusEnum.ERROR;
            });
    }
    return map;
}

```

Since the map data may take some time to arrive I am trying to use an AssetLoader, suggested by MDN, to fetch the map data as well as the spritesheets for displaying the map. So, upon game load, I construed this:

```
Game.load = function () {
return [
    AssetLoader.LoadImage('atlas-elevation', 'assets/atlas/elevation.png'),
    AssetLoader.LoadImage('atlas-landscape', 'assets/atlas/landscape.png'),
    LoadGame(gameid),
   ];
};

```

To ensure the asynchronicity and wait for all data to be fetched, the following code has been left unchanged:

```
Game.run = function (context) {
    this.ctx = context;
    this._previousElapsed = 0;
    var p = this.load();
    Promise.all(p).then(function (loaded) {
        this.init();
        window.requestAnimationFrame(this.tick);
    }.bind(this));
};

```

So the following init-call is supposed to happen **after that**:

```
Game.init = function () {
    Keyboard.listenForEvents(
        [Keyboard.LEFT, Keyboard.RIGHT, Keyboard.UP, Keyboard.DOWN]);
    this.tileAtlas = AssetLoader.GetImage('atlas-elevation');
    this.camera = new Camera(map, 512, 512);
};

```

However, I keep on running into situations where the map is still "undefined" as soon as the Camera code is hit:

```
function Camera(map, width, height) {
    //if (map != null) {
        this.x = 0;
        this.y = 0;
        this.width = width;
        this.height = height;
        this.maxX = map.Width * scale - width;
        this.maxY = map.Height * scale - height;
    //}
}

```

I did declare map at the top of the js file as global variable, so I am not sure where I am going wrong here.

# Answer
> 1 votes
It appears there may be some confusion regarding promises. From Mozilla's Promise.All documentation:

> The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

In your case you are using Promise.All to ensure your game has fully loaded, specifically that all functions returned by Game.load have completed. However in order for this to work each of these functions must return a promise.

The code hasn't been provided for `AssetLoader.LoadImage`, but looking at `LoadGame` it is clear that no promise is returned - in fact, nothing is returned.

However because JQuery's getJSON function return a jqXHR object, which implemnets the Promise interface, you can simply make `LoadGame` return the results of your `$.getJSON` call. For example:

```
function LoadGame(gameid) {
    // Note we're returning the Promise.
    return $.getJSON('/api/game/' + gameid)
    .done(function (game) {
        if (game !== null) {
            mapid = game.MapId;
            map = AssetLoader.LoadMapSection(mapid, 0);
        }
        else
            console.log("Could not load game with id: " + gameid);
    })
    .fail(function (jqXHR, status, error) {
        console.log(error);
    });
}

```

Additionally because `AssetLoader.LoadMapSection` is also asynchronous you'll need to add this change to that method aswell, and any other nested functions which are asynchronous.

---
Tags: javascript, tilemap, html5, html-canvas, viewport
---


title: What does "{ get; set;}" in Unity mean?

text:
# Question
Title: What does "{ get; set;}" in Unity mean?
I am coming back again into hobby game development after about 6 months away. I'm just trying to learn some kind of basic things again. I'm at the very start of making a very simple boxing management simulator. Later, I will be trying to re-learn using databases and might ask for more help.

But for now, I'm making a Boxer class which will hold all the data on each boxer (eg. Name, height, number of wins, punch power etc etc). I've used private variables for those and then have made my own methods for each variable called Getxyz().

I have seen people doing things like 'public int xyz { Get(); }' but i dont understand how that would work.

Is the way I'm doing ok (it does seem long-winded to me) or should I investigate these Getter Setters some more? Here's what I am doing right now:

```
public class Boxer : MonoBehaviour {
// generic boxer details:
int id;
string nameA, nameB;
int weight;
int height;
float age;
float reach;
// career info:
int wins, loses, draws, winsByKO;
// boxing attributes/stats:
float power, speed, agility, koPunch, stamina, toughness;

public int GetId()
{
    return id;
}
public string GetNameA()
{
    return nameA;
}
public string GetNameB()
{
    return nameB;
}

```

}

# Answer
> 12 votes
> I have seen people doing things like 'public int xyz { Get(); }' but i dont understand how that would work.

These are called *properties*. They're a language construct that allows you to expose data from a type that *looks like* a field when you access it, but acts like a pair of functions in that you can have behavior execute whenever the property is read (the "getter") or assigned to (the "setter").

Consider this:

```
class Thing {
  private int secret; // This is a field.

  public int Secret { // This is a property.
    get {
      Debug.Print("Somebody is accessing the secret!");
      return secret;
    }

    set {
      Debug.Print("Somebody is writing to the secret!");
      secret = value; // Note the use of the implicit variable "value" here.
    }
  }
}

```

The `Secret` property has both a getter and a setter; these are really just functions that can execute any code you want. You can then do:

```
Thing thing = new Thing();
thing.Secret = 23; // Use the setter.
Debug.Print("Set the secret to {0}.", thing.Secret); // Use the getter.

```

Note that it *looks* like you're accessing a field here (no `()` is used to get or set `Secret`), but you're still actually calling the `get` and `set` functions you wrote above.

C# supports quite a bit of shorthand around properties. For example, declaring a property like you've seen:

```
public int Secret { get; set; }

```

Tells the compiler to generate a backing field for `Secret` for you, and set the getter/setter to some code that just returns or writes to that backing field.

Quite a bit more detail can be found at the MSDN link I shared at the start of this post.

> Is the way I'm doing ok (it does seem long-winded to me) or should I investigate these Getter Setters some more?

What you are doing is fine, if you are happy with it. It will be worth your while to learn about C# properties, however. If nothing else, you will encounter them often in code other people have written even if you prefer not to use them yourself, so it will be good to understand them. It is also useful to know how to use properties because they are treated differently from regular fields in reflection, and many tools (Unity included) use reflection to find and identify data associated with your types. Some of those techniques will not work with simple fields because they *assume* the use of properties, and so you may need to use properties if you want to take advantage.

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


# Question
Title: Applied force is backward instead of forward when shooting an object
I have this FPS I'm making and I wanted to apply force to objects I shoot at however when I shoot on them, instead of going away from the camera they come towards it.

I don't get it. I could fix the problem by putting a `-myTransform.forward` but I want to understand the cause of the problem so I can fix it better.

Here's the logic behind the calculation:

```
void ApplyForce(Vector3 hitPosition, Transform hitTransform)
{
    if ((hitTransform.GetComponent<Rigidbody>() != null))
    {
        hitTransform.GetComponent<Rigidbody>().AddForce(myTransform.forward * forceToApply, ForceMode.Impulse);
    }
}

```

# Answer
I'm not sure what `myTransform` refers to, but with your code you are applying force based on that object's +Z axis. If that this is the player, the object will move either towards or away from it. Since you use `myTransform.forward`, this means the object will move on the +Z axis of the player. Have you checked that the player is looking at the +Z axis? or is it looking at the -Z?

Assuming this is the intended behaviour, everything else in your code seems about right, since you are using object's local axis to apply force, there's a chance one of your object is "flipped". Maybe it's rotated by 180 degrees on the Y axis, maybe it's Z scale is -1 because it's imported model was made that way. That's not necessarily wrong, but it's good to keep an eye one that.

Edit:

If the only problem is that the imported model is imported in the wrong angle, unfortunately Unity (as far as I know) cannot change that. You can open the imported model on a 3D software (like Blender), and edit the model to look in the desired axis. Then export again in your preferred format, and import it on Unity. If you are using Blender, you can take a look how to do that here.
> 1 votes

# Answer
Okay I fixed the problem:

What I did was to just put my imported weapon into an empty object in the right Z axis and then rotate the imported weapon (now child of the empty object) at 180°.
> 0 votes

---
Tags: unity, c#, first-person-shooter, projectile-physics
---


# Question
Title: One pass rendering with GL_TEXTURE_CUBE_MAP_ARRAY
I try to rework rendering of point light shadows from "pass per cube face" to "one pass using geometry shader".

initialization:

```
glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, texId);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 0, GL_DEPTH_COMPONENT, getWidth(), getHeight(), 6 * lightsNumber, 0, GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer) null);
glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, 0);

glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texId, 0);

int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
   throw new IllegalStateException("Could not create FrameBuffer: " + status);
}

glBindFramebuffer(GL_FRAMEBUFFER, 0);

```

using:

```
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadowBuffer.getTexture().getId(), lightNumber);

glClear(GL_DEPTH_BUFFER_BIT);

renderMeshes(scene, transformation);

depthShaderProgram.unbind();
glBindFramebuffer(GL_FRAMEBUFFER, 0);

```

GS:

```
#version 430

layout (triangles) in;
layout (triangle_strip, max_vertices=18) out;

uniform mat4 projLightViewMatrix[12]; // just two light
uniform int lightNumber;

void main() {
  for (int lIdx = 0; lIdx < lightNumber; lIdx++) {
    for(int face = 0; face < 6; face++) {
      gl_Layer = lIdx * 6 + face;
      for(int i = 0; i < 3; i++) {
        gl_Position = projLightViewMatrix[gl_Layer] * gl_in[i].gl_Position;
        EmitVertex();
      }
      EndPrimitive();
    }
  }
}

```

It casts shadows only for 1st light. Could you notice something wrong?

# Answer
> 3 votes
What a simple point it was!

```
max_vertices=18

```

18 it is only for one cube! If I need n cubes, then I must emit 18 * n vertices.

---
Tags: cubemap
---


# Question
Title: What is wrong with my Respawn coroutine?
I am creating a 2D Platformer game in which if the player falls off the base/ground then I want the player to respawn at the nearest checkpoint. However I want there to be a delay between the player falling off the ground and the respawn. This is the section of my code to achieve this goal:

```
private void OnTriggerEnter2D(Collider2D collision)
{
    Debug.Log(collision.tag);
    if (collision.tag.Equals("Kill"))
    {
        StartCoroutine("Respawn");
    }
    else if(collision.tag.Equals("Checkpoint"))
    {

        Animator flag = collision.GetComponent<Animator>();
        if (!flag.GetBool("hasCrossed"))
        {
            flagCounter++;
            flag.SetBool("hasCrossed", true);
            checkpoint = collision.gameObject.transform.position;
        }
    }
}

IEnumerator Respawn()
{
    yield return new WaitForSeconds(respawnDelay);
    transform.position = checkpoint;

}

```

This works fine for small respawn delays like 1 or 2 seconds. But on increasing the delay to 5 seconds, the player after appearing at the nearest checkpoint vanishes off in an instant and then after quite a few repetitions the player reappears.

This is for the 2 second time delay

This is for the 5 second time delay

How can I fix this?

# Answer
This doesn't seem to have anything to do with how you set up the coroutine. What is probably happening is that the player gets a high enough acceleration while falling to glitch past the ground and the fallout collider. When you move the position during the respawn, it will still be falling at the same rate. In your Respawn method, sometime after your wait line, set the velocity back to zero: `GetComponent<Rigidbody2D>().velocity = Vector2.zero`.
> 50 votes

---
Tags: unity, coroutines
---


# Question
Title: Why am I getting these errors when including stb_image.h?
I'm trying to put an include guard around including `stb_image.h` (from the well-known public domain image library).

I have noticed that, unusually, the include guard works inside the `.cpp` file but not inside the header file.

Let me explain: Inside `texture.h`:

```
//This is something that stb image defines in its own include guard, so I should be able to test for it
#ifndef STBI_INCLUDE_STB_IMAGE_H
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#endif

```

This gives me errors (multiple definitions of everything inside `stb_image.h`), but the same code in `Texture.cpp` does not give me an error.

Also, I'd like to note that this does not work either:

```
#ifndef WHOMST
#define WHOMST
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#endif

```

# Answer
From the stb\_image.h file itself:

> Do this: #define STB\_IMAGE\_IMPLEMENTATION before you include this file in *one* C or C++ file to create the implementation.

You must **not** `#define STB_IMAGE_IMPLEMENTATION` in header (.h) files.

Only in one C/C++ file to create the implementation (the stuff that has to be unique and done only once.)

The header files can include stb\_image.h but must not have this preprocessor macro defined.

Screenshot with added highlight:
> 5 votes

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


# Question
Title: Code optimalization - Mass selecting units (RTS)
**Yo fellow game developers!**

*So recently gamedev became my favorite hobby and I started working on my RTS game module which would then let me create different RTS games with just few changes (W3 inpiration :3). Anyway I am new to optimalization since my previous games had quite serious optimalization issues so I need your help with a pieace of code!*

I am having a mass selection of units with drawn rectangle on screen. **I've got it all worked out** but now I am wondering if there **could be anything done about optimalization for cycling through list of units every time my mouse position changes** even for a little bit.

This is inside my Update function. There is much more in there so i cut it out but this is the piece I am worried about:

```
    void Update(){
        //...previous code blah blah blah...
        if (Input.GetMouseButton(0)) {
            oldPos2 = point2;
            point2 = Input.mousePosition;
            if (oldPos2!=point2) {//performance optimalization
                Debug.Log ("Performing selection");
                if (Vector2.Distance(point1,point2) >= selBoxIniDist) {
                    isSelecting = true;
                    foreach (var item in Game.Units) {
                        if (IsWithinSelectionBounds (item.gameObject)) {
                            item.Selected = true;
                        } else {
                            item.Selected = false;
                        }
                    }
                }
            }
        }
        //...rest of the code here...
    }

```

So as i told you, there is no problem with the code. I just need your opinion if there could be any changes especialy to this part of the code. Or maybe general advices for optimalization.

Even tho **I am checking every update if the mouse moved** (so I dont cycle every update) I still feel like **checking every "milimeter" 5 times** if any of the units are contained in the viewport rectangle is a little bit overkill just for the selecting units. At the end of selection I usualy **end up with around less than 100 cycles**.

**What do you think?**

***EDIT:*** I might as well add a method that checks if the unit is in the viewport bounds and a utility method that calculate the bounds. Just so you why I am worried about performance.

Checking if bounds contain unit:

```
public bool IsWithinSelectionBounds( GameObject gameObject )
    {
        if (!isSelecting) {
            return false;
        }

        var camera = Camera.main;
        var viewportBounds = Utilities.GetViewportBounds( camera, point1, point2);

        return viewportBounds.Contains(camera.WorldToViewportPoint(gameObject.transform.position));
    }

```

Static utilities:

```
public static Bounds GetViewportBounds( Camera camera, Vector2 screenPosition1, Vector2 screenPosition2 )
{
    var cam = Camera.main;
    var v1 = cam.ScreenToViewportPoint( screenPosition1 );
    var v2 = cam.ScreenToViewportPoint( screenPosition2 );
    var min = Vector3.Min( v1, v2 );
    var max = Vector3.Max( v1, v2 );
    min.z = camera.nearClipPlane;
    max.z = camera.farClipPlane;

    var bounds = new Bounds();
    bounds.SetMinMax( min, max );
    return bounds;
}

```

# Answer
As your edit mentions, culling these checks to things outside of your frustrum is a good start; which is essentially free because only those being animated are selectable. You may consider finding a way to store the list of references to the things you just drew to make this nearly free at the cost of a few KBs of memory.

---

The next thing is you only have to actually check FROM a single direction. That is to say that the units that are selected near the Right and Lower bounds (in most cases, what bounds your mouse is currently manipulating) are likely to be released. Thus you can imagine those within 100 pixels of these bounds are much more **volatile** than those 200 pixels away, and so forth.

One could thusly imagine that you could use a pair of Stack data structures, one that adds units from Starting Y to Finishing Y order, and another that adds units from Starting X to Finishing X order. These stacks would mean that you pop off units that are now out of your boundary and that as soon as you can no longer pop the next unit off you know that all other units are *guaranteed* to be within your boundary; negating their calculations.

Admittedly, this is a lot to go through for some cycles, but it probably looks pretty darned cool in action :p

---

It's worth noting you're losing a *gigantic* amount of cycles by casting your units from World to Viewport rather than the other way around. Each one those is series of Matrix Multiplies which are very expensive (relative to other code.) If you casted your two mouse coords (START and CURRENT) you would only ever do Two projections of points per frame. This is O(1) rather than O(n). Quite an improvement.

---

Lastly, two things to mention about your algorithm itself:

\***You're calling a relatively expensive function of Distance on your two coordinates. I'm not sure why you're doing this given that you can just bounds check your units. The reason this is expensive is the Sqrt that is implicit in the call. Not huge, but it may be completely unnecessary (at least how I imagine I'd do it in the future.)

\***Why are you selecting units when the user hasn't released the mouse button? Is this simply to draw a box around the soon-to-be selected units or similar? You can actually get rid of this entire check by the logic of most RTS out there and simply do this work in a pixel or vertex shader (outline or draw a box around the unit) and simply \*only perform this check when the user releases their mouse-box-selection-click.

Best of luck! Hope this helps!
> 2 votes

# Answer
Unity internally organizes game objects in an AABB tree. This allows Unity to quickly get all game objects within an area without having to iterate every single object in the scene.

To make use of that, you might use Physics.OverlapBox or you could represent your selection-rectangle with a temporary BoxCollider and use the OnTriggerEnter and OnTriggerLeave events to set and unset the selection-flag.
> 3 votes

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


# Question
Title: MonoBehavior Script that uses UnityEditor - Best practice for Location?
I've created a script which helps me auto-generate a `GameObject` prefab. It uses some `UnityEditor`, so it can't be used at runtime (and its not meant to be).

Normally, a script like this I would put in the "Editor" folder.

However, since it needs to be attached to a `GameObject` as a `Component` to do its thing, I'm not sure where I should put it. I can't store it in the Editor folder, because Unity yells at me and says I'm not allowed.

Are there any best practices defined for things like this?

# Answer
> 1 votes
You could use **Platform dependent compilation blocks** in your scripts, so certain parts would be compiled just if they are in a specific platform. Example:

```
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class PrefabCreatorExample : MonoBehaviour
{
    public string path;

    private void Start()
    {
#if UNITY_EDITOR
        PrefabUtility.CreatePrefab(path, GenerateObject());
#endif
    }

    private GameObject GenerateObject()
    {
        GameObject newObject = new GameObject();

        // Your creation logic here...

        return newObject;
    }
}

```

I use this a lot to write Gizmos' attributes for the Editor without generating unnecessary data types on the final build.

You could also use **Inspector classes** that will only be compiled on Editor mode, this scrips must be on **Editor**'s folder of course. With this solution you separate the Game's functionality from the Editor's (on this case, I have created the PrefabUtilities MonoBehaviour class). Example:

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

[CustomEditor(typeof(PrefabUtilities))]
public class PrefabUtilitiesInspector : Editor
{
    private PrefabUtilities prefabUtilities;    /// <summary>Inspector's Target.</summary>

    /// <summary>Sets target property.</summary>
    void OnEnable()
    {
        prefabUtilities = target as PrefabUtilities;
    }

    /// <summary>OnInspectorGUI override.</summary>
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        if(GUILayout.Button("Substitute with Prefab.")) prefabUtilities.SubstituteGameObjectsForPrefab();
    }
}

```

This would draw a button on the inspector, but you can also do the Editor's exclusive logic there.

Hope it helps.

# Answer
> 1 votes
Myself I'll usually just wrap the whole file in a preprocessor conditional directive block like this:

```
#if UNITY_EDITOR
using UnityEditor;

public class Foo : MonoBehaviour {
    // All contents here...
}

#endif

```

That way when I compile a build, the compiler sees the file as effectively empty and skips over it, even if it's not sitting in an Editor folder.

---
Tags: unity, unityscript
---


title: Basic Random Tile Map Generation

text:
# Question
Title: Basic Random Tile Map Generation
Currently I've got a map like this:

It's pretty simple but what I want is that area of tiles to be random, with the number of tiles present being random (Within a minimum and maximum amount of tiles of course) and the positions of the tiles being random (but still all connected to each other), but I'm not exactly sure how I should go about implementing that.

I'm sort of looking for a system that will generate random sections of tiles, a bunch of tiles within a group at random positions around the screen with all these sections being connected to each other via a larger section of tiles. Like the example shown in this perfect drawing I've quickly done:

Each square would be a group of tiles, they're all of different shapes and sizes but all connected together via another large (or small) group of tiles in the middle.

I have looked into grid map generation before making this post but all the information I found would tend to go over more advanced map generation methods that have multiple layers which is not really what I need for my game so I was wondering if someone would possibly be able to advice me on what the best method would be to do this?

I'd very much appreciate it.

# Answer
Generate a room.

Roll a die for how many adjacent rooms should be near it.

For each of those, Generate a Room

```
while(true)

    Pick an edge-tile of the original room

    Attempt to place this room there

    if successful

        break

```

I think that's all you're looking for. Let me know if you'd like something more detailed than an algorithm

NOTE: the above loop technically has a flaw that could cause an infinite loop. You would probably want a second break condition that says "if all adjacent squares have been checked, break"
> 2 votes

---
Tags: procedural-generation, tilemap
---


title: JME3 Fragment/Shader not compiling

text:
# Question
Title: JME3 Fragment/Shader not compiling
Here is the fragment shader code (MyShaders/Shader1.frag):

```
void main(){
   gl_FragColor = vec4(1.0,1.0,1.0,1.0);
}

```

And the vertex shader code (MyShaders/Shader1.vert):

```
void main(void)
{

    gl_Position=vec4(1.0,1.0,1.0,0.0);

}

```

And the .j3md material code:

```
MaterialDef Shader1 {
    MaterialParameters {
    }

    Technique {
        VertexShader GLSL100 GLSL150:   MyShaders/Shader1.frag
        FragmentShader GLSL100 GLSL150: MyShaders/Shader1.vert
    }
}

```

The error stack trace is:

```
WARNING: Bad compile of:
1   #version 110
2   #define FRAGMENT_SHADER 1
3   void main(void)
4   {
5
6       gl_Position=vec4(1.0,1.0,1.0,0.0);
7
8   }

May 01, 2018 3:35:57 PM com.jme3.app.LegacyApplication handleError
SEVERE: Uncaught exception thrown in Thread[jME3 Main,5,main]
com.jme3.renderer.RendererException: compile error in: ShaderSource[name=MyShaders/Shader1.vert, defines, type=Fragment, language=GLSL100]
ERROR: 0:6: Use of undeclared identifier 'gl_Position'

```

And here is the code for instantiating the material:

```
Material mat=new Material(assetManager,"MyShaders/Shader1.j3md");

```

I think that the bug is somewhere in me not passing any `gl_Position` parameters into the shader, but how do I do that?

I am using JME3 and Java.

# Answer
> 1 votes
You switched your vertex and fragment shader filenames inside `Technique{...}`

```
Technique {
  VertexShader GLSL100 GLSL150: MyShaders/Shader1.frag
  FragmentShader GLSL100 GLSL150: MyShaders/Shader1.vert
}

```

should become

```
Technique {
  VertexShader GLSL100 GLSL150: MyShaders/Shader1.vert
  FragmentShader GLSL100 GLSL150: MyShaders/Shader1.frag
}

```

---
Tags: opengl, java, lwjgl, jmonkeyengine
---


# Question
Title: For character animation, is it better to use sprite sheets or animating "pieces" with keyframes?
First I want to say that I am not an artist, and I intend to work with an artist to complete my project. I'm looking for the solution that makes it the easiest to work with the artist and create the best final product.

I also want to clarify what my two choices are, in case I've used imprecise language.

1) Sprite sheets. By this, I mean that each frame of animation is a complete picture, as shown on the *right-hand side* of this image.

2) Animating pieces with keyframes. By this I mean each piece of the character is a separate sprite as shown on the *left-hand side* of the same image. In this case, the developer must specify keyframes and the engine interpolates between them to create a smooth animation.

Here are some pros and cons of each as I see it.

**1 Pros**

* Each frame looks better, more connected and whole
* Less work for the developer, just drop it in as a new animation

**1 Cons**

* Potentially choppy animations (an artist isn't likely to draw 60 frames per second of animation)
* A lot of work for the artist if the character has to move in lots of different ways
* Difficult to communicate ideas about exactly how the character should move

**2 Pros**

* Smooth animation
* Very dynamic, the character can move in an infinite number of ways without requiring more assets to be produced
* Less work for the artist (this is good for the developer too because you can have faster iteration and create new assets easier)

**2 Cons**

* Potential for wonky looking characters (joints moving in weird ways or not looking fully connected)
* More work for the developer (must animate everything themselves)

If it helps, I have two main use-cases. The first game that I want to make is an infinite runner style game which should be pretty simple, the character only moves in one direction with limited actions. The second is a more complex story-based platformer. Here the characters will move in all four directions, jump, shoot, shoot while jumping, shoot forward while running backwards, etc.

However in either case, I can see these questions being relevant. Even when there is very little animation, is it better to go for flexibility and smoothness, or for good detail?

I think Mark of the Ninja showcases what I'm looking for very well, even knowing that I probably can't hit that level of production quality with one developer and one artist. For that game, it *looks* like each animation frame is completely drawn, but it's so smooth and dynamic that it's hard to tell.

So which method is better given the output that I'd like? Or would it be better to do a hybrid in some way?

# Answer
> 2 votes
I must say I strongly disagree on some of your pros and cons. The keyframe method in my opinion is a much better choice, both for the animator and the programmer. It is (usually) less work for both the programmer and the artist. Each frame does not necessarily look more connected with sprite sheet animation, on the contrary, it may look worse than key animation (see this example) unless you take extra care tailoring each and every frame (which is time consuming).

It is *not* more work for the developer when using key frame animation (I guess it also depends on the tools you are using), but you can have tooling where the developer only cares about playing the correct animation in the game, it being idle, walking, running or jumping. There is no need to animate anything for the programmer. However, some advanced animation can be done using inverse kinematics where you manipulate the skeleton of the character using the mouse pointer for aiming.

Having key frame animation is also less space consuming because you deal with less sprites.

There are games that look good using both methods, but in my opinion go for the key animation method. Mark of Ninja is probably used with key frame animation. Rayman Legends is also made with that method. I think this method will save time for both the artist and the developer, and the game will probably look better. This being my two cents.

# Answer
> 1 votes
My answer is here as a complement to John's answer. And I will directly point to an excellent article published in Gamasutra : 5 tips for making great animations for 2D games.

I think that your choice should be made depending on your artistic vision of your game (and budget and time). While John covered some good aspects of key frame animation, sprite sheets allow you to breath life into your creation like nothing else. It is the main problem with rotoscoping, your characters move according to physics, but the artistic result if far from what you can see from great animators. You can even see it in the example page provided by John : "Spine with frame based animation" (watch some old Disney movies, or some greatly animated 2D games that don't use rotoscoping).

At the end, using softwares like Spine will maybe save you time and money, but if you want to really do complex things, to create bigger-than-life animation, you will have to go the sprite-sheet way (even with Spine).

My advice for you in particular is :

1. Try to define the artistic style you want for your game, the feeling, the atmosphere (you already made some researches by quoting Mark of the Ninja as inspiration, but go a step further)
2. According to the answer of point 1, try to find an artist that have necessary skills to create your vision. Hire someone who can do the job according to the method you chose.

TL;DR, before trying to balance pros and cons, try to find an artistic perspective for your game. I don't think that art is a problem to resolve, but the embodiment of a vision you have for your game. If you miss money or time, change your goals and choose the appropriate tool (which can be sprite-sheet, key frame animation, or both).

---
Tags: unity, animation, art
---


# Question
Title: Securing feasibility in procedurally generated endless runner
I am currently in the concept phase for an endless runner I want to develop with libgdx in Java.

As I can not preassemble an infinite level, the generation of obstacles and power-ups needs to be "random" and during the game itself. In my last endless runner, I simply had randomness to determine the next obstacle type, as well as its position.

This time, however, I want to integrate two resources that play a major role and change the way I need to handle feasibility fundamentally.
One resource is some sort of an energy bar, which decreases over time, as well as due to collision with obstacles (possible to get over in the beginning, deadly as the game proceeds) and increases with the collection of power-ups.
The other resource is a coin-like entity, which you can collect during a run and which need to be present to a certain amount, in order to collect the energy-filling power-ups on collision.

I have a vague to solid idea of securing feasibility in terms of creating manageable obstacle-chains, but can't think of generation procedures, that ensure the possibility to collect enough power-ups while being provided the opportunity of collecting enough coins first. Furthermore, this procedure needs to increase the difficulty with the games duration.

I am not asking for code itself, but rather for adequate ways to approach my issue, such as dividing my endless runner in minilevels, that have some transition and are feasible on their own. Alternatively, experienced statements on which ways not to use and why are very welcome as well!

Feel free to ask further questions - Thanks in advance!

# Answer
Prebuild sections that you can smoothly transition between. Randomly select sections as the game is going on. The simplest one is a blank road with spawning points for obstacles and coins. When selected you randomly fill some obstacles and some coins, add some tests to make sure it's reasonable like not having coins/powerups inescapably in front of an obstacle and that there is a path through that picks up the powerup.

Every so often have a bit of free space where the player can take a breather and you can make a prelude to each difficult section that way telegraphing what the obstacle will be.

You can also vary the obstacle look even if the gameplay for them is the exact same, like something that swings in that must be jumped over or dodged. that is litterally like any other obstacle that must be jumped or dodged but it doesn't look the same.

Then you can add decorations to break up the monotony. A section of tunnel, a bush, the occasional animal jumping out of the way, creatures on the side taunting/cheering, ...
> 3 votes

---
Tags: libgdx, procedural-generation
---


# Question
Title: What is "storage" in MMOs with vehicles good for, where all equipped items get removed?
Many games, for example Star Trek Online (Dry Dock) and Battletech (Storage) have a concept of placing a vehicle in storage. It is not ready for use, you're not destroying unused vehicles, but rather you eject all equipped weapons etc. from it and then store the "husk" of the ship/mecha where it can be retrieved for later.

This seems to be a surprisingly common mechanic, so I'm wondering if I'm overlooking some use this mechanism has over just adding more slots for more ships. The only advantage(s) of this I can think of right now:

1. Take load off the database that has to associate vehicles and items equipped on them. A stored ship has nothing in it (guaranteed) so is just a simple item.
2. Encourage people to buy more vehicles (in games with a money store like STO) even if those are Bound To Character. Instead of deleting them when your ship slots run out, you store them.

Is the load on databases really big enough to warrant this? But why does a single player game like Battletech then have the mechanic? It should be irrelevant for the numbers involved in that.

Also, vehicles generally only grant bonuses when actually in use (i.e. in STO when the player is flying it, in Battletech when it is one of the 5 or so deployed mechs on a mission) So shouldn't the effect of having more ships on a user be totally unimportant?

# Answer
> 2 votes
You might want to consider this solution for your game if you noticed one of these problems:

* The players accumulate a large number of vehicles over the course of the game, which causes the vehicle selection menu to become cluttered with vehicles the player rarely or never uses, but doesn't want to get rid of permanently either.
* Managing the equipment of the frequently used vehicles becomes cumbersome. For example, the player might remember they had that really cool ultra-rare gun on one of their vehicles, but they forgot on which one.

By allowing (or rather forcing) the player to moth-ball rarely used vehicles, you keep the number of vehicles more manageable. There is a lower number of vehicles to pick from, so you can make sure they and all their relevant information always fit on one screen without scrolling. And when the player is looking for a specific piece of equipment, there is a limited number of vehicles where they could have placed it.

---
Tags: game-mechanics, mmo, databases, inventory, single-player
---


# Question
Title: How to write a transparent shader for a sprite that ignores transparent sprites behind it?
I have multiple UI Sprites that have their alpha set so you can see what's behind them. I would like to make these UI Sprites ignore other UI Sprites.

So take this first picture. There are 4 UI Sprites that overlay over a part of each other.

Note: These sprites can appear in a random location and the number is unknown, so I thought a Shader would make sense for this.

I would like to still adjust their alpha, but I would like them to ignore each other so that they appear to be 1 image like below.

I tried modifying a Shader, but I couldn't work it out.

```
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)

Shader "UI/Default"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)

        _StencilComp ("Stencil Comparison", Float) = 8
        _Stencil ("Stencil ID", Float) = 0
        _StencilOp ("Stencil Operation", Float) = 0
        _StencilWriteMask ("Stencil Write Mask", Float) = 255
        _StencilReadMask ("Stencil Read Mask", Float) = 255

        _ColorMask ("Color Mask", Float) = 15

        [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Stencil
        {
            Ref [_Stencil]
            Comp [_StencilComp]
            Pass [_StencilOp]
            ReadMask [_StencilReadMask]
            WriteMask [_StencilWriteMask]
        }

        Cull Off
        Lighting Off
        ZWrite Off
        ZTest [unity_GUIZTestMode]
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask [_ColorMask]

        Pass
        {
            Name "Default"
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 2.0

            #include "UnityCG.cginc"
            #include "UnityUI.cginc"

            #pragma multi_compile __ UNITY_UI_CLIP_RECT
            #pragma multi_compile __ UNITY_UI_ALPHACLIP

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

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                float2 texcoord  : TEXCOORD0;
                float4 worldPosition : TEXCOORD1;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            fixed4 _Color;
            fixed4 _TextureSampleAdd;
            float4 _ClipRect;

            v2f vert(appdata_t v)
            {
                v2f OUT;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
                OUT.worldPosition = v.vertex;
                OUT.vertex = UnityObjectToClipPos(OUT.worldPosition);

                OUT.texcoord = v.texcoord;

                OUT.color = v.color * _Color;
                return OUT;
            }

            sampler2D _MainTex;

            fixed4 frag(v2f IN) : SV_Target
            {
                half4 color = (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd) * IN.color;

                #ifdef UNITY_UI_CLIP_RECT
                color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);
                #endif

                #ifdef UNITY_UI_ALPHACLIP
                clip (color.a - 0.001);
                #endif

                return color;
            }
        ENDCG
        }
    }
}

```

# Answer
Just change your Stencil like below Image:

Stencil Op/Comparison Values

**Comparison Functions**

```
0 - Always
1 - Never
2 - Less
3 - Equal
4 - LEqual
5 - Greater
6 - NotEqual
7 - GEqual
8 - Always // (This is the default for the UI shaders so I suspect this one is technically the 'correct' Always, but any value beyond it will also count as Always)

```

**Stencil Operations**

```
0 - Keep
1 - Zero
2 - Replace
3 - IncrSat
4 - DecrSat
5 - Invert
6 - IncrWrap
7 - DecrWrap

```

References: unity forum & khronos

---

# Adding Enum to Inspector

It's hard to remember above stencil number so you can use enum

change your properties like this:

```
[Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp ("Stencil Comparison", Int) = 3
[Enum(UnityEngine.Rendering.StencilOp)] _StencilOp ("Stencil Operation", Int) = 3

```

useful link : configurableStencil shader

---

# Final Result
> 8 votes

---
Tags: unity, shaders, sprites, transparency
---


# Question
Title: Is there a way to read unity console outside of unity?
my unity project keeps crashing and it does not let me read the exception error, I am wondering if there is a way to read the unity console externally outside of unity. Any pointers will be highly appreciated. Thanks

# Answer
Don't forget to do a quick search - here's the top result for "Unity Editor Log"

> ## Log Files
>
> There might be times during development when you need to obtain information from the logs of the standalone player you’ve built, the target device, or the Editor. Usually you need to see these files when you have experienced a problem, to find out exactly where the problem occurred.
>
> On macOS, the player and Editor logs can be accessed uniformly through the standard Console.app utility.
>
> On Windows, the Editor logs are placed in folders which are not shown in the Windows Explorer by default. See below.
>
> **Editor**
>
> To view the Editor log, select Open Editor Log in Unity’s Console window.

```
OS         Log files
macOS      ~/Library/Logs/Unity/Editor.log
Windows    C:\Users\username\AppData\Local\Unity\Editor\Editor.log

```

> On macOS, all the logs can be accessed uniformly through the standard Console.app utility.
>
> On Windows, the Editor log file is stored in the local application data folder \Unity\Editor\Editor.log, where is defined by CSIDL\_LOCAL\_APPDATA.
>
> **Player**

```
OS      Log files
macOS   ~/Library/Logs/Unity/Player.log
Windows C:\Users\username\AppData\LocalLow\CompanyName\ProductName\output_log.txt
Linux   ~/.config/unity3d/CompanyName/ProductName/Player.log

```
> 3 votes

---
Tags: unity, console, error-management
---


# Question
Title: Transfering an inertia tensor from local coordinates to another one
If we have an inertia tensor in local coordinates with a basis matrix *B* and we want to transform it to other local coordinates with basis matrix *A*, is it right to do the following:

A\* inv(B) \*Inertia Tensor

Where my idea is to shift the inertia tensor to world coordinates by multiplying it by the inverse of *B*, then from the world coordinates to the *A* coordinates by multiplying it with *A* matrix?

# Answer
> 1 votes
I'm sure sure of the practical value of this, but yes.

If you take a 3x3 inertia tensor matrix IB, and multiply it by the inverse of local basis matrix B, the result will be the tensor in the world coordinate system, I

You can then transform it again by the local transform for B which will give you IA:

```
//Indirect transform
I = inv(B) * IB
IA = A * I
//direct transform
=== IA = A * inv(B) * IB
//Alternatively, store the transform if you need to
=== BA = A * inv(B)
    IA = BA * IB

```

As I said though, I don't know what the practical value of this is though, as the inertia tensor is supposed to be unique to each collider, though without seeing your implementation I can't say for certain.

---
Tags: physics, transformation, physics-engine
---


# Question
Title: How can I use more than one mouse connected to the same computer as different input devices in Unity?
How can I use more than one mouse connected to the same computer as different input devices in Unity? I want to read the input axis of each mouse individually for local multiplayer games.

# Answer
At the moment Unity Window does not allow that. There is a new input device system in Unity that is work in progress\[LINK\]. An experimental prototype beta is available but I recommend to wait for the final one \[2018.3 or 2019\]. As pay alternative option there is in the asset store a better alternative LINK. All these new tools allowed you to catch any kind of input.
> 1 votes

---
Tags: unity, mouse
---


title: Pong AI - Raycasting

text:
# Question
Title: Pong AI - Raycasting
I've been focusing on other games recently but it annoyed me that I skipped the AI part of making my pong game a 1 player game too. I have found out how to RayCast but am struggling with being able to make a path to predict where the ball will end up on the computer side. I have managed to get the first ray to work but in the second if-statement from the code below, it's somehow a loop. If anyone is able to help me, I would be extremely grateful!

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

public class RaycastTest : MonoBehaviour {

private Rigidbody2D rb2d;
private RaycastHit2D hit;
private Vector2 predictedCollision;
private Vector2 collisionPoint;
private int numberOfCollisions;

void Start () {
    rb2d = GetComponent<Rigidbody2D> ();
    numberOfCollisions = 0;
}

void FixedUpdate () {
    //Directions of the ball (normalized)
    Vector3 forward3 = new Vector3 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y, 0) * 20;
    Vector2 forward2 = new Vector2 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y);

    // If the ball has just hit the player paddle
    if (BallMovement.isOnPath == true) {
        if (numberOfCollisions == 0) {
            //make sure we have the correct initial collision point from another script
            collisionPoint = BallMovement.collisionPoint;

            //draw and cast a ray to detect the next point of collision
            Debug.DrawRay (collisionPoint, forward3, Color.red, 20f);
            hit = Physics2D.Raycast (collisionPoint, forward2, Mathf.Infinity);
            //print the name of the object that has been hit
            print (hit.collider.name);

            //change the initial collision point to the new one
            collisionPoint = new Vector2 (hit.point.x, hit.point.y);
            print (collisionPoint);

            //add on to the number of collisions
            numberOfCollisions += 1;
            print (numberOfCollisions);
        }

        //if we still haven't reached the HitArea we need to do another bounce
        if (hit.collider.name != "HitArea") {

            //make sure we get the velocity after impact and reverse the direction of the y velocity.
            forward2 = new Vector2(rb2d.velocity.normalized.x, rb2d.velocity.normalized.y * -1f);
            forward3 = new Vector3 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y * -1f, 0) * 20;

            //draw and cast a ray to detect the next point of collision
            hit = Physics2D.Raycast(collisionPoint, forward2, Mathf.Infinity);
            Debug.DrawRay(collisionPoint, forward3, Color.red, 20f);

            //change the initial collision point to the new one
            collisionPoint = hit.point;
            print (collisionPoint);

            //add on to the number of collisions
            numberOfCollisions += 1;
        }

        //If we've hit the HitArea, we reset everything so it stops looping and we've got our predicted point of collision on the computer side.
        if (hit.collider.name == "HitArea") {
            predictedCollision = hit.point;
            numberOfCollisions = 0;
            BallMovement.isOnPath = false;
        }
    }
}

```

}

# Answer
> 1 votes
The loop isn't in this code *(it's in the caller to this code)*; but I think I know what's causing it:

```
    //if we still haven't reached the HitArea we need to do another bounce
    if (hit.collider.name != "HitArea") {

```

This assumes that you WILL find a HitArea. This means the calling code will then call this function again and raycast again.

Were I to guess at why, you are probably allowing yourself no buffer between HitArea and your hit detection, so a bounce happens in an area that a bounce is not supposed to occur. This is likely an issue with your hit detection code, but could be fixed by shrinking your "hit area" to have a buffer around the edge so that when the *edge* of your pong-ball hits the edge of the screen it counts, rather than the middle.

Without more code it is not possible to definitively point to the root cause of the bug; but the loop your seeing IS because you're not colliding with "HitArea" for some reason.

# Answer
> 1 votes
If your ball is travelling straight towards its path, then you could do a delta of positions, or if it has a **Rigidbody** you could use it's velocity vector.

In both cases, you will get a vector that points to the current direction your ball is facing relative to the world space. You could then make a raycast from that velocity vector, so the hit point will be it's final destination with that velocity vector.

Example:

```
using UnityEngine;

public class ExampleBall : MonoBehaviour
{
    public Vector3 predictionPoint;
    private Vector3 latePosition;
    private Rigidbody rigidbody;

    void Awake()
    {
        rigidbody = GetComponent<Rigidbody>();
        latePosition = transform.position;
    }

    void Update()
    {
        /// With Velocity
        RaycastHit hit;
        if(Physics.Raycast(transform.position, rigidbody.velocity, out hit, Mathf.Infinity))
        {
            predictionPoint = hit.point;
        }

        /// With delta positions
        Vector3 delta = transform.position - latePosition;

        if(Physics.Raycast(transform.position, delta, out hit, Mathf.Infinity))
        {
            predictionPoint = hit.point;
        }

        latePosition = transformPosition;
    }
}

```

The script's **predictionPoint** is public, so you can access it, maybe it's expensive to make raycasts each frame, but it was for the sake of example.

You can also use **extrapolations**, considering your velocity vector, (**LerpUnclamped** does the trick). Example:

```
using UnityEngine;

public class ExampleBall : MonoBehaviour
{
    public Vector3 predictionPoint;
    public float pedictionTime;
    private Vector3 latePosition;
    private Rigidbody rigidbody;

    void Awake()
    {
        rigidbody = GetComponent<Rigidbody>();
        Vector3 delta = transform.position - latePosition;
    }

    void Update()
    {
        /// With Velocity
        predictionPoint = Vector3.LerpUnclamped(transform.position, transform.position + rigidbody.velocity, predictionTime);

        /// With delta positions
        Vector3 delta = transform.position - latePosition;
        predictionPoint = Vector3.LerpUnclamped(transform.position, transform.position + delta, predictionTime);

        latePosition = transformPosition;
    }
}

```

Hope it helps.

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


title: Detect mouse over a line in Phaser

text:
# Question
Title: Detect mouse over a line in Phaser
We're developing a game in Phaser as a university project and have come across an obstacle. We need to detect when the mouse is over a line between two points. There are not a lot of lines, definitely fewer then 500. We were thinking of just checking it with line equations on every update call, but that might slow the game down. We haven't found anything useful on google. Should we just stick with the equations or is there a more elegant way?

Cheers

# Answer
You can approach this problem backwards.

* First, find which lines best "bound" your current mouse position. This would (after the first frame) only check the lines closest to the mouse. This is as simple as walking each line and taking the four (or so) that have the closest distance to the mouse cursor.
* Second, check only these lines when you perform an update until the mouse breaks one of these boundaries
* Third, only perform the check if the mouse is moving

While you will still be checking the mouse every update (that it is moving) against every "boundary" line, it will reduce the number of lines you're checking against to about 4.

Note: Without knowing properties of the lines (are they random, are they in a grid pattern, etc) this is as helpful as I can get.

---

A dirtier option would be to draw your lines with a piece of encoded data, such as a special alpha value that the eye doesn't perceive very well, or a special color. Draw your lines first, then (when you draw your cursor) first check if it would be drawn over a pixel with this encoded value. If it would, then you're hitting a line.
> 1 votes

---
Tags: phaser, lines
---