# Question
Title: OpenGL Parallax Displacement Mapping Not Working
I am attempting to implement parallax displacement mapping into my OpenGL code but it is not working as it should.

https://i.stack.imgur.com/oHnhm.jpg

As I move around, double-lines moves around and if I am looking and positioned at just the right angle, the extra lines disappears and it looks like a normal texture, but without any displacement mapping.

I have tried various texture/displacement mapping combos and all of them have the same issue, so it is not my textures.

VS Code:

```
#version 330 core

layout (location = 0) in vec3 position;
layout (location = 1) in vec2 uvCoordinates;
layout (location = 2) in vec3 normal;
layout (location = 3) in vec3 tangent;

out Vertex
{

    vec3 position;
    vec2 uvCoordinates;
    vec3 normal;
    mat3 tbnMatrix;

} vertex;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

void main()
{

    gl_Position = projection * view * model * vec4(position, 1.0);

    vertex.position = (model * vec4(position, 1.0)).xyz;
    vertex.uvCoordinates = uvCoordinates;
    vertex.normal = normalize((model * vec4(normal, 0.0)).xyz);

    vec3 n = normalize((model * vec4(normal, 0.0)).xyz);
    vec3 t = normalize((model * vec4(tangent, 0.0)).xyz);

    t = normalize(t - dot(t, n) * n);

    vec3 b = cross(t, n);

    vertex.tbnMatrix = mat3(t, b, n);

}

```

FS Code:

```
#version 330 core

layout (location = 0) out vec4 color;

in Vertex
{

    vec3 position;
    vec2 uvCoordinates;
    vec3 normal;
    mat3 tbnMatrix;

} vertex;

struct Material
{

    vec3 ambientLight;
    vec3 diffuseLight;
    vec3 specularLight;
    float transparency;
    float shininess;
    int useDiffuse;
    int useSpecular;
    int useNormal;
    int useDisplacement;
    sampler2D diffuse;
    sampler2D specular;
    sampler2D normal;
    sampler2D displacement;

};

uniform vec3 ambientLight;

uniform vec3 eyePosition;

uniform Material material;

uniform float displacementScale;
uniform float displacementBias;

vec2 calculateTextureCoordinates(vec3 eyeDirection, vec2 uvCoordinates, mat3 tbnMatrix, sampler2D displacement)
{

  return uvCoordinates + (eyeDirection * tbnMatrix).xy * (texture(displacement, uvCoordinates).r * displacementScale + displacementBias);

}

void main()
{

    color = vec4(ambientLight * material.ambientLight, material.transparency);

    if(material.useDiffuse == 1)
    {

        vec2 uvCoordinates;

        if(material.useDisplacement == 1)
        {

            uvCoordinates = calculateTextureCoordinates(normalize(eyePosition - vertex.position), vertex.uvCoordinates, vertex.tbnMatrix, material.displacement);

        }
        else
        {

            uvCoordinates = vertex.uvCoordinates;

        }

        color *= texture(material.diffuse, uvCoordinates);

    }

}

```

I also have other lighting shaders that use the exact same tbn matrix to calculate normal mapping, which works just fine. This leads me to believe that both my tangent calculations and tbn matrix are working just fine. This scene is using no lighting, so lighting should have no impact on this code.

The displacementScale uniform is set to 0.04 and my displacementBias is set to -0.02. Increasing the scale causes the lines to become even more and more disoriented and decreasing it causes less of the disoriented effect but does not provide any displacement whatsoever.

I've also checked to make sure I have binded all my textures to the correct sampler2D and they are correct. I've been working on this for awhile now and I am completely stuck. Any help would be immensely appreciated.

# Answer
In order to properly implement this, you have to understand which "space" you are working in. In computer graphics, you have five discrete spaces to work in:

1. Object space. This is the un-transformed vertex coordinates.
2. Model, or World space, this is the position of a vertex when transformed into it's world position.
3. View space. This is the world, relative to the camera, or eye.
4. Projection, or screen space. This is when fragments get rasterised.
5. Tangent space. This is space relative to the texture coordinates. Call it UV space if you like.

In your example, we will ignore lighting, as it complicates matters.

In order to correctly displace the UV coordinates according to the view vector, you have to take your view vector, and transform it into tangent space, like so:

```
view_dir = eyePosition - (model * position).xyz;
TS_View = normalize(tbn * view_dir);

```

In doing so, when you perform your view direction calculations with uv coordinates, they are using the same coordinate system, and the displacement will be correct regardless of the orientation of the model.

You may find that it's still not quite right. If so, try flipping the sign of the y or x component of the view direction, by multiplying it by -1.
> 0 votes

---
Tags: opengl, glsl, displacement-mapping
---


# Question
Title: Make a glass cup look like it's full of water
I've been struggling to figure out a way to make a glass cup full of water, and since the cup is made of glass a plane on the top of the glasse won't really do it, so how can i go around making the glass looks like it's full of water?

# Answer
Actually recreating the effect would probably require raytracing, but you can fake it with a blur effect and a distortion that "blows up" the pixels behind your glass. It is especially convincing if you have a few simple shapes that use the effect (a glass, for example, is usually a cylinder or a truncated cone).
> 1 votes

---
Tags: unity, physics, shaders, water
---


# Question
Title: Unity Manual Instance Example Shader contains errors
The Unity Manual has a page on GPU instancing. One of the examples, titled "Adding instancing to vertex and fragment Shaders", causes the following errors to printed to the console when saved in a Shader file:

```
... unrecognized identifier 'UNITY_INSTANCING_BUFFER_START' at line ... (on d3d11)
... not enough actual parameters for macro 'UNITY_ACCESS_INSTANCED_PROP' at line ... (on d3d11)

```

This error message does not make any sense. The identifier is supposed to be created in the UnityInstancing.cginc file, if the render target is supported. This thing is, d3d11 **is supported**:

```
Line 211: #ifdef UNITY_INSTANCING_AOS
    #define UNITY_INSTANCING_BUFFER_START(buf)
    ...
    #define UNITY_INSTANCING_BUFFER_END(arr)
    ...
#endif

Line 41: #if defined(SHADER_API_D3D11) || ...
    #define UNITY_INSTANCING_AOS
#endif

```

**My question:**

Why does Unity say that these operations are not supported on this platform?

# Answer
> 0 votes
To solve this problem, I had a look at the copy of my (unaltered) UnityInstancing.cginc included with my own version of Unity. The `UNITY_INSTANCING_BUFFER_START` function does not exist in my copy, instead it is called `UNITY_INSTANCING_CBUFFER_START`. The `UNITY_ACCESS_INSTANCED_PROP` function also only takes one argument in my version.

To anybody who has similar problems with definitions not existing, I highly recommend looking at the file included with your version of unity. You may find, as I did, that the answer to your problem lies there!

---
Tags: unity, shaders
---


# Question
Title: How Can I See, Have, Use, and Not Compile Available Assets in Unity?
In short, I own a bunch of asset packages. I don't know what's in them until I bring them into Unity. Some of them have scripts that are not compatible with my current Unity build, but I may not care, I still want to see what I have and perhaps even fix them if I want them. My problem is that I'm having to import everything into my project just to see what I have and then further I can no longer run my project because these assets have compiler errors even though I'm not using them in my scene. So what can I do here? I don't want it compiled, using a "~" at the end of the folder as often suggested makes it disappear entirely so I can't even see the files, and yet I still want to see everything and choose what I want. Am I missing some process flow here? This really sucks.

# Answer
**Simple approach #1:** Version-control your project, add an asset, and decide if you want to keep it in place. If not, revert the changes. (This workflow is also good for isolating and evaluating updates to assets, which will frequently cause issues.)

**Simple approach #2:** Create an empty test project, import packages there, and evaluate. Then import into your real project as appropriate.

**Complex approach:**

Downloaded, not-yet-imported packages (`.unitypackage` files) should be located on your system as follows:

* Windows: `C:/Users/<username>/AppData(hidden)/Roaming/Unity/Asset Store`
* OSX: `Users/<username>/Library/Unity/Asset Store`

You can extract/view contents of these files using the process described here.

Gist is that the `.unitypackage` files are just renamed `.tar.gz` files, so you can extract them as usual. What you get seems to be a set of folders containing *one* or *three* files each. The folder names are 32-character hex strings (like `37526ede3c47c47d281bebffadfe4fd7`), corresponding to the asset's GUID inside Unity. (You can find these GUIDs in each file's `.meta` partner.)

If the GUID-y bit refers to what was a folder in the package, `pathname` is all you get. If it referred to any other kind of file (so far as I know), you get all three: `asset`, `metaData or asset.meta` , and `pathname`.

Folder contents:

* `pathname`: The path of the asset as a string.
* `asset`: The original file, renamed to `asset`.
* `metaData or asset.meta`: Not exactly sure what they do to the files, but these seem to be what you find in `<projectRoot>/Library/metadata`, under the GUID-based subfolders.
    + The GUID earlier would be under `.../metadata/37/`, with two files: `37526ede3c47c47d281bebffadfe4fd7` and `37526ede3c47c47d281bebffadfe4fd7.info`). The first one seems to be what gets added to the `.unitypackage`.
> 1 votes

---
Tags: unity, asset-management
---


# Question
Title: Compensate for animation time in multiplayer network game
I'm developing a multiplayer turn-based card game. In certain scenarios, the clients are required to perform an animation before moving on with the game. For example, the server informs the clients to animate dealing cards to all players. This animation takes around 5 seconds. Afterwards, the server informs a client to make a move, with a timer showing how long they have to play.

How can the server wait for the animation to finish before moving on and starting a timer and informing a client to play? The timer obviously needs to start after the animations are complete.

I've thought of the following:

1) Hardcode the animation durations on the server side and delay sending out the next message to the clients until after the duration of the animation.

2) Have the clients inform the server when an animation is complete.

..but I feel that there should be a better way.

Is there any other way to do this?

# Answer
Due to network latency, hard coding the animation duration on the server won’t necessarily work well. Especially if the animation could vary based on frame rate, or if the animation is skippable. What I have done before is have a general “grace period” timer of X seconds, which is long enough to accommodate any animation that might play plus a few seconds network latency. As soon as the client reaches the end of the animation, it notifies the server, whereupon the server continues gameplay. But if the server has not received the notification in time, it will either kick the player out or give other players an option to do so (with a few more seconds delay, just in case).

