# Question
Title: Why does rendering to a texture cause transparency here?
As a quick background, this is in the context of a custom game engine I'm writing in C# on top of the SharpDX framework. In the engine, when I render UI, I do so by creating a canvas object with its owner render target texture. I render to that texture, wrap this texture on the canvas quad, then render the canvas to the world. As a note, I am using forward rendering, not deferred.

But, the problem is, the canvas renders the texture, but the actual rendering of my UI test panel, to the texture, generates a transparent patch rather than the desired panel. Here's a screen-shot of what I'm describing:

The back buffer was cleared to solid red for now just for testing, and I've attempted to render a panel to the center of it with a test image. As you can see, the red back buffer was rendered to the canvas nicely, but the test image I rendered to the panel is rendering transparently. I use the same shaders/hlsl files to render both the canvas and the panel on the canvas, so I'm skeptical that this is the source of the problem.

Here's a code snippet, for where I render my canvas array, that might help:

```
//start preparing matrix buffer
viewMatrix = activeCamera.GetViewMatrix();
MatrixBuffer matrices = new MatrixBuffer();
matrices.viewMatrix = Matrix.Transpose(viewMatrix);
matrices.projMatrix = Matrix.Transpose(DXEnv.orthoProjectionMatrix);

//change context if needed, and draw using the shader
if (activeShader != ShaderID.TEXTURE_UNLIT)
{
            textureUnlitShader.SetActive(DXEnv.device, DXEnv.context);
            activeShader = ShaderID.TEXTURE_UNLIT;
}

for (int i=0 ; i< canvases.Length; i++)
{
    //clear render depth/render target & set the render-to-texture target
    DXEnv.context.ClearDepthStencilView(DXEnv.depthView, D3D11.DepthStencilClearFlags.Depth, 1, 0);
    DXEnv.context.ClearRenderTargetView(canvases[i].renderTarget, new Color4(1.0f, 0.0f, 0.0f, 1.0f));
    DXEnv.SetNewRenderTarget(canvases[i].renderTarget);

    //recursively render to the new texture
    textureUnlitShader.SetTextureResource(DXEnv.device, DXEnv.context, canvases[i].source);
    RenderPanelRecursive(canvases[i].root, matrices);

    canvases[i].CalculateModelMatrix(transforms[i]);
    matrices.modelMatrix = Matrix.Transpose(canvases[i].modelMatrix);

    //set texture to the new resource and reset render view, then render canvas
    DXEnv.SetNewRenderTarget(DXEnv.renderView); //TODO: batchh up canvas rendering to minimize context switch
    textureUnlitShader.SetTextureResource(DXEnv.device, DXEnv.context, canvases[i].shaderTexture); //this is the line i tried commenting out
    textureUnlitShader.UpdateShader(DXEnv.device, DXEnv.context, matrices, canvases[i]);
}

```

The call to `textureUnlitShader.UpdateShader(...)` are most likely not the issue I've found. I tried commenting the line `textureUnlitShader.SetTextureResource(..., canvases[i].shaderTexture)` that was set in the above code, and, as expected, instead of the render-to-texture buffer being rendered to the canvas, my test image was rendered to the canvas. But interestingly enough, the hole remained. Which leads me to believe that the panel is not actually being rendered to the canvas's texture properly. Rather, it seems to be being rendered somehow separately. Which leads me to believe that the most likely culprit is the way I'm implementing the render to texture technique that is somehow off. Here's a screenshot of when that happens:

My call to render panel recursive looks a bit like the render call for the canvas, but it is as follows:

```
    private void RenderPanelRecursive(Panel p, MatrixBuffer matrices)
    {
        //render lowest level to highest level to preserve order
        if ( (p.active == true) && (p.renderable == true))
        {
            ImagePanel castP = p as ImagePanel;

            castP.CalculateModelMatrix();
            matrices.modelMatrix = Matrix.Transpose(castP.modelMatrix);
            textureUnlitShader.UpdateShader(DXEnv.device, DXEnv.context, matrices, castP); //perhaps build this into the shader instead?
        }

        //recurse down further if more children exist
        if (p.currentNumberControls != 0)
        {
            for (int i = 0; i < p.currentNumberControls; i++)
            {
                RenderPanelRecursive(p.children[i], matrices);
            }
        }

    }

```

I don't believe much could have gone wrong with panel itself. The matrix constant buffer seems to be being written to properly, as the panel renders in the right spot on the canvas. And the vertex-position/uv-coord constant buffer is identical to the structure of the canvas's vertex-position/uv-coord constant buffer. To make sure of this, I've read over the section a couple of times now and ran through it with some break points set to make sure that these buffers we're being written correctly. Nothing turned up out of the ordinary.

Which brings me back to my statement earlier, that there is probably something to the way in which I set up my render-to-texture that is going wrong.

Thanks in advance for any help you can provide.

# Answer
> 2 votes
A couple of things i try to do first to debug it. For your ui just set the pixel shader to write out white with alpha set to 1.0f. If that is rendering and is no longer transparent then you can localize it. But if not i would also look at your blend state. I assume your ui isnt using a zbuffer? If it is then is it cleared every frame? You are rendering something so it's not around geometry.

I use a similar method to what you have done in the ui. I find just methododicly going through those items you usually find the issue. If not post again and i will try and think of other possibilities

# Answer
> 1 votes
In the event that somebody with a similar problem stumbles onto this thread, I'll share what eventually fixed my issue. I took ErnieDingo's advice and took a closer look at the z-buffer. Looking for things wrong with my z-buffer, I ran into this thread, which reminded me of a crucial detail I had forgotten.

In the code above, I'm using the same z-buffer for each canvas, which can be seen in the call to `ClearDepthStencilView(DXEnv.depthBuffer, ...)`. Except, z-buffers can't be shared between render targets of different sizes, because the buffers are created with a specific size in mind. This was the monkey wrench in the machine, so I gave each canvas its own z-buffer and attached a unique depth stencil view to each z-buffer.

The new code for that `for` loop looks like this (I also went ahead and batched up my render-to-texture calls and my canvas renders, to avoid excessive switching between targets):

```
    for (int i = 0; i < canvases.Length; i++)
    {

        if (canvases[i] != null && canvases[i].active)
        {

            //set the new render target to be the canvas, and set texture to be the spritesheet
            DXEnv.context.ClearRenderTargetView(canvases[i].renderTarget, new Color4(1.0f, 0.0f, 0.0f, 1.0f));
            DXEnv.context.ClearDepthStencilView(canvases[i].depthView, D3D11.DepthStencilClearFlags.Depth, 1, 0);
            DXEnv.SetNewRenderTarget(canvases[i].renderTarget, canvases[i].depthView);

            //recursively render to the new texture
            textureUnlitShader.SetTextureResource(DXEnv.device, DXEnv.context, canvases[i].source);
            RenderPanelRecursive(canvases[i].root, matrices);
        }
    }

    DXEnv.SetNewRenderTarget(DXEnv.renderView, DXEnv.depthView);

    for (int i = 0; i < canvases.Length; i++)
    {
        if (canvases[i] != null && canvases[i].active)
        {
            canvases[i].CalculateModelMatrix(transforms[i]); //TODO: return types make this more intuitive
            matrices.modelMatrix = Matrix.Transpose(canvases[i].modelMatrix);

            //set texture to the new resource and reset render view, then render canvas
            textureUnlitShader.SetTextureResource(DXEnv.device, DXEnv.context, canvases[i].shaderTexture);
            textureUnlitShader.UpdateShader(DXEnv.device, DXEnv.context, matrices, canvases[i]);
        }
    }

```

**NOTE**: the above code doesn't showcase the fact that my differently-sized render targets also require different projection matrices to be rendered properly. If you have different sized render targets, each render target will also require its own localized projection matrix, just for the record.

Thanks for the help.

---
Tags: c#, rendering, sharpdx, rendertexture
---


# Question
Title: What happens when Time.time gets very large in Unity?
As it is said here :

**Time.time**

*The time at the beginning of this frame (Read Only). This is the time in seconds since the start of the game.*

And as I know the time is stored in float. So, my question is what will happen when the value of time becomes very large? Can it overflow? Will it lose precision and cause bugs? Will the game just crash or what?

# Answer
> 72 votes
There is a real risk to loss of time accuracy from using a single-precision float.

It will still retain accuracy to the nearest second for 97 days. But in games we often care about accuracy on the order of a frame duration.

**A single-precision float time value in seconds starts to lose millisecond accuracy after about *9 hours*.**

That's already not outside the realm of possibility for a single play session, or leaving the game running "AFK" while you're at work/school or sleeping. (This is one reason why a common way to test a game is to run it overnight and check that it still plays correctly in the morning)

On modern consoles, where games are often suspended and resumed between play sessions rather than shut down entirely, it's not unexpected for a "single session" from the game's eye view to exceed 9 hours of runtime even when played in short bursts.

Assuming Unity's `deltaTime` is computed from a higher-precision time source, which is borne out by Peter's experiments in another answer, relying on `deltaTime` for frame-scale timings is relatively safe (just be cautious of accumulating very long durations by summing `deltaTime` values - adding small increments to a larger float is a classic recipe for precision loss, even when you compensate with savvy algorithms).

Since `fixedDeltaTime` keeps the same value you set, rather than dynamically changing from frame to frame, you can also put timing-sensitive behaviour in FixedUpdate to get stronger guarantees of consistency. `deltaTime` will automatically return the appropriate fixed delta in these methods. While there can be a beat frequency between fixed & frame updates, you can smooth this out through interpolation.

**What you want to avoid is computing durations by subtracting one timestamp from another**. After hours of play this can cause catastrophic cancellation, leading to far less precision than you get early in the run. If comparing timestamps is important to your systems, you can generate your own higher-resolution time value using other methods, like `System.Diagnostics.Stopwatch` instead of `Time.time`.

If sticking to floating-point numbers from the `Time` class is unavoidable for your application, then there is one more fallback, as pointed out by Kevin in the comments. Unity has added properties to access time as a `double`, including versions for `fixedTime`, `fixedUnscaledTime`, `realtimeSinceStartup`, `timeSinceLevelLoad`, and `unscaledTime`. The larger mantissa in a `double` is enough that your game could run for centuries before the precision loss would be significant.

(Though my recommendation would be to architect your code in such a way that precision loss is not an issue in the first place, rather than just throwing more bits at it)

# Answer
> 18 votes
The maximum value of float is 3.40282347 * 10^38, which equals 10^31 years when measured in seconds (or 10^28 years when measured in milliseconds). Trust me, it won't overflow.

The only thing that may appear is inaccuracy. But a single precision floating point number has an accuracy of 7-8 decimal digits. If using it to measure seconds, it is accurate for about 194 days. If measuring milliseconds it's accurate for only 4,5 hours. So it completely depends on the accuracy you need and you may need to find alternative ways if you need to be accurate to the millisecond (which you probably don't).

