title: How can I avoid "Moonwalking"

text:
# Question
Title: How can I avoid "Moonwalking"
Let me explain my question:

I have a sprite sheet with the different frames of the animations. Each animation has 8 frames.

Based on the player's input, I modify the character's coordinates, thus I also modify where the given frame of the animation should be rendered. Based on if the character is running or walking, I either speed up the animation or slow it down (since while running he should take 3 steps per second, and 2 steps per second when walking, so I play 12 frames per second when he's running, and 8 when he's walking).

However in the case of the walk cycle, I also get an unwanted side effect: the character "moonwalks". This means that while the X and Y coordinates are changing, thus the character is moving forward, his current sprite does not change at that instance. This gives the impression that the character is sliding or skating on his feet.

I'm trying to create something similar to Prince of Persia or Flashback. As I see they don't have this problem in their animation, and I wonder how could I eliminate it in mine.

I can not simply just speed up my walk cycle animation, since a fast walking looks weird. Maybe I should have more frames in my animation? Is there a simpler way of doing it? When I search for sprite sheet animation algorithm I find so little.

Update: I have added an image to demonstrate the issue. As you can see, the character does this weird sliding.

# Answer
> 6 votes
If I recall correctly, both Prince of Persia and Flashback (as well as its predecessor, Another World/Out of This World) only allowed movement in set 'steps': if the player ran or walked, they would move a predetermined amount of space (i.e. 8 pixels for a single step, or 32 pixels for a running stride). They were effectively tile-based, and the player's avatar was confined to moving increments of one tile. As mentioned by Philipp, this led to very smooth animation but could feel 'floaty' as players didn't have absolute control over their avatars. Clever level design stopped this from being an issue - as well as the fact that the terrain didn't scroll (the action just moved from screen to screen).

The animation is the problem here, rather than anything programmatic. I've opened up your .gif file in Adobe Fireworks, and I can see that the feet are only changing position every four frames while the floor is moving at a constant rate, which looks to be four pixels per frame. The player's stride appears to be around the right length - 40-odd pixels - but because the feet don't move as fluidly as the ground, it looks like they're sliding.

I took the liberty of putting together a gif showing your character walking over a stationary floor. The stride looks a little odd:

Prince of Persia and Flashback both used rotoscoping for their animation, which gave them their fluidity. I don't suggest you go down this route yourself, but you really need to study how people walk- your animation doesn't seem very natural at all.

To really address the issue, you'll need to re-animate your walk cycle. However, for a quick fix you could:

* slow down the movement of the terrain (though I suspect you'd end up with rather jerky scrolling)
* add more frames to your walk cycle (the foot in contact with the floor needs to animate at the same speed as the floor)

I'd be inclined to take the second approach, though it means more work.

Animation is hard. Even harder than programming. But if you really want to make your game look good, you could do much worse than invesing in some books on the subject. I've added a few links to ones I personally recommend below. The only way to get better at animating is to practice, so don't worry if your early efforts don't work out.

**Animation books:**

# Answer
> 1 votes
A lot of games with walking animations (2D and 3D) suffer from this problem, and big ones, not just indies.
I think it would be solved fairly easy by having the animation system support marking the spot where each foot touches the ground in each frame.
Then the algorithm that moves the animated sprite should just make sure that the same spot E.G. `left_foot` is always in the same place in relation to the background.
This would of course create problems with the time between frames, which the animator could not control anymore, but I think with some adjustments and collaboration between artists and programmers, it could be done effectively.

I see one restriction arising from this, which is that consecutive frames where both feet are on the ground, should have both reference points fixed and not moving relative to each other. But that's how walking in the real world works, anyway.

---
Tags: 2d, animation, platformer
---


# Question
Title: Architecture of networking in game engine
I am currently building a 2d game engine, with the future intention of adding some sort of networking functionality. I have past experience making networking games in Unity and whatnot, however I am sort of conflicted as to how to structure the networking part. So far I have thought of two scenarios:

1. I give a low-level/high-level API to the user to do networking on their own (like UNet I guess?). Basically just building the networking on top of the game engine, which means the other functionalities (like rendering, physics, etc.) don't need to know about networking right?
2. I assume every game is multiplayer (multiplayer with 1 player if single player) and kind of build networking into the engine natively.

In past experiences adding networking to a single-player game is quite hard, and I assume this principle will apply to a game engine as well (ie. add networking later down the line). But this would only be the case if I choose to go with scenario 2 right? Meanwhile if I go with scenario 1, I could just add networking whenever because the game engine isn't dependant on it. Or am I misunderstanding something?

# Answer
> 0 votes
If you go with option two, there's a good chance you'll make things harder for game developers that want to build a single-player game. So, your choice depends on what goal you have in mind for the engine that you're building.

Making multiplayer functionalities the core of the engine can be super interesting for game devs who want to focus on that, but you'll need to take into account things like lag compensation, client-side prediction and other features for a multiplayer deterministic engine.

If your goal is just to make a fun 2D game engine that can appeal to a broader audience, I would go with option 1 and just give the building blocks of multiplayer networking so that developers can use them for their specific needs.

---
Tags: architecture, networking
---


# Question
Title: What are "free vertex indices" in WebGL 2 and how do they relate to geometry shaders?
In January Notch tweeted about WebGL 2:

> WebGL 2 is happening. Bye, compatibility! Hello, 3d textures and pixel buffers!
>
> oh god it's got free vertex indices in the shader. That is basically a geometry shader.
>
> .. which is great considering I'm rendering like five triangles..

What are these "free vertex indices" and how do they relate to geometry shaders? I'm new to all this and my google-fu is failing me on this occasion.

# Answer
I'm just guessing it's using `gl_VertexID` to generate vertices in the shader. Example:

```
function main() {
  const gl = document.querySelector("canvas").getContext("webgl2", { alpha: false });
  if (!gl) {
    alert("needs WebGL2");
    return;
  }
  const programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);
  const vertexCount = 100000;

  function render(time) {
    twgl.resizeCanvasToDisplaySize(gl.canvas);
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
    gl.clearColor(0, 0, 0, 1);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);

    var uniforms = {
      time: time * 0.001,
      resolution: [gl.canvas.width, gl.canvas.height],
      vertexCount: vertexCount,
    };

    gl.useProgram(programInfo.program);
    twgl.setUniforms(programInfo, uniforms);
    gl.drawArrays(gl.TRIANGLES, 0, vertexCount);

    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);
}
main();
```

```
body {
  margin: 0;
}
canvas {
  width: 100vw;
  height: 100vh;
  display: block;
  background-color: black;
}
```

```
<canvas></canvas>
<script id="vs" type="notjs">
#version 300 es
uniform vec2 resolution;
uniform float time;
uniform float vertexCount;

out vec4 v_color;

#define PI radians(180.0)

vec3 hsv2rgb(vec3 c) {
  c = vec3(c.x, clamp(c.yz, 0.0, 1.0));
  vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
  vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
  return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}

mat4 rotX(float angleInRadians) {
    float s = sin(angleInRadians);
    float c = cos(angleInRadians);

    return mat4(
      1, 0, 0, 0,
      0, c, s, 0,
      0, -s, c, 0,
      0, 0, 0, 1);
}

mat4 rotY(float angleInRadians) {
    float s = sin(angleInRadians);
    float c = cos(angleInRadians);

    return mat4(
      c, 0,-s, 0,
      0, 1, 0, 0,
      s, 0, c, 0,
      0, 0, 0, 1);
}

mat4 rotZ(float angleInRadians) {
    float s = sin(angleInRadians);
    float c = cos(angleInRadians);

    return mat4(
      c,-s, 0, 0,
      s, c, 0, 0,
      0, 0, 1, 0,
      0, 0, 0, 1);
}

mat4 trans(vec3 trans) {
  return mat4(
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    trans, 1);
}

mat4 ident() {
  return mat4(
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1);
}

mat4 scale(vec3 s) {
  return mat4(
    s[0], 0, 0, 0,
    0, s[1], 0, 0,
    0, 0, s[2], 0,
    0, 0, 0, 1);
}

mat4 uniformScale(float s) {
  return mat4(
    s, 0, 0, 0,
    0, s, 0, 0,
    0, 0, s, 0,
    0, 0, 0, 1);
}

mat4 persp(float fov, float aspect, float zNear, float zFar) {
  float f = tan(PI * 0.5 - 0.5 * fov);
  float rangeInv = 1.0 / (zNear - zFar);

  return mat4(
    f / aspect, 0, 0, 0,
    0, f, 0, 0,
    0, 0, (zNear + zFar) * rangeInv, -1,
    0, 0, zNear * zFar * rangeInv * 2., 0);
}

mat4 trInv(mat4 m) {
  mat3 i = mat3(
    m[0][0], m[1][0], m[2][0],
    m[0][1], m[1][1], m[2][1],
    m[0][2], m[1][2], m[2][2]);
  vec3 t = -i * m[3].xyz;

  return mat4(
    i[0], t[0],
    i[1], t[1],
    i[2], t[2],
    0, 0, 0, 1);
}

mat4 lookAt(vec3 eye, vec3 target, vec3 up) {
  vec3 zAxis = normalize(eye - target);
  vec3 xAxis = normalize(cross(up, zAxis));
  vec3 yAxis = cross(zAxis, xAxis);

  return mat4(
    xAxis, 0,
    yAxis, 0,
    zAxis, 0,
    eye, 1);
}

mat4 cameraLookAt(vec3 eye, vec3 target, vec3 up) {
  #if 1
  return inverse(lookAt(eye, target, up));
  #else
  vec3 zAxis = normalize(target - eye);
  vec3 xAxis = normalize(cross(up, zAxis));
  vec3 yAxis = cross(zAxis, xAxis);

  return mat4(
    xAxis, 0,
    yAxis, 0,
    zAxis, 0,
    -dot(xAxis, eye), -dot(yAxis, eye), -dot(zAxis, eye), 1);
  #endif

}

// hash function from https://www.shadertoy.com/view/4djSRW
float hash(float p) {
 vec2 p2 = fract(vec2(p * 5.3983, p * 5.4427));
    p2 += dot(p2.yx, p2.xy + vec2(21.5351, 14.3137));
 return fract(p2.x * p2.y * 95.4337);
}

// times 2 minus 1
float t2m1(float v) {
  return v * 2. - 1.;
}

// times .5 plus .5
float t5p5(float v) {
  return v * 0.5 + 0.5;
}

float inv(float v) {
  return 1. - v;
}

vec3 getQuadStripPoint(const float id) {
  float ux = floor(id / 6.) + mod(id, 2.);
  float vy = mod(floor(id / 2.) + floor(id / 3.), 2.);
  return vec3(ux, vy, 0);
}

void getCirclePoint(const float numEdgePointsPerCircle, const float id, const float inner, const float start, const float end, out vec3 pos) {
  float ux = floor(id / 6.) + mod(id, 2.);
  float vy = mod(floor(id / 2.) + floor(id / 3.), 2.); // change that 3. for cool fx
  float u = ux / numEdgePointsPerCircle;
  float v = mix(inner, 1., vy);
  float a = mix(start, end, u) * PI * 2. + PI * 0.0;
  float s = sin(a);
  float c = cos(a);
  float x = c * v;
  float y = s * v;
  float z = 0.;
  pos = vec3(x, y, z);
}

#define CUBE_POINTS_PER_FACE 6.
#define FACES_PER_CUBE 6.
#define POINTS_PER_CUBE (CUBE_POINTS_PER_FACE * FACES_PER_CUBE)
void getCubePoint(const float id, out vec3 position, out vec3 normal) {
  float quadId = floor(mod(id, POINTS_PER_CUBE) / CUBE_POINTS_PER_FACE);
  float sideId = mod(quadId, 3.);
  float flip   = mix(1., -1., step(2.5, quadId));
  // 0 1 2  1 2 3
  float facePointId = mod(id, CUBE_POINTS_PER_FACE);
  float pointId = mod(facePointId - floor(facePointId / 3.0), 6.0);
  float a = pointId * PI * 2. / 4. + PI * 0.25;
  vec3 p = vec3(cos(a), 0.707106781, sin(a)) * flip;
  vec3 n = vec3(0, 1, 0) * flip;
  float lr = mod(sideId, 2.);
  float ud = step(2., sideId);
  mat4 mat = rotX(lr * PI * 0.5);
  mat *= rotZ(ud * PI * 0.5);
  position = (mat * vec4(p, 1)).xyz;
  normal = (mat * vec4(n, 0)).xyz;
}

float Hash( vec2 p) {
     vec3 p2 = vec3(p.xy,1.0);
    return fract(sin(dot(p2,vec3(37.1,61.7, 12.4)))*3758.5453123);
}

float noise(in vec2 p) {
    vec2 i = floor(p);
     vec2 f = fract(p);
     f *= f * (3.0-2.0*f);

    return mix(mix(Hash(i + vec2(0.,0.)), Hash(i + vec2(1.,0.)),f.x),
               mix(Hash(i + vec2(0.,1.)), Hash(i + vec2(1.,1.)),f.x),
               f.y);
}

float fbm(vec2 p) {
     float v = 0.0;
     v += noise(p*1.0)*.5;
//     v += noise(p*2.)*.25;
//     v += noise(p*4.)*.125;
     return v;
}

float crv(float v) {
  return fbm(vec2(v, v * 1.23));
  //float o = sin(v) + sin(v * 2.1) + sin(v * 4.2) + sin(v * 8.9);
  //return o / 4.;
}

vec3 fgetCurvePoint(float t) {
//  return vec3(sin(-t), sin(t * 0.8), sin(t * 0.6));
//  return vec3( mod(t, 1.) * 0.01, 0, mod(t, 1.));
  return vec3(
    crv(t),
    crv(t + .3),
    crv(t + .6)
  ) * 2. - 1.;
}

vec3 getCurvePoint(const float id) {
  return vec3(
    sin(id * 0.99),
    sin(id * 2.43),
    sin(id * 1.57));
}

const float expand = 80.0;

void sky(const float vertexId, const float vertexCount, float base, const mat4 cmat, out vec3 pos, out vec4 color) {
  float starId = floor(vertexId / 3.);
  float numStars = floor(vertexCount / 3.);
  float starV = starId / numStars;

  float h = hash(starId * 0.017);

  float pId = mod(vertexId, 3.);
  //float sz = h * 2.;
  float sz = clamp(500.0 / min(resolution.x, resolution.y), 2., 200.);

  pos = normalize(vec3(
    t2m1(hash(starId * 0.123)),
    t2m1(hash(starId * 0.353)),
    t2m1(hash(starId * 0.627)))) * 500. + cmat[3].xyz;
  pos += cmat[0].xyz * sz * step(0.5, pId);
  pos += cmat[1].xyz * sz * step(1.5, pId);

  color = vec4(h, h, h, 1);
}

void cube(const float vertexId, const float vertexCount, const float base, const mat4 cmat, const mat4 vmat, out vec3 pos, out vec4 color) {
  vec3 cpos;
  vec3 cnormal;

  float pointId = vertexId;
  getCubePoint(pointId, cpos, cnormal);
  float cubeId = floor(pointId / 36.);
  float numCubes = floor(vertexCount / 36.);
  float down = floor(pow(numCubes, .333));
  float across = floor(floor(numCubes / down) / down);
  float deep = floor(numCubes / (down * across));

  float cx = mod(cubeId, across);
  float cy = mod(floor(cubeId / across) , down);
  float cz = floor(cubeId / (across * down));

  float cu = cx / (across - 1.);
  float cv = cy / (down - 1.);
  float cw = cz / (deep - 1.);

  float ca = cu * 2. - 1.;
  float cd = cv * 2. - 1.;
  float ce = cw * 2. - 1.;

  float tm = time * 0.1;
  mat4 mat = ident();

  const float dim = 640.0;
  vec3 t = vec3(
      hash(cubeId * 0.123),
      hash(cubeId * 0.719),
      hash(cubeId * 0.347)) * 2. - 1.;

  float s = pow(abs(sin(cubeId + time * 0.01)), 1000.) * .9;

  float pump = step(0.7, s);

  #if 0
    mat *= trans(vec3(ca, ce, cd) * 120.0);
    mat *= uniformScale(2.);
  #else
    mat *= trans(t * dim * .5);
    mat *= rotX(time * 1. + cubeId);
    mat *= rotZ(time * 1.1 + cubeId);
    mat *= uniformScale(mix(4., 20. + pump * 20., pow(s, 5.)));
   #endif

  pos = (mat * vec4(cpos, 1)).xyz;
  vec3 n = normalize((mat * vec4(cnormal, 0)).xyz);

  float hue = time * .03 + mix(1., 1.1, pump);//abs(ca * cd) * 2.;
  float sat = 1.;mix(1., 0., abs(ca));
  float val = 1.;mix(1., 0.5, abs(cd));
  vec3 tcolor = hsv2rgb(vec3(hue, sat, val));

  vec3 lightDir = normalize(vec3(0.3, 0.4, -1));
  vec3 lightPos = vec3(0);
  vec3 surfaceToLight = normalize(lightPos - pos);
  vec3 surfaceToView = normalize(cmat[3].xyz - pos);
  vec3 halfVector = normalize(surfaceToLight + surfaceToView);

  float light = dot(n, surfaceToLight);
  float specular = pow(clamp(dot(n, halfVector), 0., 1.), 20.);

  //color = vec4(tcolor * (dot(n, lightDir) * 0.5 + 0.5), 1);
  color = vec4(tcolor * light + vec3(specular), 1);

  color.a = mix(1., 10., pump);
  color.rgb *= color.a;
}

void main() {
  float vertexId = float(gl_VertexID);
  const float numCubePoints = 90000.0;

  //float base = 15.;  // good place to adjust
  float base = time * 0.125;

  const float coff = 0.14;

  vec3 b0 = getCurvePoint(base + coff * 0.);
  vec3 b1 = getCurvePoint(base + coff * 1.);
  vec3 b2 = getCurvePoint(base + coff * 2.);

  vec3 c0 = normalize(b1 - b0);
  vec3 c1 = normalize(b2 - b1);

  vec3 czaxis = normalize(c1 - c0);
  vec3 cxaxis = normalize(cross(c0, c1));
  vec3 cyaxis = normalize(cross(czaxis, cxaxis));

  mat4 pmat = persp(radians(60.0), resolution.x / resolution.y, .1, 1000.0);

  vec2 ms = vec2(0); //texture2D(touch, vec2(0, 0)).xy + vec2(0, 1);

  vec3 eye    = b0 * expand + cyaxis * .001 + czaxis * 2.2;
  vec3 target = b1 * expand + cyaxis * .002 + czaxis + ms.x * cxaxis * 2. + ms.y * cyaxis * 40.;
  vec3 up     = cyaxis;

 // eye = vec3(1, 1, 1);
//  target = vec3(0);
//  up = vec3(0,1,0);

  mat4 cmat = lookAt(eye, target, up);
  mat4 vmat = rotZ(asin(up.y) * 1.) * inverse(cmat);

  vec3 pos;
  vec4 color;

  if (vertexId < numCubePoints) {
    cube(vertexId, vertexCount, base, cmat, vmat, pos, color);
  } else {
    sky(vertexId, vertexCount, base, cmat, pos, color);
  }

  gl_Position = pmat * vmat * vec4(pos, 1);
  v_color = color;

  float cz = gl_Position.z / gl_Position.w * .5 + .5;
  v_color.rgb = mix(v_color.rgb, vec3(0), mix(4., 0., cz));

}
  </script>
  <script id="fs" type="notjs">
#version 300 es
precision mediump float;

in vec4 v_color;
out vec4 outColor;

void main() {
  outColor = v_color;
}
  </script>
<script src="https://twgljs.org/dist/3.x/twgl.min.js"></script>
```

Here's a website based on that concept.

As a simple probably more useful example if you just want to draw a fullscreen quad you can do it without setting up buffers and attributes like this

```
function main() {
  const gl = document.querySelector("canvas").getContext("webgl2", { alpha: false });
  if (!gl) {
    alert("needs WebGL2");
    return;
  }
  const programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);
  const vertexCount = 6;

  function render(time) {
    twgl.resizeCanvasToDisplaySize(gl.canvas);
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
    gl.clearColor(0, 0, 0, 1);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);

    var uniforms = {
      time: time * 0.001,
      resolution: [gl.canvas.width, gl.canvas.height],
    };

    gl.useProgram(programInfo.program);
    twgl.setUniforms(programInfo, uniforms);
    gl.drawArrays(gl.TRIANGLES, 0, 6);

    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);
}
main();
```

```
body {
  margin: 0;
}
canvas {
  width: 100vw;
  height: 100vh;
  display: block;
  background-color: black;
}
```

```
<canvas></canvas>
<script id="vs" type="notjs">
#version 300 es

void main() {
  int x = gl_VertexID % 2;
  int y = (gl_VertexID / 2 + gl_VertexID / 3) % 2;
  gl_Position = vec4(vec2(x, y) * 2. - 1., 0, 1);
}
  </script>
  <script id="fs" type="notjs">
#version 300 es
precision mediump float;

uniform vec2 resolution;
uniform float time;

out vec4 outColor;

void main() {
  // taken from glslsandbox.com
 vec2 position = ( gl_FragCoord.xy / resolution.xy );

 float color = 0.0;
 color += sin( position.x * cos( time / 15.0 ) * 80.0 ) + cos( position.y * cos( time / 15.0 ) * 10.0 );
 color += sin( position.y * sin( time / 10.0 ) * 40.0 ) + cos( position.x * sin( time / 25.0 ) * 40.0 );
 color += sin( position.x * sin( time / 5.0 ) * 10.0 ) + sin( position.y * sin( time / 35.0 ) * 80.0 );
 color *= sin( time / 10.0 ) * 0.5;

 outColor = vec4( vec3( color, color * 0.5, sin( color + time / 3.0 ) * 0.75 ), 1.0 );
}
  </script>
<script src="https://twgljs.org/dist/3.x/twgl.min.js"></script>
```
> 2 votes

# Answer
This question was a useful starting point for me, so, to expand on previous answers:

`gl_VertexID` lets you generate vertices as pure functions of a monotonically increasing integer, which the examples on vertexshaderart.com illustrate very well. You can produce a wide range of abstract visuals this way without passing any data to the GPU at all (because `drawArrays` lets you read any number of values from an empty vertex buffer).

By itself, though, that technique is quite limited, because it also means you *can't* pass any data to the GPU in the usual way. If you use `drawArrays` to pass actual data, you have to supply exactly one set of attributes per vertex, as with WebGL 1; and if you use `drawElements` then `gl_VertexID` is fairly useless anyway, as then it just reads back the index you passed in – if you process the same input vertex 10 times, your shader can't tell whether it's on the first or the tenth instance.

The missing piece of the puzzle is that you can call `drawArrays` with no actual array, but pass attributes to your shader via **textures**, and WebGL 2 has a couple of features that make this much more practical. Firstly, the GLSL `textureFetch` function makes it easier to treat a texture as an array; and more importantly, WebGL 2 provides specific texture formats that are useful for this sort of thing. For instance, a texture in `RGBA32F` format is simply an array of single-precision `vec4` values, which (despite the name) you are free to load as vertex coordinates, or quaternions, or 2D rectangles, or whatever you want. (In WebGL 1, RGBA texel components are 8-bit ints at best, and you can't even guarantee that)

**Concrete example:** If you want to draw thick lines with OpenGL, you have to convert each line segment into a rectangle (i.e. a pair of triangles). There are several pages describing how to do this using WebGL 1, but it involves doing much of the geometry calculation in JavaScript, then passing quite a lot of data to the GPU (at least 6 vertices for each 2-vertex line segment), so as well as being much harder than using `CanvasRenderingContext2D`, it might even be slower, too.

But with WebGL 2, you can dump the vertices of your lines straight into a texture, put all the calculations into a vertex shader, and run it `6 * (number of lines)` times:

```
    #version 300 es
    out vec3 vertexColor;
    uniform float u_weight;    // line weight parameter
    uniform sampler2D u_lines; // "texture" containing vertices
    int DIM;                   // dimension of the (square) texture
    vec4 vertex(int i) {
        // load vertex i from the RGBA32F texture
        return texelFetch(u_lines, ivec2(i%DIM, i/DIM), 0);
    }
    void main() {
        DIM = textureSize(u_lines,0).x;
        // get line vertices, reversed for corners 1, 3 and 5:
        vec4 p1 = vertex(2*(gl_VertexID/6) + gl_VertexID%2);
        vec4 p2 = vertex(2*(gl_VertexID/6) + 1&~(gl_VertexID%2));
        // offset direction, reversed for corners 2, 3 and 4:
        float sign1 = float( ((1+gl_VertexID%3)&2) - 1 );
        // matrix to rotate by +/- pi/2:
        mat2 m = mat2( 0.0, -sign1, sign1, 0.0 );
        // displace by (weight/2) * rotated unit vector of line:
        vec2 ofs = m * normalize(p2.xy - p1.xy) * (u_weight/2.0);
        p1 += vec4(ofs, 0.0, 0.0);
        gl_Position = p1;
        vertexColor = vec3(0.7, 0.3, 0.5);
    }

```

(the purpose of all that crunchy integer math is to generate the six different vertex positions from a single calculation. Code like this is unreadable without working it out on paper, but the common wisdom says it's best to write shaders without using `if` statements)

It is easy to see how you could adapt this for things like particle systems, displacement textures, or any other task that processes lots of fixed-size packets of data.

I'm sure there are performance implications to using textures vs. regular vertex attribute buffers, but it's a safe bet that moving tons of calculations from JS to the GPU makes it worthwhile.
> 2 votes

# Answer
Presumably this is a reference to the availability of `gl_VertexID` in WebGL 2.

In a vertex shader, this variable holds the index of the vertex. If you were interested in this information in WebGL 1, you'd have to provide it to the shader yourself. In WebGL 2 the presence of the built-in variable provides the information to you "for free."

I'm not sure preciously what the comparison is when calling this feature "basically a geometry shader." It's possible in some cases one could use the vertex index for the same kinds of operations you might use `gl_PrimitiveIDIn` (from a geometry shader) for, depending on the other context available to (or that can be assumed by) your shader programs.
> 0 votes

---
Tags: opengl, shaders, opengl-es, webgl, geometry-shader
---


# Question
Title: How to change GUI box background color for each gui button individual?
The problem is at this part, the color is changing the background also for the PAUSE button and not only for the PLAY/STOP button.

Before i added this part the PAUSE button color changing was working fine but after adding this part in the PLAY/STOP button now the PAUSE part with the colors change is not working good as before. The background colors in the PLAY/STOP button also affecting the PAUSE background color when trying to change the PAUSE button color in runtime in the inspector.

```
if (test == false)
        {
            GUI.backgroundColor = Color.green;
            test1 = "STOP";
        }
        else
        {
            GUI.backgroundColor = Color.red;
            test1 = "PLAY";
        }

```

What i want to do is to be able to manipulate the background color for each button individual so one will not override/affect the other/s.

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

public class GUIExamples : MonoBehaviour
{
    public Texture btnTexture;
    public Color color;

    public string colorInf;

    private GUIStyle currentStyle = null;
    private Color oldColor;
    private bool test = false;
    private string test1;

    private void Start()
    {
        oldColor = color;
    }

    private void OnGUI()
    {
        if (!btnTexture)
        {
            Debug.LogError("Please assign a texture on the inspector");
            return;
        }

        //GUI.backgroundColor = color;
        if (GUI.Button(new Rect(10, 10, 170, 30), "LOOP"))
            Debug.Log("Clicked the button with an image");

        //GUI.backgroundColor = color;
        if (GUI.Button(new Rect(10, 50, 170, 30), "CHANGE DIRECTION"))
            Debug.Log("Clicked the button with text");

        //GUI.backgroundColor = color;
        if (GUI.Button(new Rect(10, 90, 170, 30), "PING PONG"))
            Debug.Log("Clicked the button with text");

        if (test == false)
        {
            GUI.backgroundColor = Color.green;
            test1 = "STOP";
        }
        else
        {
            GUI.backgroundColor = Color.red;
            test1 = "PLAY";
        }
        if (GUI.Button(new Rect(10, 130, 170, 30), test1))
        {
            Debug.Log("Clicked the button with text");
            test = !test;
        }

        InitStyles();
        GUI.Box(new Rect(10, 170, 170, 30), "PAUSE", currentStyle);
        if (GUI.Button(new Rect(10, 170, 170, 30), "PAUSE", currentStyle))
            Debug.Log("Clicked the button with text");

    }

    private void InitStyles()
    {
            currentStyle = null;

            if (oldColor != color)
            {
                currentStyle = null;
            }

            if (currentStyle == null)
            {
                currentStyle = new GUIStyle(GUI.skin.box);
                currentStyle.normal.background = MakeTex(2, 2,
                    new Color(color.r, color.g, color.b));

                oldColor = color;
            }
    }

    private Texture2D MakeTex(int width, int height, Color col)
    {
        Color[] pix = new Color[width * height];
        for (int i = 0; i < pix.Length; ++i)
        {
            pix[i] = col;
        }
        Texture2D result = new Texture2D(width, height);
        result.SetPixels(pix);
        result.Apply();
        return result;
    }
}

```

# Answer
First of all, It is strongly recommended that you use the updated unity GUI tools. Check UI-system-compare.

Back to this question. Let's look at the definition of GUI-backgroundColor:

```
Global tinting color for all background elements rendered by the GUI.
This gets multiplied by color.

```
1. It's a global value for all elements.
2. It's not the element color but a "correction value". Just like "multiply blend mode" in photoshop.

Maybe this button Need to have its own GUIStyle object. Try this:

```
    var playButtonStyle = new GUIStyle(GUI.skin.box);
    if (test == false)
    {
        playButtonStyle.normal.background = MakeTex(2, 2, Color.red);
        test1 = "STOP";
    }
    else
    {
        playButtonStyle.normal.background = MakeTex(2, 2, Color.green);
        test1 = "PLAY";
    }
    if (GUI.Button(new Rect(10, 130, 170, 30), test1, playButtonStyle))
    {
        Debug.Log("Clicked the button with text");
        test = !test;
    }

```

Another way:

```
    var defaultColor = GUI.color;
    if (test == false)
    {
        GUI.color = Color.red;
        test1 = "STOP";
    }
    else
    {
        GUI.color = Color.green;
        test1 = "PLAY";
    }
    if (GUI.Button(new Rect(10, 130, 170, 30), test1))
    {
        Debug.Log("Clicked the button with text");
        test = !test;
    }
    GUI.color = defaultColor;

```

Modify the global color of GUI and restore it after use. This preserves the style of the default button.
> 1 votes

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


# Question
Title: How to fix texture atlas border bleeding?
I am having an issue with texture bleeding, I am getting these lines that border each tile:

I have tried to solve the issue by rounding/flooring, but that does not work either.

The texture atlas has 32x32 pixel tiles.

# Answer
> 1 votes
The texture size usually does not match the screen area, so it needs to be enlarger or reduced.

That means that the border of your tiles are blended with the transparent border between tiles. And it shows part of the color that you use to clear the screen.

**Option 1:** Modify the way you access the texture data.

Texture2D - set\_filter

Texture2D - FilterMode

```
atlas.set_filter(FilterMode::Nearest);

```

**Option 2:** Your tiles are 32x32 with 3 pixels between tiles. Using the same atlas (do not modify the picture), try using 30x30 as you tile area and 5 pixels between tiles.

```
match tiles[1] {
    ' ' => blit(atlas, 0, 0,  1.0, 36.0, 30.0, 30.0),
    '*' => blit(atlas, 0, 0, 71.0,  1.0, 30.0, 30.0),
    _=> (),
}

```

**Option 3:** Modify the picture adding a border (1 pixel) of the same color to each tile.

Disclaimer: I have never used neither Rust nor Macro-Quad.

---
Tags: texture-atlas, tilesets, rust
---


# Question
Title: Why are all materials pink in my Unity URP project?
Version: Unity 2020.2.0f1

I started my project with Universal Render Pipeline template but I don't know why all materials are pink. I even tried to upgrading but nothing happened.

This error was coming after upgrading:

And when I am creating new materials then I still getting pink materials and I am also not able to upgrade them:

# Answer
> 4 votes
To upgrade built-in Shaders (ref):

> Open your Project in Unity, and go to **Edit** \> **Render Pipeline** \> **Universal Render Pipeline**. According to your needs, select either **Upgrade Project Materials to URP Materials or Upgrade Selected** Materials to URP Materials.

# Answer
> 1 votes
A way I've managed to fix this is by right-clicking on the Project then selecting "Reimport all".

# Answer
> 1 votes
In addtion to what has being said, you might check if there is indeed a Render Pipeline selected in your project.

Go to **Edit \> Project Settings \> Graphics**

Check if **Scriptable Render Pipeline Settings** is not marked as **None**.

If it is **None** you'll certainly experience pink materials.

# Answer
> 0 votes
Finally I fixed it; just downgrade your URP from 12.0 to an older version.

# Answer
> 0 votes
First of all, you need to create a URP asset. To do so, right click in the project window and choose create/Rendering/URP asset. Then make sure that this asset is set to your scriptable render pipeline setting. (check Edit/Project settings/Scriptable Render Pipeline Setting). on the final steps, you can Upgrade your materials by going to Edit/Render Pipeline/Universal Render Pipeline/Upgrade.

---
Tags: unity, materials, unity-urp
---


# Question
Title: VariablesSaver.cs is corrupted after project migration in newer Unity version
I updated Unity Editor version to 2021.3.0f1 from I do not remember which version where I had a project.

After reimporting, almost all is fine, except 2 exceptions in console about syntaxis error in `VariablesSaver.cs`. I opend that file to explore the problem, and found out that the part of file seems to be just erased. That's what it has:

```
using UnityEngine;

namespace Unity.VisualScripting
{
/// <summary>
/// Listens to the OnApplicationQuit on OnApplicationPause
/// hooks to trigger the serialization of saved variables into PlayerPrefs.
/// </summary>
[Singleton(Name = "VisualScripting SavedVariablesSerializer", Automatic = true, Persistent = true)]
[AddComponentMenu("")]
[DisableAnnotation]
[IncludeInSettings(false)]
public class VariablesSaver : MonoBehaviour, ISingleton
{
    private void Awake

```

Does anyone have the full file, or how to fix it?

# Answer
> 1 votes
As @DMGregory pointed, the problem with stuff (packages) like visual scripting can be managed via package manager. In my case I just deleted it at all, and it fixed my problem.

1. On top tabs go to `Window` -\> `Package Manager`
2. In top left select `In project`
3. From the packages list that will be loaded choose needed and in bottom right there will be `Remove` button

---
Tags: unity
---


# Question
Title: Orthographic camera in libgdx does not work with constructor when passing viewports size
I am playing around with LibGdx and its OrthographicCamera and notice something, what is really strange for me. I mean if you look into the code below you will see that I am initialising OrthographicCamer without passing arguments (viewportwidth, viewportHeight) and setting up them later, and this code is working properly, I mean it showing me what I have expected I mean smaller area of my map (which is later rendered) in render method.

And I try second way of initialising OrthographicCamera where I pass the same values to the constructor, but this give me nothing. I mean I do not see my map at all just color BLACK(which I pass as `ScreenUtils.clear(color)` argument) and I am trying to understand the different behaviour of this code which for me should have the same output.

I hope someone will be able to help me understand that, I looked into the LibGdx source code, but I am missing something cause I still not understand why this behaviour is different.

```
// this is working code
camera = new OrthographicCamera();
camera.setToOrtho(false); // this set Y axis pointing up
camera.viewportWidth = 60;
camera.viewportHeight = 30;

// this code below is not working as expected
camera = new OrthographicCamera(60, 30);
camera.setToOrtho(false); // this set Y axis pointing up

```

# Answer
It looks like you are not actually updating the camera in the first version. You are supposed to call camera.update() if you change those values.

Try commenting out these lines

```
//camera.viewportWidth = 60;
//camera.viewportHeight = 30;

```

Does it still "work"? I think your map rendering is relying on the default camera.
> 0 votes

---
Tags: libgdx
---


# Question
Title: How to keep gui button original color including the white content color?
This is just a test.

The PING PONG button color is in Red and also the START/STOP button start with the Red color. but in the START/STOP button i'm trying to keep the original color and then to change the color. The problem is that the content of the START/STOP button color is changed to red too and i want to keep the content color of the START/STOP to be white like in the PING PONG button.

In this screenshot the LOOP and CHANGE DIRECTION buttons are in the original colors. The PING PONG is in red color and original content(white). The STOP button is what i'm trying to to be able to change it's background color with keeping the original background settings but the content color is not white.

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

public class GUIExamples : MonoBehaviour
{
    public Texture btnTexture;
    public Color color;
    public GUISkin skings;

    public string colorInf;

    private GUIStyle currentStyle = null;
    private Color oldColor;
    private bool test = false;
    private string test1;

    private void Start()
    {
        oldColor = color;

    }

    private void OnGUI()
    {
        if (!btnTexture)
        {
            Debug.LogError("Please assign a texture on the inspector");
            return;
        }

        //GUI.backgroundColor = color;
        if (GUI.Button(new Rect(10, 10, 170, 30), "LOOP"))
            Debug.Log("Clicked the button with an image");

        //GUI.backgroundColor = Color.green;
        if (GUI.Button(new Rect(10, 50, 170, 30), "CHANGE DIRECTION"))
            Debug.Log("Clicked the button with text");

        GUI.backgroundColor = Color.red;
        if (GUI.Button(new Rect(10, 90, 170, 30), "PING PONG"))
            Debug.Log("Clicked the button with text");

        var defaultColor = GUI.color;
        if (test == false)
        {
            GUI.color = Color.red;
            test1 = "STOP";
        }
        else
        {
            GUI.color = Color.green;
            test1 = "PLAY";
        }
        if (GUI.Button(new Rect(10, 130, 170, 30), test1))
        {
            Debug.Log("Clicked the button with text");
            test = !test;
        }
        GUI.color = defaultColor;

        InitStyles();
        GUI.Box(new Rect(10, 170, 170, 30), "PAUSE", currentStyle);
        if (GUI.Button(new Rect(10, 170, 170, 30), "PAUSE", currentStyle))
            Debug.Log("Clicked the button with text");
    }

    private void InitStyles()
    {
        if (oldColor != color)
        {
            currentStyle = null;
        }

        if (currentStyle == null)
        {
            currentStyle = new GUIStyle(GUI.skin.box);
            currentStyle.normal.background = MakeTex(2,2,
                new Color(color.r, color.g, color.b));

            oldColor = color;
        }
    }

    private Texture2D MakeTex(int width, int height, Color col)
    {
        Color[] pix = new Color[width * height];
        for (int i = 0; i < pix.Length; ++i)
        {
            pix[i] = col;
        }
        Texture2D result = new Texture2D(width, height);
        result.SetPixels(pix);
        result.Apply();
        return result;
    }
}

```

# Answer
> 1 votes
Check GUI API here.

**backgroundColor** Global tinting color for all background elements rendered by the GUI.

**color** Applies a global tint to the GUI. The tint affects backgrounds and text colors.

**contentColor** Tinting color for all text rendered by the GUI.

In IMGUI, It retains many old GUI drawing modes(this reminds me of java awt or something like that).

Here's a hint:

Think of these variables as **brushes**. When you change the brush color, it affects all subsequent paints until it is set to another value. So restore the color after each drawing to keep the brush clean.

If you want to set the background color only. You can try this:

```
    var defaultColor = GUI.backgroundColor;
    if (test == false)
    {
        GUI.backgroundColor = Color.red;
        test1 = "STOP";
    }
    else
    {
        GUI.backgroundColor = Color.green;
        test1 = "PLAY";
    }
    if (GUI.Button(new Rect(10, 130, 170, 30), test1))
    {
        Debug.Log("Clicked the button with text");
        test = !test;
    }
    GUI.backgroundColor = defaultColor;

```

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


# Question
Title: rendering the position of a mesh in a shader as a color, but the color does not match the actual position
```
//Vertex shader
o.baseWorldPos = unity_ObjectToWorld._m03_m13_m23;

//Frag shader
fixed4 col = fixed4(1,0,0,1);

if (i.baseWorldPos.x >= 0.5 && i.baseWorldPos.y >= 0.5 && i.baseWorldPos.z >= 0.5) {

    col = fixed4(i.baseWorldPos.x,i.baseWorldPos.y,i.baseWorldPos.z,1);

}

```

so in my vertex shader, i grab the meshes world position, and based on tests using the if statement in this code i can confirm that the value matches the position of the model in world space in the game/editor. If the objects xyz are all below 0.5, it draws in a full red color, if not then it becomes a color based on the positions as it should. So we know that the position being passed in is correct.

The problem is, the color that is generated based of this position, is something entirely different. When I set the positions so that each xyz = 0.51, you would expect to get a color of rgb = 0.51, but instead i get rgb = 0.7411.

does anyone have any idea why this is the case?

# Answer
> 0 votes
It turns out the displayed color is different than the actual data in the texture, which has the correct values, and I had just neglected to check that.

By rendering the object to a render texture, and copying that render texture to a regular texture using `Texture2D.ReadPixels`, I can then use `GetPixel` to get the literal RGB data of each color rendered, which match up to the object's position.

---
Tags: unity, shaders, rendering, color
---


# Question
Title: Can't make simple shader transparent in Unity
I have already visited a lot of links, but non of them did not help me.

I just want to make a window as a plane (face) with texture with transparency.

`.shader`:

```
Shader "Custom/NewSurfaceShader"
{
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
}
SubShader
{
    Tags {"Queue" = "Transparent" "RenderType"="Transparent"}
    LOD 200

    CGPROGRAM
    // Physically based Standard lighting model, and enable shadows on all light types
    #pragma surface surf Standard fullforwardshadows

    // Use shader model 3.0 target, to get nicer looking lighting
    #pragma target 3.0

    sampler2D _MainTex;

    struct Input
    {
        float2 uv_MainTex;
    };

    half _Glossiness;
    half _Metallic;
    fixed4 _Color;

    UNITY_INSTANCING_BUFFER_START(Props)
    UNITY_INSTANCING_BUFFER_END(Props)

    void surf (Input IN, inout SurfaceOutputStandard o)
    {
        // Albedo comes from a texture tinted by color
        fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
        o.Albedo = c.rgba;
        // Metallic and smoothness come from slider variables
        o.Metallic = _Metallic;
        o.Smoothness = _Glossiness;
        o.Alpha = c.a;
    }
    ENDCG
}
FallBack "Diffuse"
}

```

Material:

Test texture on imgur(I think it did not erase alpha when upload)

Result:

Result, if in material set `Render Queue` to `Alpha Test` or `Geometry` (others are opaque):

Seems like it renders begind it only geometry with clear white faces without texture in this case. And, anyway, it has dark background, when image texture does not.

What am I doing wrong? Unity 2021.3.0f1

---

Example of texture I want to use as window.

What do I want (in Blender):

# Answer
This is covered in the documentation:

> # Optional parameters
>
> **Transparency and alpha testing** is controlled by `alpha` and `alphatest` directives. Transparency can typically be of two kinds: traditional alpha blending (used for fading objects out) or more physically plausible “premultiplied blending” (which allows semitransparent surfaces to retain proper specular reflections). Enabling semitransparency makes the generated surface shader code contain blending commands; whereas enabling alpha cutout will do a fragment discard in the generated pixel shader, based on the given variable.
>
> * `alpha` or `alpha:auto` \- Will pick fade-transparency (same as `alpha:fade`) for simple lighting functions, and premultiplied transparency (same as `alpha:premul`) for physically based lighting functions.
> * `alpha:blend` \- Enable alpha blending.
> * `alpha:fade` \- Enable traditional fade-transparency.
> * `alpha:premul` \- Enable premultiplied alpha transparency.
> * `alphatest:VariableName` \- Enable alpha cutout transparency. Cutoff value is in a float variable with `VariableName`. You’ll likely also want to use `addshadow` directive to generate proper shadow caster pass.
> * `keepalpha` \- By default opaque surface shaders write 1.0 (white) into alpha channel, no matter what’s output in the Alpha of output struct or what’s returned by the lighting function. Using this option allows keeping lighting function’s alpha value even for opaque surface shaders.
> * `decal:add` \- Additive decal shader (e.g. terrain AddPass). This is meant for objects that lie atop of other surfaces, and use additive blending. See Surface Shader Examples
> * decal:blend - Semitransparent decal shader. This is meant for objects that lie atop of other surfaces, and use alpha blending. See Surface Shader Examples

So depending on your exact needs, you likely want to change:

```
#pragma surface surf Standard fullforwardshadows

```

to something like:

```
#pragma surface surf Standard fullforwardshadows alpha

```
> 2 votes

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


title: Why do prefabs speed up loading?

text:
# Question
Title: Why do prefabs speed up loading?
I have a scene with a massive terrain. It took a long time to load (approximately 60 seconds) when I pressed play. I am in the editor.

I prefabbed it.

Now it only took about 5 seconds to load when I pressed play. Why?

My best guess is that there is some preloading done when it is prefabbed, but it only takes a few seconds to prefab it. So that couldn't be the reason. Any ideas? I am at a loss.

# Answer
> -1 votes
So the original question ***"why do prefabs speedup loading"*** is an very interessting question.

You may check out the memory part of the profiler when working with prefabs.

Every asset you once prefabed will use memory for reference. Even when you unload and destroy the prefab - there is still some information kept in the memory ***(as an example the texture part of the prefab).***

When you load the prefab unity will access this information by reference and speedup loading.

When your project getting very large though it could eat up your memory even when you destroy thous prefabs. ***This also applies to prefabs whch are currently not loaded into scene.***

You should check out Unitys Addressable Asset for qualified information.

Greetings :)

# Answer
> -2 votes
## What are Prefabs

The Unity Documentation for Prefabs simply describes it as

> A template from which you can create new object instances in the scene. Any edits made to a prefab asset are immediately reflected in all instances produced from it but you can also override components and settings for each instance individually.

## How does it effects performance

My experience tells, it does not. Since google does not point to any rigid analysis that whether or not prefabs improve performance nor I have done any experimentation regarding this, this Unity answers.com question explains it like this:

> There's nothing magic about prefabs; they are simply a convenience. There's no performance difference between putting two cubes in a scene, or making a prefab out of the cube and then putting two cube prefabs in the scene.

That's all. If there is any performance improvement reports or analysis or anything regarding this, I might want to know about it as well. Thank you.

**EDIT:** I tried what you said, made a terrain of 50k by 50k with heightmap resolution of 512 (couldn't get any higher).

1. Pressed play button first ~ 5seconds
2. Pressed play button second time ~ 4-5 Seconds(roughly)
3. Prefabbed it and pressed Play ~ 4-5 Seconds
4. Waited for a while, may be 5minutes and pressed play 2-3 seconds

Time difference was not significant but here's what I noticed. Whenever you change Terrain settings, on the bottom right corner, there is some processing happening. If you let that complete, the startup time would decrease.

Here's what it looks like:

I didn't know your terrain settings and how complex it was but from this I can deduce that bottom-right processing might be the thing that manages the load time. It might be loading in the memory and could be doing some one-time calculations/ processing.

# Answer
> -5 votes
Prefab is just for reusability and for a repeatable task it doesn't have any connection with preprocessing. When rendering process happens with any game objects and it has any retrace to the project panel unity make its meta file and store some information on it and for next time Unity uses that information for next time.

---
Tags: unity, performance, loading, preload
---


title: How to round to a multiple of 0.25?

text:
# Question
Title: How to round to a multiple of 0.25?
I have a problem when I any rational number so that it's 0.25, 0.5, 0.75, etc.

```
public float Coins, Money, Total;

void Start()
{

    Total = Coins / Money;
    // 3 / 7 = 0.4285714
    // In this case I need to get [1.5 or 0.5]. How to do that?
}

```

# Answer
This is the solution I implemented in my code:

```
public float Coins, Money, Total;

void Start()
{

Total = Coins / Money;
Total = QuarterValue(Total);

}
float QuarterValue(float value)
{
    return 0.25f * Mathf.Round(value / 0.25f);
}

```
> 0 votes

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


# Question
Title: Struggling with breadth first search for hex grid
I cant seem to get breadth first search right. Ive gone through redblobs implementation guides of hex grids and have that all figured out but pathfinding is proving to be difficult.

So I have a search function that implements the algorithm.

```
function searchPath(graph, start, goal) {
    let cameFrom = [start]
    let frontier = new Queue()
    frontier.enqueue(start)

    while (!frontier.isEmpty) {
        const current = frontier.dequeue()

        if (current === goal) break

        graph[current].forEach(next => {
            if (!cameFrom.includes(next)) {
                frontier.enqueue(next)
                cameFrom.push(next)
            }
        })
    }
    return cameFrom
}

```

my graph is a two dimensional array where each index corresponds to a tile on the map and the value of each is an array of indexes of neighbors of that tile.

Example:

```
const graph = [
    [3,1,4],
    [0,4,2,5],
    [1,5,6],
    [7,0,4,8],
    [0,3,8,1,5,9],
    [1,4,9,2,6,10],
    [2,5,10,11],
    [3,8,12],
    [3,7,12,4,9,13],
    [4,8,13,5,10,14],
    [5,9,14,6,11,15],
    [6,10,15],
    [7,8,13,16],
    [8,12,16,9,14,17],
    [9,13,17,10,15,18],
    [10,14,18,11],
    [12,13,17],1
    [13,16,14,18],
    [14,17,15]
]

```

The function returns the indexes of searched tiles.

Example 1: `searchPath(graph, 12, 13)` will return `[12, 7, 8, 13, 16, 3, 4, 9]` Example 2: `searchPath(graph, 8, 1)` will return `[8, 3, 7, 12, 4, 9, 13, 0, 16, 1, 5, 10, 14, 17]`. Its returning a lot of nodes for what would seem to be a

Now I attempt to reconstruct a path with this function but I cant get it to work. It ends up with an infinite loop.

```
function findPath(cameFrom, start, goal) {
    let current = goal
    let path = []
    while (current !== start) {
        path.push(current)
        current = cameFrom[cameFrom.indexOf(current)]
    }
    return path
}

```

I have a feeling my graph data structure is off but I just don't know. Heres a link to the current version of the "game". If you open the console you should see the output of the search and the start + goal arguments that are supplied.

https://cwahlfeldt.github.io/hex-game/

Any help would be much appreciated. Thanks!

# Answer
> 2 votes
It looks like you are confusing **Predecessor Node List** and **Closed Set**.

What's the meaning of `cameFrom`? In `searchPath` you use it to store all visited node, but in `findPath` you use it to reconstruct a path. That's the crux of the matter.

Fix:

```
function searchPath(graph, start, goal) {
    let frontier = new Queue();
    frontier.enqueue(start);

    var predecessorMap = {}; //a map of the node found by which node

    while (!frontier.isEmpty) {
        const current = frontier.dequeue();
        if (current === goal) break;

        graph[current].forEach(next => {
            if (!(next in predecessorMap)) {
                frontier.enqueue(next);
                predecessorMap[next] = current;
            }
        });
    }
    return predecessorMap;
}

function findPath(predecessorMap, start, goal) {
    let current = goal;
    let path = [];
    while (current !== start) {
        path.push(current);
        current = predecessorMap[current];
    }
    return path;
}

```

---
Tags: javascript, path-finding, html-canvas, hexagonal-grid
---


title: How to find words on a hex grid

text:
# Question
Title: How to find words on a hex grid
I am trying to make a hex grid based word game. Currently the words are placed from a list of pre-defined words(a list of animals in this case). All colored cells make a word that was placed, while white cells are just random letter. As each word is placed, the word and the indexes needed to make that word are saved to a list for AI to use.

now:

* It is possible to make the words CAT and DOG (marked in red), other words my be possible as grid is randomly generated.
* A Human player can make these words, no problem there
* how do i add those words and their indexes to a list of words that can be made

# Answer
> 2 votes
I once wrote a word finder that worked with a precomputed list. Basically each letter knows which next letter is valid. You can exit the search if there is no valid letter anymore. A flag indicated that it was a whole word.

Example word list:

* Bee
* Bear
* Bees
* Bat

The only start letter with this list would be a `B`. If you found a `B` in your grid, you would check around that `B` if you can find either an `a` or an `e`. If you found an `a`, you would look around again if there is a `t`. No `t` means no valid animal. If instead of the `a` you found the `e`, you would continue to look again now for either again `a` or `e`.

# Answer
> 1 votes
You can do this with a series of depth-first searches, starting from each cell.

Your starting cell's letter forms the initial word prefix. In each iteration, you check if some word in your dictionary either wholly matches the current prefix (if so, add the word and the indexes you traversed to get here to the possible answer set) or if no word in your dictionary starts with this prefix (if so, abort this search branch, backtracking to the next shorter prefix).

Then you examine the neighbours of the current cell, and if any have not already been crossed in the path you took to get here, recurse on them, adding their index to your path-so-far and their letter to the end of your prefix.

If you sort your dictionary in lexicographical order, then all words matching a particular prefix will correspond to a contiguous range of indices in that list, which you can represent with a start/end index or start and count. Then you only ever have to search smaller and smaller ranges of your list, not the whole thing.

Or if you want to get fancy, you could implement your dictionary as a Finite State Acceptor that accepts only valid words, or a Transducer that maps valid words to their corresponding string or id, or a trie similarly. Then your search is effectively a constrained walk of the state graph of this data structure.

---
Tags: unity, algorithm, hexagonal-grid
---


title: Making interacting gears in 2D

text:
# Question
Title: Making interacting gears in 2D
I want to create mutually rotating gears for a puzzle game.

I looked at a lot of material, but didn't understand how to make a RigidBody2D stay in one place correctly and interact with each other.

Here is the code I use:

```
extends RigidBody2D
var angle = 1
signal clicked
var held = false
var c
var vec
var speed:float = 100
var angele:float = 100
func _input_event(viewport, event, shape_idx):
    if event is InputEventScreenTouch:
        if event.pressed:
            c=true
            emit_signal("clicked", self)
    if event is InputEventScreenTouch:
        if !event.pressed:
            c=false

func _physics_process(delta:float)->void:
    global_transform.get_rotation()
    global_transform.interpolate_with(transform.rotated(rotation), 10)
    if c == true and held:
        global_transform.origin = get_global_mouse_position()
        vec = Vector2(get_position())
    if c == false and vec != null:
        position = vec
    #rotation = deg2rad(angle)

func _integrate_forces(state):
    #global_transform.get_rotation()
    #global_transform.interpolate_with(transform.rotated(rotation), 10)
    transform = transform.interpolate_with(transform.rotated(rotation), rotation)
    #contact_monitor = true
    #print(transform.rotated(rotation))

func pickup():
    if held:
        return
    mode = RigidBody2D.MODE_STATIC
    held = true

func drop(impulse=Vector2.ZERO):
    if held:
        mode = RigidBody2D.MODE_RIGID
        held = false

```

# Answer
> 1 votes
> how to make a RigidBody2D stay in one place

From a design approach, you would make an `StaticBody2D` (or some other body) and a `PinJoint2D` with your `RigidBody2D`.

From a programmer approach, you would write `state.transform` in `_integrate_forces` (which is also the most common way to do a teleport). *For reference, the `state` parameter you get in `_integrate_forces` is of type `Physics2DDirectBodyState`.*

And if you rather use a lower level API, you can write the transform of the `RigidBody2D` at any time with `Physics2DServer.body_set_state`, which will be understood as a teleport (Godot will not solve the collision as if the `RigidBody2D` moved from the prior transform to the new one). For example:

```
Physics2DServer.body_set_state(
    get_rid(),
    Physics2DServer.BODY_STATE_TRANSFORM,
    Transform2D.IDENTITY.translated(new_position)
)

```

And neither of the approaches described above would require changing the `mode` of the `RigidBody2D`.

---
Tags: 2d, rotation, godot, rigidbody
---


# Question
Title: Player object changes position when I click the pause button
I have a simple mobile game where every time I touch the screen, the car changes direction.

The thing is, I need to implement a pause button, but when I click pause I need the car to stay still and not move. Right now it keeps responding to the inputs even when the game is frozen. Could someone help me find a way to overcome this issue?

Here's what happens:

This is how I check for input and change direction:

```
void CheckInput()
{

    if (firstInput)
    {
        firstInput = false;
        return;
    }

    if (Input.GetMouseButtonDown(0) && firstInput == false)
    {
        ChangeDirection();
    }
}

void ChangeDirection()
{
    if (movingLeft)
    {
        movingLeft = false;
        transform.rotation = Quaternion.Euler(0, 270, 0);
    } else
    {
        movingLeft = true;
        transform.rotation = Quaternion.Euler(0, 180, 0);
    }
}

```

And how I pause my game:

```
public void PauseButton()
{
    if(isPaused == false)
    {
        Time.timeScale = 0f;
        //_pauseButton.SetActive(false);
        //_pauseButton.GetComponent<SpriteRenderer>().sprite = reload;

        Debug.Log("Clicou");
        isPaused = true;
    }
}

```

I tried to check the "isPaused" bool on the character controller, but even like this it moves the first time I click. I tried to use a Raycast like I read in a few places, but I couldn't get it working.

# Answer
> 0 votes
Try using this methods when pressing the pause button (im assuming that you added a button for that):

```
bool gameIsPaused = false;
void PauseGame ()
    {
       if(!gameIsPaused )
       {
         Time.timeScale = 0;
         gameIsPaused = true;
       }
        Time.timeScale = 0;
       else
       ResumeGame();
    }
void ResumeGame ()
    {
        Time.timeScale = 1;
        gameIsPause = false;
    }

```

---
Tags: unity, c#, input, unity-ui
---


title: Unity Multiplayer Sync Bools

text:
# Question
Title: Unity Multiplayer Sync Bools
I have a little problem with syncing booleans on my networking game.

I use the Mirror-Package for networking and use KCP for transport.

When the players basicly collide each other ***(**using a sphere trigger box for detection**)*** they should change their state from false to true or otherwise.

Sometimes it is working and sometimes booth get the same state displayed by color - ***the problem mostly accures when running.***

Tested with a friend - ***the color get synced correctly*** but ***the booleans sometimes do not get set correctly.*** For debugging purposes the state can be changed by key press.

Thanks for advice!

```
private void OnTriggerEnter(Collider other)                  // Getting called a player enter collision
{
    if (isLocalPlayer)                                       // Check if this is local player
    {
        if (other.gameObject != gameObject)                  // Double check it not own body - problematic on begging
        {
            if (cooldown == false)                           // Make sure player is not on cooldown
            {
                if (other.gameObject.CompareTag("Player"))   // Make sure the gameobject has right tag
                {
                    ChangePlayerState(caught);               // Call function an pass in current state which is a boolean
                }
            }
        }
    }
}

#region Player State

[Client]
public void ChangePlayerState(bool state)
{
    cooldown = true;                                          // Activate cooldown

    if (state == true)                                        // Do logic for true
    {
        caught = false;
        stateLight.color = Color.green;
    }
    else
    if (state == false)                                       // Do logic for false
    {
        caught = true;
        stateLight.color = Color.red;
    }

    Invoke("ChangeCooldown", 3);

                                                             // Networking-Part - Changing only color when networking

    if (isClient) CmdChangePlayerState(caught);              // Execute Command
    if (isServer) RpcChangePlayerState(caught);              // Execute Rpc

}

[Command]
private void CmdChangePlayerState(bool state)                // Change color according to statebool
{
    if (state == true)
    {
        stateLight.color = Color.red;
    }

    else

    if (state == false)
    {
        stateLight.color = Color.green;
    }
}

[ClientRpc]
private void RpcChangePlayerState(bool state)                // Change color according to statebool
{
    if (state == true)
    {
        stateLight.color = Color.red;
    }

    else

    if (state == false)
    {
        stateLight.color = Color.green;
    }
}

```

# Answer
> 1 votes
I solved the problem by calling the initial `OnTriggerEnter` event only on the server.

***The server*** changes the state for itself, and then for the player.

---
Tags: unity, networking, multiplayer, unity-networking, mirror-networking
---


# Question
Title: How to prevent a huge backlog of physics calculations from freezing browser when tabbing out of browser game?
I'm developing a browser game and am using the timestep implementation from the famous Fix your timestep! article.

It works perfectly, but there is one problem. If you tab out of the tab and then come back 5 minutes later or so, it freezes, because it has to execute all the missed physics calculations. That is, this code:

```
accumulator += frameTime;

while (accumulator >= dt)
{
    previousState = currentState;
    integrate( currentState, t, dt );
    t += dt;
    accumulator -= dt;
}

```

Seems to have to execute for quite a while because the accumulator has missed so many calculations while the tab was .. sleeping I guess?

I'm confused though. Shouldn't Javascript continue to run while the tab is not active? Why is this happening?

Is there any way to fix this? Ideally the Javascript would continue to run so that it wouldn't cause the tab to freeze for 2 minutes when coming back to it after being in other tabs for a while.

# Answer
The way the Unity engine solves the problem of freezing the game while physics catches up is to enforce a maximum value the accumulator can ever hit.

You can implement this by replacing

```
accumulator += frameTime;

```

with

```
accumulator = Math.min(accumulator + frameTime, maxDeltaTime);

```

...for a maximum time delta that you control. It should be at least as large as `dt`. A good way to pick this value is to consider your lowest acceptable framerate, then invert it. So for instance, if you don't want your game to drop below 15 frames per second, then `maxDeltaTime = 1/15`.

This way you'll keep pace with real time as long as the browser/CPU is able to keep up. If tabbing away and back, or heavy processor load causes more real time to pass than what you can keep pace with at your minimum acceptable framerate, then instead of stalling (and dropping to an even lower framerate), this code instead allows the game to fall behind real time. So the game runs slow, but keeps updating and showing progress, rather than hard locking.
> 2 votes

# Answer
Looks like I found a decent solution. So while `requestAnimationFrame` doesn't really seem to run at all when the tab is tabbed out (makes sense), `setTimeout` and `setInterval` seem to get throttled to run once a second (good enough for me!)

So the solution is to put all the rendering logic in `requestAnimationFrame` (so that this doesn't run at all because who cares about rendering when you can't see it), and then put all physics logic in a `setTimeout(physics, 0);` which calls itself with another `setTimeout(physics, 0);`

Then every second it processes all the physics and sleeps for another second on repeat. This seems to solve the issue somewhat decent enough, such that when I come back to the tab after being gone for 10 minutes, it only seems to freeze for like half a second, where previously it would freeze for like 10 seconds.

I looked into using WebWorkers but those can't access the DOM so they seem pretty useless in this case, because I'm not going to be cloning the entire state of the game every frame to pass back to the main thread.. it'd be too slow.

Anyways, this seems okay enough as a solution so I'll probably accept my own answer in a couple days if I remember, unless someone comes up with something better in the interim.
> 0 votes

# Answer
Okay, I think I found the actual answer. This prevents all freezing from occurring (because it keeps your game running in the background even if you tab out). Here's how you do it:

First, in your main file, have something like this for drawing:

```
function drawGame() {
  // Drawing code goes here

  requestAnimationFrame(drawGame);
}

requestAnimationFrame(drawGame);

```

The reason you put all your drawing code in `requestAnimationFrame` is because it's not called while the tab is not visible. This is good, because we only want to do physics when the tab is not visible, not rendering.

Next, create a file called `worker.js` that only contains these 3 lines of code:

```
setInterval(() => {
  postMessage(1); // IDE complains if we don't pass a useless parameter.
}, 1);

```

Then in your main file, have something like this:

```
let prevTime = 0;
let remainingTime = 0;

function gameLoop() {
  const elapsed = performance.now();

  let delta = (elapsed - prevTime) / 1000;
  prevTime = elapsed;

  remainingTime += deltaTime;

  while (remainingTime > PHYSICS_TIMESTEP) {
    doPhysics(PHYSICS_TIMESTEP);

    remainingTime -= PHYSICS_TIMESTEP;
  }
}

let intervalWorker = new Worker('./src/worker.js');
intervalWorker.onmessage = gameLoop;

```

The logic here is that the web worker still sends a "tick" message every 1 millisecond, even if the browser tab is not active. It's basically a hack that allows you to run fast intervals even if the browser tab isn't open. But the game loop will only be executed if it's not already running (the `ready` variable ensures this)

However, you still use an accumulator in your physics loop. This prevents the physics from running every frame. You still use a fixed timestep and calculate the delta using `performance.now()` math.

This is a bit complex I know, but it seems to work perfectly.
> 0 votes

---
Tags: physics, javascript, architecture, performance, timestep
---


# Question
Title: How to synchronize the main thread (rendering, 60 FPS) with the game logic thread (10 FPS)
I wrote some games years ago, and they were always in sync with the main thread. So, for example if the monitor refresh rate is 60 Hz it would look like below.

```
OnPaint =
  Advance game 1/60th of a second
  Render at 60 FPS

```

This works well for arcade type games, but not necessarily for other game types.

```
I want to run something more like this:
  Game logic at 10 FPS
  Render at 60 FPS

```

This is mainly because the "game logic" takes much longer than 16 ms now.

I still want to render at 60 FPS, because the animations run faster than 10 FPS, and also the moving of sprites needs to be smooth. I don't see the point in moving a sprite from 0 to 10 to 20, etc. It should move at a higher constant rate, e.g. from 0 to 1 to 2, etc.

So, I was thinking of adding a game logic thread:

```
Game thread =
  Setup animations
  Setup physics, e.g. move object to x/y at some speed, and direction, etc

OnPaint =
  Update animations and sprite positions
  Render

```

This then means there has to be some kind of sprite object between the two threads.

```
ISprite = interface
  x/y: integer
  width/height: integer;
  image: PImage;
end;

```

So, the game logic then sets up the x/y, the image (or animation), and the OnPaint then renders it to the screen. The OnPaint also advances the x/y according to the direction and speed, which makes for smooth moving.

So, the game logic might say "animate sequence X on sprite Z", or "move sprite Z to x/y at speed/direction" (the physics), and the OnPaint then takes whatever frames to complete that smoothly.

I would need to add a lock for accessing the sprite data.

```
ISprite = interface
  BeginUpdate(); // acquire lock
  x/y: integer
  width/height: integer;
  image: PImage;
  EndUpdate(); // release lock
end;

```

The idea is to lock the entire object, so there won't be any glitches where the sprite appears at the wrong location temporarily, because the render came after setting X, but before setting Y, etc.

I will also have to be extremely careful with other objects, e.g. the list of sprites needed in both threads, etc.

Is all that even right?!? Is there an easier way to achieve all this? Am I missing something obvious here? :)

Maybe I should just compromise and run the game logic, and the rendering all at say 40 FPS. Or 30. At least then, I won't need any threads...

Any thoughts on this? :)

# Answer
> 1 votes
You may want to consider triple buffering your game state (or at least the display state), instead of locking individual sprites. This gives you several advantages:

* It's faster, because you don't have the overhead of taking and releasing locks hundreds or thousands of times in every update/draw.
* It's simpler, because the thread management logic can stay in one place external to your game entities, rather than its tendrils reaching down into every entity you might want to update.
* It ensures you never draw an inconsistent state, where some sprites have been updated to the next time step while others haven't yet, which could lead to visual contradictions and glitches.
* Having multiple copies of the game data helps you implement interpolation, to smooth out the rendering of movement between simulation updates.
* It might even help you get more parallelism in your simulation tick, to improve your update rate. You could spread the work of updating each component or entity across multiple threads that can simultaneously read the unmodified previous state, without risk of them stepping on each other and overwriting data that another part of the sim process is trying to read.

It would work something like this: you have three copies of a data structure giving the current position/orientation/size/image of each active sprite, and a counter or pointers to identify them as "previous" "current" and "next".

Your simulation thread writes to "next" while "previous" and "current" remain read-only for the rendering thread to use. Each time your simulation thread finishes an update, it swaps the pointers/counter so that "next" becomes "current", "current" becomes "previous", and "previous" gets marked as "next", to be overwritten in its next tick. This is the only place in your code you need thread synchronization — or you could even add an extra buffer so you can start your next update lock-free without overwriting the "previous" buffer that might still be in use for interpolating the renderer state.

Your rendering thread then just takes the current and previous buffers at the start of the frame and computes an interpolation factor between them, based on the elapsed time. It loops over each sprite, looking up its corresponding info in the previous and current data structures, and rendering it at an interpolated position/orientation/size between the two states. If its image changes between the two states, you choose one image or the other to draw.

A sprite that exists in only one buffer or the other can be skipped — so newly spawned sprites appear and destroyed sprites disappear at frame corresponding to the start of the next sim tick.

---
Tags: game-loop, synchronization, thread
---


# Question
Title: Determine if a static mesh is lit by directional light
I want to determine if a mesh is lit by the directional light on my scene in editor to automatically disable its "dynamic shadow casting" property (let's say I have one light source in my scene which is this directional light).

The mesh is a static object: it can't move and it's not animated. It has a bounding box and a bounding sphere. All I need to do is to provide a *plausible* (not 100% accurate) answer to the following question: "is my static mesh fully occluded by some other static meshes?". I am not going to do that in real time, it's just an editor check, but my scene has several thousand static meshes, so it shouldn't be dead slow.

I'm afraid that the only way to do that is by performing a ray (or line) tracing in the direction of my light source. I can just trace the vertices of my bounding box, but the mesh can be **partially** occluded (e.g. vertices are, the centre of the bounding box is not) so my guess is that I need to trace a projection of the bounding box in the direction of my light source but I don't know how to calculate things like that and my idea may not be correct. :(

# Answer
Here's a wild solution:

Step.1

**backup** your scene.

Step.2

Gives all meshes in the scene a new material, it will just return the set color. the shader just like:

```
float4 frag (v2f i) : COLOR
{
    return _Color;
}

```

Step.3

Number each mesh and give it a color according to certain rules.(id-\>rgb, alpha=1)

Step.4

Create a orthographic camera, set its direction to be the same as the light. Set its size so that it sees all meshes in the scene. **Turn off antialiasing**.

Step.5

Set the camera's target texture, Iterate over all pixels, check if color "x" exists.This way you can tell if an object is illuminated. The accuracy depends on texture resolution.
> 1 votes

---
Tags: algorithm, lighting, raycasting, projection, occlusion
---


# Question
Title: Reducing adjacency bookkeeping work in constrained Delaunay triangulation
I'm using the Sloan algorithm for constraining a generated Delaunay triangulation. This primarily consists of edge flipping for the edges that overlap the constrained edges.

In order to flip an edge, I have to know what two triangles contain that edge, and so for every edge I currently maintain an index (into the triangle array) of the current and opposite triangles for that edge. This gets built from the triangle array, where each triangle maintains indices for all adjacent triangles.

While this works, I've found that the vast bulk of my code is dealing with the maintenance of these triangle adjacencies. Every time an edge gets flipped, I not only have to update the two triangles that share the edge, but also update all of the other neighboring triangles that may have adjacency to one of those triangles, as well as go through and update any adjacency indexes within my list of edges to be flipped.

And then again, after the edges are flipped and you get a list of final "good" edges to use, you have to go through them and make sure they still satisfy Delaunay circumcenter rules, and if not, flip them again. Which means repeating all of the same work to maintain adjacency indexes.

Is there an algorithm for efficiently maintaining triangle/edge adjacency without all of this work? Or, better, is there an efficient method of determining neighboring triangles that share a common edge without the need to maintain these links?

I feel like I'm doing more adjacency maintenance than actual triangulation...

# Answer
> 2 votes
You should be encapsulating in functions / methods as much as possible such that repetition is ultimately minimal (seek and extract common factors, ad nauseam). But that goes without saying.

The other way to view this is that you need some independent, reactive component that does the necessary things automatically, each time you modify the set, by "watching" when the set container changes. This at least takes the management logic out of your main body of code.

You could write a module that represents the collection of nodes (and edges, if these are distinct in your implementation) which, every time a node / edge is added to or removed from the set, calls one of its own helper functions to perform the necessary auxiliary updates. Access this module from your primary (cleaner) code, via the appropriate functions, to avoid excess management.

# Answer
> 0 votes
You can try the Quad-Edge data structure introduced by Guibas & Stolfi (1985). It puts all adjacencies in groups of 4 directed edges - 2 for each dual versions of the graph, or in other words the directed edges which connect 2 vertices and those that connect the corresponding 2 faces.

I found it hard to grok; especially the code that works with it. But it leads to dense code and quite normalised data structures, and other approaches might be even harder to follow.

---
Tags: algorithm, procedural-generation, c, mesh, delaunay-triangulation
---


# Question
Title: Remove gaps between 2D trail that is based on particle engine
Hi I'm using a particle engine suggested from this answer

I'm trying to create a seamless particle trail effect every similar to this (same) question

However, when the vehicle is travelling too fast gaps start to emerge between the particles and the seamless trail effect wears off:

How can I improve the effect so that it is seamless?

I'm using Monogame and each particle is generated in every Update() call

# Answer
> 0 votes
Store your last particle spawn position in a variable that persists from frame to frame. Then do something like this:

```
direction = Vector2.Normalize(currentPosition - lastParticlePosition);

float spacing = 1.0f;

while ( Vector2.Dot(direction, currentPosition - lastParticlePosition)
        > spacing * particleDiameter )
{
    lastParticlePosition += direction * spacing * particleDiameter;
    SpawnParticle(lastParticlePosition);
}

```

This fills the gap between the last particle and your current position with as many particles as needed. If you want more overlap, make the `spacing` value smaller.

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


# Question
Title: How do we convert a pex file to a psc file?
How do we convert a pex file to a psc file?

https://skyrim.nexusmods.com/downloads/file.php?id=2909

There used to be a file here that allegedly converted pex files to psc files, but it's no longer available, so I was wondering if there was a alternative GUI program that allows you to do this. I am trying to modify a pex file in a Skyrim mod.

# Answer
> 2 votes
You can use `PapyrusAssembler.exe` to decompile the `.pex` (which is a compiled Papyrus script) into something more human-readable:

```
PapyrusAssembler.exe <name of .pex without extension> -D

```

However the documentation notes that this output isn't the `.psc` file itself. You can also look for a `.pex` decompiler (or write one yourself). The Creation Kit documentation doesn't seem to detail the format of the `.pex` file, so unless you want to spend a lot of time reverse-engineering it you're probably better off finding a pre-written tool.

Searching the web for "Skyrim pex decompiler" yields a few results, including a link to this tool. These sorts of tools are usually never able to recover the *original* source code (since often, most of that information -- such as comments -- is lost when compiling). Poking around a little, it looks like they're useful for producing human-readable stuff but that stuff isn't necessarily human *friendly* and may not immediately be re-compilable as a new `.pex` without editing.

This one claims to be able to produce something that is round-trip capable, even if it isn't the original file.

---

If you're doing this to recover source code to scripts you've written, and subsequently lost, it won't get you all the way there (and next time, you may want to consider a backup solution).

If you're doing this to try to figure out how scripts you didn't write function, you may have better results trying to contact the author of the script and see if they can't just explain it to you. If they're not willing to do that, they may also not be okay with your decompiling their scripts.

# Answer
> 0 votes
Compiling happens for instance via Champollion compiler, an external application added by Bethesda to Creation Kit. You can find it here. You can also use Notepad++ and Sublime to compile or just use the version of the compiler build in the Creation Kit.

If you use the Notepad tools, it's a good idea to install the library of Papyrus for Skyrim. Here, in the official Bethesda CK wiki for Skyrim, you find a walkthrough how to use 5 different text editors for compiling scripts.

---
Tags: skyrim-modding
---


# Question
Title: How do we add a spell in Skyrim with the Creation Kit that can spawn several variants of the same NPC?
I am thinking of adding a spell that can summon a Nord, but I want it to have a random chance of spawning a female nord. I also want the NPC to appear in different armors, have different tattoos and different hairstyles. Is it possible to do this without using a script? What's the easiest way to achieve this?

# Answer
You would have to have a function that is able to create new reference objects of any base object selected. The edits you talk about, character attributes, are usually manually adjusted, but there once was a mod that did loop through a list of prevously defined colours of wolf's fur to spawn differently looking enemies randomly. This mod did require SKSE.

So you would have to prepare different base objects and then call them via script and spawn them, following your own rule. Perhaps on activate event, similar as a magic effect. The mod that could work as a proof of concept for your idea is "Automatic Variants" - but it requires manual preparation of these encounters. https://www.nexusmods.com/skyrim/mods/21377?tab=description

I am not sure how to access the actor properties via script and adjust them inside the script without GUI - i guess that would require much more work, to have variables randomly change these properties.

best success
> 0 votes

---
Tags: skyrim-modding
---


# Question
Title: Is it possible to make a 2D game using Unreal engine 5?
Is it true that UE5 can't be used to make a 2D game?

# Answer
Yes, you can use Unreal Engine 5 for 2D games. A quick search will confirm this and there are also tutorials that will tell you how to do it.

But possible and ease of usage are not necessary the same thing. Any engine that is capable of creating a 3D game *can* create a 2D game as well. It is just a question of how determined you are.

A few years back, Unity was by default for 3D games. Over the years they got a lot of 2D support. But it was always possible to create 2D games. The new tools just made it easier for creating content, easier/ simpler physics and optimization. This could be a problem for example in mobile builds when the tool is too powerful and you try to fit it.

Choosing the correct engine is not easy. Some people prefer visual scripting/ blueprints. Some just use scripts and not the editor. Some just want to have a lot of options available. When you choose one, a good indicator is how many tutorials are available and how active the community is. If you can't decide between a few, download them all and make a simple game (pong or breakout) in all of them. Compare how easy it was or with what you struggled. If a simple game already is giving you trouble (trouble as in the engine does not want as you want it to be, either not understanding how it works or just interactions), a full blown game like you plan to do will be a nightmare.

In the end you need to be happy with it when you code with it.
> 2 votes

---
Tags: c++, 2d, unreal-5
---


# Question
Title: How to port a Skyrim Legendary Edition mod to Skyrim Special Edition, and vice-versa?
There are a lot of mods I want to port, but I don't know how to go about it and do it properly to avoid crashes, etc. Could you put all of the steps and relevant information here so I can use it as a future reference? I am trying to port a major mod with scripts, 3d models, new items, new spells and whatnot.

# Answer
> 2 votes
There is quite some elaborate process description available. The gist of it is, ESMify the masters, open in the SE CK, resave. Use SE NifOptimizer on the skinned meshes. Use the SE version of the archiving tool. By skinned meshes I refer to creatures and armors -- anything that's rigged to Skyrim's vanilla animations via bones and joints. I would run NifOptimizer on everything except particle effects for good practice.

https://www.nexusmods.com/skyrimspecialedition/mods/17990

**Changes from LE to SE:**

* vertex definitions for meshed and bounding meshes for particles (all quads)
* textures formats were a bit changed due to the change of direct x sdk (tga formate no longer supported, dds compression slightly changed)

**So the involved nodes are:**

* Nitristrips, who are deprecated
* Nitrishapes that become bstrishapes
* Niskin instances that have the new vertex data
* Niparticles due to the change from the old bounding box to the bsbound

**For porting to Xbox**

For conversion of the ESP for SE Xbox, you open up the CK in Version Control, and check out every single form from the esm you are trying to convert. Then you save that to a plugin. Then you run it through the auto clean in xedit to remove any *identical to master* (itm) records. Then you merge the resulting plugin back into the master (ESM) file as in a normal merge. The new esm will have the correct version number, and all of the forms that are different in SE will be updated.

Best of success

Post Scriptum: *You cannot "port back" to LE. The updates on esm/esp entries and meshes are irreversible.*

# Answer
> 1 votes
While the comments sum up how this question isn't particularly valuable for this site I will add an answer that I think can be valuable for those searching the same thing.

Many (I would go as far to say a majority) of the mods available on the Nexus for Skyrim SE are ports of existing LE mods. In fact, if you head over and look at both Nexus sites you'll find many of the "New Files" and "Hot Files" are on both, because modders tend to create them for both games simultaneously. As such, you have a plethora of existing sample cases to learn from.

Download mods from both sites that have parts of what you intend to do and examine the differences. If you want to port a mod that adds new models, find an already ported mod that adds new models. If it's scripts then do the same with that. Many mods will only need opening with the SE Creation Kit, then saving anew, to complete the port.

A key outlier here is mods that use SKSE. SKSE had to be entirely rewritten for SE and was renamed SKSE64 (because SE is 64 bit, compared to 32 bit LE). As such, while the developers of SKSE intended to create the plugin with an identical API to LE it's vital that all usage of SKSE within the mod are completely checked in-game running SKSE64 to ensure they work. Otherwise the scripts will need to be modified to match the new API.

Another point is to look out for dependencies. It's great if you port a mod to LE but if it has a dependency that hasn't been ported you'll have trouble running it (or parts of it) at all. Make sure any dependencies have been ported (by yourself or someone else) and that all references within the mod point to the ported dependency.

I would say to just dive in. Start with an LE mod loaded into the SE CK and save it - see what happens when you run the game. Troubleshoot any errors and if you can't find an answer, by all means come back and ask another question here (with a more specific problem in mind!).

---
Tags: skyrim-modding
---


# Question
Title: Trying to get sprite from isometric "z as y" tilemap
I'm using code like the following with a tilemap and tilemap collider 2d:

```
var ray = Physics2D.RaycastAll(worldCoordinate, Vector2.zero);

```

Unfortunately, when I click where I have a sprite in my tilemap, the array value that comes back in `ray` only ever contains one entry which ends up being for the entire tilemap, rather than the sprite I clicked on in the tilemap.

Is there a special technique I should be using to cast a ray from a world coordinate, into the tilemap to determine which tile has been hit?

**Please note**: I'm using "z as y", so something like `WorldToCell` seems to not be enough as I *also* wish to match based on elevation and based on objects that are partially occluded by things in front of them.

Update, here's an image I can reference in discussion:

# Answer
> 2 votes
Allow me to clarify more in this answer.

Raycast inspection(or any other physical inspection) only focuses on the physical world. They can not recognize one sprite on top of another, or something like that. They only care about the geometry of the colliders.

When you edit the scene with tilemaps, all the sprites in the tilemap share a single collider (TilemapCollider2D). So raycast can not tell which sprite you actually clicked. it can only tell you at what point does the collision occur.

So then the solution is clear: Let the sprite have **its own** gameobject and collider.

I found two ways to achieve it:

**Option1**:

Use TilemapExtrasPackage, Directly use ray inspection and sort the results.

Give each sprite a physical shape, and use gameobject brush to edit them into the scene. And you will get a lot of overlapping colliders like:

Use RaycastAll to find all colliders that the current screen point passes through, and sort them. Pick the first one.

Code:

```
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        var hits = new List<RaycastHit2D>(Physics2D.RaycastAll(ray.origin, ray.direction));
        if (hits.Count > 0)
        {
            hits.Sort((l, r) =>
            {
                var p1 = l.transform.position;
                var p2 = r.transform.position;
                return (int)(((p1.y - p2.y) * 10 + (p2.z - p1.z)) * 10);
            });
            var target = hits[0].transform.GetComponent<SpriteRenderer>();
            target.color = target.color == Color.red ? Color.green : Color.red;
        }
    }
}

```

Precautions:

1. Set sort axis as (0,1,-0.49)
2. The tilemap of interactive objects needs to set a smaller y value to facilitate sorting.

**Option2**:

If there are no additional interactable objects on the tile, the tile click area can be mapped algorithmically.

Core idea: split the grid into smaller-grained areas, record which grid covers each small area, traverse the grid from back to front, and refresh the record.

Assuming the grids are "half-height", That is to say a plot of 2 heights with the bottom side overlapping with a diamond behind it.(Most of the games I've seen are like this, and so are the Unity presets). Now divide a grid into 6 areas as follows,This is the smallest partition case:

To find out which areas a grid covers, we can do this:

For the grid of integer layers(Here is a multiple of 2), we can divide it into two parts:

1. The plot where it is located(red)
2. The area covered by each layer(blue and yellow):

For non-integer grids, just add the area occupied by the extra half-tile(pink):

When click hapens, Find out which area was clicked, and find the real grid that covered it last time. That's all.

Code:

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

public class NewBehaviourScript : MonoBehaviour
{
    public GridLayout gridLayout;
    public Tilemap tilemap;
    private Dictionary<Tuple<int, int>, Vector3Int[]> tileInfoDict = new Dictionary<Tuple<int, int>, Vector3Int[]>();
    void Start()
    {
        var bounds = tilemap.cellBounds;
        var allTilePos = new List<Vector3Int>();
        for (int x = bounds.xMin; x < bounds.xMax; x++)
        {
            for (int y = bounds.yMin; y < bounds.yMax; y++)
            {
                for (int z = bounds.zMin; z < bounds.zMax; z++)
                {
                    var pos = new Vector3Int(x, y, z);
                    if (tilemap.HasTile(pos))
                    {
                        allTilePos.Add(pos);
                    }
                }
            }
        }
        allTilePos.Sort((left, right) =>
        {
            return (right.x + right.y) - (left.x + left.y);
        });
        foreach (var item in allTilePos)
        {
            DealInfo(item.x, item.y, item.z);
        }
    }
    private void DealInfo(int x, int y, int z)
    {
        var fullLayerCount = z / 2;
        var isHalfLayer = (z % 2) == 1;

        var posNow = new Vector3Int(x, y, z);
        var selfInfo = EnsureGetInfo(x, y);
        for (int index = 0; index < 6; index++)
        {
            selfInfo[index] = posNow;
        }
        for (int i = 1; i <= fullLayerCount; i++)
        {
            var midX = x + i;
            var midY = y + i;
            //mid
            var midInfo = EnsureGetInfo(midX, midY);
            for (int index = 0; index < 6; index++)
            {
                midInfo[index] = posNow;
            }
            //left
            var leftInfo = EnsureGetInfo(midX - 1, midY);
            for (int index = 3; index < 6; index++)
            {
                leftInfo[index] = posNow;
            }
            //right
            var rightInfo = EnsureGetInfo(midX, midY - 1);
            for (int index = 0; index < 3; index++)
            {
                rightInfo[index] = posNow;
            }
        }
        if (isHalfLayer)
        {
            var midX = x + fullLayerCount + 1;
            var midY = y + fullLayerCount + 1;
            //mid
            var midInfo = EnsureGetInfo(midX, midY);
            midInfo[2] = posNow;
            midInfo[5] = posNow;
            //left
            var leftInfo = EnsureGetInfo(midX - 1, midY);
            leftInfo[4] = posNow;
            leftInfo[5] = posNow;
            //right
            var rightInfo = EnsureGetInfo(midX, midY - 1);
            rightInfo[1] = posNow;
            rightInfo[2] = posNow;
        }
    }
    private Vector3Int[] EnsureGetInfo(int x, int y)
    {
        var key = new Tuple<int, int>(x, y);
        if (!tileInfoDict.ContainsKey(key))
        {
            tileInfoDict.Add(key, new Vector3Int[6]);
        }
        return tileInfoDict[key];
    }
    private int GetAreaIndex(Vector3 p1, Vector3 p2)
    {
        var v = p2 - p1;
        var gridX = gridLayout.cellSize.x;
        var gridY = gridLayout.cellSize.y;
        v = new Vector3(v.x * gridY / gridY, v.y, 0);
        var v1 = new Vector3(-1, 1);//left
        var v2 = new Vector3(1, 1);//right
        var len = Mathf.Sqrt(2) * gridY / 4;
        var m1 = Vector3.Project(v, v1).magnitude;
        var m2 = Vector3.Project(v, v2).magnitude;
        if (m1 > len)
        {
            if (m2 < len)
                return 1;
            else if (v.x > 0)
                return 3;
            else
                return 0;
        }
        else
        {
            if (m2 > len)
                return 4;
            else if (v.x > 0)
                return 5;
            else
                return 2;
        }
    }
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
            if (hit.collider != null)
            {
                Vector3Int cellPosition = gridLayout.WorldToCell(hit.point);
                var key = new Tuple<int, int>(cellPosition.x, cellPosition.y);
                if (tileInfoDict.ContainsKey(key))
                {
                    var center = gridLayout.CellToWorld(cellPosition);
                    var index = GetAreaIndex(center, hit.point);
                    var targetPos = tileInfoDict[key][index];
                    if (targetPos != null)
                    {
                        tilemap.SetTileFlags(targetPos, TileFlags.None);
                        if (tilemap.GetColor(targetPos) == Color.red)
                        {
                            tilemap.SetColor(targetPos, Color.green);
                        }
                        else
                        {
                            tilemap.SetColor(targetPos, Color.red);
                        }
                    }
                }
            }
        }
    }
}

```

---
Tags: unity, sprites, tilemap, raycasting, isometric
---