You can also get more complex by having the client send regular updates about its current state (eg. how far along it is in the animation), and the server can verify that the client is progressing in a timely manner. If the server stops receiving these updates, or the client does not seem to be progressing, the server can act accordingly, without having to wait for the end of the animation to tell whether the client has stopped responding.
> 0 votes

---
Tags: animation, networking, multiplayer
---


title: 3D Perspective issues

text:
# Question
Title: 3D Perspective issues
My team is currently developing a 3D Sidescroller game and we encountered some issues regarding the whole in-game perspective of the levels. The levels are composed of 3D modeled corridors which are specifically modified to simulate the effect of - 'immersive-depth'.

Example(Front View - InGame View):  Example(Side View - Angled Floor):  Example(Flat Floor Comparison - Angle vs No Angle)

The issues I spoken of are appearing at the moment I start adding 3D objects on the corridor, like lamps, crates, cabinets etc. They all seem off, due to the fact that the whole floor of the corridor is angled forward (even if the objects themselves are angled forward).

I know it seems like a strange question to ask but are there any smarter ways/alternatives of simulating the same depth of the corridor without angling it's floor?

P.S.

1) 2D is not an option. The camera isn't static.

2) Increasing the Angle of the camera on a flat floor doesn't simulate the same effect. The camera was meant to change dynamically in certain situations, via it's angles and position (up and down). The higher it is the more it resembles the perpendicular version. However, if the camera is lower, at a lower position and angle (on the same level as the floor is) the difference comes in place, due to the back walls being higher.

EDIT:

We've decided to stick with the 'flat'- 90 deg, floor, it's easier to maintain.

Although the Angled version is more entertaining, it is limited by the fact that increasing the depth - means increasing the angle, which at a certain point will generate an inadequate look.

# Answer
I think you can achieve this look with non-skewed / regular perpendicular walls & floors just by adjusting your camera.

Here's an example where I took your image and overlaid it in a scene with partial transparency, then arranged perpendicular cube primitives to form the corner of the room, and adjusted my camera settings, object positions & scales until the rendered scene matched the perspective of your image:

For this particular example I used a camera with the default 60 degree field of view, pitched downward 7.5 degrees to get the vertical lines to converge slightly. I used an oblique camera frustum to shift the rendered image vertically, so the horizon at the top of the wall sits close to the top of the screen. Doing it this way, we can control the vertical position of features on the screen without changing their shape from moving the perspective viewpoint.
> 1 votes

---
Tags: 3d, camera, level-design, perspective
---


# Question
Title: How to design prefabs in Entity Component Systems
In Unity (and I presume other game engines) you can create "prefabs" which are blueprints for game objects. They contain a list of components, and default values for those components. Prefabs can be instantiated many times, which is an efficient way of creating many objects of the same kind.

One feature in particular of prefabs is that you can modify an attribute on a single instance of a prefab, without modifying the prefab itself. Similarly, you can modify the prefab, which will propagate the change to all instances.

I've been working on an implementation of the Entity Component System (for a high-level description of ECS see this question: How to implement n-body in an Entity Component System), and I got stuck on how to implement prefabs efficiently in ECS. I think it's a powerful capability of EC-design, and implementing this on native ECS would be awesome.

I can come up with a few approaches:

* Create archetypes, which are predefined lists of components (Unity approach). This does not let me set initial values for the components, nor override them (there is nothing to override). Easy to implement, but doesn't really do what I want it to do.
* Create a "prototype" entity from which other entities are cloned, including component values. With this design I can override individual attributes, but when I update the prototype, the clones don't get updated.
* Create entities with a reference to a "base" entity. When getting a component from an entity, first look in its component list, then try the base entity. This way when I update a base component, base instances change as well. To override a base component I can simply add it to the instance entity.

Of these three approaches the third approach comes closest, but I don't see a straightforward way to extend it so I can override a single attribute. How can I make this work?

# Answer
The trick to this is that Unity's prefabs aren't strictly part of its component system (though they use features of components). They're part of its serialization system.

Try setting Unity's asset serialization mode to "Force Text" and examine a scene file in a text editor to see this in action.

The serialized version of a game object inside the scene references that object's prefab, as well as listing any parameters that have been overridden from the prefab.

When you open a scene, exit play mode, or make a change to a prefab, Unity's deserializer populates each of those instances by first creating a clone of the prefab's data (like your prototype example), then overwriting each parameter that the instance being deserialized overrides, as described in its serialized record.

The inspector can read this serialized data (or an equivalent in-memory structure) to know which fields to draw in the overridden style or inherited style. When you change an inherited field, it can be added as another override to record when serializing the instance. When you click "revert", Unity clears all override notes associated with the instance.

Nowhere in this process do the components themselves have any concept of inheritance or overriding of their fields. That layer can be applied completely external to the component system, used at runtime only when an object in a scene (or the new nested prefabs) needs to be deserialized. (Though this inheritance could presumably get "baked out" at build time and avoid any runtime inheritance of component parameters at all)
> 1 votes

---
Tags: unity, software-engineering, entity-component-system
---


title: Unity LWRP & Projection Shader

text:
# Question
Title: Unity LWRP & Projection Shader
I recently added the Lightweight Render Pipeline to my project as I'd like to start experimenting with Shadergraph to see if I can get a better basic understanding of shaders.

Everything has gone pretty smoothly except the Shader used by my Projectors, the Projection Shader Standard asset no longer works (does not project the texture) and I have very little experience with Shaders.

The main concern for me is that I cannot find anyone else who seems to be having this problem.

I have tried reading through the older shader and recreating it in ShaderGraph but I'm out of my depth.

So could anyone provide me with a simple projection shader or materials on where I could learn to write one, or just learn more about them projection specifically.

thanks

edit: To clarify I was using the Projectors to project a simple square texture on to each tile that I could tint, to show selectable/current/target tiles.

Old shader that no longer works under Lightweight Render Pipeline From DevGuy @ Unity Forums

```
// Upgrade NOTE: replaced '_Projector' with 'unity_Projector'
// Upgrade NOTE: replaced '_ProjectorClip' with 'unity_ProjectorClip'
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

  Shader "Projector/AdditiveTint" {
     Properties {
       _Color ("Tint Color", Color) = (1,1,1,1)
       _Attenuation ("Falloff", Range(0.0, 1.0)) = 1.0
       _ShadowTex ("Cookie", 2D) = "gray" {}
     }
     Subshader {
       Tags {"Queue"="Transparent"}
       Pass {
         ZWrite Off
         ColorMask RGB
         Blend SrcAlpha One // Additive blending
         Offset -1, -1

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

         struct v2f {
           float4 uvShadow : TEXCOORD0;
           float4 pos : SV_POSITION;
         };

         float4x4 unity_Projector;
         float4x4 unity_ProjectorClip;

         v2f vert (float4 vertex : POSITION)
         {
           v2f o;
           o.pos = UnityObjectToClipPos (vertex);
           o.uvShadow = mul (unity_Projector, vertex);
           return o;
         }

         sampler2D _ShadowTex;
         fixed4 _Color;
         float _Attenuation;

         fixed4 frag (v2f i) : SV_Target
         {
           // Apply alpha mask
           fixed4 texCookie = tex2Dproj (_ShadowTex, UNITY_PROJ_COORD(i.uvShadow));
           fixed4 outColor = _Color * texCookie.a;
           // Attenuation
           float depth = i.uvShadow.z; // [-1 (near), 1 (far)]
           return outColor * clamp(1.0 - abs(depth) + _Attenuation, 0.0, 1.0);
         }
         ENDCG
       }
     }
  }

```

# Answer
Sounds like exactly my situation that I've been looking into.

The new HD pipeline does have a decal projector that can give you the same effect. Though I am unsure of the overhead and if switching to the HD pipeline is worth it for this one effect. It takes a little tweaking to get it to work, but there is a discussion on it here: https://forum.unity.com/threads/deferred-decals-built-in-with-new-srp.514296/

Or, like people mentioned, you can use quads. In your case it would give you the same effect. But, if you have bumpy terrain, then your decal is either going to hover over parts of the terrain or clip into it.

Hopefully they will add something to solve this with LWRP. Though from all of the discussions that I've read with Unity devs, it seems unlikely.
> 1 votes

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


title: Unity assets turned binary from text

text:
# Question
Title: Unity assets turned binary from text
I'm working with unity and `git`, and for some reason, from some point - the assets started being `Binary` files, meaning that they're not visible as normal `YAML` files, and I cannot see textual `git diff` results on them.

Has anyone experiences it and knows how to revert to the textual format from the binary format?

# Answer
> 1 votes
https://stackoverflow.com/questions/47836334/convert-unity-settings-from-binary-to-text

This post has the answer. Apparently, I have some bugs with the unity editor that I've encountered, which show something in the Edtior, but is actually something different in the backend.

In my case, it was set to `Mixed` (Probably), while still showing `Force Text` in the `Edtior Settings`.

The fix was to set it to something other than `Force Text`, forcing it to reimport the assets,
And then, set it again to `Force Text`, forcing the assets to be reimported as `Text`. Hurray!

---
Tags: unity, git
---


title: OpenGL additive vertex color mode

text:
# Question
Title: OpenGL additive vertex color mode
Surely OpenGL has a way to set the vertex color mode. By default it is multiplication.

When I have an existing texture on a quad to represent a player in my game, I want to add color to it. As of now, doing so only multiplies the color with the texels on the quad. So if I have a color that represents bright light say (128,128,128) what I want is *additive* behavior: take the color in the texel and add the channels together.

I have not found anything to do this automatically in OpenGL without the use of shaders or including a second draw step on one sprite with a different blend mode to simulate this.

# Answer
The default (multiply) is specified by using (via the old fixed pipeline):

```
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

```

To change this to add, use:

```
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);

```

Some things to note.

* `GL_ADD` is *not* available in OpenGL 1.1; if you're limiting yourself to that version you will not be able to use this.
* This is almost certainly not what you actually wish to do; I'd encourage you to try it anyway, see what it looks like, and understand what happens and why; then come back and ask a follow-up question outlining your requirement.
> 2 votes

---
Tags: opengl, color
---


# Question
Title: Why loss of floating point precision makes rendered objects vibrate?
I'm working on an open-world game. I noticed glitches when I move far away from the origin. The objects seem to be shaking or wiggle. Especially the z-fighting seems to wiggle. And the objects that move. If I understand correctly this is caused by floating point precision problems. Currently I'm using floats for everything on CPU side and in shaders, I don't use doubles.