# Answer
> 14 votes
How much precision does your game need?

A 32-bit float has 24 bits of precision. In other words, at time t, the precision is ±2-23 × t. (This isn't exactly correct, but it's close, and the exact details aren't terribly interesting.)

* If you need 1ms precision, then after 1ms ÷ 2-23 = 8400 s = 2h 20m, a 32-bit float is no longer acceptable. A precision of 1ms is not necessary for most games, but it is considered necessary for musical applications.
* If your game runs on a 144 Hz monitor, and you want frame-accurate graphics, then after 1 ÷ 144 Hz ÷ 2-23 = 58000 s = 16h, a 32-bit float is no longer acceptable. 16h is a long time to run a game, but it's not inconceivable. I bet a significant percentage of us have run a game for 16 hours in a single stretch--even if just because we left the game running and got some sleep. At that point, animations and physics updates would be reduced to below 144Hz.

If Unity's `Time.deltaTime` is calculated from a higher-precision clock, then you could use that and still get full precision. I don't know if this is true or not.

## Side Note

Games and other programs on Windows often use `GetTickCount()` to figure out the time. Since it uses a 32-bit integer to count milliseconds, it wraps around about every 50 days, if you leave your computer on that long. I suspect that many games would hang, crash, or misbehave in bizarre ways if you were playing them at the 50-day mark.

Integers, like Windows' `GetTickCount()`, have a risk of overflow, whereas floats, like Unity's `Time.time`, have a risk of losing precision.

# Answer
> 13 votes
The other answers only speculate, so I wrote a simple Unity project and let it run for a while. After a couple hours this is the result:

* `UnityEngine.Time.time` looses accuracy rather quickly. As expected, after running the game for 4 hours the values jump by 1 millisecond, and the inaccuracy does increase after that.
* `UnityEngine.Time.deltaTime` keeps its initial sub-millisecond accuracy even after Unity has been running for hours. Thus it's virtually guaranteed that `deltaTime` is derived from a platform-dependent high resolution counter (which usually overflow after 10-1000 years). There remains a tiny risk that `deltaTime` will still lose precision on some platforms.

The inaccuracy of Time is an issue for everything that depends on `UnityEngine.Time.time`. One specific example is rotation (e.g. of a windmill), which is usually based on `UnityEngine.Mathf.Sin(UnityEngine.Time.time*rotationSpeed)`. Even more of an issue is `_Time` which is explicitly used for animations by shaders. How high does the inaccuracy need to be before it starts to be noticable? 20-30 ms accuracy (2 days) should be the point where people who are aware of the issue, and pay close attention, will notice. At 50-100 ms (5-10 days) sensitive people who don't know about the problem will start figuring it out. From 200-300 ms (20-30 days) the problem will be obvious.

So far I haven't tested the accuracy of `_SinTime`,`_CosTime`, and `Unity_DeltaTime`, so I can't comment on these.

This is the Script I've used for testing. It's attached to a `UI.Text` element, the Player Settings of the project allow the project to run while in the background, and VSync in Quality Settings is set to Every Second V Blank:

```
public class Time : UnityEngine.MonoBehaviour {
    void Start () {
        LastTime = (double)UnityEngine.Time.time;
        StartTime =  System.DateTime.Now;
        LastPrintTime =  System.DateTime.Now;
    }
    double LastTime;
    System.DateTime StartTime;
    System.DateTime LastPrintTime;
    void Update () {
        double deltaTimeError = (double)UnityEngine.Time.deltaTime - ((double)UnityEngine.Time.time - LastTime);
        if (System.DateTime.Now - LastPrintTime  > System.TimeSpan.FromMilliseconds(1000))
        {
            GetComponent<UnityEngine.UI.Text>().text = "StartTime: " + StartTime.ToLongTimeString()
                + "\nCurrentTime: " + System.DateTime.Now.ToLongTimeString()
                + "\n\nTime.deltaTime: " + UnityEngine.Time.deltaTime.ToString("0.000000")
                + "\nTime.time - LastTime: " + ((float)(UnityEngine.Time.time - LastTime)).ToString("0.000000")
                + "\nAbsolute Error: " +  System.Math.Abs(deltaTimeError).ToString("0.000E0");
            LastPrintTime = System.DateTime.Now;
        }
        LastTime = UnityEngine.Time.time;
    }
}

```

If you're wondering about the `0.033203` value, I'm pretty sure that's actually `0.033203125`, which has a binary floating point representation of `00111101000010000000000000000000`. Notice the many `0`s in the mantissa.

**Workarounds**

Most genres do not need a workaround. Most players won't even play a game for 100 hours total, so investing money to fix a problem people will only notice after a hypothetical few days of continuous playtime is economically not viable. Unfortunately I cannot come up with a simple universal workaround that fixes the entirety of the problem without carrying along some significant drawbacks.

---
Tags: unity
---


title: Rotating a Quad around it center

text:
# Question
Title: Rotating a Quad around it center
How can you rotate a quad around its center?

This is what I am trying to do but it is not working:

```
    GL11.glTranslatef(x-getWidth()/2, y-getHeight()/2, 0);
    GL11.glRotatef(30, 0.0f, 0.0f, 1.0f);
    GL11.glTranslatef(x+getWidth()/2, y+getHeight()/2, 0);
        DRAW

```

my main problem is that it renders it off the screen..

draw code:

```
    GL11.glBegin(GL11.GL_QUADS);
    {
        GL11.glTexCoord2f(0, 0);
        GL11.glVertex2f(0, 0);
        GL11.glTexCoord2f(0, getTexture().getHeight());
        GL11.glVertex2f(0, height);
        GL11.glTexCoord2f(getTexture().getWidth(), getTexture().getHeight());
        GL11.glVertex2f(width,height);
        GL11.glTexCoord2f(getTexture().getWidth(), 0);
        GL11.glVertex2f(width,0);
    }
    GL11.glEnd();

```

# Answer
> 2 votes
The quad's center is the position (0, 0, 0) in local space. Local space is the space in which you define your vertex positions.

For instance, if you draw your quad using the opengl glvertex\* commands, you should specify each vertex relative to (0, 0, 0):

```
glBegin(GL_QUADS);                  // Draw A Quad
glVertex3f(-1.0f, 1.0f, 0.0f);      // Top Left
glVertex3f( 1.0f, 1.0f, 0.0f);      // Top Right
glVertex3f( 1.0f,-1.0f, 0.0f);      // Bottom Right
glVertex3f(-1.0f,-1.0f, 0.0f);      // Bottom Left
glEnd();                            // Done Drawing The Quad

```

The code was taken from the NeHe website: Your First Polygon

If you draw your quad like this, each rotate command will rotate the quad around it's center. That's because the rotation matrix will be multiplied with each vertex position, which will result in the vertex being rotated around (0, 0, 0).

You should have a look at the NeHe article, it's a good starting point. Also have a look at the other articles there: http://nehe.gamedev.net/tutorial/lessons\_01\__05/22004/ ( there's one dealing with rotations in particular ).

**EDIT:**

You're drawing the quad relative to the lower left corner, so in order to match the center of the quad with the object space origin, you should first translate it by ( -width()/2, -height()/2, 0 ). Keeping in mind that matrices are multiplied in the reverse order, I would try something like:

```
GL11.glTranslatef(x+getWidth()/2, y+getHeight()/2, 0); // M1 - 2nd translation
GL11.glRotatef(30, 0.0f, 0.0f, 1.0f);                  // M2
GL11.glTranslatef( -getWidth()/2, -getHeight()/2, 0);  // M3 - 1st translation

```

Matrices are multiplied in order, and then multiplied on the left side with the vertex. So the resulting formula would be M1 * M2 * M3 * V. Notice that V is first multiplied by M3, so that's the matrix we use to translate the quad into the origin.

# Answer
> 1 votes
I'm not sure what x & y do in your code, you just need;

```
GL11.glTranslatef(-getWidth()/2, -getHeight()/2, 0);
GL11.glRotatef(30, 0.0f, 0.0f, 1.0f);
GL11.glTranslatef(+getWidth()/2, +getHeight()/2, 0);
    DRAW

```

Looking at your drawing code, the centre of the quad seems to be `[getWidth()/2, getHeight()/2]`, so you need to translate the centre to the origin, rotate, and translate back again

# Answer
> 0 votes
If you don't want to use glRotatef(), you can use this method with x,y the coordinates of quad(top-left) and sx : the weight and sy : the height.

```
rotation+=45;
double rot = Math.toRadians(rotation);
double rot2 = Math.toRadians(rotation+90);
double rot3 = Math.toRadians(rotation+180);
double rot4 = Math.toRadians(rotation+270);

float cx = x+sx/2;
float cy = y+sy/2;

float x1 = cx-(float)Math.cos(rot)*sx;
float y1 = cy-(float)Math.sin(rot)*sy;

float x2 = cx-(float)Math.cos(rot2)*sx;
float y2 = cy-(float)Math.sin(rot2)*sy;

float x3 = cx-(float)Math.cos(rot3)*sx;
float y3 = cy-(float)Math.sin(rot3)*sy;

float x4 = cx-(float)Math.cos(rot4)*sx;
float y4 = cy-(float)Math.sin(rot4)*sy;

GL11.glBegin(GL11.GL_QUADS);
    GL11.glTexCoord2f(0f, 0f);  GL11.glVertex2f(x1, y1);
    GL11.glTexCoord2f(1f, 0f);  GL11.glVertex2f(x2, y2);
    GL11.glTexCoord2f(1f, 1f);  GL11.glVertex2f(x3, y3);
    GL11.glTexCoord2f(0f, 1f);  GL11.glVertex2f(x4, y4);
GL11.glEnd();

```

---
Tags: opengl, rotation, lwjgl
---


# Question
Title: Why is my game object generated by a custom Unity editor script missing its sprite?
I have a number of sprites that I generate outside of Unity. I'd like to automate the process of importing these sprites into Unity as fully-configured game objects. I'm trying to do this through a Unity editor script, but I'm having some difficulty. When I run my script, my game object is saved as a `.prefab` as expected. However, the `Sprite` I'm assigning to my game object's `SpriteRenderer` component is missing:

In my script, I'm assigning my `SpriteRenderer`'s `sprite` property to a `Sprite` object that I dynamically create in the script. Here's the relevant excerpt from my editor script:

```
GameObject gameObject = new GameObject(fileName);

SpriteRenderer spriteRenderer = gameObject.AddComponent<SpriteRenderer>();

// texture size will be replaced during the LoadImage() call
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(File.ReadAllBytes(Path.Combine(generatedOutputPath, fileName + ".png")));

spriteRenderer.sprite = Sprite.Create(
    texture,
    new Rect(0.0f, 0.0f, texture.width, texture.height),
    new Vector2(0.0f, 0.0f)
);

PrefabUtility.CreatePrefab("Assets/Prefabs/" + fileName + ".prefab", gameObject);
DestroyImmediate(gameObject);

```

I can verify through logging that the image path to my `.png` is correct and that the `Texture2D` and `Sprite` objects seem to be instantiated correctly. For example, I can do this:

```
// logs "580" as expected
Debug.Log(texture.width);

```

What am I doing wrong? How can I save this game object as a `.prefab` without losing its sprite information?

# Answer
> 1 votes
Figured it out. I needed to first copy my images into the `Assets/Resources` directory, and then use `Resources.Load<Sprite>("path/to/sprite/here")` to load my `Sprite` instance (instead of loading them from an arbitrary location on the file system). Here's my updated script:

```
// "files" is a List<string> of file names to load as Sprites.
// first, copy each image to the "Assets/Resources/Sprites" directory
files.ForEach(fileName => {
    File.Copy(
        Path.Combine(generatedOutputPath, fileName + ".png"),
        Path.Combine("Assets/Resources/Sprites", fileName + ".png"),
        true
    );
});

// refresh our AssetsDatabase since we made changes.
AssetDatabase.Refresh();

// for each file, create a new GameObject to hold the loaded Sprite
files.ForEach(fileName => {
    GameObject gameObject = new GameObject(fileName);
    SpriteRenderer spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
    spriteRenderer.sprite = Resources.Load<Sprite>("Sprites/" + fileName);
    PrefabUtility.CreatePrefab("Assets/Prefabs/" + fileName + ".prefab", gameObject);
    DestroyImmediate(gameObject);
});

```

A big thanks to Draco18s and Byte56 for their comments, which pointed me in the right direction. The example script in this write-up also helped me get my script straightened out.

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


title: LWJGL3 key released and pressed

text:
# Question
Title: LWJGL3 key released and pressed
How to make a method in **LWJGL** 3 that when you press a key it tells you when its pressed and when its released only one time.

# Answer
> 0 votes
Handling input in LWJGL3 is easily done by using GLFW. In LWJGL2 they used their own bindings for keys. I still don't know why they switched. In LWJGL3 we need to call glfwPollEvents() to get the events that have already been received.

Another thing you might want to use is `glfwSetInputMode(window, mode, value)`. The mode must be one of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or `GLFW_STICKY_MOUSE_BUTTONS`. For `GLFW_STICKY_KEYS` and `GLFW_STICKY_MOUSE_BUTTONS` the value can be one of `GLFW_TRUE` and `GLFW_FALSE`. With `GLFW_CURSOR` the value can be one of `GLFW_CURSOR_NORMAL`, `GLFW_CURSOR_HIDDEN` or `GLFW_CURSOR_DISABLED`.

Now you are asking: ***How to make a method in LWJGL 3 that when you press a key it tells you when its pressed and when its released only one time.***

So from this I assume you want to log the keys, and if *any* key is pressed/released you print that log. LWJGL provides a `GLFWKeyCallback` class for this. But you need a strong reference to the callback, so that it won't get garbage collected, so just put a reference like private `GLFWKeyCallback keyCallback` in your class.

```
glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {

    @Override
    public void invoke(long window, int key, int scancode, int action, int mods) {
        /* Do something */
    }
}

```

This now polls for input from the keyboard. If you wanted to print what key it was you could say

```
System.out.prinltn("KEY: " + key + " was pressed");

```

Inside the invoke method.

Lets say you wanted to do only specific keys:

first, create a field for the key like this

```
int ctrlAlt = GLFW_MOD_ALT | GLFW_MOD_CONTROL;

```

Then if you want to check if it was pressed and only log that, you could say:

```
if ((mods & ctrlAlt) == ctrlAlt && key == GLFW_KEY_F && action == GLFW_PRESS) {
    System.out.println("Control + Alt + F was pressed!");
}

```

This can be applied to mouse and text input as well.

reference: https://github.com/SilverTiger/lwjgl3-tutorial/wiki/Input

---
Tags: lwjgl, lwjgl3
---


# Question
Title: How to prevent clicking through object in GameMaker
I've been making my first, simple game in Game Maker. You have to click a moving ball (obj\_ball), each time you click it, it wil start moving faster. I wanted to add a way to lose the game: if you would miss a ball, it would redirect you to another room. I tried creating a new object (obj\_gameover) covering the whole backgroud and adding a 'left pressed' event with a proper execute line to it, but whenever I click on a obj\_ball, it also clicks on a obj\_gameover, executing events from both objects. Is there any way to fix my problem?

# Answer
You could check in obj\_gameover whether the ball is clicked too or not. Something like:
**Left Pressed (obj\_gameover):**

```
if (!obj_ball.clicked)
{
    // proceed your obj_gameover's onclick actions
}

```

Where **clicked** is the variable in obj\_ball, which becomes true in obj\_ball's Left Pressed, and becomes false in Step Event.

**HOWEVER**
I would like to suggest you to implement your system in a differeny way, without the giant obj\_gameover. Use something like this in obj\_ball's Step Event:
**Step Event (obj\_ball):**

```
if (mouse_check_button_pressed(mb_left)) // if button is pressed...
    if (instance_position(mouse_x, mouse_y, obj_ball) == id) // if cursor is on object
    {
        // do all the actions you currently do in Left Pressed Event
    }
    else
    {
        // mouse is pressed, but cursor is not on the ball
        // do your gameover actions
    }

```
> 1 votes

---
Tags: game-maker, events, objects
---


# Question
Title: Use Stage's draw() method to invoke Actor's draw method in Libgdx
**Question :** In the following snippet, I wish to draw different shapes such as rectangles, circles, triangles etc. I will be creating different class files for each of such objects, as I did for Rectangle class here.

I've been trying to invoke the draw method of Rectangle object from Stage object, but I am unable to do so. If I make a plain call to the draw method of the Rectangle object, I can draw the object.

Can some one suggest me how is this possible ? Also, I had many other queries which I'd tried to put in comments. Please have a look at them and kindly help me in figuring out the concept beneath it.

Disclaimer : I am new to game programming, started with Libgdx.

Following is the Scan class :

```
package com.mygdx.scan.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.scenes.scene2d.Stage;

public class Scan extends ApplicationAdapter {
private Stage stage;
public static ShapeRenderer shapeRenderer;

@Override
public void create () {
    stage = new Stage();
    shapeRenderer = new ShapeRenderer();
    Rectangle rect1 = new Rectangle(50, 50, 100, 100);
    stage.addActor(rect1);

}

@Override
public void render () {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    shapeRenderer.setProjectionMatrix(stage.getCamera().combined);
    shapeRenderer.begin(ShapeType.Filled);
    shapeRenderer.setColor(Color.BLACK);
    //new Rectangle(50, 50, 100, 100).draw();
    shapeRenderer.end();
    // This should call Rectangles draw method. I want a Shapetype.Filled Rectangle.
    // But I'm unable to invoke this method if I add the actor in stage object and invoke it's draw method.
    stage.draw();
}

public void dispose() {
    stage.dispose();
}
}

```

Following is the Rectangle Actor class :

```
package com.mygdx.scan.game;

import com.badlogic.gdx.scenes.scene2d.Actor;

public class Rectangle extends Actor {

float xcord, ycord, width, height;
public Rectangle(float x , float y , float width, float height) {
    this.xcord = x;
    this.ycord = y;
    this.width = width;
    this.height = height;
}

// This needs to be called in the Scan class. I just want the draw       method to be invoked.
// Also I wish to draw many such rectangles. What is the best practice to get hold of ShapeRenderer object from Scan class ?
// Should I use one instance of  ShapeRenderer object in Scan class or should I create ShapeRenderer object for each of the Rectangle object ??
// I also plan to repeat the activity for another object such as circles. So I would like to know the best practice here.
public void draw() {
    Scan.shapeRenderer.rect(this.xcord, this.ycord, this.width, this.height);
}

```

}

# Answer
You should use your ShapeRenderer as an input into your draw function.

```
// The shapeRenderer as input
public void draw (ShapeRenderer renderer) {
     renderer.set(ShapeType.Filled);
     renderer.drawRect(this.xcord, this.ycord, this.width, this.height);
}

```

Taking the ShapeRenderer as input also allows you to iterate over a list of rectangles to draw your rectangles. I personally prefer 'for : in' loops, but anything but a while loop will work (while loops will crash your game).

```
for( Rectangle rect : rectangles) {
    rect.draw(shapeRenderer);
}
// always end when you finish renderering!
shapeRenderer.end();

```

Lastly, I recommend that you put this before you begin your ShapeRenderer.

```
 shapeRenderer.setAutoShapeType(true);

```

This will make the ShapeRenderer swap to a workable ShapeType for you (automatically) if it can't draw with the current ShapeType.

Edit: Reread your question, and I didn't answer it perfectly. Stages have their own batches, which means if you want to render your rectangles (or anything) using them, they need to have sprites (or some image/texture), as batches can't draw the basic shapes. (Rectangle, circle, ellipses).
> 0 votes

# Answer
Try moving `shapeRenderer.end()` to after `stage.draw()`. You must not draw anything using the shape renderer after it has been ended.

Alternatively also try doing `stage.act()` before `stage.draw()` in addition to the above. Not sure what that would fix but it's a possibility.
> 0 votes

---
Tags: libgdx, rendering
---


# Question
Title: How to run JarSplice from the command line?
I've tried `java -jar jarsplice.jar --help` and `"" /?` which just launches the UI. I'd like my game to automatically be packaged into a single jar when it's built so it would be very useful to be able to call it from the command line.

e.g-

```
java -jar jarsplice.jar -jars "..." -natives "..." -output "..." -exe -sh -mac

```

# Answer
## Answer: It's not possible

There are forks however that allow you to do this.

For example: https://github.com/lquesada/JarSplicePlus
> 1 votes

---
Tags: java, lwjgl, slick, jarsplice
---


# Question
Title: Why is my SpriteSheet displayed over my player character in MonoGame?
I'm trying to make a little Zelda clone.

I'm just starting with MonoGame, following tutorials, and I have a problem when loading the sprite for my player character: it loads the whole spritesheet over him. In this image, you can see what i mean:

Any help? Animation and Sprite classes should be ok, I think. Sorry if this is too long for such a little thing. Here's my code:

```
namespace Game1
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        private BaseObject _player;
        private ManagerInput _managerInput;
        public Game1()
        {

            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            this.graphics.PreferredBackBufferHeight = 240;
            this.graphics.PreferredBackBufferWidth = 320;
            _player = new BaseObject();
            _managerInput = new ManagerInput();

        }

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        protected override void LoadContent()
        {

            spriteBatch = new SpriteBatch(GraphicsDevice);
            _player.AddComponent(new Sprite(Content.Load<Texture2D>("player"), 50, 50, new Vector2(50, 50)));
            _player.AddComponent(new PlayerInput());
            _player.AddComponent(new Animation(16,16));

        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            _managerInput.Update(gameTime.ElapsedGameTime.Milliseconds);
            _player.Update(gameTime.ElapsedGameTime.Milliseconds);

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(new Color(196,207,161));

            spriteBatch.Begin();
            _player.Draw(spriteBatch);
            spriteBatch.End();
                    base.Draw(gameTime);
        }
    }
}

```

Animation class:

```
 class Animation : Component
    {
        public override ComponentType ComponentType
        {
            get { return ComponentType.Animation; }
        }

        private int _width;
        private int _height;
        public Rectangle TextureRectangle { get; private set; }
        public bool LockDirection { get; set; }
        public bool LockAnimation { get; set; }

        public Direction CurrentDirection;
        public State CurrentState { get; private set; }
        private double _counter;
        public int AnimationIndex { get; private set; }
        private int _animationFrames;
        private int _animationSpeed;

        private bool _loop;
        private int _count;
        private int _current;

        public Animation(int width, int height, int animationFrames = 1, int animationSpeed = 200)
        {
            _width = width;
            _height = height;
            _counter = 0;
            AnimationIndex = 0;
            CurrentState = State.Standing;
            _animationFrames = animationFrames;
            _animationSpeed = animationSpeed;
            TextureRectangle = new Rectangle(0, 0, width, height);
        }

        public override void Update(double gameTime)
        {
            if (LockAnimation)
                return;

            if (!_loop && _current > _count - 1)
            {
                CurrentState = State.Standing;
                return;
            }

            _counter += gameTime;
            if (_counter > _animationSpeed)
            {
                switch (CurrentState)
                {
                    case State.Walking:
                        ChangeState(0, _animationFrames);
                        _counter = 0;
                        break;
                }
            }
        }

        public void PlayAnimation(State state, Direction direction, int count = 1, bool loop = false, bool forceReset = false)
        {
            if ((CurrentDirection != direction && !LockDirection) || forceReset)
            {
                _counter = 1000;
                AnimationIndex = 0;
            }

            CurrentState = state;
            if (!LockDirection)
                CurrentDirection = direction;
            _count = count;
            _current = 0;
            _loop = loop;
        }

        public void StopAnimation()
        {
            _current = _count + 1;
            _loop = false;
        }

        private void ChangeState(int y = 0, int animationFrames = 2)
        {
            if (AnimationIndex + 1 > animationFrames)
            {
                AnimationIndex = 0;
                _current++;
            }

            switch (CurrentDirection)
            {
                case Direction.Down:
                    TextureRectangle = new Rectangle(_width * AnimationIndex, y, _width, _height);
                    break;
                case Direction.Up:
                    TextureRectangle = new Rectangle(_width * AnimationIndex, y + _height, _width, _height);
                    break;
                case Direction.Left:
                    TextureRectangle = new Rectangle(_width * AnimationIndex, y + _height * 2, _width, _height);
                    break;
                case Direction.Right:
                    TextureRectangle = new Rectangle(_width * AnimationIndex, y + _height * 3, _width, _height);
                    break;
            }

            if (AnimationIndex + 1 <= animationFrames)
                AnimationIndex++;

        }

        public override void Draw(SpriteBatch spritebatch)
        {

        }

    }
}

`

```

Sprite class:

```
   class Sprite : Component
    {
        private Texture2D _texture;
        private int _width;
        private int _height;
        private Vector2 _position;

        public Sprite(Texture2D texture,int width,int height,Vector2 position)
        {
            _texture = texture;
            _width = width;
            _height = height;
            _position = position;
        }
        public override ComponentType ComponentType
        {
            get { return ComponentType.Sprite; }
        }
        //Los sprites se mueven por la pantalla para generar acción
        public void Move(float x,float y)
        {
            _position = new Vector2(_position.X + x, _position.Y + y);

            var animation = GetComponent<Animation>(ComponentType.Animation);
            if (animation == null)
                return;
            if (x > 0)
            {
                animation.PlayAnimation(State.Walking, Direction.Right);
            }
            else if (x<0)
            {
                animation.PlayAnimation(State.Walking, Direction.Left);
            }
            else if (y > 0)
            {
                animation.PlayAnimation(State.Walking, Direction.Down);
            }
            else if (x < 0)
            {
                animation.PlayAnimation(State.Walking, Direction.Up);
            }
        }

        public override void Draw(SpriteBatch spritebatch)
        {
            var animation = GetComponent<Animation>(ComponentType.Animation);
            if (animation != null)
            {
                spritebatch.Draw(_texture, new Rectangle((int)_position.X, (int)_position.Y, _width, _height),animation.TextureRectangle, Color.White);
            }
            spritebatch.Draw(_texture, new Rectangle((int)_position.X, (int)_position.Y, _width, _height), Color.White);
        }

        public override void Update(double gameTime)
        {

        }
    }
}
`

```

Thank you.

# Answer
> 0 votes
```
public override void Draw(SpriteBatch spritebatch)
{
    var animation = GetComponent<Animation>(ComponentType.Animation);
    if (animation != null)
    {
        spritebatch.Draw(_texture, new Rectangle((int)_position.X, (int)_position.Y, _width, _height),animation.TextureRectangle, Color.White);
    }
    spritebatch.Draw(_texture, new Rectangle((int)_position.X, (int)_position.Y, _width, _height), Color.White);
}

```

Your `Draw` method here contains two lines that draw the texture. The first one draws your player correctly underneath with the animation source rectangle, and the second one draws the whole texture to the position.

I think you want to place the second `spritebatch.Draw(...)` inside an `else` statement, so that your `Sprite` object can render just single sprites to the screen in combination with animated objects.

---
Tags: c#, sprites, monogame, spritesheet
---


# Question
Title: Direct3D - ways to retrieve world position from depth buffer without matrix information
For an existing game (VBS3) I'd like to write a plugin which exports all the rendered pixels with their world position (basically something like a LIDAR point cloud).

Actually I don't need the position of each pixel, instead I could also use the application's internal collision checking system with equally spaced ray endpoints, but it turned out that this approach is way too slow and coarse.

The game provides a callback which gets called whenever the back buffer has been filled. Then this callback provides references to a depth buffer and a render target, both of type IDirect3DSurface9.

As a first shot I just wanted to do it like Andon M. Coleman described in \[1\] but my problem is that the IDirect3DDevice9 linked to the surfaces only returns identity matrices when I call GetTransform() on it with types D3DTS\_PROJECTION and D3DTS\_VIEW.

Therefore I suppose the application does not use those matrices at all and instead does all the matrix / projection stuff internally. Am I right? Is this common? And are there other approaches I could take?

Thanks in advance!

\[1\] https://stackoverflow.com/questions/32227283/getting-world-position-from-depth-buffer-value

# Answer
SetTransform/GetTransform only apply if the programmer is using the legacy fixed-function pipeline. They don't apply at all if a vertex shader is used, so yes, I would say that it is very common to not use them.

Assuming that shaders are used, these matrices will instead be stored in vertex shader constant registers, of which there are typically 256 (legacy hardware may have fewer). Each register is 4 floats and a matrix therefore consumes 4 registers.

This holds true even if the Effects framework is used, which typically doesn't expose registers to the programmer but is nonetheless just a wrapper around the underlying register-based API.

To retrieve the contents of these registers you would use **IDirect3DDevice9::GetVertexShaderConstantF**.

Unfortunately there is no standard or even convention for which registers matrices typically go into. Some programs may also store each of the required matrices separately whereas other programs may just store a single concatenated MVP.

To complicate things slightly more, programs may also apply custom transforms that are not even matrix-based at all; part of the flexibility of vertex shaders is that the programmer is not limited to the built-in fixed transforms, so you should expect this on occasion.

So what you're going to have to do is make a number of GetVertexShaderConstantF calls, examine the results, and experiment until you hopefully find something that works, but be prepared to accept that if the program does anything more unusual than just replicating the behaviour of the 3 fixed-pipeline matrices you may never find anything that works.