Before I try to come up with a solution I want to understand how does float imprecision lead to objects shaking on the screen. (Why do they shake instead of disappearing or stopping or something?) And where does the error come from: the calculations on CPU side (camera movement / physics calculations of objects) or calculations on GPU side (transform in shaders / depth-buffer not being precise enough)? Why do objects not shake when they are far away from the camera?

(I asked this before but realized my question was very broad, I wanted to be more specific.)

# Answer
> 18 votes
Quick recap (this is probably not news to you): a floating point number is broken into...

* A **sign bit** to distinguish positives & negatives
* Some **exponent bits** which tell us what broad range of numbers we're talking about (eg. 0.25-0.5, 0.5-1, 1-2, 2-4, 4-8...)

Note that the ranges double in size each time we take another step further from zero
* Some **mantissa bits** which address a specific number in that range.

00000000000000000000000 = lowest number in the range
11111111111111111111111 = last number before the start of the next range

For a 32-bit "single-precision" floating point number, we have 24 (23 stored + 1 implicit) of these mantissa bits to work with. That means in the range \\$\[2^n, 2^{n+1})\\$ we have \\$2^{23}\\$ representable numbers, spaced \\$2^{n-23}\\$ apart.

If we try to store a number that falls between two representable numbers, it gets rounded to the nearest one, making an error of up to \\$2^{n-24}\\$. That could, for example, nudge an object or vertex or camera position a little to the left or to the right of where it's supposed to be. This answer includes a table of what relative precision we have at various ranges from the origin.

Once we lose that precision in a calculation, we don't get it back if we later bring the result back closer to the origin - there are no bits left to encode that lost high-precision information, so it's not visible to any calculations downstream. This precision loss can snowball through repeated calculations, if we round a number, then use the rounded result to make a new number that also gets rounded...

There's also a phenomenon called "catastrophic cancellation" which can happen if we try to subtract two large numbers that are reasonably similar (like finding the offset between a camera 10 km from the origin, and an object 1 m away from the camera). Most of the bits in each object's position are talking about what they have in common (their 10 km offset from the origin) and fewer are left to talk about how they differ (the 1 m offset from the camera to the object). When we subtract them, the bits in common all cancel out and we're left with only a few significant digits in the result.

Where exactly this precision loss hits your game will depend on a lot of details of your setup and the exact order in which you apply your operations. A worst case would be transforming all your vertices to world space (so vertices far from the origin get rounded to a coarser grid of representable positions) before then transforming those worldspace vertices into view/screen space. If you combine these operations into a single matrix, you might be able to save some intermediate rounding and/or take advantage of higher precision available for intermediate results in processor registers. But even algorithms tuned for numerical stability will start showing rounding errors if you push them far enough.

It also depends on how you're looking at the content in question:

> Why do objects not shake when they are far away from the camera

They do, in the sense that their rendered position gets rounded away from their "true" position we might calculate if we had infinite precision available. But here perspective cameras save us: things very far away get drawn very small. That includes shrinking the size of the errors. And we have only a finite precision output to present: the number of pixels on the screen. At a long distance away, even a substantial error due to floating point precision might project to a difference much smaller than a single screen pixel, so we don't see any jitter or error in the rendered result.

But when the camera itself is a long way from the origin, then we can expect those rounding errors to occur for nearby objects as well, where a much smaller error projects to a pixel difference or more.

So that's the basic idea: a long way from the origin, the vectors we can represent with floating point numbers get sparser. When we want some specific vector (like the position of a vertex relative to the camera), we might be able to compute only a rounded result *close* to that desired vector.

As the object or the camera moves, this desired vector will change, and it might move from being close to one representable value to being close to another. At that point, the rounded result will snap to the new closest representable value, which can be visible as a discrete "pop." When our desired value hovers close to the threshold between two representable results (eg. when you have two very similar surfaces z-fighting), it might pop back and forth between one rounded value and another on consecutive frames, so it appears to jitter, vibrate, or dance in a distracting way.

See a high-res version of this visualization rendered in WebGL here

In this example, I'm visualizing the travel of a blue dot along a 2D plane in floating point coordinates. To make it easier to see, I'm using only 4 mantissa bits, so there are only 16 representable values within each exponent band. The grid lines represent representable x & y values, and the black dot tracks the closest representable point to the blue dot's true location.

Close to the origin, the two dots look like one, but as we go further out, the black representable point strays further and further from the blue source position, bouncing back & forth around it.

These effects can also creep in through the game's physics, limiting the precision with which the physics engine can apply impulses or integrate velocities, so what would have looked like a smooth diagonal movement close to the origin takes on a stairstep quality as an object's path snaps to the nearest representable positions. Or making an offset that would have correctly separated two penetrating objects close to the origin get rounded to a result that keeps them overlapping, leading to more corrections next frame that can make the objects appear to shake or swim through each other.

---
Tags: c++, rendering, floating-point, open-world, precision
---


# Question
Title: 2d water animation is jagged and not smooth
As a solution for this question I implemented the shader with a test program:

```
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.backends.lwjgl.LwjglApplication
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShaderProgram

class ShaderTestApp : ApplicationAdapter() {
  lateinit var batch: SpriteBatch
  lateinit var noiseTexture: Texture
  lateinit var sprite: Sprite
  lateinit var shaderProgram: ShaderProgram

  private val vertexShaderString = """
    attribute vec4 a_position;
    attribute vec4 a_color; //required by libgdx
    attribute vec2 a_texCoord0;

    uniform mat4 u_projTrans;

    varying vec4 v_color;
    varying vec2 v_texCoords;

    void main() {
      v_color = a_color;
      v_texCoords = a_texCoord0;
      gl_Position = u_projTrans * a_position;
    }
  """.trimIndent()

  private val fragmentShaderString = """
     #ifdef GL_ES
      precision mediump float;
  #endif

  varying vec4 v_color;
  varying vec2 v_texCoords;

  uniform sampler2D u_noise;
  uniform sampler2D u_texture;
  uniform mat4 u_projTrans;

  uniform float u_noise_scale;
  uniform vec2 u_noise_scroll_velocity;
  uniform float u_distortion;
  uniform float u_time;

  void main() {
          vec2 waveUV = v_texCoords * u_noise_scale;
          vec2 travel = u_noise_scroll_velocity * u_time;
          vec2 uv = v_texCoords;
          uv = uv + (u_distortion * (texture2D(u_noise, waveUV + travel).rgb - 0.5));
          waveUV += 0.2;
          uv = uv + (u_distortion * (texture2D(u_noise, waveUV - travel).rgb - 0.5));
          vec3 color = texture2D(u_texture, uv).rgb;
          gl_FragColor = vec4(color, 1.0);
  }
  """.trimIndent()

  override fun create() {
    batch = SpriteBatch()
    val img = Texture("background/water-surface-reflection-withBg.png")
    img.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat)
    noiseTexture = Texture("background/gradient.png")
    noiseTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat)
    sprite = Sprite(img)
    sprite.setSize(Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat())

    shaderProgram = ShaderProgram(vertexShaderString, fragmentShaderString)
    if (!shaderProgram.isCompiled) {
      println(shaderProgram.log)
    }
  }

  var time = 0f
  override fun render() {
    time += Gdx.graphics.deltaTime
    Gdx.gl.glClearColor(1f, 0f, 0f, 1f)
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)

    batch.begin()
    noiseTexture.bind()
    shaderProgram.setUniformf("u_noise_scale", 0.1f)
    shaderProgram.setUniform2fv("u_noise_scroll_velocity", floatArrayOf(.006f, .007f), 0, 2)
    shaderProgram.setUniformf("u_distortion", 0.04f)
    shaderProgram.setUniformf("u_time", time)
    batch.shader = shaderProgram
    batch.draw(sprite, sprite.x, sprite.y, sprite.width, sprite.height)
    batch.end()
  }
}

object ShaderTestLauncher {
  @JvmStatic
  fun main(arg: Array<String>) {
    val config = LwjglApplicationConfiguration()
    config.samples = 2
    config.width = 640
    config.height = 640
    LwjglApplication(ShaderTestApp(), config)
  }
}

```

Which looks like this:

# Answer
> 2 votes
After an input from DMGregory I added the following lines after instantiating all textures:

```
img.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)
noiseTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)

```

It looks perfect now.

Result as requested:

---
Tags: 2d, libgdx, animation, water
---


# Question
Title: Moving/spilling water inside a cup of glass
I made a glass of water but there are somethings i didnt know how to do well, what i did is i put a mesh on the top of the glass to represent the surface of the water but it doesnt really work well with glass because if you look from the sides you wont really see that there is water in there, this is what i did :

the glass from the side :

as you can see it doesnt really work well in my case. I also tried putting an object that has the same shape as the cup inside to represent water but that would make it difficult for what i want to do next, because my next step would be to make the water rotate in the opposite rotation of the cup and make it spill if it reaches the top of the cup, and that is my second question how do i make the water spill from the cup?

Any help is very much appreciated.

# Answer
you can use world space to make this effect:

> the transformation from object space to world space is put into a 4×4 matrix, which is also known as “model matrix” (since this transformation is also known as “model transformation”). This matrix is available in the uniform parameter unity\_ObjectToWorld, which is automatically defined by Unity in this way:
>
> ```
>  uniform float4x4 unity_ObjectToWorld;
>
> ```
>
> Since it is automatically defined, we don't need to define it (actually we must not). Instead we can use the uniform parameter unity\_ObjectToWorld without definition in the following shader: https://en.wikibooks.org/wiki/Cg\_Programming/Unity/Shading\_in\_World\_Space