Finally, you should be aware that GetVertexShaderConstantF may involve a round-trip to the GPU which will impact your performance (I would expect that drivers would cache registers locally and flush to the GPU in batches so this may not be such a big deal, but I wouldn't depend on it).
> 1 votes

---
Tags: directx, graphics, directx9
---


# Question
Title: Drawing a graph in Java JPEG/PNG for a simple map
For my game i need to create a map based on a graph starting from the coordinates of the nodes, using "roads" instead of simple lines (for the edges) and circles instead of points (for nodes), but i don't now exactly which library to use.

As far as I now the standard graph visualization libraries wouldn't make me create this kind of graph.

Here is a quick example of what i mean:

If possible for the points i would like to use a custom textures

I only need to learn how to create the picture, because i know how to handle it in my game

# Answer
This question is just very vague and lacks any details. I think you question should be, what graphics library you should use.

I'm not working with Java but maybe you look for something like lwjgl, which is one of many possible graphics libraries you can use. Second there are many tutorials on how to use it. If you want to keep your Nodes any dynamic, don't just create a static png for that.

Now, if you use one of those libraries, you will likely create those nodes and paths as entities. With positions, orientation and a graphical representation. The nodes will have an array of paths, so in game you can move a unit from one node to another via a path.

There is just not more to say, since your request is so vague.
> 1 votes

---
Tags: java, maps, android-studio
---


# Question
Title: Can this singleton class cause a memory leak?
In a game I'm writing using LibGdx, I'm wondering if a memory leak will occur on Android when the home key is pressed or a phone call gets received and the game gets put into pause.

I have a Singleton class which holds all of my games assets and I use a static method to get access to it.

```
public class Assets
{
    private static Assets assetsInstance;

    private Assets()
    {
        //load assets....
    }

    public static Assets getInstance()
    {
        if (assetsInstance == null)
        {
           assetsInstance = new Assets();
        }
        return assetsInstance;
    }

    public void nullAssets()
    {
        //here things are set to null
        assetsInstance = null;
    }
}

```

In my Main class:

```
public class Main extends ApplicationAdapter
{
    public static Assets gameAssets;
    private GameStateManager gsm;
    public void create()
    {
        gameAssets = Assets.getInstance();
        gsm = new GameStateManager(this);
    }

    public void pause()
    {
        gameAssets.nullAssets();
        gameAssts = null;
    }
}

```

My GameStateManager looks like this:

```
private int currentState;
private Main m;
private GameState[] gameStates;
private final in NUMBEROFSTATES = 6;
public static final int TITLESTATE = 0;
public static final int PLAYSTATE = 1;
//more states

public GameStateManager(Main m)
{
    this.m = m;
    gameStates = new GameState[NUMBEROFSTATES];
    currentState = TITLESTATE;
    loadState(currentState);
}

```

My GameState class:

```
public abstract class GameState
{
    protected GameStateManager gsm;
    protected Main m;

    protected GameState(GameStateManager gsm)
    {
        this.gsm = gsm;
        m = gsm.m;
    }

    //abstract methods
}

```

The game states all extend GameState.

By calling pause() in the Main class which sets `gameAssets` to null and also assigning `assetsInstance` to null, does that take care of everything needed to let the garbage collector remove the singleton? Or does the fact that GameState class has `m = gsm.m;` mean something will remain in the memory and become a problem?

# Answer
*In Theroy*, when there is no longer anything pointing to the old `assetsInstance`, all of the assets in it should be eligible for garbage collection.

But note that if any of the assets which your `Assets` class handles are still referenced by other objects, those references will still be active and will prevent garbage-collection of those assets. So when the constructor of `Assets` loads everything again, you will have two copies of each asset which is still referenced.

You can avoid that if all classes which use `Assets` never keep any references to assets around.

If you can't or don't want to avoid this for some reason, consider using at least a `WeakReference`. Weak references are ignored when it comes to determining what can be garbage-collected. A drawback of this is that you can not rely on a weak reference being valid. Always check the return value of `weakReference.get()` for `null`.
> 1 votes

---
Tags: java, android, libgdx
---


# Question
Title: Keyboard input not working for me in derived class
My code is unable to accept keyboard inputs in a specific class.

I know that I have used inheritance for that class, but I'm pretty sure that it is not the main reason why it doesn't work.

Can you guys look over my code to see if you can help me with my specific issue? The problem is in the `Update()` in HowToPlayMenu.cs.

`HowToPlayMenu.cs (derived class)`

```
using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Our_First_Game
{
    class HowToPlayMenu : SplashScreen
    {
        private static KeyboardState keyOldState, keyNewState;

        public HowToPlayMenu(Texture2D Instructions) : base(Instructions)
        {
            image = Instructions;
            endScreen = true;
        }

        public override void Update()
        {
            if (endScreen && keyNewState.IsKeyDown(Keys.M))
            {
                endScreen = false;
                Console.WriteLine("end Screen false!");
            }
            else if (!endScreen && keyNewState.IsKeyDown(Keys.M) && keyOldState.IsKeyUp(Keys.M))
            {
                endScreen = true;
                Console.WriteLine("end Screen true!");
            }
        }

        public override void Draw(SpriteBatch spriteBatch)
        {
            base.Draw(spriteBatch);
        }
    }
}

```

`SplashScreen.cs (base class)`

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Our_First_Game
{
    class SplashScreen
    {
        protected Texture2D image;
        protected bool endScreen = false;

        public SplashScreen(Texture2D SplashImage)
        {
            image = SplashImage;
        }

        public virtual void Update()
        {
            if (!endScreen)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Space))
                {
                    endScreen = true;
                    Game1.isGameActive = true;
                    Game1.reload1 = 0;
                    Game1.reload2 = 0;
                }
            }
        }

        public virtual void Draw(SpriteBatch spriteBatch)
        {
            if (!endScreen)
            {
                Game1.isGameActive = false;
                spriteBatch.Draw(image, new Rectangle(0 ,0 , 800, 480), Color.White);
            }
        }
    }
}

```

# Answer
You're not updating `keyOldState` or `keyNewState`. You probably meant to add `keyOldState = keyNewState; keyNewState = Keyboard.GetState();` to the beginning of your `Update()` method.
> 4 votes

---
Tags: c#, xna, monogame, input
---


# Question
Title: Are there any math limitations on the near plane in a perspective matrix?
I've noted that if in the perspective camera I put near plane to a low number like `0.000001` and far plane to `1000` my render has some problems, like strange depth artifacts (see images below) or division by zero during the unprojection procedure.

I'm not very skilled in math but there should be something strange because if I put near plane at `0.1` everything is working as expected.

Is there any mathematical limitation to the near plane value I'm not aware of?

I'm on WebGL with JavaScript (I'm *not* using Three.js; my question is related to the math, not to a particular framework). If it matters, I'm using `Float32Array` to store matrices, and I'm using those libraries to do the math:

In particular the division by zero happens here:

```
function project (out, vec, m) {
  var x = vec[0],
    y = vec[1],
    z = vec[2],
    a00 = m[0], a01 = m[1], a02 = m[2], a03 = m[3],
    a10 = m[4], a11 = m[5], a12 = m[6], a13 = m[7],
    a20 = m[8], a21 = m[9], a22 = m[10], a23 = m[11],
    a30 = m[12], a31 = m[13], a32 = m[14], a33 = m[15]

  // DIVISION BY ZERO HERE:
  var lw = 1 / (x * a03 + y * a13 + z * a23 + a33)

  out[0] = (x * a00 + y * a10 + z * a20 + a30) * lw
  out[1] = (x * a01 + y * a11 + z * a21 + a31) * lw
  out[2] = (x * a02 + y * a12 + z * a22 + a32) * lw
  return out
}

```

# Answer
The GPU uses more bits to store distances closer to the camera than ones farther, and this becomes worse the closer you set the near plane to 0. With a near plane of 0.01 the error between the stored distance and actual distance at 1000 units becomes 100 unit.

What happens basically is that different distances start to have the same value in the depfh buffer, so the GPU can't decide which one goes on top, and z-fighting happens.

You should always set the near plane to the largest value you're comfortable with.
> 1 votes

---
Tags: mathematics, matrix, webgl, perspective
---


# Question
Title: If a 3D vector represents a point, how can it have a length?
I am trying to understand vector arithmetic (and specifically its use in the Unity engine). I am not able to figure out how a vector can have a length (magnitude) even though it only represents a point (position and direction)?

Does that mean that the magnitude is simply its distance from the origin point (0, 0, 0)? Or am I missing something?

# Answer
> Does that mean that the magnitude is simply it is distance from the origin point (0, 0, 0)?

The **tl;dr** answer may be: Yes, you can imagine it like that.

But I'm not sure whether this might not lead to a wrong understanding.

---

**A vector is not a point, and there is a crucial difference between the two!**

The fact that a vector is usually represented as an "arrow" might give a wrong impression. A vector is, in fact, **not** a single arrow. It would be more precise to say that a vector is *the set of **all** arrows that have the same length and direction*. (The arrow that is usually painted is just *one* representative of all these arrows). But I don't want to go too far into the boring details of mathematics here.

More importantly, there is a crucial difference between a point and a vector, that becomes obvious in graphics programming when you *transform* the point or vector. I'm not familiar with Unity, but from a quick glance at the documentation, they are modeling the most important difference between a point and a vector in the `Matrix4x4` class. It has two different functions:

The difference is, roughly speaking, that a vector is not translated, whereas a point is. Imagine the following 4x4 matrix:

```
1.0   0.0   0.0   1.0
0.0   1.0   0.0   2.0
0.0   0.0   1.0   3.0
0.0   0.0   0.0   1.0

```

It describes a translation about (1,2,3). Now, when you have the following pseudocode

```
Vector3 tp = matrix.MultiplyPoint (new Vector3(2,3,4));
Vector3 tv = matrix.MultiplyVector(new Vector3(2,3,4));

```

Then `tp` will be (3,4,5), wheras `tv` will still be (2,3,4). Translating a vector does not change it (because, as mentioned above, it is the set of all arrows with the same magnitude and direction).

---

The fact that Unity uses the `Vector3` class for both, vectors **and** for points, is legitimate, but may be confusing. Other libraries dedicatedly differentiate between `Point3D` and `Vector3D`, sometimes with a common base like `Tuple3D`.
> 20 votes

# Answer
> Does that mean that the magnitude is simply it is distance from the origin point (0, 0, 0)?

That's exactly that.

Among other things, a vector can represent a point (a position), a direction and/or a velocity, depending on the context.

If you have this variable:

```
Vector3 mPosition;

```

It generally represents *only* the position, i.e. where it is located in 3d space.

If you have this variable:

```
Vector3 mDirection;

```

It generally represents the direction. Typically, these vector are unit vectors, i.e. vectors of length 1 (but it's not always needed). A unit vector and a Normalized vector are the same thing, they're both of length 1. These vectors are often used with *other* vectors to change their positions.

When normalizing a vector, you lose its length (its magnitude), but the direction stays the same. There are situations when you only need the direction (e.g. when you want to move an object in that direction), and having the (non-unit-length) magnitude in the vector would introduce unexpected calculation results.

If you need a normal vector for a single calculation, you can use `myVec3.normalized`, it will not affect `myVec3`, and if you intend to use that normalized vector often, you should probably create a variable:

```
Vector3 myVec3Normalized = myVec3.normalized;

```

to avoid repeated calls to the `normalized` method.

And if you see variables:

```
Vector3 mVelocity;