```
Shader "Smkgames/WaterFill" {
       Properties{
           _Fill("Fill",Range(-1,1)) = 0
           _Pos("Pos",Vector) = (0,0,0,0)
       }
   SubShader {
      Pass {
         CGPROGRAM

         #pragma vertex vert
         #pragma fragment frag

         // uniform float4x4 unity_ObjectToWorld;
            // automatic definition of a Unity-specific uniform parameter

         struct vertexInput {
            float4 vertex : POSITION;
         };
         struct vertexOutput {
            float4 pos : SV_POSITION;
            float4 position_in_world_space : TEXCOORD0;
         };
        float _Fill;
        float4 _Pos;
         vertexOutput vert(vertexInput input)
         {
            vertexOutput output;

            output.pos =  UnityObjectToClipPos(input.vertex);
            output.position_in_world_space =
               mul(unity_ObjectToWorld, input.vertex)-_Pos;
               // transformation of input.vertex from object
               // coordinates to world coordinates;
            return output;
         }

         float4 frag(vertexOutput input) : COLOR
         {
            //  float dist = distance(input.position_in_world_space,
            //    float4(0.0, 0.0, 0.0, 1.0));
               // computes the distance between the fragment position
               // and the origin (the 4th coordinate should always be
               // 1 for points).

            if (input.position_in_world_space.y < _Fill)
            {
               return float4(0.0, 1.0, 0.0, 1.0);
                  // color near origin
            }
            else
            {
               return float4(0.1, 0.1, 0.1, 1.0);
                  // color far from origin
            }
         }

         ENDCG
      }
   }
}

```

then we need to send position waterfill shader attach this script to your object:

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

[ExecuteInEditMode]
public class WaterFill : MonoBehaviour {
    void Update () {
        GetComponent<MeshRenderer>().material.SetVector("_Pos",transform.position);
    }
}

```

I will update my answer and improve this shader
> 4 votes

---
Tags: unity, shaders, water
---


# Question
Title: My Java Game's movement looks awfull. Maybe Problem with Thread.sleep
I have a big problem with my Java games. In every game I make the movement of the player and objects just looks awfull. The framerate is 60 fps without any problems. But the movement looks extremly unsmooth. I tried several things but nothing worked. The game code is too long and unstructured to show the hole one but here are some parts that may cause the problem:

```
this.repaint();

//Framerate
try {
    Thread.sleep(15);
} catch (InterruptedException e) {
    e.printStackTrace();
}

```

and that's how I tested the framerate:

```
 //FPS anzeigen

    if(RaumNr >= 0){

        FPSCount += timesincelastframe;
        howoften ++;
        if(FPSCount > 1){
            FPSCount = 0;
            FPS = howoften;
            howoften = 0;
            System.out.println(FPS);
        }
    }