```

It generally represents a force/speed: these vectors represent a direction *and* their magnitude (their length) is important. They could also be represented with `Vector3 mDirection;` and a `float mSpeed;`.

All of these are used with regard to their local origin, which can be (0, 0, 0), or can be another Position.
> 36 votes

# Answer
> Does that mean that the magnitude is simply it is distance from the origin point (0, 0, 0)?

You *can* see it that way, but only seeing it that way may lead to a wrong understanding.

---

First of all, a vector is not a point, and a point is not a vector.

The difference between a *vector* and a *point* is the same as between a *duration* and a *time of day*. The former is an interval of time, the latter is a single point in time. Its obviously that 6 hours is not the same as 6 o'clock. You wouldn't say "The race lasts 1 o'clock" and neither would you say "Lets meet at 13 hours". The race lasts one hour - an interval - and you meet at 13 o'clock - a specific point in time.

The same applies to vectors and point. A vector is an intervall - a displacement if you will. It points in a certain direction, and yes, it has a length.

Points and vectors are therefore related, just as durations and times of day. The race starts at 13 o'clock and ends at 15 o'clock. Both are points in time. But 15 o'clock - 13 o'clock = 2 hours, a duration. The race lasts two hours, not 2 o'clock.

The same applies to points. The difference between point A and B is denoted as ⃗v = B - A, where ⃗v denotes a vector and A and B denotes points.

Now, there is something that called a *position vector*. You *can* consider a vector a point to a certain degree, when you say that the vectors points from the origin to a certain other point. In other words: If all your friends know that you call times of day as durations since midnight (0 o'clock), you can say "We meet at 6 hours". They would know that 0 o'clock + 6 hours = 6 o'clock and therefore, when to meet you. This is in fact what naval times do. "We meet at o-six-hundred hours" means 6 o'clock.

So the vector \<1,2,3\> points to the point (1,2,3), if you consider the origin the anchor point, and yes, the length of this vector is the distance of that point from the origin.

But the vector \<1,2,3\> *also* points from (1,1,1) to (2,3,4), and in that case its length denotes the distance between *those* two points.

---

So, as you can see a vector has a length because it is not a point, but an interval -- a displacement.
> 8 votes

# Answer
A vector can represent a line between two points in 3d space (direction and distance) or a location in 3d space (length is the distance from origin).

If you have point A, and point B, then B-A = AB = the direction and distance you would have to travel to get from A to B.
> 5 votes

# Answer
What Unity says about points vs. vectors is meaningless in the long run, because geometry APIs just pick distinct definitions to make the tool more accessible, they don't correspond to how these things are conceptualized in geometry. Take a look at the implementations of the classes, if you can. Because it's arbitrary, to know its definition is the only way to understand what the concept is. Full disclosure, I don't have Unity experience.

A vector is a point **in a vector space**, in that the concept of a point in the geometry is encoded by elements of the underlying set. A vector space has **a distinguished vector, called the origin or 0**. Linear algebra is an attempt to encode a fragment of euclidean geometry w/ an origin algebraically.

# The arrow and its length

Motions across a space of points are frequently **interpreted as all the arrows** from source/before points to their target/after points.

A function of two arguments can be applied to one argument to produce a function of one argument - we can speak of *x*+, the function which takes each vector *y* to the vector *x*+*y*. This is the translation associated w/ adding *x*. The associated arrows run from points *y* to points *x*+*y*. See: partial application, currying.

So **why do we only use the one arrow**? The arrow from the origin points to a specific vector, the *x* in *x*\+ - the origin is the identity of vector addition. So, we can recover the translation *x*\+ from just its value *x*+0 = *x*.

As a graphical representation of the space, the arrow representation has to do with our ability to visually or physically extrapolate the effect of a translation from the value determining it. When do we have that ability?

To give the vector space a **norm** making it a **normed vector space** is to provide a notion of the **length** of a vector that makes sense as its distance from 0. As well, this is to be a distance satisfying the triangle inequality, which is a strong constraint on how the lengths of two vectors relate to that of their sum. From length we can define distance to make this a metric space, and a geodesic is a path that's intrinsically straight in that it's as short as possible. The euclidean norm induces euclidean distance and the geodesics are the line segments of the arrows, but if you draw the arrows as geodesics using different norms, you could extrapolate the geometric effect of the translation from the geodesics to learn about the geometry.

# The meaning of point and vector

In some cases in doing games geometry, **your space of points is not a vector space**. An affine space of dimension *n* can be embedded in a projective space of dimension *n*. Affine maps reduce to projectivities. Projectivities also let you do FOV, w/c I think is not affine. Projectivities have benefits:

The projective *n*-space over a field can be constructed from the linear (*n*+1)-space (vector space), by treating the points of the projective space as the lines through the origin of the linear space. Planes through the origin in turn give projective lines. Multiplying vectors by a fixed matrix is a linear map, this is what matrix multiplication is for. Linear maps preserve the origin and are compatible w/ incidence. In particular, if *f* is a linear automorphism (corresponding to an invertible (*n*+1)x(*n*+1) matrix), and two lines *L, M* through the origin span a plane *A*, then *f L, f M* are lines through the origin spanning *f A*, so *f* will preserve incidence on the projective space as well - an invertible matrix has an associated projectivity. Matrix multiplication encodes composition of linear maps, and hence of the projectivities.

Removing the origin from the linear space, all the points on a given line through the origin are scalar multiples of one another. Exploiting this fact, homogenization picks a linear point to stand in for each projective point and an invertible matrix to stand in for each projective transformation (as in this 2D -\> 2D affine maps as 3D -\> 3D linear maps video), in such a way that the representatives are closed under matrix-matrix and matrix-vector products and give and are given by unique projective things. This description of construction of the projective plane from the linear plane ties some things together.

So, in the model-view-projection matrix pipeline, we're using vectors to represent the points of our projective space, but the projective space is not a vector space, and not all vectors in the vector space we're using represent points of our geometry (see picture of affine plane at right). We use translation matrices instead of vector sum if we want translations. Sometimes, people call projective or affine points vectors, especially when using a setup in this vein.
> 1 votes

# Answer
The length (or magnitude) of the vector is `square root of (x*x+y*y+z*z)`. Vectors are always considered as a ray passing from the origin of `<0,0,0>` ***through*** the point described in the vector `<x,y,z>`

The unity documentation on this is found here.
> -1 votes

---
Tags: vector, geometry
---


# Question
Title: Event handling in Pure Entity Component Systems, is this approach correct?
I want to ask if the following is an effective way to architect event propagation using an ECS?

Here is a hypothetical collision scenario using an ECS.

**Components**:

```
class Collider {
    public var rect:Rectangle;
}

```

and

```
class Health {
    public var health:Int;
}

```

Now for the behaviour logic:

We can create entities with `Collider` and/or `Health` components.

Some `ColliderSystem` handles entities (more specifically, nodes) with `Collider` components. It deals with handling collision logic and determining if two `Collider` component rectangles overlap.

Moreover, if an entity with a `Collider` component has a `Health` component, the `Health` component's value should decrease.

How would I implement this behaviour?

---

I see three ways to approach it, 2 bad, 1 good.

1. Bad idea 1: We could check for a collision on all `ColliderHealthNode`s in a `HandleCollisionsSystem` each frame, but this seems like a waste of computation. The value likely won't be changing every frame.
2. Bad idea 2: Instead of an events system however, we can use the ECS to pass this logic via system registration. Our `HandleCollisionsSystem` could add a `Collided` component (really just a tag) to the `Collider` component's entity. Then our `HandleCollisionsSystem` would be registered to our ECS with an aspect of `<Collider, Health, Collided>`.

Besides this looking like an overuse/abuse of ECS, it also silently couples logic between systems (how do we know that `CollisionSystem` will add `Collided` component tags to the entities of the `ColliderNode`s it processes?) How do we know that our `HandleCollisionsSystem` needs to have an aspect that includes a `Collided` tag? `CollisionSystem` and `HandleCollisionsSystem` need to know each others inner workings and so become logically, but invisibly, coupled.
3. Good idea (?): The approach that makes the most sense in my mind is to use an event-listener pattern and to have our `CollisionSystem` broadcast `CollisionEvent`s, while our `HandleCollisionsSystem` can listen to `CollisionEvent`s. The implementation is described below:

---

We'd create an enum:

```
enum CollisionEvent {
    BEGIN_COLLISION;
    // ... could have more types
}

```

And we create our CollisionSystem like so

```
//aspect:<Collider>
class CollisionSystem {

    // some collision determining logic to determine if a Collider
// is being collided with -> calls the broadcastCollisionEvent function
// on those Colliders that are colliding

    function broadcastCollisionEvent(event:CollisionEvent, collider:Collider){
        eventSystem.broadcastEvent(event, collider)
    }
}

```

We'd then have an interface

```
interface CollisionEventListener {
    function handleCollisionEvent(event:CollisionEvent, collider:Collider);
}

```

And our HandleCollisionsSystem would look like

```
//aspect:<Collider, Health >
class HandleCollisionsSystem implements CollisionEventListener

    public function handleCollisionEvent(collisionEvent:CollisionEvent, collider:Collider) {
        colliderHealthNode = findNodeForColliderComponent(collider)
        switch(collisionEvent){
            case BEGIN_COLLISION:
                assocNode.health.health -= X; // some computation
            // other cases
        }
    }