```

That's how my delta time system works:

```
 while(true){

        long thisframe = System.currentTimeMillis();
        timesincelastframe = ((float) (lastframe - thisframe)) / -1000f;
        lastframe = thisframe;

        if(!M.hasFocus())
            M.requestFocus();

```

and so on.

```
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2d.scale(BreiteMulti, HöheMulti);

```

And that's how I move the player for example:

```
 x -= 350 * timesincelastframe * speed;

```

I hope you have any ideas wht the problem might be. If you need more code examples please tell me.

# Answer
There are three problems here:

* When you call `Thread.sleep(15)` you forget to account for the time it took to calculate and render the previous frame. Before you suspend the thread, check how long it took to process the last frame, and subtract that number.
* `Thread.sleep(15)` does not mean "pause for exactly 15ms" it means "tell the OS thread scheduler to suspend the thread for at least 15ms and then unsuspend it as soon as it has the time". Also, unsuspending a thread is a costly operation which might take non-negligible time in itself. The result is that sleep might "oversleep" occasionally and pause a bit longer than you intended it to. A good way to deal with that is calculate the timecode where the next frame is supposed to start before you put the thread to sleep.
* `System.currentTimeMillis();` is not the most precise method to obtain a timestamp. Use `System.nanoTime();` instead. It returns the time in nanoseconds, not milliseconds. So you need to divide it by `1000000` to convert it to milliseconds.

To fix these three problems, you game loop might look like this:

```
    public static final long NANOSECONDS_PER_MILLISECOND = 1000000;
    public static final long MS_PER_FRAME;

    private long frameStart = System.nanoTime();

    while(gameIsRunning) {
         updateAndRenderTheGame();
         elapsedTime = (System.nanoTime() - frameStart) / NANOSECONDS_PER_MILLISECOND;
         frameStart = System.nanoTime() + MS_PER_FRAME * NANOSECONDS_PER_MILLISECOND;
         Thread.sleep(15 - elapsedTime);
    }

```

A fourth problem you might encounter is if you are using a variable timestep but handle your game mechanics with integers. If you do this, you will get a lot of jitter due to rounding errors. Use `float`'s or `double`'s instead. When you pass coordinates to the drawing API, then you might want to round them to integers to avoid blurring. But do not use the rounded values afterwards.
> 2 votes

---
Tags: java, movement, game-loop, multithreading, lag
---


# Question
Title: How to find points of a reflected 2d bezier curve about a line
Pardon me if this sounds primitive. I have created a bezier curve with control points A, B, C, D, which are known (see image below). How can I find control points B1, C1, D1 for a new bezier curve reflected in AR1 and A2, B2 and C2 for a new bezier curve reflected in DR2?

# Answer
> 2 votes
Take the line going through AR1, the equation of this lines is

```
(x-A.x)(R1.y-A.y)=(y-A.y)(R1.x-A.x)
(R1.y-A.y)x - (R1.x-A.x)y = A.x(R1.y-A.y)-A.y(R1.x-A.x)

```

So the normal vector of this line is `(R1.y-A.y, R1.x-A.x)`. This is the direction vector of the line perpendicular to it and since that goes through D, we can get the equation of that as well:

```
(R1.x-A.x)x-(R1.y-A.y)y=(R1.x-A.x)D.x-(R1.y-A.y)D.y

```

From this we isolate x for later use:

```
x = ((R1.x-A.x)D.x-((R1.y-A.y)(D.y+y))/(R1.x-A.x)
x = D.x - (R1.y-A.y)(D.y+y)/(R1.x-A.x)

```

Then we replace x in the other line's equation using this

```
(D.y+y)(R1.y-A.y)^2/(R1.x-A.x) - (R1.x-A.x)y = A.x(R1.y-A.y)-A.y(R1.x-A.x)

```

We then isolate y

```
y = (A.x(R1.y-A.y)-A.y(R1.x-A.x)-D.y*(R1.y-A.y)^2/(R1.x-A.x))/(R1.x-A.x+(R1.y-A.y)^2/(R1.x-A.x))

```

This is the only equation you actually need to implement.The right side should be given. After you find y, use it to calculate x using the

```
x = D.x - (R1.y-A.y)(D.y+y)/(R1.x-A.x)

```

equation

You should now have the coordinates of the closest point on the AR1 line to the D point (I suggest abstracting it and implementing a function, that given a line and a point does this, since you need to use it a couple of times). Now you just get the vector pointing from D to this new point, multiply it by 2 and add it to D to get D'. Repeat this process with C and B and you should have every control point.

---
Tags: unity
---


# Question
Title: Why do GPUs have limited amount of allocations?
I've been learning Vulkan lately and I read that you can allocate VRAM memory only set amount of times and it doesn't matter if it's 2gb or 2kb, why is it?

I'm specifically referring to `VkPhysicalDeviceLimits` structure which has a field `maxMemoryAllocationCount`.

# Answer
> 4 votes
**It's not correct to say that - as a general case - GPUs have a fixed limit on the number of allocations that may be made.**

What the Vulkan documentation for `VkPhysicalDeviceLimits` specifies is that:

> `maxMemoryAllocationCount` is the maximum number of device memory allocations, as created by vkAllocateMemory, which **can** simultaneously exist.

The key destinction here is that the limit only applies to *allocations that can simultaneously exist*. For example, if the maximum is 256, and if you have 256 simultaneous allocations, then you've obviously hit that maximum. However, if you subsequently free 128 of those, then you can obviously make a further 128 new allocations.

If we drill down further into the documentation for `vkAllocateMemory`, we find the following statement:

> The maximum number of valid memory allocations that **can** exist simultaneously within a `VkDevice` **may** be restricted by implementation- or platform-dependent limits.

This therefore tells us that the limit may be imposed by the hardware, by the driver or by the underlying OS, but also that *in some cases there may not be such a limit*.

Looking further at https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html in "Table 48. Required Limits" we find the entry for `maxMemoryAllocationCount` and we see that it specifies a required *minimum* value of 4096, with no specified maximum.

From this we can say that a Vulkan device is required to support at least 4096, but (once more) may also have no limit on the count of, simultaneous allocations.

This is obviously to enable Vulkan to be implemented on the widest possible range of hardware; hardware where such limits might exist and hardware where they might not.

**To wrap it all up**.

* Vulkan allows for the capability of drivers to restrict the number of simultaneous allocations that may exist.
* This restriction is just on the number of simultaneous allocations, not the absolute number of total allocations.
* Vulkan also allows for this number to be unrestricted.
* Whether the number is restricted or not depends on the individual implementation.
* This is a Vulkan-specific feature which may not exist in other APIs.

---
Tags: graphics-programming, gpu, vulkan
---


# Question
Title: How can I make 3D games in 4K that are a few megabytes?
I would like to make 3D games in 4K that are a few Megabytes (MB) in download size.

Is there a way to use 3D Vector Graphics in games to reduce the file size ? Or is there any other way to achieve the same level of compression achieved by Flash(.swf) and Swift3D ?

# Answer
There are ways to make nice 3d graphics with low memory footprint, however that requires you to have the right experience and knowledge. There are games like .kkrieger which is a 3d first person shooter, with the size of a few kilobytes.

This is not just compression algorithms. You can't just make a massive game and press a button and suddenly its 100kb, that's not how it works.

Also you have to make the right balance between quality and file size. Sure we all want an HD experience with realistic graphics and very low memory requirements, but the higher quality, the heavier it gets.

Here are a few tricks:

* **Procedural generation**: The more data you generate on the fly, the less data need to be saved on the disk. Instead of having a massive static world, it's lighter (filesize-wise) to have a randomly generated one.
* **Repeating assets**: Have objects share the same textures, maybe switch some material settings to make them look different. For example, imagine you have one texture for the ground, one for the walls, and one for the ceiling. You can theoretically make an dungeon roguelike game, that has infinite size, because it keeps adding new rooms that are fully textured.
* **Custom Engine**: Game engines try to be as abstract as possible, to allow users to create a big variety of games. Unfortunately this comes with an overhead, that can't be avoided. Using a custom engine would ensure that there's not that many unnecessary data, and that everything is optimised to your needs. (Thanks @Sidar)
> 53 votes

---
Tags: 3d, architecture, flash, swf
---


title: Correctly drag object with mouse

text:
# Question
Title: Correctly drag object with mouse
I already have a `MouseMotionListener` with the `mouseDragged` method implemented. I can drag an object with the mouse, but it doesn't matter where I put the mouse inside the object, it will move it's origin point to the mouse.

I know that this is what the simple `x = mouseX; y = mouseY` code should do, but what is the code to drag the object relative to the position of the mouse inside the shape?

I tried this, but it doesn't work when the object is in the position 0:

```
x = mouseX - (mouseX - x);
y = mouseY - (mouseY - y);

```

The code doesn't work because when X and Y are 0, it is basically `x = mouseX - mouseX; y = mouseY - mouseY`, that is 0 both. What is the algorithm that is "0-pos-proof" that I can use?

# Answer
I believe you should ignore the position of the mouse and the game object while moving, they should not really make any difference, right? Focus on just offseting the game object's position acording to how much the mouse has moved while the button is pressed.

EX:

```
 public void Update()
{
    if(Input.GetMouseButton(1) && isDragging)
    {
        transform.Translate(Input.GetAxis("Horizontal") * Time.deltaTime, Input.GetAxis("Vertical") * Time.deltaTime, 0);
    }
}

```

I really don't know if this code will work, just hope it helps you.
> 0 votes

---
Tags: java, textures
---


# Question
Title: Function is not showing up in the OnClick editor
I'm just a beginner and I am currently having problems with the OnClick editor. I already drag and dropped my script to an empty gameobject and dragged that game object to the OnClick editor but still my function of "Pause" won't show up even if I already have it set to public. Please help

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

public class uiManager : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }
    public void Pause() {

        if (Time.timeScale == 1) {
            Time.timeScale == 0;
        }
        else if (Time.timeScale == 0) {
            Time.timeScale == 1;
        }
    }
}

```

# Answer
> 2 votes
Based on your screenshot, you have an error in your `uiManager` script. The function will not appear in the inspector until you resolve this error.

The problem is in your if/else statement. You are trying to use `==` to assign a value to `Time.timeScale`. You should use the assignment operator, `=`, as seen below.

```
if (Time.timeScale == 1)
{
    Time.timeScale = 0;
}
else if (Time.timeScale == 0)
{
    Time.timeScale = 1;
}

```

Once you make this correction, save the script. Then open Unity and press ctrl+s to save it. This will force the editor to update the list of functions available for OnClick().

---
Tags: unity
---


# Question
Title: Implementing multiplayer aspect of a simple HTML5 game
I've been thinking about this a lot. I am trying to implement a simple multiplayer game but I have difficulty figuring out how to "share the scene". For example, there are non-player entities like trucks and ideally I am thinking I will just send all the connected clients the bus location (x,y) and the rotation angle ,however, I am running into difficulty because the bus rotates each frame so I am wondering how I may achieve that on server-side?

It seems like a really tough nut to crack and I went over countless examples online and I think I just can't conceptually clarify how something like that can be accomplished.

Any ideas will be very appreciated.

EDIT: Somewhat related simplified question is this. **How to simulate animation by sending (x,y, angle) from the server to the clients?** Is it with setTimeout() on the server-side, what about each client having different frame-rate on their end?

EDIT2: Just to give one more example which I think would clarify. Consider a rotating triangle that all players should see. How do you accomplish this, do you adjust the angle in the server part of the code and then just emit to all players, because then the server side of code needs an `update()` for that object. Damn I hope I am not poorly expressing myself.

# Answer
I remember struggling with the same thing actually and here it is. I figured it out not long time ago. I will use the rotating triangle as an example. The server is the one that needs to figure out that the triangle needs to start rotating. The triangle should have two things:

* Rotation
* Rotation velocity

Now, let's say that the every client has it's own triangle. There are two triangles on the screen, yours and your opponents.

When you press the button to start rotating, you need to tell the server that you want to start rotating. When the server finds out, the server needs to change the rotation velocity and continue updating the angle of the triangle. Also, it needs to inform the clients about the triangles rotation. 10 times a second(or it can be less, it depends), the server needs to send the rotation angle to all the clients.

That way the rotation on the clients will update 10 times a second. Now, the only thing that is left is interpolation. The server, instead of just sending the angle, it should send the velocity too. Then the client can use the velocity and simulate it for itself and make it update at the frame it's running on. When the next packet arrives, it just sets the new position and the new velocity that the server said and keeps interpolating.

That is basically it. There are a few links that helped me understand this:

https://gafferongames.com/post/what\_every\_programmer\_needs\_to\_know\_about\_game\_networking/

https://www.cakesolutions.net/teamblogs/how-does-multiplayer-game-sync-their-state-part-1

> Damn I hope I am not poorly expressing myself.

Sometimes I suck at it too and hope I didn't poorly express myself either haha. That's why I provided those links.

Good luck.
> 2 votes

# Answer
Two things for sure,

(1) You'll NEVER get satisfactory results by pumping out a sequence of precisely timed commands. You have to program the behavior to operate mostly autonomously at the client's end

(2) Clients will not agree on the relationship between events they see and their reactions. In other words, client A sees a spaceship appear and shoots it, client B sees client A was able to shoot before the ship even appeared.
> -1 votes

---
Tags: multiplayer, html5, node.js
---


# Question
Title: How to manage ammo when firing and reloading
I have this script and I need to fix one thing which is count correctly the number of bullets I have.

```
public GameObject ebullet;
public Transform Bullet_position, target;

public int ammo = 200;
public int ammo_Hold = 600;
public bool reload = false;
public bool readyToShoot;

// Update is called once per frame
void Update()
{

    if (ammo == 0)
    {
        ammo_Hold = ammo_Hold - 200;
        ammo = 200;
    }

    if (reload == true && ammo_Hold >=0)
    {
        ammo_Hold = ammo_Hold - ammo;
        reload = false;
    }

    if (readyToShoot == true)
    {

        Quaternion rotation = Quaternion.LookRotation(target.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 5.0f);

        GameObject bullets = Instantiate(ebullet) as GameObject;
        bullets.transform.position = Bullet_position.transform.position * 1;
        Rigidbody rb = bullets.GetComponent<Rigidbody>();
        rb.velocity = transform.forward * 100;
        Destroy(bullets, 2f);
        ammo--;

    }
    else
    {
        print("Don't Shoot");
    }

} // end update

```

# Answer
> 2 votes
If I understand your code correctly, I believe you are using `ammo` as the ammo that has been loaded, and `ammo_Hold` as the ammo remaining in the player's inventory. So the player should be able to fire 200 rounds before they have to reload, and they can do this up to 4 times since they have 200 rounds + 600 in the inventory. Please correct me if I have this wrong. I made some slight modifications to your code below without overhauling how it was written.

First of all, you want a variable to keep track of the magazine size. In your case, it is 200. We will call this `magazineSize`. When the player reloads, you want to subtract the number of rounds that were used from `ammo_Hold`. As it is written, you are subtracting the number of *unused rounds* from the player's inventory. We can use `(magazineSize - ammo)` to figure out the number of rounds that were used. Also, add a check to avoid ammo\_Hold from going negative.

```
if (reload == true && ammo_Hold >=0)
{
    if (ammo_Hold >= (magazineSize - ammo))
    {
        ammo = magazineSize;
        ammo_Hold = ammo_Hold - (magazineSize - ammo);
    }
    else
    {
        ammo = ammo + ammo_Hold;
        ammo_Hold = 0;
    }

    reload = false;
}

```

Also, when ammo reaches 0 I don't think you want to blindly load the player's gun with 200 rounds. You want to add as much to `ammo` as you can without going over how much you have remaining in `ammo_Hold`. Add a simple check to handle this.

```
if (ammo == 0)
{
    if (ammo_Hold < magazineSize)
    {
        ammo = ammo_Hold;
        ammo_Hold = 0;
    }
    else
    {
        ammo = magazineSize;
        ammo_Hold = ammo_Hold - magazineSize;
    }
}

```

Finally, you should add a check to see if you have any ammo available before firing.

```
if (readyToShoot == true && ammo > 0)

```

**Complete Code:**

```
public GameObject ebullet;
public Transform Bullet_position, target;

public int magazineSize = 200;
public int ammo = 200;
public int ammo_Hold = 600;
public bool reload = false;
public bool readyToShoot;

// Update is called once per frame
void Update()
{

    if (ammo == 0)
    {
        if (ammo_Hold < magazineSize)
        {
            ammo = ammo_Hold;
            ammo_Hold = 0;
        }
        else
        {
            ammo = magazineSize;
            ammo_Hold = ammo_Hold - magazineSize;
        }
    }

    if (reload == true && ammo_Hold >=0)
    {
        if (ammo_Hold >= (magazineSize - ammo)) //Check if you have enough ammo to do a full reload.
        {
            ammo = magazineSize;
            ammo_Hold = ammo_Hold - (magazineSize - ammo);
        }
        else
        {
            ammo = ammo + ammo_Hold;
            ammo_Hold = 0;
        }

        reload = false;
    }

    if (readyToShoot == true && ammo > 0)
    {

        Quaternion rotation = Quaternion.LookRotation(target.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 5.0f);

        GameObject bullets = Instantiate(ebullet) as GameObject;
        bullets.transform.position = Bullet_position.transform.position * 1;
        Rigidbody rb = bullets.GetComponent<Rigidbody>();
        rb.velocity = transform.forward * 100;
        Destroy(bullets, 2f);
        ammo--;

    }
    else
    {
        print("Don't Shoot");
    }

} // end update

```

# Answer
> 1 votes
```
if (ammo == 0)
{
    ammo_Hold = ammo_Hold - 200;
    ammo = 200;
}

```

If ammo\_Hold is not a multiple of 200 it will break.

```
if (reload == true && ammo_Hold >=0)

```

Not really important and it comes to preference I think but `reload` is a boolean so basically you check `true == true` or `false == true`, so instead you can just type `if (reload && ammo_Hold >=0)`.

```
if (readyToShoot == true)

```

Same thing. Also I don't where you set it to be true.

Another thing, you use `Update` instead of `fixedUpdate`, this means someone with a higher frameRate can shoot faster then someone with a lower frameRate.

About the question... It would be better to work with timing. It happens that the unity time example is also about shooting!

https://docs.unity3d.com/ScriptReference/Time-time.html

In case the docs ever break, here (part of) the code referenced from the link.

```
public class ExampleClass : MonoBehaviour {
    public GameObject projectile;
    public float fireRate = 0.5F;
    private float nextFire = 0.0F;
    void Update() {
        if (Input.GetButton("Fire1") && Time.time > nextFire) {
            nextFire = Time.time + fireRate;
            GameObject clone = Instantiate(projectile, transform.position, transform.rotation) as GameObject;
        }
    }
}

```

Now you are back to the bullet problem again. Before you shoot you can check if `Ammo > 0`. Within the shooting you can check if it reaches 0. If it does I would set a boolean `reload_required` to `true`. But I leave that up to you as an exercise. I hope it helps.

---
Tags: unity
---


# Question
Title: Realtime Multiplayer - How to handle user updates coming in different times
I have a game loop that sends new positions of every player to other players.

But there is no guarantee that the users will send the server their new positions at the same time. Actually if their connection is slow or some errors happen inbetween, then the data of the clients will flow to the server in a very varying way for every other user.

My question is, how should I handle so varying data on the server, and decide who should win in a fast-paced multiplayer game. Is the key, timestamp of the requests (seems like it is widely open to cheating), or just the clients sending me directions where they go, and their actions like pressing a button etc?

I've read lots of articles on the web, but none of them seems to completely cover the subject.

PS: I just want to decide on the server side, what should be the next 'frame' in the game by applying the game scenario to the user inputs.

# Answer
> 1 votes
Common approach, as you suggested yourself, is to make clients send only their inputs and view angle(for FPS games), then handle all events on a server and send updated information back to the clients. However, with this approach player could experience very unresposive controls due to ping. This could be solved by using server data only as a synchronization fallback in case of a big deviance from the server state and calculating game information in parallel to the server. For example, you could let player move freely on the client side and send his inputs to the server. Then every packet you check if difference between server state and client state is too big and move player accordingly to synchronize client and server. Also, predicting movement of the opponents is a good way to hide most of the problems you encounter with bad server-client connections.

---
Tags: javascript, multiplayer
---


title: Pros and cons of randomised item stats?

text:
# Question
Title: Pros and cons of randomised item stats?
I'm working on an old-style isometric RPG like the early Diablo or Fallout games. It has a central story with branching paths, and a lot of player freedom to explore the open world. The combat system is pretty integral to the game as well, considering the number of spells, attacks and enemies I'm hoping to add.

Currently I'm wondering whether I should have fixed item stats, or have them randomised within a given range (say, +-0-10% from a given value). But I can only see disadvantages with the randomised stats system. If the range is too large it'll become grindy, and if it's too small it'll become irrelevant.

Could someone give me a list of the pros and cons for each approach?

# Answer
The advantage of randomizing item stats is that it is a cheap way to get more content and more variety. But even if you spend a lot of time into fine-tuning your generation algorithms, procedurally generated content will never reach the quality of hand-designed content. So you are trading quality for quantity here.

When you have a large number of items with similar stats, **you invite the player to compare their numbers and meta-game**. The player will have to decide whether the weapon with +16 base damage, +10 accuracy or +5% attack speed is the better choice. In order to make that call, the player needs to gain a deeper understanding of your game mechanics.

The question is *do you want this*? There are players who like to treat games like mathematical puzzles. I can understand the appeal in this. It appeals to me, too. But there are also players who do not want to play number games. They just want to pick up the weapon which looks and feels cool, have a good time with it and get immersed in the game's narrative. Which demographic you want to focus on is your decision. It is an important decision to make, because it greatly affects your UI design.

Another aspect of randomized items is that **the game experience becomes less planned**. This is a double-edged sword. On the one hand, this increases replayability. The player can play the game multiple times and will have a different game experience each time because the different items they got during their run will mean that they will have to approach problems in a different manner.

But on the other hand, this uncertainty makes it harder for you as a designer to fine-tune the game experience. You can not rely on the player having or not having specific equipment at a specific stage of the game. That makes it harder for you to anticipate how difficult a combat encounters will be and how the player will approach it. The player might be lucky, find a ridiculously overpowered item and the game becomes far too easy and far too monotonous. Or the player might be unlucky, not find the stuff their character build relies on and get stuck. Both result in bad game experiences you can avoid by deciding yourself when the player receives which item. You also have problems with balancing rewards. When the player accomplishes something awesome, you will want to reward them with some loot. But when your loot is randomly-generated, then the reward for a major accomplisment might turn out to be useless junk while the reward for a minor random encounter turns out to be far too good.

By the way: Extra Credits made a video about this topic you might find interesting.
> 2 votes

# Answer
You can certainly do randomised stats, as long as you make sure the weapons are still balanced.

Depending on how the rest of the game goes, think of it this way: whenever an item appears, randomise its stats. For each point of damage it loses, it gains one point in speed. This creates weapons which are random, but still balanced, and also makes the player pick a weapon based on their strategy (some like attacking speed, some damage etc).

You can also make items which are stronger (like uncommon or rare in some games) that have better stats, like for each point of damage it loses, it gains 2 points in speed.

To answer your question:

Pros:

* Bigger variety of weapons, which makes grinding more fun

Cos:

* It takes time to create a nice balancing algorithm to apply to the weapons. In my example I assumed that `1 damage == 1 speed` but that is not true for all games, it varies greatly with gameplay and other factors.
* You have slightly less control over how powerful the player is. Obviously you can control the randomness of the stats, but there is a chance the first enemy killed will give the player either the worst weapon that it can drop, or the best, so you now have to balance the rest of the level to accommodate both players. Since its not their fault, they shouldn't be punished.

Is it worth it? The cons indicate that you need to spend more time to think of a good approach, if you are willing to do that, the result is better, if however you are unsure or don't have the right experience, maybe it would be easier to start with a simpler mechanism for weapons.
> 1 votes

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


# Question
Title: Pros and Cons of making one complex mesh vs more simpler ones
Looks like I have a problem with basic understanding of how OpenGL works. Lets say I have a mesh made out of three cylinders that is shown on the picture:

So are there any major difference in performance/memory if I make three different cylinder objects or one object made out of three cylinders? Well, if I make them separately with OpenGL, there would obviously be memory overhead because I repeat vertices for each of these cylinders in the middle (section area). That I can see. But, what about difference between having one big vertex shader vs having more smaller ones? Lets say we have 20 objects in the scene. Are their vertex shaders all sent separately to the GPU or are they all collected and sent together? If they are sent separately should that be slower than making one big vertex shader that will have to be sent to the GPU at once?

Second part is question about UV-s. Lets say all three cylinders have same texture, or one cylinder has half of the texture and second braching parts have second half of the texture. If I make an object containing all cylinders then obviously I would have to define UV array only for each of my vertices. Taking this into consideration are there any memory/performance issues if I use values for U and V greater than 1. For instance "lower" vertices of cylinder down would have V = 0, "upper" would have V = 1, and "upper" vertices of cylinder up would have V = 2. Does usage of UVs coordinates greater than 1 have any influence on performance or does the OpenGL only do basic rescaling? However, if I use same texture on each cylinder that are made separately then I would have to make UV array only once and just reuse it for each cylinder. Again I'm not sure what is the better option

Basically, lets say branching in this picture is repeated, like in a tree structure. What are the pros and cons of making a whole tree as one object and making it as a collection of a lot of small branches, besides simplicity of second option?

# Answer
> 1 votes
For the first part, it depends on rendering pipeline and/or the game engine. If you choose to make them separate, engine *could* load them as a different subsets/objects and perform frustum culling, so only visible parts are rendered. In terms of memory, not a big difference, and neither in terms of speed, for modern hardware. (But again, it depends - could be a great deal if you're doing it for an ancient console or hardware.)

For the second part, I'd suggest you to stick with UV in \[0; 1\] range, because OpenGL sampler would require repeat to be enabled, otherwise your model would look weird on parts where your UV's are out of the range. But if you're sure about what you're doing (meaning that you're under control of texture sampling mode), tiled textures are usually achieved through UV's being scaled, meaning they are out of \[0; 1\] range, obviously. Regarding performance, again, I don't think there's that big of a difference. In theory, there could be made some optimisations if tiling is disabled on a sampler, but I have no idea if some OpenGL implementations actually do them, very low-level stuff here, and implementation dependent.

# Answer
> 0 votes
The real question is, why would you want to create separate simple objects? If there is no reason, creating one complex one sounds like the best solution, so you have one object to worry about, which makes it more maintainable.

If for any reason you want to have separate objects (to animate them manually, or for any other reason) then you should have them separate, but they'd be harder to maintain, as now you have more objects in your scene.

Performance-wise you won't notice any difference, sure using 10 extra vertices costs some memory, but considering modern games have millions of vertices, this shouldn't be noticeable. CPU-wise you don't really get any penalty, you draw the same amount of triangles (assuming the two separate objects connect perfectly), so the same amount of pixels on the screen are being drawn. You may get an overhead if you execute more drawing calls, but that really depends on the game engine / graphics library.

For the UV part, I'm not sure if I understand it correctly, but when you have UVs greater than 1 there isn't any important penalty in performance, and the behaviour depends on the engine / library that you use. For instance, OpenGL has the `GL_REPEAT` flag, so if you have UVs greater than 1, the texture simply repeats itself like tiles. So `U = 2;` and `V = 2;` would mean that the texture would be drawn 2 times horizontally and 2 times vertically.

---
Tags: opengl, c++, textures, 3dsmax, maya
---


# Question
Title: How can I implement a revealing light beam?
In SEARCHLIGHT, you control a ray of light that illuminates incoming enemies that are otherwise invisible in the night sky. Here is an illustration:

How would I go about doing this, preferably in Unity? I imagine this is less about lighting and more about shaders, but I'm not sure on details. The fact that I know very little about coding shaders makes it worse.

If it *is* about shaders, what are the specifics? Is there a stretched quad that moves with said shader applied to it, or perhaps is using the Line Renderer a better option?

As a beginner, may I try to achieve a similar effect, or should I leave it for when I'm better?

(P.S.: The game was made in Unity. Here is its itch.io page.)

# Answer
One way to implement an effect like this is with the stencil buffer.

This is an extra few bits the renderer keeps around for every pixel in a render target, that you can use for scratch notes about what you've drawn there or are allowed to draw later.

You can create a new shader using one of Unity's built-in templates, and add some stencil operations to the top of the `SubShader` or `Pass` section:

```
Stencil {
    Ref 1
    Comp always
    Pass replace
}

```

This says "write a 1 into the stencil buffer, no matter what was there before" - put this on the shader/material that you use to render your light beam quad, and it will mark all the on-screen pixels it's touched.

Then, for objects that should only show up inside the light beam, use:

```
Stencil {
    Ref 1
    Comp equal
}

```

This checks to see if the magic number 1 got written into this pixel previously (ie. is this pixel illuminated by the light beam?) - if not, the shader aborts rendering this pixel of the object, neatly clipping it to just the illuminated region of your screen.

Make sure your objects that read the stencil information render later in the queues than the objects that write it, so the information is ready for them when they look for it.
> 9 votes

---
Tags: unity, 2d, shaders, lighting
---


# Question
Title: Turn Based Game - Best approach for Server communication. TCP/IP or REST API?
I want to create a turn base multiplayer game where each player simultaneously takes his/her actions, and ends the turn. Both will see what the other player did afterwards and the next round begins.

Think of it as some kind of chess, but both players take turns at the same time without seeing it until both end their turn.

I though about a server software that creates direct TCP/IP connections to both players and communicates the necessary stuff like what the other player did, who lost/won ect. The usual stuff.

But thinking of TCP/IP port limitations this could mean a limitation of about 65000+ users per server? Meaning 32500 active matches per server?

Then I thought about some kind of dispatcher. Like a REST API server that generates a unique game id and all players call the service with their ID (e,g transferring everything with JSON or some binary data).

I am not quite sure which approach is the better one. Maybe I am wrong at some point? Running a background service for each match seems to be my approach for both solutions (GameManager Class instance creation or a new process gets started communicating via named pipes or localhost). Maybe someone has some experience with this or another great idea? :)

# Answer
> 4 votes
First of all, 65000 peak current users is quite a lot. Many games don't even get near that number. Looking at the current player stats on Steam, there are just 7 games which broke that limit today. And if you think you are playing in the same league as CS:GO, DOTA 2 or PUBG, then you should be able to afford more than one gameserver.

But the number of available TCP ports is not a problem for the server anyway. The server only needs one open port per server application which is running on it. The number of simultaneous clients connected to the same server-sided port is unlimited. The 65000 port limit is only relevant for *outgoing* connections or if you want to run multiple servers on the same host.

Considering that there will be intervals of several seconds where no communication happens between client and server (an eternity for a large-scale client/server application), a REST API seems like a viable approach. You could even suspend the game-state to the database and only get it out after everyone sent their move.

But there is one problem: You might not be able to build your game without any push-events whatsoever. There will be some cases where you want to tell the player something while they are making their moves. For example that the opponent left the game or that all other players made their moves and are waiting for them to finally make up their mind about theirs. Or maybe you want to have chat? Push-events either require to maintain a network connection or that the player acts as a server. Many players might not be able to act as servers, because they are behind a NAT router. So the only solution is to keep the TCP connection with the player alive.

---
Tags: architecture, networking, multiplayer, turn-based
---


# Question
Title: Preparing A Grid in Unity (Procedurally)
I am trying to create a grid. But the renderer only renders ONE cell of the grid.

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

public class Cell
{
    public List<Vector3> Vertices;
    public List<int> Triangles;

    public Cell(int x, int y)
    {
        Vertices = new List<Vector3>();
        Triangles = new List<int>();

        Vertices.Add(new Vector3(x - 1, y + 1, 0));
        Vertices.Add(new Vector3(x + 1, y + 1, 0));
        Vertices.Add(new Vector3(x + 1, y - 1, 0));
        Vertices.Add(new Vector3(x - 1, y - 1, 0));

        Triangles.Add(0);
        Triangles.Add(1);
        Triangles.Add(3);
        Triangles.Add(1);
        Triangles.Add(2);
        Triangles.Add(3);
    }
}

public class GridComponent : MonoBehaviour
{
    public int resolution = 8;

    List<Cell> cells = new List<Cell>();

    List<Vector3> gridVertices;
    List<int> gridTriangles;

    Mesh gridMesh;

    void Awake()
    {
        gridMesh = GetComponent<MeshFilter>().mesh;
    }

    void Start()
    {
        gridVertices = new List<Vector3>();
        gridTriangles = new List<int>();

        for (int x = 0; x < resolution; x++)
        {
            for (int y = 0; y < resolution; y++)
            {
                Cell cell = new Cell(x, y);
                cells.Add(cell);
            }
        }

        foreach (Cell cell in cells)
        {
            foreach (Vector3 vertex in cell.Vertices)
            {
                gridVertices.Add(vertex);
            }
            foreach (int triangle in cell.Triangles)
            {
                gridTriangles.Add(triangle);
            }
        }

        gridMesh.vertices = gridVertices.ToArray();
        gridMesh.triangles = gridTriangles.ToArray();
    }
}

```

# Answer
> 0 votes
Actually, this doesn't render one cell. Not really at least, it renders the same single identical cell resolution * resolution times.

Let me first say something about the creation of a new Cell object for every cell. You don't need that, it doesn't actually provide anything *good*. It causes a ton of memory allocations that will then all be destroyed, don't do that but instead just write a Cell method that takes the list of vertices, list of triangles and the start coordinates.

But on to why you're rendering one cell, resolution * resolution times. If you enter the debugger and view what your triangles list has at the end of it, you'll see that it's a repetition of "0, 1, 2, 1, 2, 3".

Just because you put the indices and vertices in a different object for a moment does not mean that the 0 from `cells[10].triangles[0]` refers to `cells[10].vertices[0]`, it will just refer to `gridVertices[0]`, which happens to be copied from `cells[0]`.

You'll want something like this as a method:

```
public void Cell(int x, int y, List<Vector3> vertices, List<int> triangles)
{
    int indexStart = vertices.Length;

    vertices.Add(new Vector3(x - 1, y + 1, 0));
    vertices.Add(new Vector3(x + 1, y + 1, 0));
    vertices.Add(new Vector3(x + 1, y - 1, 0));
    vertices.Add(new Vector3(x - 1, y - 1, 0));

    triangles.Add(indexStart + 0);
    triangles.Add(indexStart + 1);
    triangles.Add(indexStart + 3);
    triangles.Add(indexStart + 1);
    triangles.Add(indexStart + 2);
    triangles.Add(indexStart + 3);
}

```

---
Tags: unity, procedural
---


# Question
Title: C# Unity - Multiplying Colors in loop results in wrong results
Good day, I'm trying to generate a tilemap, my current setup is a base tileset, and a few overlays for the different biomes / terrain heights. In my code, I generate each biome's tileset, based off of the base tileset, multiplied by the biome's overlay. However, as you can see in he image, it's reusing the first biome's overlay for all biomes.

Preview of result

Base Tileset

Overlays

Here's my code:

```
        for (int i = 0; i < biomes.Length; i++)
        {
            StatusText.text = "Generating Biome["+i+"] Tileset...";
            biomes[i].TileSet = new Sprite[_tileSet.Length]; // Creates the sprite array for the tileset of biome [i].
            Color[] b = biomes[i].Overlay.texture.GetPixels(); // Gets biome[i] overlay in a color array.
            for (int x = 0; x < _tileSet.Length; x++)
            {
                Debug.Log(biomes[i].Name);
                Debug.Log(biomes[i].Overlay);
                Color[] a = _tileSet[x].GetPixels(); // Get's base tile [x] in tileset pixels.
                for (int j = 0; j < a.Length; j++)
                {
                    a[j] *= b[j]; // Multiplies each pixel of the copy of base tile in the new color array with the overlay of biome[i].
                }
                Texture2D tex = new Texture2D(8, 8);
                tex.SetPixels(a);
                tex.filterMode = FilterMode.Point;
                tex.Apply();

                biomes[i].TileSet[x] = Sprite.Create(tex, new Rect(0, 0, 8, 8), new Vector2(4, 4), 8); // Creates sprite from generated texture.
            }
        }

```

# Answer
Sprite.texture retrieves the base texture off of which the sprite is based, so in this case instead of getting the overlay sprite, it gets the entire overlay texture. It's easily solved retrieving the pixel data directly from the base texture.

Here is the edit

```
overlays = new Texture2D[biomes.Length];
    for (int i = 0; i < biomes.Length; i++)
    {
        overlays[i] = new Texture2D(tileSize.x, tileSize.y);
        overlays[i].filterMode = FilterMode.Point;
        overlays[i].wrapMode = TextureWrapMode.Clamp;
        for (int x = 0; x < tileSize.x; x++)
        {
            for (int y = 0; y < tileSize.y; y++)
            {
                int Y = tileSize.y - y;
                overlays[i].SetPixel(x, y, biomes[i].Overlay.texture.GetPixel(x, y + i * tileSize.y));
            }
        }
    }
    for (int i = 0; i < biomes.Length; i++)
    {
        StatusText.text = "Generating Biome["+i+"] Tileset...";
        biomes[i].TileSet = new Sprite[_tileSet.Length];
        for (int x = 0; x < _tileSet.Length; x++)
        {
            Color[] b = overlays[i].GetPixels();
            Color[] a = _tileSet[x].GetPixels();
            for (int j = 0; j < a.Length; j++)
            {
                a[j] *= b[j];
            }
            Texture2D tex = new Texture2D(tileSize.x, tileSize.y);
            tex.SetPixels(a);
            tex.filterMode = FilterMode.Point;
            tex.wrapMode = TextureWrapMode.Clamp;
            tex.Apply();

            biomes[i].TileSet[x] = Sprite.Create(tex,new Rect(0,0,tex.width,tex.height),new Vector2(.5f,.5f), Mathf.Min(tex.width,tex.height));
        }
    }

```
> 0 votes

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


# Question
Title: Unity - Adding a sphere volume to this shader
I'm trying to create a spherical effect around my player that when they walk into range of hidden object, it gradually renders the object.

I found a shader that would work pretty well for this. When applied to an object, that object doesn't render, but when the object is brought into range of a cube shaped volume (by default it's located at the world origin) it renders.

```
Shader "Custom/ClipVolume" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0

        // Expose parameters for the minimum x, minimum z,
        // maximum x, and maximum z of the rendered volume.
        _Corners ("Min XZ / Max XZ", Vector) = (-1, -1, 1, 1)
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        // Allow back sides of the object to render.
        Cull Off

        CGPROGRAM

        #pragma surface surf Standard fullforwardshadows
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
            float3 worldPos;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        // Read the min xz/ max xz material properties.
        float4 _Corners;

        void surf (Input IN, inout SurfaceOutputStandard o) {

            // Calculate a signed distance from the clipping volume.
            float2 offset;
            offset = IN.worldPos.xz - _Corners.zw;
            float outOfBounds = max(offset.x, offset.y);
            offset = _Corners.xy - IN.worldPos.xz;
            outOfBounds = max(outOfBounds, max(offset.x, offset.y));
            // Reject fragments that are outside the clipping volume.
            clip(-outOfBounds);

            // Default surface shading.
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    // Note that the non-clipped Diffuse material will be used for shadows.
    // If you need correct shadowing with clipped material, add a shadow pass
    // that includes the same clipping logic as above.
    FallBack "Diffuse"
}

```

Issue 1: I want this effect to be spherical so that it looks like it radiates from the player. I followed some signed distance and volumetric rendering tutorials to create the sphere, but I can't seem to hook that in with my existing shader (most likely because I'm very new to creating shaders).

Issue 2: I can't seem to figure out how to move the volume with my player. I can get the volume to shift in the inspector using the vector4 coordinates, but I can't get my player's position to translate in a way that uniformly moves the volume.

Can someone give me some tips or examples on how I can shape and move this volume?

Any help would be greatly appreciated!

# Answer
> 0 votes
First, spheres have a center and a radius, not a min/max corner. We can pack those into one 4-vector, with the center in `xyz` and the radius in `w`:

```
 Properties {
    _Color ("Color", Color) = (1,1,1,1)
    _MainTex ("Albedo (RGB)", 2D) = "white" {}
    _Glossiness ("Smoothness", Range(0,1)) = 0.5
    _Metallic ("Metallic", Range(0,1)) = 0.0

    // Change the exposed property for positioning / sizing the volume.
    _CenterRadius ("Center(xyz) + Radius(w)", Vector) = (0, 0, 0, 1)
}

```

And then use the variable like so:

```
float4 _CenterRadius;

void surf (Input IN, inout SurfaceOutputStandard o) {

    // Calculate offset from the center of the sphere.
    float3 offset = IN.worldPos.xyz - _CenterRadius.xyz;

    // Reject fragments that are outside the clipping volume.
    // (squared length of offset > squared radius)
    clip(_CenterRadius.w * _CenterRadius.w
        - dot(offset, offset));

    // Default surface shading.
    fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
    o.Albedo = c.rgb;
    o.Metallic = _Metallic;
    o.Smoothness = _Glossiness;
    o.Alpha = c.a;
}

```

You can update the position in your C# script like...

```
Vector4 centerRadius = player.transform.position;
centerRadius.w = radius;

clippingMaterial.SetVector("_CenterRadius", centerRadius);

```

(Assuming you've populated suitably named variables for your `player` avatar object, your `radius` parameter, and your `clippingMaterial`. You can of course replace the string "\_CenterRadius" with a cached integer ID for efficiency)

---
Tags: unity, shaders, rendering, clipping
---


title: Why the timer is not showing the hours?

text:
# Question
Title: Why the timer is not showing the hours?
It's showing minutes seconds milliseconds but I want to show also the hours.

At the top:

```
private int seconds; // Seconds.
private int minutes; // Minutes.
private int hours;   // Hours.

```

In Update:

```
void Update()
{
if (seconds < 1)
        {
            seconds = 59;
            minutes--;
        }
        if (minutes < 1)
        {
            minutes = 59;
            hours--;
        }
        if (hours < 1)
        {
            hours = 59;
        }
        seconds--;

        EditorGUILayout.LabelField("Next: ", hours.ToString() + ":" + minutes.ToString() + ":" + seconds.ToString());

```

Update, This is what I tried:

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

public class Timer : EditorWindow
{

    private static Timer editor;
    private static int width = 300;
    private static int height = 110;
    private static int x = 0;
    private static int y = 0;
    int totalSeconds;

    [MenuItem("Window/Timer")]
    static void ShowEditor()
    {
        editor = EditorWindow.GetWindow<Timer>();
        editor.Init();
    }

    public void Init()
    {
        StartTimer(1, 1, 50);
        Debug.Log("The level will now be saved automatically");
    }

    void OnGUI()
    {
        EditorGUILayout.LabelField("Next: ", TimeString());
    }

    public void StartTimer(int hours, int minutes, int seconds)
    {
        totalSeconds = seconds + 60 * minutes + 60 * 60 * hours;
    }

    string TimeString()
    {
        return string.Format("{0:00}:{1:00}:{2:00}",
                      totalSeconds / (60 * 60),   // Hours
                      (totalSeconds / 60) % 60, // Minutes
                      totalSeconds % 60);     // Seconds
    }
}

```

But the timer is not moving not counting back it stay still. I tried also to move the line:

```
StartTimer(1, 1, 50);

```

To be inside the OnGUI before the LabelField.

# Answer
Writing your own date and time handling code from scratch is a path towards agony and despair. It is usually far better to use the time handling features provided by your platform. In the case of C#, the standard library offers you a handy `TimeSpan` class.

```
 TimeSpan timer = new TimeSpan(1, 1, 50);
 Debug.Log("The timer is set to " + timer.ToString("hh\\:mm\\:ss"));

```

The class also has a bunch of methods which allow you to modify the value in an easy and painless way. For example, if you want the Update method of a MonoBehaviour to reduce the remaining time:

```
 Update() {
    TimeSpan deltaTimeSpan = TimeSpan.FromSeconds(Time.deltaTime);
    timer = timer.Subtract(deltaTimeSpan);
    Debug.Log("Time left: " + timer.ToString("hh\\:mm\\:ss"));
 }

```
> 4 votes

# Answer
Your logic for advancing the time from one variable to the other is not correct. It skips over second 0 every minute, and minute 0 every hour.

You can simplify this greatly by storing just one variable internally, and splitting out the hours/minutes only when needed:

```
int totalSeconds;

public void StartTimer(int hours, int minutes, int seconds) {
    totalSeconds = seconds + 60 * minutes + 60*60 * hours;
}

string TimeString() {
    return string.format("{0:00}:{1:00}:{2:00}",
                  totalSeconds/(60*60),   // Hours
                  (totalSeconds/60) % 60, // Minutes
                  totalSeconds % 60);     // Seconds
}

```
> 2 votes

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


# Question
Title: How do I set something when 2 or more touches are pressed?
I currently have a working controller with left and right but I want to set the velocity of the character to 0/Stop when 2 or more touches are detected. This is my current working code but I want to make the player stop when 2 touches are detected.

```
void TouchMove(){

    if(Input.touchCount > 0){

        Touch touch = Input.GetTouch(0);

        float middle = Screen.width / 2;

        if(touch.position.x < middle && touch.phase == TouchPhase.Began) {
            MoveLeft();
        }
        else if (touch.position.x > middle && touch.phase == TouchPhase.Began) {
            MoveRight();
        }

    }
    else {
        SetVelocityZero();
    }
}`

```

This is how my game looks like

# Answer
The solution for this problem is by inserting this code in the touchmove function

`if(Input.touchCount >= 2){
 SetVelocityZero();
 }`

Thank you DMGregory for the answer!
> 1 votes

---
Tags: unity, android, touch, multitouch
---


title: How to add high score?

text:
# Question
Title: How to add high score?
I wanted to add a high score to my game but I don't know how I already tried to find some videos for it but I just can't find the right one. I already have a scoreUI on my game I just wanted to add a high score.

Here is my UIManager's script which consists of different functions including the score system.

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

public class uiManager : MonoBehaviour {

public Button[] buttons;
public Text scoreText;
int score;
bool gameOver;

// Use this for initialization
void Start () {
    gameOver = false;
    score = 0;
    InvokeRepeating("scoreUpdate", 0.5f, 0.25f);
}

// Update is called once per frame
void Update () {
    scoreText.text = "" + score;
}

void scoreUpdate(){
    if (gameOver == false) {
        score += 1;
    }
}
public void gameOverActivated(){
    gameOver = true;
    foreach(Button button in buttons) {
        button.gameObject.SetActive(true);
    }
}

public void Play() {
    SceneManager.LoadScene("level1");
}

public void Menu(){
    SceneManager.LoadScene("Menu");
}

public void Retry()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}

public void Pause() {

    if (Time.timeScale == 1) {
        Time.timeScale = 0;
    }
    else if (Time.timeScale == 0) {
        Time.timeScale = 1;
    }
}
}

```

I got the score system from Charger Games. Here is the link to the Video

and here is what my game looks like

# Answer
To implement any form of a highscore system, you would need the following:

* A persistent storage, ie: not in memory (variables)
* A way to write to this storage
* A way to read from this storage
* A way to draw the highscore onto the screen.

You already have the last item ticked off - your high score UI objects. So let's talk about storing your score somewhere on the device.

**Persistent storage**

There are plenty of options to pick from. This includes writing to some file on the disk, or the cheaty way of writing it into PlayerPrefs. For the sake of a simple example, let's use `PlayerPrefs` to store our highscores for now.

**Reading from storage**

Before writing any data to your high score storage, you would want to read from it and check it against the current score. This will determine if the highscore is to be updated. In your case, it would probably be in your `gameOverActivated()` function.

```
public void gameOverActivated(){
    gameOver = true;
    foreach(Button button in buttons) {
        button.gameObject.SetActive(true);
    }

    // Check what the current highscore is
    int highestScore = PlayerPrefs.GetInt("highscore", 0);
    // take 0 if 'highscore' has not been set
}

```

**Writing to storage**

Once we know what the highest score is, we can decide if we want to update the score with the current score. In the same function:

```
if (score > highestScore) {
    PlayerPrefs.SetInt("highscore", score);
}

```

With that done, from wherever you need to draw the highscore, just call `PlayerPrefs.GetInt()` with the key `highscore` and you have yourself an (albeit simple) highscore system.

It is important to note at this point that `PlayerPrefs` was never intended to be used for storing highscores. We use it in this example as it is a simple way to write to persistent storage on the device. For some further reading, you could try to write to your own file on the device, use an array of scores instead of a single score, or even look up Google Play Services to implement an online highscore/leaderboard system. In whichever way you do it, the fundamental idea remains the same.
> 6 votes

---
Tags: unity, android, leaderboards
---