```

Our `HandleCollisionsSystem`then gets registered as a listener for `CollisionEvent`s to the `EventSystem`. When the `CollisionSystem` broadcasts a `CollisionEvent`, the `EventSystem` will propagate that call to the `HandleCollisionsSystem` to handle.

**Is this the best approach for handling event propagation between systems?**

**If it isn't: is there a better way?**

**If it is: how would we implement findNodeForColliderComponent()?**:

Would we always register `ColliderHealthNode`s within a `Collider->ColliderHealthNode` map within our `HandleCollisionsSystem` upon registration to be looked up later?

---

**Note 1** Specifically referring to a *ECS* to mean *pure ECS*: that is, all behaviour would be encompassed by systems and all components are data-only. Systems don't have access to entities directly and only operate on "nodes"- bags of components that match their respective aspect; ie `ColliderSystem` operates on "nodes" with only a `Collider` component, and `HandleCollisionsSystem` operates on "nodes" with both a `Collider` and `Health` component.

**Note 2** In this simplification, it may look like merging `CollisionSystem` and `HandleCollisionsSystem` would make sense, but the separation is there to allow extension to a more complex scenario where we have multiple different `HandleCollision` systems that care about `CollisionEvent`s and affect different aspects.

# Answer
Merging systems, such as collision and collision response, is a bad idea. The reason being that there can be many different responses to collisions: Physics based, and game-logic based.

In most game engines I have seen (ECS and non-ECS and all the greys in-between), there is some kind of inter-system communication system, because this is what makes the creation of games possible.

As far as communication goes, you want your engine to handle two basic message types: events, and commands.

Events get queued up, and processed at the beginning of the next frame(synchronously), or handled asynchronously (as soon as they are received). Which you choose is up to you (but I recommend async).

Commands are for something that does not affect the game state, but modifies the engine state (startup/shutdown/change settings/log error).

Both can be routed very similarly, but this distinction is very important: An event is something that occurred in the *past*, and a command is something that is to occur in the *future*. What is also very important is whether you let the processing of one event generate other events. If handled incorrectly, you may end up blowing the program stack.

My personal approach, is for the highest level of the engine to have a central event queue, which is emptied at the beginning of the update cycle, and filled up again during the update cycle, as game events occur. Each system has it's own event queue, but the events that end up in there are filtered by each systems responsibilities.

When these events are processed by each system, they can generate additional events which are passed back up to the engine level, and en-queued.

Once this is in place, you can then have multiple collision event handler systems, each of which behaves differently (and could be run off scripted behaviours if you want).

Now, here is where we get to the meat of the question:

How do we handle things like health from say, a bullet hitting the player?

Well, that's simple enough. Both entities should have some kind of GameObjectData component, which, to keep this simple, contains a type (string, enum, whatever). The player has a CharacterData component too.

So, when a collision event is received by our "GameCollisionHandler" system, we can query a couple of things, like so:

```
GameCollisionHandler::handleCollisionEvent(CollisionEvent& e, Engine& engine){
    //find entities by unique id provided by event

    auto entityA = findEntity(e.first.getID());
    auto entityB = findEntity(e.second.getID());

    //Query if we have a bullet/player match
    if ( entityA->hasComponent<GameObjectData>() ){

        auto data = entityA->getComponent<GameObjectData>();
        if ( data->getType() == "Player"){

            if ( entityB->hasComponent<GameObjectData>() ){

                auto data = entityB->getComponent<GameObjectData>();
                if ( data->getType() == "Bullet"){

                    if (entityA->hasComponent<CharacterData>()){

                        entityA->getComponent<CharacterData>()->decrementHealth(10);
                        // and let the engine know that the bullet is to be removed
                        engine.sendCommand(RemoveEntityCommand(e.second.getID());

                        if ( entityA->getComponent<CharacterData>()->getHealth() <= 0){
                            engine.sendEvent(PlayerDeath(e.first.getID());
                       }
                   }
                }
            }
        }
    }
}

```

This is a very crude example, but I think it illustrates the idea reasonably well.

So, to more concisely answer your question:

**Is this the best approach?** Possibly, there are no silver bullets in programming. I believe so, but could be wrong.

**Is there a better way?** I don't believe so.

**How would we implement findNodeForColliderComponent()**? I have no I idea what you mean by that, except that it is some form of search function. Your engine, at this stage, should already have some form of multi-function search ability, so that should cover it.
> 11 votes

# Answer
Your question boils down to

> Is it a good idea to use a publisher-subscriber-based GUI and to keep this subsystem distinct from my ECS (while enabling interop between them)?

Yes, keep your UI and your ECS systems totally separate.

Notice what I'm *not* saying here: I'm not saying you should not have mouse-clickable entities. What I *am* saying is that it would be ideal to keep your primary UI system totally separate from your clickable entities system. But first... Why is it a good idea to keep them distinct?

* You are obeying the Single Responsibility Principle
* Low coupling brought by pub-sub (event dispatchers and handlers)
* "Silent coupling" that you mentioned is avoided - you never, *ever* want to think about side effects of what a system is doing. You want systems that do the minimum possible to fulfill their role, whether that is at the function, class, or module level. "Do the job and go home" - see FP.
* You indeed want to avoid polling if you can help it, as it is costly and unnecessary in most cases. Handle things as they happen, this means function call stacks which means your event system.
* `Btn` components - bad, *bad* idea. You are *smearing* (for lack of a better term) one layer of logic into another, embedding an aspect of the UI system into your ECS. It quickly becomes unclear who should be controlling whom, and that's a bad place to be at in a codebase.

So how can you achieve this?

**Option A** There's the play area, and superimposed over it, the UI. If a click misses everything in UI, it gets delegated down to the play area / game world viewport. At this stage, your entity system takes over entirely, and uses its own custom approaches to handling clicks. Notice that what is shared between these systems (UI and ECS) is fairly trivial - primarily the ability to decide who, if anyone, gets the click. It's generally a lot easier in the game viewport however, because you usually haven't got nested elements to contend with, as in UI. So it's a simple box, circle, and/or pixels based collision check that returns an entity ID. And away you go.

Don't be taken in by that little voice that says, "but... but... I could reuse so much of the architecture if I could only make the entities use the UI system!" It's a seductive lie that never works out. YAGNI. Better to copy some logic from one to the other where needed, and avoid mangled architecture.

**Option B** Create a simple UI element (button?) with bounds to represent each entity and have these track the entity positions each frame, *only for those entities that are in view and thus clickable*. In order to do this, your UI system should listen for additions, removals, and positional changes of individual entities as broadcast by the ECS core (preferably not from individual entities themselves). This way as far as the UI system is concerned, it is dealing only with its own known types (UI elements) and not some foreign types (Entities) which it would then have to be re-written to handle (tight coupling).

**P.S.** I made a joke on another ECS post today that "In order to discuss ECS, you first have to define ECS... in full." That holds true here as well. I am not telling you how ECS is supposed to work. Everyone has a different view of that, and some approaches are considered more "pure" than others. I *am* giving you the benefit of experience - don't mix the primary subsystems of your game. ECS is a direct submodule of your larger game logic, and game *logic* should never be dealing with *raw input* or *rendering*, which is exactly what UI is. That's why you are advised to have the UI system, as a View (in the MVC sense), subscribe to the ECS system which is a Model (in the same sense) in **B**, ensuring your core game logic concerns remains clean, vs. being polluted by unrelated concepts.

---

**EDIT**

Let's look at your proposals again (now that they've been updated via the comments).

* Use an ECS in the pure sense of having supercontrollers make changes to, and read state from, data elements; (consequently) have pure data elements with *no functions*.
* Not separate your logic between view/render/UI at the ECS components level,
* Yet separate it at the supercontroller level (`BtnSystem`vs. `BtnGraphicSystem` where you have your pub-sub).

Focusing on ECS, I suggest that you read Mick West's Evolve Your Hierarchy, the seminal text on pure ECS. Mick does not disallow mixing of view vs logic components; whereas for the record, I do.

On my (deleted) answer you mentioned:

> ...all behaviour would be encompassed by systems... For an ECS-based GUI, Btn would be a component (data-only). Btn would not have an OnDown function and BtnSystem (which would have a aspect) would handle all entities with Btns behaviour. Thats why the BtnSystem would receive events from an InputMgr and handle logic per Btn. A BtnGraphicSystem would receive events passed from a BtnSystem to apply graphic changes to entities who have both Btn and Graphic components.

You are planning to implement several new classes just to implement this one, tiny, new bit of functionality. That's a code smell. Good engineering primarily centres around one thing: Keep moving parts to a minimum. Every interface between parts is a potential point of failure.

In addition to the above wants, you presumably also need a generalised UI system that will be generic to all sorts of UI elements (menu buttons, inventory etc.), that will in any case replicate some of the functionality of clickable entities. If you already have such a system that amply accommodates UI elements, and/or can be easily extended to accommodate a new sort of UI element *while still remaining utterly generic* (i.e. no knowledge of Btn\* at all), then why would you introduce new classes to do what the UI system can already do? Let the regular UI system handle button state changes, as it would for any other button. For the UI supercontroller to find out about entities, have a proxy, be it your main game loop or a distinct UIEntityProxy controller, subscribe to events dispatched by the ECS supercontroller, which it then routes to your regular UI system (which could be anything from QT to DOM to your own custom but encapsulated OpenGL-based system). That is, the proxy will inform the UI to add remove entities for the current viewable area of the world. The UI system can then act to add clickable elements for each entity, as appropriate, and maintain graphical state for these.

**However,** I think you are proposing that the graphics are *instead* handled by the ECS supercontroller. Also, I think entities sound like your primary interest here, and not generic UI systems, so let's ignore the latter. ECS system then handles all clicks, game logic changes and graphics. The pub-sub approach is unnecessary, and I do see a problem with the separation into `BtnSystem`vs. `BtnGraphicSystem`; since your entity components may be either view or game logic related, then you may as well conflate this logic in your supercontroller as well, and avoid class proliferation (fewer moving parts). Doing Controller vs. View in once place, yet not in another, just leads to confusion. It can be as simple as the following (pseudocode ahead - interpret rather than taking literally):

```
ECS.BtnSystem
{
    //register for event from your OS, platform, or library
    Initialise()
    {
        SomeAPI.RegisterMouseDownCallback(OnMouseDown);
    }

    //receive callback from your OS/platform/library indicating that mouse device state has changed
    OnMouseDown(pos)
    {
        entity = GetEntityAtClick(pos);
        entity.UpdateModelState(); //cache game logic state of the entity as caused by mouse interaction
        entity.UpdateGraphicState(); //cache render (or "frame") state induced
    }
}

//main game loop
...
{
    ...
    //by here, OnMouseDown should already have run and stored some state - both logical and graphics - for the following steps to use.
    RunGameLogic(); //use game logic state
    ...
    RenderBackground();
    ECS.RenderEntities(); //use stored graphic state
    ...
}

```

Why set up event systems when you can just do everything where the device input event comes in?
> 3 votes

---
Tags: entity-system, events, entity-component
---


# Question
Title: How do I correctly project a point behind the camera?
I am making a 3D game in which I put an exclamation marker above points of interest.

In order to find out where in the 2D screen should I put my marker, I am manually projecting the 3D point where the marker should be.

It looks like this:

Looks pretty good. When the marker is outside of the screen, I simply clip the coordinates so they fit into the screen. It looks like this:

So far the idea is going pretty well. However, when the points of interest are behind the camera, the resulting X,Y coordinates are inverted (as in positive/negative), and I get the marker to appear on the opposite corner of the screen, like this:

(The projected-then-clamped point is the tip of the marker. Don't mind the rotation of the marker)

It makes sense, since the coordinates behind the frustum are inverted in X and Y. So what I'm doing is to invert the coordinates when they are behind the camera. However, I still don't know what is exactly the condition when the coordinates should be inverted.

This is currently what my projection code looks like (in C# with SharpDX):

```
    public override PointF ProjectPosition(float viewportWidth, float viewportHeight, float y)
    {
        var projectionMatrix = Matrix.PerspectiveFovRH(GetCalibratedFOV(Camera.FOV, viewportWidth, viewportHeight), viewportWidth / viewportHeight, Camera.Near, Camera.Far);
        var viewMatrix = Matrix.LookAtRH(new Vector3(Camera.PositionX, Camera.PositionY, Camera.PositionZ), new Vector3(Camera.LookAtX, Camera.LookAtY, Camera.LookAtZ), Vector3.UnitY);
        var worldMatrix = Matrix.RotationY(Rotation) * Matrix.Scaling(Scaling) * Matrix.Translation(PositionX, PositionY, PositionZ);
        var worldViewProjectionMatrix = worldMatrix * viewMatrix * projectionMatrix;

        Vector4 targetVector = new Vector4(0, y, 0, 1);
        Vector4 projectedVector = Vector4.Transform(targetVector, worldViewProjectionMatrix);

        float screenX = (((projectedVector.X / projectedVector.W) + 1.0f) / 2.0f) * viewportWidth;
        float screenY = ((1.0f - (projectedVector.Y / projectedVector.W)) / 2.0f) * viewportHeight;
        float screenZ = projectedVector.Z / projectedVector.W;

        // Invert X and Y when behind the camera
        if (projectedVector.Z < 0 ||
            projectedVector.W < 0)
        {
            screenX = -screenX;
            screenY = -screenY;
        }

        return new PointF(screenX, screenY);
    }

```

As you can see, my current idea is to invert the coordinates when either the Z or W coordinates are negative. It works -most- of the time, but there are still some very specific camera locations where it doesn't work. In particular this point shows one coordinate working and the other one not (the correct location should be the bottom right):

I have tried inverting when:

* `Z` is negative (this is what makes most sense to me)
* `W` is negative (I don't understand the meaning of a negative W value)
* Either `Z` or `W` is negative (what's currently working most of the time)
* `Z` and `W` are of different sign, a.k.a.: `Z / W < 0` (makes sense to me. doesn't work though)

But have still not found a consistent way with which all my points are correctly projected.

Any ideas?

# Answer
How about doing it a bit differently?

Start as usual and render all markers within viewport. If a marker is outside of the viewport - proceed:

1. Get positions of the marker `A`
2. Get position of the camera `B` (maybe slightly in front of it)
3. Calculate 3D vector `AB` between these two
4. Convert and normalize that vector into 2D screen bounds (`A` will be in view center and `B` will hit a views border)

*Color lines are `AB` vectors. Thin black lines are characters heights. On the right is the 2D screen*

5. Maybe add a rule, that everything behind camera always goes on to bottom edge
6. Draw the marker in screen space with regard to markers sizes and overlaps

You might need to try that to see if marker going off viewport will jump between positions. If that happens you can try lerping the position when marker approaches the border of the viewport.
> 2 votes

# Answer
Given the three vectors `[camera position]`, `[camera direction]` and `[object position]`. Compute the dot product of `[camera direction]` and `[object position]-[camera position]`. If the result is negative, the object is behind the camera.

Given that I understood your code right it would be:

```
if((PositionX - Camera.PositionX) * Camera.LookAtX
    + (PositionY - Camera.PositionY) * Camera.LookAtY
    + (PositionZ - Camera.PositionZ) * Camera.LookAtZ
    < 0)

```
> 2 votes

# Answer
Test only (projected.W \< 0), not (Z \< 0 || W \< 0).

In some clip space formulations (*cough* OpenGL *cough*), the visible range includes positive and negative Z values, whereas W is always positive in front of the camera and negative behind.
> 0 votes

# Answer
```
float screenX = (((projectedVector.X / abs(projectedVector.W)) + 1.0f) / 2.0f) * viewportWidth;
float screenY = ((1.0f - (projectedVector.Y / abs(projectedVector.W))) / 2.0f) * viewportHeight;

```

And remove this part

```
// Invert X and Y when behind the camera
if (projectedVector.Z < 0 || projectedVector.W < 0)
{
    screenX = -screenX;
    screenY = -screenY;
}

```
> 0 votes

# Answer
Try a billboard, which will automatically make the pic face the camera, and will automatically draw the pic onto the screen at the proper location
> -2 votes

---
Tags: mathematics, projection, linear-algebra, projection-matrix
---


# Question
Title: How to achieve dotted trail behind moving object with use of Trail Renderer?
How can I achieve effect shown on picture below with use of Trail Renderer in 2D game? Is it even possible? I need dotted (dashed) trail behind my object and i can't figure it out.

don't know why stack can't load my images LINK HERE

Why trail renderer? Because I feel this is the right way to do this. Earlier, (Unity ver 5.3) I achieved this using: **Mesh Particle Emitter** \+ **Particle Animator** (Fade) + **Particle Renderer**, but sometimes it behaves strangely in multiplayer. Particles not always came out from object, sometimes they were offset. Anyway, Unity in ver. 5.5 released new component (TrailRenderer), which I would like to use (if it is possible to accomplish effect I need).

I am looking for efficient ways, so answers like "you can instantiate"dot" every X sec. at position of your moving object" ... Please no.

**What I have tried.**

I added to my gameobject a child (gameobject) with Trail Renderer. Then I put material into Materials array field.

Material shader currently is set to Mobile/Particles/Additive (I am targeting Mobile devices). Material Texture is:

don't know why stack can't load my images LINK HERE
I've tried different settings to accomplish my needs but with no success.

Trail Renderer -\> Texture Mode -\> Tile (my gameobject is followed by one dot and line)

Texture Import- \> Wrap mode -\> Repeat (my gameobject pulls dots without gaps behind instead leaving dots in place it was)

Also i tried different shaders, different Trail Renderer parameters with no success. Most of time, my gameobject is followed by stretched dot, line or dots without gaps which are pulled instead of left in place where object was.

# Answer
Here's the effect:

And here's the setup:

Texture on the shader is just a blurred dot made in photoshop. Here it is:

# Texture (it's really there, but it's white)

Attach this particle system to an empty `Gameobject` and make the `Gameobject` a child of your moving object. You can play with `Emission` and it's `Rate over time` to make the trail more 'filled'. Also, you can play with `Start lifetime` to make the trail longer. Change the `Color over lifetime` to make it disappear eariler, or fade-in/out these dots.

You can try to change the texture to anything else - it'll work.

And yes - it's efficient. 10 small objects with a Mobile/Blend shader won't really affect any device. Even if you spawn 10k of these. Maybe 5k :\>
> 1 votes

---
Tags: unity, trail-renderer
---


# Question
Title: How can I save a high score using PlayerPrefs?
I'd like to save the player's high score using Unity's `PlayerPrefs` API. This is the code I have so far:

```
public int coins;
public int score;
public int highscore;
public int points;
public Text pointsText;
public Text HighScore;
public Text Score;
public Text coinsText;

void start(){
    highscore = PlayerPrefs.GetInt ("HighScore");
}
void Update () {
    if(points > highscore){
        highscore = points;
        HighScore.text = ("HighScore: " + points);
        PlayerPrefs.SetInt ("HighScore", highscore);
        PlayerPrefs.Save ();
    }
    score = points;
    pointsText.text = ("x  " + points);

    Score.text = ("Score  " + points);
    PlayerPrefs.SetInt ("Score", points);

    coinsText.text = ("Coins  " + points);

}

```

However, it does not work. Every time I restart the game, the high score is 0 again. How can I make this work?

# Answer
The problem appears to be, as I noted in the comments originally, that you have a function called `start()` in your code (which I am presuming is a `MonoBehavior` class). C# is case-sensitive, however, and the MonoBehavior function that is invoked at the start is called `Start()` (with an upper-case "S").

Your `start()` function is likely not being called at all, which means the code to read the high score from the `PlayerPrefs` is never executed, at the high score remains at its default value of 0.
> 3 votes

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


# Question
Title: How to make one box Collider 2D go through another in Unity?
How can I make one Box Collider 2D go through another one in Unity? I tried this, but it seems to work only for ordinary Box Collider, but not for Box Collider 2D.

# Answer
You should use `Pyhsics2D.IgnoreCollision()` since Box Collider 2D inherits from **Collider2D**, not Collider. Found more info here, check this one out.
> 1 votes

---
Tags: unity, collision-avoidance
---


title: Antialiasing shader grid lines

text:
# Question
Title: Antialiasing shader grid lines
I would like to have in-game grid lines similar to ones found in Unity editor. There is simple solution(first listing) based on shaders found on unity forums(on right image). However, that solution does not take in account antialiasing and drawn lines looks terrible even few units away from camera.

```
float4 frag(vertexOutput input) : COLOR {
    if (frac(input.worldPos.x / _GridSpacing) < _GridThickness
        || frac(input.worldPos.z / _GridSpacing) < _GridThickness) {
        return _GridColour;
    }
    else return _BaseColour;
}

```

In order to address that, I tried using typical `fwidth`/`smoothstep` combination:

```
float4 frag(vertexOutput input) : COLOR{
    float distX = min(frac(input.worldPos.x / _GridSpacing), 1.0 - frac(input.worldPos.x / _GridSpacing));
    float distZ = min(frac(input.worldPos.z / _GridSpacing), 1.0 - frac(input.worldPos.z / _GridSpacing));
    float dist = min(distX, distZ);
    float delta = fwidth(dist);
    float alpha = smoothstep(_GridThickness - delta, _GridThickness, dist);
    return lerp(_GridColour, _BaseColour, alpha);
}

```

Even though it has nice fade, the result is not quite near to perfect - not only the lines looks thinner(which can be somewhat fixed by increasing width), but also have various artifacts(e.g. in joints) and horizontal lines disappear much sooner than vertical ones. Detail image(anti aliased on left):  I am interested in shader solutions, since according to answer to similar question relying textures there in can be no solution with textures. In addition I would like grid lines fade at reasonable distance(when closely inspecting aliased overview image you can see where plane ends) rather than continuing to infinity.
Full current version(for testing purposes) with signed distance.

# Answer
Here's an antialiased grid shader that seems to work pretty well.

The main difference is calculating a screenspace distance to the nearest gridline in each direction *separately*, and then taking the minimum of these two distances.

```
Shader "Unlit/Grid"
{
    Properties
    {
        _GridColour ("Grid Colour", color) = (1, 1, 1, 1)
        _BaseColour ("Base Colour", color) = (1, 1, 1, 0)
        _GridSpacing ("Grid Spacing", float) = 0.1
        _LineThickness ("Line Thickness", float) = 1
    }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent"}
        LOD 100

        Blend SrcAlpha OneMinusSrcAlpha
        ZWrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
            };

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

            fixed4 _GridColour;
            fixed4 _BaseColour;
            float _GridSpacing;
            float _LineThickness;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = mul(unity_ObjectToWorld, v.vertex).xz / _GridSpacing;

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                float2 wrapped = frac(i.uv) - 0.5f;
                float2 range = abs(wrapped);

                float2 speeds;
                /* // Euclidean norm gives slightly more even thickness on diagonals
                float4 deltas = float4(ddx(i.uv), ddy(i.uv));
                speeds = sqrt(float2(
                            dot(deltas.xz, deltas.xz),
                            dot(deltas.yw, deltas.yw)
                         ));
                */  // Cheaper Manhattan norm in fwidth slightly exaggerates thickness of diagonals
                speeds = fwidth(i.uv);

                float2 pixelRange = range/speeds;
                float lineWeight = saturate(min(pixelRange.x, pixelRange.y) - _LineThickness);

                return lerp(_GridColour, _BaseColour, lineWeight);
            }
            ENDCG
        }
    }
}

```
> 7 votes

---
Tags: unity, shaders
---


# Question
Title: Initiated a animation in unity via use of an animator component
I've written a coroutine that starts an animation.

```
GameObject.FindWithTag(names[number]).GetComponent<Animator>().StartPlayback();

```

This is the line of code that I wrote to start the animation. However, the animation does not start. I've even replaced the GameObject.FindWithTag(String) method with a reference to the actual object by declaring a GameObject in the script and setting it to a particular object in Unity's IDE. The animation still didn't start. Also, I must say the GameObject does have an animator component, you can see it in the inspector panel. No error messages can be seen in the console during play mode. What can I do to get the animation to play when I want it to play.

# Answer
> 1 votes
Apparently on this site I don't have enough "rep" to comment. Animators should begin playing automatically, so the problem is not with how you're "starting" it. Ensure that

-The animator component is enabled

-The game object is enabled

-The state you want to play is the default

-The animator isn't transitioning to another state at the beginning

Barring that, if you are trying to explicitly tell the animator what state to play, you need to name the state, not the name of the animation file.

---
Tags: unity, animation
---