title: OpenGL calculate UV sphere vertices

text:
# Question
Title: OpenGL calculate UV sphere vertices
I am trying to implement a class `Sphere` in C++.

Therefore I want to calculate the vertices in the constructor of the class (or in a seperate function..). Although I read tons of articles about creating spheres in different ways (UV Sphere, Quad Sphere, Icosphere etc.) I did not understand how to create the vertices for my buffer object.

I decided to use the UV Sphere since it is easy to map a texture on it.

A "UV sphere" in this sense is one where the (quad) edges run like lines of latitude and longitude, and the texture is mapped to the sphere like an equirectangular projection.

(Equirectangular Earth texture by Strebe via Wikimedia Commons, CC BY-SA 3.0)

But how can I calculate all the vertex positions and texture coordinates?

For my vertices I use a `Vertex` struct:

```
struct Vertex
{
    glm::vec3 position;
    glm::vec2 texture;
};

```

# Answer
Let's start by generating all unique vertices. You can then decide whether to index those vertices, or copy them into strips/fans, depending on your needs. Here's some example code showing how to organize these vertices into triangles for rendering.

```
// One vertex at every latitude-longitude intersection,
// plus one for the north pole and one for the south.
// One meridian serves as a UV seam, so we double the vertices there.
int numVertices = numLatitudeLines * (numLongitudeLines + 1) + 2

vec3[] positions = vec3[numVertices]
vec2[] texcoords = vec2[numVertices]

// North pole.
positions[0] = vec3(0, radius, 0)
texcoords[0] = vec2(0, 1)

// South pole.
positions[numVertices - 1] = vec3(0, -radius, 0)
texcoords[numVertices - 1] = vec2(0, 0)

// +1.0f because there's a gap between the poles and the first parallel.
float latitudeSpacing = 1.0f / (numLatitudeLines + 1.0f)
float longitudeSpacing = 1.0f / (numLongitudeLines)

// start writing new vertices at position 1
int v = 1
for(latitude = 0; latitude < numLatitudeLines; latitude++) {
    for(longitude = 0; longitude <= numLongitudeLines; longitude++) {

      // Scale coordinates into the 0...1 texture coordinate range,
      // with north at the top (y = 1).
      texcoords[v] = vec2(
                        longitude * longitudeSpacing,
                        1.0f - (latitude + 1) * latitudeSpacing
                     )

      // Convert to spherical coordinates:
      // theta is a longitude angle (around the equator) in radians.
      // phi is a latitude angle (north or south of the equator).
      float theta = texcoords[v].x * 2.0f * PI
      float phi = (texcoords[v].y - 0.5f) * PI

      // This determines the radius of the ring of this line of latitude.
      // It's widest at the equator, and narrows as phi increases/decreases.
      float c = cos(phi)

      // Usual formula for a vector in spherical coordinates.
      // You can exchange x & z to wind the opposite way around the sphere.
      positions[v] = vec3(
                        c * cos(theta),
                        sin(phi),
                        c * sin(theta)
                      ) * radius

      // Proceed to the next vertex.
      v++
    }
}

```

This puts the north Pole at position 0 in the array, then the vertices of each line of latitude in a row (with the first and last vertices in the row being coincident along the texturing seam), one line after another until we reach the south pole at the end of the array.

We've arbitrarily made just one vertex for each pole, all the way on the left side of the texture. You could also choose to make multiple pole vertices to make the texture distortion less extreme, but you'll always have some seams or stretching here due to the nonlinear nature of equirectangular mapping.
> 4 votes

---
Tags: opengl, c++, opengl-es, geometry, sphere
---


# Question
Title: Repeating a background texture forever in libgdx
My "game" works with a pretty large playing field, so I need a repeating background. I've implemented this the following way:

Loading:

```
assetManager.get("texture_bg.png", Texture.class).setWrap(Repeat, Repeat);
bgRegion = new TextureRegion(assetManager.get("texture_bg.png", Texture.class));
bgRegion.setRegion(0, 0, 16384, 16384);

```

Drawing:

```
batch.draw(bgRegion, 0, 0);

```

This does as expected: Creates a background of 16384 by 16384 pixels from a 512x512px texture. But now that I'm getting further in the testing, I foresee running out of space quickly almost no matter what I set the region to.

Is there a way I can have it simply repeat forever and not specifying a finite number?

# Answer
You don't want to make a Really Large Sprite because it will just look bad when you hit the limits of floating point precision (when it gets larger than 2^24).

it just needs to be at least large enough to cover your screen + an extra 512 pixels, and then just render `batch.draw(bgRegion, camera.x % 512, camera.y % 512)`. Since the texture repeats every 512 pixels, you won't notice that it's moving.
> 1 votes

---
Tags: java, libgdx, textures
---


title: Can't Unity draw fine and smooth line?

text:
# Question
Title: Can't Unity draw fine and smooth line?
I'm working on drawing lines in `Unity`, but find there is no way to draw clear, fine and smooth line in `Unity`, neither `LineRenderer` nor `GL.LINES`, both of them got jaggy, pixelated and coarse lines, even set `Anti-Aliasing` to `8x`, just a tiny improvement. But when I turn to see `iOS`, I find it's easy to draw perfect and smooth line with the original `iOS Graphic API`, just as the screenshot of `Paper` app in `iOS` below, while we can see the screenshot of Unity drawing with `LineRenderer`, it's really ugly, even use `Bezier`, still jaggy.

Isn't there any way to draw smooth line in `Unity`? Will `Shader` do some great help? Does anyone have a good idea? Very appreciate it.

**Paper on iOS**

**Unity with `LineRenderer`**

# Answer
@ZEKE briefly figured out the problem might be wrong settings of game rendering resolution. When I looked into it I found there had been a `Low Resolution Aspect Ratios` option checked on at top of `Unity Game view > Free Aspect`, I tried turning off it, then got clear lines.

(Meanwhile, I've also tried changing the `Default Is Native Resolution` in `Player Settings` to something like `3000x2000`, but it looked none affection to this issue)

Thanks to @ZEKE!
> 2 votes

---
Tags: unity, opengl, shaders, graphics, ios
---


# Question
Title: Delta time causing comparison issues due to floating points
I am working on a game in **Game Maker Studio: 2** and am using *Delta Time* for the time. I understand what it is, how to get it, and how to use it, but I am running into issues when I need to make comparisons that contain values that have been modified by *Delta Time*.

Example: an item from my game is moving along the x-axis at 2 pixels-per-sec. at 60 frames. The speed the item is moving is then modified by *Delta Time*, with the x-coord of the item effectively being 'x = 2 * delta'.

Now, I want to check for when the x-coord of the item has reached a certain spot, i.e. 'if(x = "specific spot on axis") {do something}.

The "specific spot on axis" that I am looking for is an integer (no digits after the decimal), but when using delta time, the x-coord is always off by usually miniscule amounts due to adjusting its position relative the speed of change of each frame. Instead of 'x = 12', it is 'x = 12.00387562' or 'x = 11.99943345'.

Right now, I'm thinking that just rounding 'x' at end of each step is all I have to do to fix this, but I also have a nagging feeling that I am possibly missing something right in front of my face. One reason being that, If I round the x-coord at every frame, does that not make a lot of the adjustments made by *Delta Time* pointless? Is there a (preferably easy and/or concise) way to do comparisons looking for values inside a certain range of digits after the decimal?

All help and insight is appreciated.

# Answer
Your feeling is right, don't round your `x` at every frame because you need that value as an accumulator and it should remain accurate for a consistent simulation. Instead, round the `x` as a temporary variable when you need to compare it to an integer.

```
if(round(x) =="specific spot on axis") {do something}

```

If you need to check if `x` has only *passed* the spot, you can just do the comparison without rounding:

```
if(x > "specific spot on axis") {do something}

```

You can also use the `floor` method, which will always "round" down, and never "up". This *could* give you a more consistent behaviour: you're not at "specific spot on axis" if you haven't reached it. Period.

```
if(floor(x) =="specific spot on axis") {do something}

```

---

*Disclaimer: I'm not an expert with GMS.*
> 2 votes

---
Tags: mathematics, game-maker
---


# Question
Title: How to efficiently filter by a component with a specific value in an entity component system (all entities in grid position [x,y,z], for example)?
I'm working on a 3d grid based game, and I am trying to implement it using an ECS.

I have a position component which indicates the entity's position on the grid. It is comprised of 3 integers (for example \[1,3,2\]). Now lets imagine the user clicked on position \[1,3,2\]. I now want to efficiently retrieve all entities in position \[1,3,2\].

I can see only one way to achieve that using an ECS. I need to filter for all components that have a position component (this can be done in O(1)), then filter through all the position components to find only those positions that equal \[1,3,2\]. This is extremely inefficient, since I have a hundred thousand entities with a position component to loop through, but I only need a minuscule fraction of them.

It's important to note that I never need to loop through all the hundred thousand position components in a single frame in any other case. For all other systems, I filter entities that have both a position component as well as other components, so I end up only looping through a small fraction of positions in each frame. This means I cant just retrieve all the relevant entities as part of the loop that goes through all the positions, since I dont have such a loop.

Traditionally using OOP, I would have a dictionary from a position to a container that contains all the objects in that position, which would allow me to accomplish the above in O(1). This isn't correct design for an ECS though, from what I understand.

Am I misunderstanding something about Entity Systems? If anyone has any advice I would be glad to hear it.

Thank you.

# Answer
Basically you miss use a ecs system. Such a system isn't about collision detection, it is about organization. It's a system on how to plan and structure your game parts.

So now that you accept this fact it is easy to find more infos on how to retrieve entities that are needed to apply actions on them like clicking and selecting.

For this is mostly used tequniques like the commenter mentioned space oriented structures which are mostly binary trees like a octree with n, s, e, w,... From each point.
> 0 votes

---
Tags: architecture, entity-system, entity-component
---


# Question
Title: Unity Player Movement Y Axis(Something like Swing Copters)
My Player moves on Y AXIS , but sometimes it doesnt go up but stucks in one place, Script is like in swing copters , when you touch it rotates to another side but its on X Axis , i took and made it on Y axis , but it doesnt work properly , player sometimes doesnt turn around and go up or back Please help out , sorry for bad english

```
void MovePlayerOnYAxis()
    {

        foreach (Touch touch in Input.touches)
        {

            moveL = !moveL;

            if (moveL)
            {

                transform.localScale = new Vector3(1, -1, 1);
            }
            else
            {
                transform.localScale = new Vector3(1, 1, 1);
            }

            huongbay = transform.localScale.x;
        }
        transform.root.Translate(Vector3.up * speed * huongbay * Time.deltaTime);
    }

```

Pre-Fix From @PompeyPaul But Player still doesnt go Down , it now goes only up.

```
void MovePlayerOnYAxis()
    {

        foreach (Touch touch in Input.touches)
        {

            WasTouched = !WasTouched;

            if (WasTouched)
            {
                if (Input.touchCount == 0)
                {
                    WasTouched = false;

                    transform.localScale = new Vector3(1, 1, 1);
                }
            }
            else
            {
                if (Input.touchCount > 0)
                {
                    WasTouched = true;
                    transform.localScale = new Vector3(1,-1, 1);
                }

            }
            huongbay = transform.localScale.y;

        }
        transform.root.Translate(Vector3.up * speed * huongbay * Time.deltaTime);
    }

```

# Answer
Is it because you flip direction on each touch? So if you get multiple touches you flip up and down.

I think you need to debounce the touches, something like

```
    bool WasTouched=false; // Should go into the class

    // Debounce touches
    if(wasTouched)
    {
        if(Input.touches.Count==0)
        {
            WasTouched=false;

            // Do processing here
        }
    }
    else
    {
        if(Input.touches.Count>0)
        {
            WasTouched=true;
        }
    }

```
> 1 votes

# Answer
The `Translate` function has a second default parameter, which is the relative space it moves to. If not set, this will be `Space.Self`.

Since you set the y-component of `localScale` to -1, this will automatically account for moving different directions in world space, thus, making `huongbay` inside of `Translate` redundant.

You can either remove it, or set the relative space to `Space.World`:

```
transform.root.Translate(Vector3.up * speed * Time.deltaTime);
// or
transform.root.Translate(Vector3.up * speed * huongbay * Time.deltaTime, Space.World);

```
> 0 votes

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


# Question
Title: Different shader programs but same buffer drawing
I've setup 3 different instances of the same shader code (e.g. I've compiled the code into 3 separate programs)

For each program, I've gone through the whole route of something like this:

```
//Setup
gl.useProgram(program);
const buffer = gl.createBuffer();
const location = gl.getAttribLocation(program, aName);

//Upload (each uses the buffer/location it created in Setup
gl.useProgram(program);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, usagePattern);
gl.vertexAttribPointer(location, nComponents, dataType, false, 0, 0);
gl.enableVertexAttribArray(location);

//Draw
gl.useProgram(program);
gl.vertexAttribPointer(location, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

```

However, no matter what I pass into `data` \- e.g. different sized quads, all three are the same size.

Notably, changes to other uniforms/attributes like matrices and color *do* change per object

**How do I change this so that the changes to data per instance will be drawn properly?**

(I realize if they actually use the same shader I should maybe keep a reference to one program and use some sort of buffer pool- but I'm not there yet, just getting started with WebGL)

# Answer
> 1 votes
Your problem is that the current buffer binding is not part of the program state.

In more general terms, buffers (or more correctly, vertex attrib state) and programs are separate objects, and in earlier versions of OpenGL you can even draw without either or without both. So it makes sense that the state of one will not affect the state of the other.

So if in your case you bind 3 buffers at startup, then draw without rebinding your buffers, only the most recently bound buffer will be used for drawing.

To solve, you simply need to rebind the appropriate buffer before drawing.

---
Tags: opengl, shaders, web
---


# Question
Title: How can i change the cube scale only on Y and only to up?
This is the script I am working with:

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

public class Raise : MonoBehaviour
{
public GameObject Ladder;

float mfX;
float mfY;
float mfZ;
// Use this for initialization
void Start()
{
    mfX = Ladder.transform.position.x - Ladder.transform.localScale.x / 2.0f;
    mfY = Ladder.transform.position.y - Ladder.transform.localScale.y / 2.0f;
    mfZ = Ladder.transform.position.z - Ladder.transform.localScale.z / 2.0f;
}

// Update is called once per frame
void Update()
{
        Vector3 v3Scale = Ladder.transform.localScale;
        Ladder.transform.localScale = new Vector3(v3Scale.x + 0.1f, v3Scale.y + 0.1f, v3Scale.z + 0.1f);
        Ladder.transform.position = new Vector3(/*mfX + Ladder.transform.localScale.x / 2.0f*/0, mfY + Ladder.transform.localScale.y / 2.0f, mfZ + Ladder.transform.localScale.z / 2.0f);
}
}

```

The way it is now it's making the whole cube bigger and bigger.

But I want to make the cube grow only UP on Y. To keep the cube capacity/ extent But to make the scale change only up.

If I'm doing:

```
Vector3 v3Scale = Ladder.transform.localScale;
Ladder.transform.localScale = new Vector3(0, v3Scale.y + 0.1f, 0);
Ladder.transform.position = new Vector3(0, mfY + Ladder.transform.localScale.y / 2.0f, 0);

```

I will see it go up in scene if I select the cube in the hierarchy but if not I will not see the cube at all.

Can't figure out how to make is grow up only up side.

# Answer
Here is the problem:

```
Ladder.transform.localScale = new Vector3(0, v3Scale.y + 0.1f, 0);

```

You have set scale Vector3 to (0, *value*, 0). It should be (1, *value*, 1). I suspect the reason you can't see anything is because you've told it that object shouldn't have an X or Z axis! Scale values should default to one, not zero.
> 6 votes

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


# Question
Title: Can I make children of a moving platform also work as moving platforms?
I have a moving platform that is a kinematic body, moving by a script, which is working as expected.

I tried to parent it to another kinematic body, and make the child also function as a moving platform (the script only moves the parent), but it seems that the friction is ignored for the child object, and the carried object slips behind it and falls down when the child platform moves. The child platform is the same physical material as the parent.

Is there any way I can make the child's friction work too, while having the script only move the parent?

This is important, because in my real application the child moves and rotates inside a couple nested levels of transformations (basically the fork teeth of a fork truck).

# Answer
Parenting physics bodies can often be fraught. What I'd recommend doing instead is:

For each child that needs to move in the parent space of another body, create an empty "marker" object, and apply the animation/movement scripts to that marker.

In your kinematic rigidbodies that need to follow these markers, add a script like this:

```
public Transform followMarker;
Rigidbody _body;

void Start() {
    // Eject from our place in the child hierarchy,
    // so the parent's transform no longer affects us.
    transform.parent = null;

    _body = GetComponent<Rigidbody>();
}

void FixedUpdate() {
    // Move (in world space) to match the position & orientation
    // of our marker object under its parent(s).
    _body.MovePosition(followMarker.position);
    _body.MoveRotation(followMarker.rotation);
}

```

Now you can get the best of both worlds: Your markers can use child hierarchies to perform complex movements relative to their parent bodies, and your physics platforms can match them without interference from the parenting structure.
> 2 votes

---
Tags: unity, c#, physics, moving-platforms
---


# Question
Title: What's the proper practice to organize relationship between components in an ECS pattern?
I'm new to ECS concept and trying to refactor my app with an ECS manner. After reading some articles, I still don't get a sense about how to organize hierarchy for such pattern. My questions are

1. Is a component allowed to have another component inside? For example I saw a RenderComponent that contains a Mesh inside. Is the mesh also a component or the raw data of it, which should be stored inside the RenderComponent?
2. What happens when an instance of component needs to be shared by two entities?
3. If an entity should be just an integer, how do you organize the relationship between entities? Should it have a parent/child/linked entity or should all these relationship be managed by the system?

Thanks!

# Answer
> 7 votes
There is no "proper" practice for this. There are many ways you can approach it, each with pros and cons that need to be evaluated against all your other requirements.

> Is a component allowed to have another component inside? For example I saw a RenderComponent that contains a Mesh inside. Is the mesh also a component or the raw data of it, which should be stored inside the RenderComponent?

If you want to support the concept of having compenents nested inside or otherwise attached to other components, you can. There is nothing wrong with it. It can add some amount of flexibility, although it tends to also add complexity as a tradeoff. It's up to you: do you need or want this to accomplish your goals?

> What happens when an instance of component needs to be shared by two entities?

The same thing that happens when any piece of data needs to be shared. Generally you either simply share it (by having the entities refer to the component via some kind of referential semantics, and have actual lifetime of the component controlled elsewhere, not by the entities themselves), or refactor the system so you don't need to share the data.

> If an entity should be just an integer, how do you organize the relationship between entities? Should it have a parent/child/linked entity or should all these relationship be managed by the system?

An entity does not *have* to be just an integer. That's just one way to look at it. That "entity is literally just an integer" approach can present these kind of relationship problems: you can't store anything else with an integer, directly. Instead you can either make the entity more complex, so it can directly reference related entities, or store relationships externally in a table mapping integers to lists of related entity integers, et cetera. It is up to you.

---

Your big misconception here is that "entity component systems" are a single thing with a single objectively-best way to build them. This is false. You'll find *lots* of writing on the internet describing various different ways to implement entity systems, many of them will be written in a dogmatic style or otherwise implying strongly that this is "the" way, and that all other ways are wrong.

This is true of *almost nothing* in software engineering, and it's certainly not true of entity systems. As you can guess from the common theme in my responses to your specific questions, you can structure your entity system however best makes sense to solve the problems *you* need to solve. I'd advise you to prefer the simpler solutions first, but beyond that it is up to you.

What you build won't be "so and so's entity system," as described on their blog, but it will be *your* entity system and that's more important.

---
Tags: entity-system, design-patterns, entity-component, data-oriented
---


# Question
Title: Generating Unique Identifiers for Procedural Item Generation
I have been writing all the necessary code for procedurally generated items within my game. The database mechanism that I have built supports new items at runtime, such as when a player opens a chest. Everything works fine, but I realized a fatal flaw with the way that I generate the "unique" item identifiers. I generate items using a Prefix, such as Fiery, an item type, such as Claymore, and a suffix, such as of Greater Shadow.

I generate the database Identifier using the format of:

```
Proc_ + Prefix + Type + Suffix + Iteration

```

As an actual example, the procedural item "Fiery Claymore of Greater Shadow" would then become:

```
Proc_FCOGS_01

```

All seems well right? This looks like it could work quite nicely. However, I then realized that I can easily receive identifier clashes. Or as an example: "Freezing Claymore of Greater Striking" would also be created as:

```
Proc_FCOGS_01

```

And that's where the problem arises. Because I went through all my affixes, located here and found that a few more of my chosen affixes could also lead to clashing within the database, despite the generated item not actually being the same as the one that is already entered. The routine that I am using to generate these identifiers is as follows:

```
        public string CreateIdentifier(string prefix, string itemType, string suffix)
        {
            if (!String.IsNullOrEmpty(prefix) && !String.IsNullOrEmpty(itemType) && !String.IsNullOrEmpty(suffix))
            {
                string input = prefix + " " + itemType + " " + suffix;
                string[] segments = input.Split(' ');
                StringBuilder builder = new StringBuilder(segments.Length + 5);
                builder.Append("Proc_");
                for (int i = 0; i < segments.Length; i++)
                {
                    builder.Append(Char.ToUpper(segments[i][0]));
                }
                return builder.ToString();
            }
            return null;
        }

```

After all of this, I can really only see two options:

1. Scrap my current Unique Identifier routine and think of another one.
2. If a collision exists within the Database, simply iterate the generated identifier ending number by 1, check again, and if necessary, iterate the the ending number by 1 again until an unused identifier is found.

As for number 1, that's why I'm here showing you all this. I need ideas about how I can do this in a way that will result in zero clashes unless the item is actually the same thing as previously generated.

And as for number 2, I would really prefer not doing this. I feel as though having fifteen or more database entries of `Proc_FGSOTE` plus the unique iteration, to be a little silly. Why have fifteen database entries of the same item? Although, I guess that would indeed be putting the iteration value to use...it's just not what I had intended it to be used for and seems like a terrible waste of resources. I really feel as though a better routine is the way to go.

**Does anyone know of a better way that I can be generating unique identifiers?**

***Edit:***

Sorry, I fogot to mention that I don't want to use the entire item name as an identifier, even if it's compressed to trim out all the spaces, mainly because the identifiers are still going to be way too long. This seems like an arbitrary limitation, I know, it's just one that I wanted to enforce so that way the Database could be loaded/parsed *faster* later down the road.

# Answer
> 2 votes
Why don't you just use GUIDs?

* They can be generated client-side and still be unique.
* They generate quickly.
* They're only 16 bytes. That's only a little larger than what you're getting now, but since they're not as constrained as your algorithm, the available range is much, much larger.

They are less human-readable, but you can still always associated a short human-readable "developer name" with an item as well if you need to overcome that. You'd just want to use the actual GUID in any code that cares about being able to uniquely look up an item.

---

You could also just use auto-incrementing numeric ID keys on the database if you need to store the identifier in fewer than 16 bytes. But while smaller, this has the disadvantage of having the database need to be involved to even generate the ID.

# Answer
> 1 votes
If each keyword (suffix, prefix, etc.) more than a single letter, you would have a lot more unique combinations.

For example:
If you use four letters, then **Fiery Claymore of Greater Shadow** would become **FiryClymrGrtrShdw\_1**, which is a lot more readable as well as giving you a lot more available keywords. (26^4)

Four letters is pretty readable, but it's up to you how many letters you think you need.

---
Tags: c#, databases
---


# Question
Title: Opengl - Know when a new frame is drawn, regardless of window
I want to know the framenumber of the current frame at any time, regardless the bound window or if it was changed. I dont want to implement a framecounter in my window class, since that would 1. require every depending library to check which window is bound and only use frames from there and 2. Isnt independent of windows.

I am sure there is a way to simply know when A opengl context has something new send to it. Please help me find it!

---

I want a frame number that is in sync with other debugging tools so I can easily compare and contrast.

# Answer
> 1 votes
OpenGL cannot tell you this.

The (pure) OpenGL API doesn't even support the actual swap of the front and back buffer, the thing that we generally interpret to signal the end of one frame and the start of the next in modern code. That is all handled by platform-specific APIs, such as `SwapBuffers` on Windows, `flushBuffer` on macOS, and so on. The closest thing in the pure OpenGL API is `glFlush` or `glFinish` if you're using them, and neither of them come with a way to tell you how many times they've been called.

You have to implement this kind of counter yourself.

If you provide more information about what broader problem you're trying to solve, it's possible we can provide more concrete solutions. Lacking that information, you should probably just increment some number stored in a shared place (that is, not in each window but in a more central location, perhaps in your main `Game` class that owns all the windows, or whatever) whenever any window completes a frame. The utility of this number seems suspect to me, but I can't say for sure without knowing what you're doing.

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


# Question
Title: LWJGL/OpenGL - Textured squares not displayed behind other transparent textured squares
I've a MapView class that contains many tiles (MapTile class, a tile can be in the background), vertex array object and vertex buffer object for rendering of the map. I also have a function that update the buffers :

```
        // FloatBuffer(s) and IntBuffer for indices
        positionsBuffer = MemoryUtil.memAllocFloat( this.tiles.size() * 4 * 3 );
        colorsBuffer = MemoryUtil.memAllocFloat( this.tiles.size() * 4 * 3 );
        texCoordsBuffer = MemoryUtil.memAllocFloat( this.tiles.size() * 4 * 2 );
        indicesBuffer = MemoryUtil.memAllocInt( this.vertexCount = this.tiles.size() * 2 * 3 );

        TextureDefinition textureDefinition = game.getTexturesManager().getTextureDefinition("tiles");

        int i = 0;

        for ( MapTile mapViewTile : this.tiles ) {

            Tile tile = mapViewTile.getTile();
            if ( tile == null ) continue;

            String tileTextureIdentifier = tile.getTextureIdentifier( mapViewTile.getVariant() );

            TextureTilePosition tileTexturePosition = textureDefinition.getTextureTilePosition( tileTextureIdentifier );
            if ( tileTexturePosition == null ) continue;

            // If a tile is in the background, I place the triangles of the tile square 0.1f further back and I also darken the texture
            float z = mapViewTile.isBackground() ? -0.1f : 0f;
            float[] color = mapViewTile.isBackground() ? new float[]{ 0.5f, 0.5f, 0.5f } : new float[]{ 1.0f, 1.0f, 1.0f };

            positionsBuffer.put( mapViewTile.getX() - 0.5f ).put( mapViewTile.getY() + 0.5f ).put( z );
            positionsBuffer.put( mapViewTile.getX() - 0.5f ).put( mapViewTile.getY() - 0.5f ).put( z );
            positionsBuffer.put( mapViewTile.getX() + 0.5f ).put( mapViewTile.getY() - 0.5f ).put( z );
            positionsBuffer.put( mapViewTile.getX() + 0.5f ).put( mapViewTile.getY() + 0.5f ).put( z );

            colorsBuffer.put( color ).put( color ).put( color ).put( color );

            texCoordsBuffer.put( tileTexturePosition.getX() ).put( tileTexturePosition.getY() );
            texCoordsBuffer.put( tileTexturePosition.getX() ).put( tileTexturePosition.getY() + tileTexturePosition.getHeight() );
            texCoordsBuffer.put( tileTexturePosition.getX() + tileTexturePosition.getWidth() ).put( tileTexturePosition.getY() + tileTexturePosition.getHeight() );
            texCoordsBuffer.put( tileTexturePosition.getX() + tileTexturePosition.getWidth() ).put( tileTexturePosition.getY() );

            indicesBuffer.put( i ).put( i + 1 ).put( i + 3 );
            indicesBuffer.put( i + 1 ).put( i + 2 ).put( i + 3 );

            i += 4;

        }

        positionsBuffer.flip();
        colorsBuffer.flip();
        texCoordsBuffer.flip();
        indicesBuffer.flip();

        this.vao.bind();

        this.positionsVbo.bind( GL15.GL_ARRAY_BUFFER );
        VertexBufferObject.uploadData( GL15.GL_ARRAY_BUFFER, positionsBuffer, GL15.GL_STATIC_DRAW );
        ShaderProgram.pointVertexAttribute( 0, 3, 0, 0 );

        this.colorsVbo.bind( GL15.GL_ARRAY_BUFFER );
        VertexBufferObject.uploadData( GL15.GL_ARRAY_BUFFER, colorsBuffer, GL15.GL_STATIC_DRAW );
        ShaderProgram.pointVertexAttribute( 1, 3, 0, 0 );

        this.texCoordsVbo.bind( GL15.GL_ARRAY_BUFFER );
        VertexBufferObject.uploadData( GL15.GL_ARRAY_BUFFER, texCoordsBuffer, GL15.GL_STATIC_DRAW );
        ShaderProgram.pointVertexAttribute( 2, 2, 0, 0 );

        this.indicesVbo.bind( GL15.GL_ELEMENT_ARRAY_BUFFER );
        VertexBufferObject.uploadData( GL15.GL_ELEMENT_ARRAY_BUFFER , indicesBuffer, GL15.GL_STATIC_DRAW );

        VertexBufferObject.unbind( GL15.GL_ARRAY_BUFFER );

        VertexArrayObject.unbind();

```

But the background tiles are not display behind others squares : Screenshot

For information, i'm using an orthographic projection and the camera of this screenshot is slightly angled. OpenGL version is 4.3.0 and LWJGL version is 3.1.3. I'm using GL\_BLEND for texture transparency

I hypothesize that it would be necessary to use two different vertex array objects, is that it or something else?

# Answer
Blending happens after the fragment shader, which means that the fragments still get written to the depth buffer. If you try to draw something behind the object, then the fragments in that object will get culled. Use glsl's discard instead of blending.
> 0 votes

# Answer
Seems as though you need to enable blending. Your init function should have something like

```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```
> 0 votes

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


# Question
Title: How to Find Collision Reflection Vector on a Sphere
I have a game I'm building in Unity with some objects orbiting a sphere via rotating around a pivot point (0,0,0) at a radius of 10 units on the z-axis. The orbiting objects all have the same velocity. This all works great, but now I need to add a bouncing effect when they run into each other so they start orbiting in a new direction when colliding.

I am currently detecting a collision between two orbiting objects, and trying to determine the resulting reflection vector of the collision. The orbiting objects all have sphere colliders on them.

Here is a relevant code example for how I am orbiting the objects:

```
var velocity = 15f;
var directionVector = new Vector2(Random.Range(-1f, 1f) * velocity, Random.Range(-1f, 1f) * velocity);
transform.Rotate(directionVector.y * Time.deltaTime, -directionVector.x * Time.deltaTime, 0.0f);

```

Here is how I am currently trying to reflect the collision on the `directionVector`:

```
var bounceVector = Vector3.Reflect(transform.forward, collider.gameObject.transform.forward).normalized;
directionVector.x = bounceVector.x * velocity;
directionVector.y = bounceVector.y * velocity;

```

This does cause the objects to "bounce" off of each other, but the bounce direction doesn't seem right, so I have something screwed up. I also feel like this probably doesn't even matter that it's on a sphere because all I need to do is take two direction vectors and find their resulting reflection vector on a collision. Any thoughts?

# Answer
> 1 votes
Try using the normal. I'm not familiar with Unity, so I won't give you the straight code solution.

1)Find a collision point `C`

2)Calculate normal `N` using this formula, where `O` is an origin of the opposite sphere

```
N = normalize(C - O)

```

3)Find reflected movement vector using this formula, where `V` is an actual movement vector of the sphere

```
R = V - 2(dot(V, N))N

```

(Or use Unity's Reflect function instead)

---
Tags: unity, collision-detection, rotation, vector, orbit
---


# Question
Title: javascript game character mouse movement
When a mouse button is pressed, coordinates are stored and character begins to move towards that point.

I do a check each frame if my character reached the destination, but because of the nature of how it all works, it can never be perfectly accurate. When I normalize my vector and multiply it by speed, I will always end up around that point but never directly at it. The bigger the speed, the more distance is passed in one frame and the further I get from where I wanted to be.

```
let startX = 110;
let startY = 110;
let endX  = 400;
let endY = 200;
let speed = 5;

let dx = endX - startX;
let dy = endY - startY;

let length = Math.sqrt(dx*dx+dy*dy);

dx /= length;
dy /= length;

dx *= speed;
dy *= speed;

```

So this gives me a dx:4.775320684056187 and dy:1.4819960743622644, so that is the value that is added each frame, so in the end it gets to coords 399:191 next one is 404:193 etc. I have to pick a close one, or force object to move to the one I wanted, it never reaches exactly 400:200.

It becomes a problem when path finding and collision comes to play, because I can get 2 pixels on an obstacle etc.

How is this solved? What am I doing wrong?

# Answer
> 2 votes
First of for your pinpoint issue. You don't send an AI to walk exactly to a point. That is your first issue. You have to change the following:

On your AI/Pathfindining Agent, get the distance remaining to the target vector. If distance is lower or equal to defined radius, the target aquired radius, then the agent has reached his target.

Then you could simply additianlly snap the object of the agent to the exact point or slowly interpolate the remaining distance as an example.

I hope this get's you into the right direction. It is nto that much you are missing

---
Tags: javascript, movement, vector
---


# Question
Title: Architecture for mixing synchronous and asynchronous program flow to maximize faux real-time yet logical gameplay?
What I am attempting to make is a faux real-time game engine in node.js (taking advantage of the non-blocking I/O). When I say 'faux real-time' what I mean is I want players to interact with the world as much as possible without players blocking each other or having to 'wait in line to use the world'.

That is, unless the gameplay requires it. For example, in real life you have to wait in line to do certain things, some as simple as taking up space on a certain section of the highway. However if each person is in their own space, they can do jumping jacks or spin donuts in their car at a unique pace completely unrelated and 'in parallel' to every other person who is also taking these unrelated actions.

Related/synchronized actions would be things like trading, or even moving. If two players move into the same space and attempt to pick up the **same object** then suddenly it matters if they get there at the same time...

I hope this is making sense, but I'll add some code to try and give an example:

```
setInterval(function() {
     for(var i = 0; i < someArray.length; i++){
         someArray[i].QueuedAction();
     }
     someArray = new Array();
}, 1000);

```

If every 1 second we went through this array and then emptied it, we would effectively have a synchronized list. There may be many events coming in to add to this array while this loop is running, but this loop is blocking those events from modifying the array until it is done and has cleared the array. This would be list of things happening in order.

However if this takes too long, then it will also block players from requesting their current location or the client from requesting objects around the player, etc. So this needs to happen quickly to keep the illusion of real-time but in order to keep the illusion of a logical world.

Is there any patterns I should evaluate that could improve this balance of in-order yet non-blocking world game engine?

# Answer
> 1 votes
To allow the actions to be queued to the list while the list is processed, you could have a second list that receives the actions while the first list is being processed. With that, instead of getting through all of the elements of the list every second, you could process as many items as possible in a shorter time span, then combine the two lists.

I'm not a JavaScript programmer, but with an object oriented language, I'd go with that kind of pseudocode:

```
Class EventQueue
  queueItem( item )
    queueBuffer.apped( item )

  processItems()
    beginTime = performance.now()
    processBuffer.apped( queueBuffer )
    queueBuffer.clear()

    while( beginTime + (1/60) < performance.now() )
    {
      item = processBuffer.popFront()
      item.QueuedAction()
    }

```

The object of type `EventQueue` will be your entry point, with the method `queueItem`. You'll have to find a way to call the method `processItems` on a regular interval. In this example, it will run for a bit more than 1/60th of a second but you could change that and tailor it to your needs.

# Answer
> 1 votes
Maybe I'm oversimplifying your question, but this is what async/await are good for.

For sequences of actions that you need to happen one after another, you call them sequentially with await:

```
await doOneThing();
await doNextThing();
await doFinalThing();

```

And this entire sequence itself can be an async function that can either be awaited on or launched asynchronously.

### Larger Example Code:

```
// example actions that are slow
async function doA() { await delay(100); }
async function doB() { await delay(1000); }

// awaiting this function returns in approximately 0 milliseconds
async function do_A_and_B_and_return_immediately() {
    doA();
    doB();
}

// awaiting this function returns in approximately 1100 milliseconds
async function do_A_afterwards_do_B_afterwards_return() {
    await doA();
    await doB();
}

async function main() {
    // this is quick
    await do_A_and_B_and_return_immediately();
    // this is slow
    await do_A_afterwards_do_B_afterwards_return();
    // this seems like what you're asking for -
    // do a sequential task but don't wait up for it.
    do_A_afterwards_do_B_afterwards_return()
}

```

---
Tags: node.js, synchronization
---


# Question
Title: How to draw lines with fountain pen effect in Unity?
I'm working on drawing lines in `Unity`, I've already implemented smooth line drawing with `LineRenderer`. But I need lines have effect of fountain pen or gel ink pen, just as the picture showed below, I have no idea about this, may shaders make the effect ?can anyone help?

**Now I can draw common lines with `Unity`:**

**Effect needed:**

# Answer
If you can find areas where the derivative is reasonably high (direction changes quickly) and make this thicker, and then slowly reduce thickness until you reach another, that might work.

No idea how to implements this in unity , but thats’s my General thought.
> 1 votes

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


# Question
Title: OpenGL ES 1.1: Is it more efficient to use glClear or use glDrawArrays with primitives that render over used frames?
For example, if I have several figures rendered over a black background, is it more efficient to call glClear(GL\_COLOR\_BUFFER\_BIT) each frame, or render black triangles over artifacts from the past frame? Answers pertaining to other versions of OpenGL are also greatly appreciated.

# Answer
> 3 votes
**It depends**

* Sometimes glClear can be a signal to the driver and/or GPU that you're done with the prior contents of the framebuffer, which it can then use to optimize internally.
* Sometimes glClear needs to touch every pixel in the framebuffer whereas drawing a handful of primitives doesn't.
* Sometimes you're overdrawing the entire color buffer each frame anyway so it might be worth skipping the clear.
* Sometimes your GPU is a tile-based deferred architecture which may operate more efficiently if you clear every frame.
* Sometimes your driver or GPU may have a fast path for glClear which may be the equivalent of just swapping a couple of pointers.
* Sometimes other factors may apply.

In other words, the particular workload you're doing or the GL version you're targetting aren't the only factors that can affect this. In general terms, using the API the way it was designed to be used will be preferable to tricksy stuff, but that's not always the case and exceptions always exist.

Fortunately both options are utterly trivial to code, so you should code both and benchmark them on your own target platform(s).

---
Tags: opengl-es
---


# Question
Title: How to remap world space to screen space?
I am noob to game development, and while using a simple graphics library in Python to make a 2D game, I noticed that the coordinate system of the library had its upper left corner as (0,0), whereas conventionally (at least in math) the lower left corner is set as (0,0).

I want to keep the world space in my physics calculations, but want to map the world space coordinates into the screen space. Furthermore, I want the world space sizes to be a scale of 10 larger than the screen space sizes.

In terms of programming methodology, how should I go about doing this in the most modular fashion?

# Answer
> -1 votes
Would something like

http://www.pentadact.com/2015-01-27-help-me-with-a-trigonometry-problem-for-heat-signature/

Help? He has the solution he found a bit further down in the post.

I'll assume you don't need rotation, because you don't directly mention it in your post.

Actually, assuming that, it just looks like you need to define a world 10 times larger than your screen, and then transform the screen across it. Any objects on screen are at the screen coordinates of

```
(actualX-screenXTransform,actualY-screenYTransform)

```

Unless I'm grossly misunderstanding something, that should be it.

---
Tags: python, coordinates, spaces
---


# Question
Title: Creating an efficient 2D mobile game background
I am working on a 2D unity mobile game and would like some advice on how to save as much MB's as possible with my background images. I can either create 15 600 x 1000 png images through an image manipulation program and import them into unity, each image is roughly 300 kB's before building the project. Or I can import a base background image that i would use multiple times, and also import a sprite sheet with scenery, and just place the sprites on the background layer of my game scene. Note, if i choose the second option there will be 30 - 100 tree sprites, along with enemy and player game objects in view of the main camera at a time. I'm not sure if this second option will bog down the game, because of all the individual sprites on the screen at once.

# Answer
> 0 votes
Already having gone through the process of making a mobile app, here are my thoughts...

1) If you are looking for a static background, just do the first option and create a image of the entire background.

2)If you are looking for a dynamic background, do the second option you suggested.

In my honest opinion, I would rather draw one image and be done rather than 10-100+ different things which will potentially slow the game.

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


# Question
Title: Why when i change the Camera in the Inspector Culling Mask to Nothing when i'm running the game it return automatic to Everything?
I don't have a Main Camera. The only Camera i have for now is on the FirstPersonCharacter as component.

Either changing the Culling Mask by editor in the Inspector or by script from Everything to Nothing when running the game it return to Everything and never stay on Nothing.

The only active script that is attached to the FirstPersonCharacter is: Antialiasing: Not my script. But not sure if this what make it change back all the time the Culling Mask to Everything.

```
using System;
using UnityEngine;

namespace UnityStandardAssets.ImageEffects
{
    public enum AAMode
    {
        FXAA2 = 0,
        FXAA3Console = 1,
        FXAA1PresetA = 2,
        FXAA1PresetB = 3,
        NFAA = 4,
        SSAA = 5,
        DLAA = 6,
    }

    [ExecuteInEditMode]
    [RequireComponent(typeof (Camera))]
    [AddComponentMenu("Image Effects/Other/Antialiasing")]
    public class Antialiasing : PostEffectsBase
    {
        public AAMode mode = AAMode.FXAA3Console;

        public bool showGeneratedNormals = false;
        public float offsetScale = 0.2f;
        public float blurRadius = 18.0f;

        public float edgeThresholdMin = 0.05f;
        public float edgeThreshold = 0.2f;
        public float edgeSharpness = 4.0f;

        public bool dlaaSharp = false;

        public Shader ssaaShader;
        private Material ssaa;
        public Shader dlaaShader;
        private Material dlaa;
        public Shader nfaaShader;
        private Material nfaa;
        public Shader shaderFXAAPreset2;
        private Material materialFXAAPreset2;
        public Shader shaderFXAAPreset3;
        private Material materialFXAAPreset3;
        public Shader shaderFXAAII;
        private Material materialFXAAII;
        public Shader shaderFXAAIII;
        private Material materialFXAAIII;

        public Material CurrentAAMaterial()
        {
            Material returnValue = null;

            switch (mode)
            {
                case AAMode.FXAA3Console:
                    returnValue = materialFXAAIII;
                    break;
                case AAMode.FXAA2:
                    returnValue = materialFXAAII;
                    break;
                case AAMode.FXAA1PresetA:
                    returnValue = materialFXAAPreset2;
                    break;
                case AAMode.FXAA1PresetB:
                    returnValue = materialFXAAPreset3;
                    break;
                case AAMode.NFAA:
                    returnValue = nfaa;
                    break;
                case AAMode.SSAA:
                    returnValue = ssaa;
                    break;
                case AAMode.DLAA:
                    returnValue = dlaa;
                    break;
                default:
                    returnValue = null;
                    break;
            }

            return returnValue;
        }

        public override bool CheckResources()
        {
            CheckSupport(false);

            materialFXAAPreset2 = CreateMaterial(shaderFXAAPreset2, materialFXAAPreset2);
            materialFXAAPreset3 = CreateMaterial(shaderFXAAPreset3, materialFXAAPreset3);
            materialFXAAII = CreateMaterial(shaderFXAAII, materialFXAAII);
            materialFXAAIII = CreateMaterial(shaderFXAAIII, materialFXAAIII);
            nfaa = CreateMaterial(nfaaShader, nfaa);
            ssaa = CreateMaterial(ssaaShader, ssaa);
            dlaa = CreateMaterial(dlaaShader, dlaa);

            if (!ssaaShader.isSupported)
            {
                NotSupported();
                ReportAutoDisable();
            }

            return isSupported;
        }

        public void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (CheckResources() == false)
            {
                Graphics.Blit(source, destination);
                return;
            }

            // ----------------------------------------------------------------
            // FXAA antialiasing modes

            if (mode == AAMode.FXAA3Console && (materialFXAAIII != null))
            {
                materialFXAAIII.SetFloat("_EdgeThresholdMin", edgeThresholdMin);
                materialFXAAIII.SetFloat("_EdgeThreshold", edgeThreshold);
                materialFXAAIII.SetFloat("_EdgeSharpness", edgeSharpness);

                Graphics.Blit(source, destination, materialFXAAIII);
            }
            else if (mode == AAMode.FXAA1PresetB && (materialFXAAPreset3 != null))
            {
                Graphics.Blit(source, destination, materialFXAAPreset3);
            }
            else if (mode == AAMode.FXAA1PresetA && materialFXAAPreset2 != null)
            {
                source.anisoLevel = 4;
                Graphics.Blit(source, destination, materialFXAAPreset2);
                source.anisoLevel = 0;
            }
            else if (mode == AAMode.FXAA2 && materialFXAAII != null)
            {
                Graphics.Blit(source, destination, materialFXAAII);
            }
            else if (mode == AAMode.SSAA && ssaa != null)
            {
                // ----------------------------------------------------------------
                // SSAA antialiasing
                Graphics.Blit(source, destination, ssaa);
            }
            else if (mode == AAMode.DLAA && dlaa != null)
            {
                // ----------------------------------------------------------------
                // DLAA antialiasing

                source.anisoLevel = 0;
                RenderTexture interim = RenderTexture.GetTemporary(source.width, source.height);
                Graphics.Blit(source, interim, dlaa, 0);
                Graphics.Blit(interim, destination, dlaa, dlaaSharp ? 2 : 1);
                RenderTexture.ReleaseTemporary(interim);
            }
            else if (mode == AAMode.NFAA && nfaa != null)
            {
                // ----------------------------------------------------------------
                // nfaa antialiasing

                source.anisoLevel = 0;

                nfaa.SetFloat("_OffsetScale", offsetScale);
                nfaa.SetFloat("_BlurRadius", blurRadius);

                Graphics.Blit(source, destination, nfaa, showGeneratedNormals ? 1 : 0);
            }
            else
            {
                // none of the AA is supported, fallback to a simple blit
                Graphics.Blit(source, destination);
            }
        }
    }
}

```

# Answer
> 1 votes
You cannot add image effects to the camera if your culling mask is set to nothing. If the culling mask is not at least set to something, the Unity Engine sets it to everything by default.

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


title: How to render pixelated 3D?

text:
# Question
Title: How to render pixelated 3D?
I'd like to know how to render games like a.e. Imscared https://gamejolt.com/games/imscared-a-pixelated-nightmare/10058 Its a great game and I wanted some games with a similar art style so..... Yeah!
thanks! :D

# Answer
You just render the game in a lower resolution and then upscale it without interpolation to achieve large pixels.

The one thing where you would need a shader for is reducing the number of colors. You can do that with a pixel shader which only outputs a reduced color palette. You can do that by simply discarding the last few bits of the R, G and B component.
> 0 votes

---
Tags: rendering, pixel
---


# Question
Title: How can I replicate the look and limitations of the Super NES?
I am looking to produce graphics with the same limitations / look that in the Super Nes era. I am specifically looking for graphics similar to Chrono Trigger / FF6.

It would be a lot easier to do if I had an idea of the resolution / dpi I am supposed to use. I found that the technical specs for the SNES are:

> Progressive: 256 × 224, 512 × 224, 256 × 239, 512 × 239 Interlaced: 512 × 448, 512 × 478

But even by using these resolutions, it is pointless if I set it at 72dpi, as I will still have possibly very detailed graphics (that is the main thing, I **don't** want detailed graphics, I want to go pixelated).

I figured it might be related to the sprite size limit, i.e.:

> Sprites can be 8 × 8, 16 × 16, 32 × 32, or 64 × 64 pixels, each using one of eight 16-color palettes and tiles from one of two blocks of 256 in VRAM. Up to 32 sprites and 34 8 × 8 sprite tiles may appear on any one line.

This would work for sprites (characters, objects), but what about maps? Are they built entirely from 8x8 tiles? And then, at what resolution is the end result displayed?

It might seem like I am giving the question and answers at the same time, but all of these are suppositions I am making, so could someone confirm or correct them?

# Answer
You may want to check out this question, which is related although I don't think it's strictly a duplicate since it asks for more general information than you are.

The limitations you are quoting seem reasonable to me.

> This would work for sprites (characters, objects), but what about maps? Are they built entirely from 8x8 tiles?

The SNES had multiple background modes, all of which were palettized (I think) and consisted of 32x32 background tiles. This page may be of use to you, as might this one.

The DPI you use for the background tiles should be the same as the DPI you use for the sprites. But the actual DPI shouldn't much matter, don't worry about it -- if you're going to mimic the resolution of the system exactly, you *will* get detailed-looking sprites at that resolution on a modern monitor. They'll just be extremely small. You'll want to scale everything up anyway if you want to consume a reasonable amount of space on the screen. Probably with nearest-neighbor or simple bi-linear filtering.
> 8 votes

# Answer
In addition to the resolution and pallet limitations a lot of what made the NES experience different from modern gaming is the old CRT screens NES games were displayed on. So if you really want to capture that retro feel, I suggest using a shader that mimics the inaccuracies of these old displays.

http://filthypants.blogspot.com/2011/05/more-emulator-pixel-shaders-crt-updated.html
> 7 votes

# Answer
Just start with 32 x 32 sprites, and don't worry too much about the pallette, unless you want something truely authentic. The use of colour on the SNES was so clever, you can just use whatever pallette you like within reason, and it'll still look the part. Reducing colours at the end is easier than restricting yourself upfront.

You can make the sprites bigger or smaller than 32 x 32, but if you start there, by the time you scale up to 2x ,3x or 4x (using nearest neighbour), it'll look like SNES graphics.

This is the easiest way to get going.
> -1 votes

---
Tags: graphics, graphic-effects, resolution
---


# Question
Title: XNA How to change the sprite texture to white color
as the title,

how can i do to take the sprite to white color

here is some example,

turn to follows image

and my game planform is XNA now, and developed winphone game

thanks for reading!

# Answer
You can use Texture2D.GetData() to copy texture pixel data to a Color\[\] in XNA.

```
Texture2D texture=Content.Load<Texture2D>("asd");
Color[] tcolor=new Color[texture.Width*texture.Height];
texture.GetData<Color>(tcolor);

```

After you have your Color array, you can do whatever you want with it, for example you could change certain colored pixels to Color.White. Then you set this data to the texture. You can use Texture2D.SetData() for this:

```
texture.SetData<Color>(tcolor);

```
> 3 votes

# Answer
Try this

```
spriteBatch.Draw(sprite, position, Color.Red);

```
> 1 votes

# Answer
this works for me, at the beginning of the code, the color is loaded, and a new color is created, after that we change the color to the desired color in the for loop:

```
protected override void Initialize()
        {
            sprite = Content.Load<Texture2D>("Parado");
            Color[] data = new Color[sprite.Width * sprite.Height];
            sprite.GetData(data);
            // cor nova
            Color novaCor =Color.Blue;

            for (int i = 0; i < data.Length; i++)
            {
                // include your RGB color
                if (data[i].R == 142
                    && data[i].G == 24
                    && data[i].B == 115)
                {
                    data[i] = novaCor;
                }
            }
            sprite.SetData<Color>(data);

            posicaoNinja = new Vector2(0, 200);

            base.Initialize();
        }

```
> -2 votes

---
Tags: xna, textures
---


# Question
Title: Play a sound when moving cursor on a button?
How to play a sound when moving a cursor on a button ?

# Answer
> 2 votes
Unity has interfaces you can implement in order to detect when the pointer enters / leaves your UI element :

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;// Required when using Event data.

public class ExampleClass : MonoBehaviour, IPointerEnterHandler // required interface when using the OnPointerEnter method.
{
    public AudioClip AudioClip ;
    private AudioSource audioSource ;

    //Do this when the cursor enters the rect area of this selectable UI object.
    public void OnPointerEnter(PointerEventData eventData)
    {
        if( audioSource == null )
            audioSource = GetComponent<AudioSource>();
        if( audioSource == null )
            audioSource = gameObject.AddComponent<AudioSource>();

        audioSource.PlayOneShot( AudioClip ) ;
    }
}

```

# Answer
> -1 votes
Maybe this could help you. Add such an event to your button in the same manner as you add an OnClick() event. Let me know if it was helpful!

---
Tags: unity, gui, audio
---


# Question
Title: How can i make fade in/out of the alpha color of a material from black to none black?
This is script is attached to a black plane. I have a plane and i added to it a material and the plane is in black. When running the game the alpha color of the plane material is changing slowly.

The script is working it's getting slowly from dark black to none black. But i want to make some changes:

It's not my script i took it from the youtube and did some changes the first one converted from js to c# second added the fade bool variable.

First of all i don't see any meaning setting the variable timer to 10 at the top. Any ideas what is the point ? Second is how can i check when the alpha color value is high enough to do some stuff:

1. Enabled true the fpc again. Once it's not black again the fpc is still enabled false.
2. If i want when the alpha color value reached it's max to make automatic fade back to black Now i'm using manual fade bool variable but i wonder how to do it automatic fade in/out.

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour { public float timer = 10.0f; public FirstPersonController fpc; public bool fade = true;

```
// Use this for initialization
void Start()
{
    Color tempcolor = GetComponent<Renderer>().material.color;
    tempcolor.a = 1f;
    GetComponent<Renderer>().material.color = tempcolor;

    fpc.enabled = false;
}

// Update is called once per frame
void Update()
{
    timer = Time.deltaTime;

    if (timer >= 0)
    {
        Color tempcolor = GetComponent<Renderer>().material.color;
        if (fade == true)
        {
            tempcolor.a -= 0.1f * Time.deltaTime;
        }
        else
        {
            tempcolor.a += 0.1f * Time.deltaTime;
        }
        GetComponent<Renderer>().material.color = tempcolor;
    }
}

```

}

# Answer
> 2 votes
Here is how I would have done it (I've reworked your script, tell me if you don't understand something)

```
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour
{
    public FirstPersonController fpc;
    private Material material ;
    private float targetAlpha = 1 ;
    private float fadeDuration = 1 ;
    private float lerpParam ;
    private float startAlpha = 0 ;

    void Start()
    {
        // It's nice to cache the material to quickly and easily access it
        material = GetComponent<Renderer>().material ;
        SetMaterialAlpha( 1 ) ;

        fpc.enabled = false;
    }

    void Update()
    {
        lerpParam += Time.deltaTime ;

        // Lerp let's you change slowly the value of the alpha
        // https://docs.unity3d.com/ScriptReference/Mathf.Lerp.html
        float alpha = Mathf.Lerp( startAlpha, targetAlpha, lerpParam / fadeDuration ) ;
        SetMaterialAlpha( alpha  ) ;
        if( material.color.a >= 1 )
        {
            FadeTo( 0 );
        }
    }

    // Function to start the fade with the specific alpha with the desired duration
    public void FadeTo( float alpha, float duration = 1 )
    {
        startAlpha   = material.color.a ;
        targetAlpha  = alpha ;
        fadeDuration = duration ;
        lerpParam    = 0 ;
    }

    // Easily change the material alpha with a specific function
    private void SetMaterialAlpha( float alpha )
    {
        Color color = material.color;
        color.a = alpha;
        material.color = color;
    }
}

```

---

In your script, setting the timer value to 10 is useless since you "override" this value each frame `timer = Time.deltaTime` (the `timer` variable is not used, so I don't understand what you were trying to achieve).

About your two other questions, I didn't understand everything and I hope the script I gave you will help you to answer those questions by yourself.

---
Tags: unity, c#, alpha-blending
---


# Question
Title: UI Billboard Shader - Wrong rotation pivot - Unity
I'm trying to display several Images as billboards. All the Images are under the same Canvas. I'm using a billboard shader I've been working on:

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

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

        _ColorMask ("Color Mask", Float) = 15

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

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

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

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

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

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

            #pragma multi_compile __ UNITY_UI_ALPHACLIP

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

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

            fixed4 _Color;
            fixed4 _TextureSampleAdd;
            float4 _ClipRect;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                UNITY_SETUP_INSTANCE_ID(IN);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);

                // Method 1
                /*
                float scaleX = length(mul(unity_ObjectToWorld, float4(1.0, 0.0, 0.0, 0.0)));
                float scaleY = length(mul(unity_ObjectToWorld, float4(0.0, 1.0, 0.0, 0.0)));
                OUT.vertex = mul(
                    UNITY_MATRIX_P,
                    float4(UnityObjectToViewPos(float3(0, 0, 0)), 1) + float4(IN.vertex.x * scaleX, IN.vertex.y * scaleY, 0, 0)
                    //mul(UNITY_MATRIX_MV, float4(0.0, 0.0, 0.0, 1.0)) + float4(IN.vertex.x * scaleX, IN.vertex.y * scaleY, 0.0f, 0.0f)
                );
                */

                // Method 2
                float4x4 mv = UNITY_MATRIX_MV;

                mv[0][0] = 1.0;
                mv[0][1] = 0.0;
                mv[0][2] = 0.0;

                mv[1][0] = 0.0;
                mv[1][1] = 1.0;
                mv[1][2] = 0.0;

                mv[2][0] = 0.0;
                mv[2][1] = 0.0;
                mv[2][2] = 1.0;

                OUT.vertex = mul(
                    UNITY_MATRIX_P,
                    mul(mv, IN.vertex)
                );

                OUT.worldPosition = OUT.vertex;
                OUT.texcoord = IN.texcoord;
                OUT.color = IN.color * _Color;

                return OUT;
            }

            sampler2D _MainTex;

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

                color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);

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

                return color;
            }
        ENDCG
        }
    }
}

```

The problem is that when the Image is not at the center of the canvas (0,0,0), the billboard rotation is not around it's pivot, but the canvas pivot. Here is a small gif:

As you can see the Image on the left (2,0,0) is rotating around the same pivot of the left one (0,0,0), the Canvas pivot (0,0,0).

Here are some caps of the Images transforms and the Canvas transform:

I've tried several things but with no success. I'm still learning to programming shaders. Any suggestion is really welcome.

# Answer
> 1 votes
For optimization Unity usually batches meshes under certain circumstances. This messes up your reference system.

To prevent Unity from batching the meshes add this tag to any shader that breaks with batching:

```
"DisableBatching" = "True"

```

---
Tags: unity, shaders, gui, cg
---


# Question
Title: Java - Entity Collision only working for last index of the Entity Array
I am in the early stages of creating a Java 2d platformer / sidescroller game where the Entity class requires (at this point) basic Rectangle bounds collision detection.

In my code I check to see if the static Rectangle bounds of the Player object intersects with the Rectangle bounds of Entity Object in the array "entities\[\]" in the Screen class. My method of implementation is rendering a rectangle on the top, bottom, left, and right sides of each Entity.

My code is almost fully working since it *does* provide collision detection, however this is only true for the last Entity Object in the Array. Every Entity object besides the last one has *NO* collision detection, even though the Rectangle objects are properly positioned and rendered.

For example if I call the method "addEntities(3)" in my Screen class Constructor, only the 3rd and final Entity will actually utilize the collision detection.

I know the collision detection works because I have adjusted the "checkCollision()" method to check a specific index of the Entity array that isn't the last one. The Rectangle bounds are also rendered to the screen over each Entity sprite properly, so I know the Rectangle object of each Entity is there.

Here is some of my code for the Screen class, which is the intermediary between the Entitiy and the Game class:

```
public Screen (int width, int height) {
    this.width = width;
    this.height = height;
    addEntities(2);                  // amount of entities to spawn
}
public void tick() {
    checkCollision();                // checks collision
}

public void render(Graphics g) {     // renders all entities based on size of array
    for (int i = 0; i < this.entitySize; i++) {
        entities[i].render(g);
    }
}
                                     //
public void addEntities(int entitySize) {   // adds entities to the Screen
    this.entitySize = entitySize;

    entities = new Entity[entitySize];
    int renderX, renderY;
    for (int i = 0; i < entitySize; i++) {
        renderX = (i* 64) + 300;
        renderY = 300;
        entities[i] = new Entity(renderX, renderY, topFloorMob, topFloorSheet, 64, 64); // adds Entities to the proper index of Array 'entities[]'
    }
}

public void checkCollision() {       // checks if bounds of the Player Rectangles intersect the bounds of the Entity Array Rectangles
    for (int i = 0; i < entitySize; i++) {
        if (Player.topBorder.intersects(entities[i].getBottomBounds()))  Player.topCollision = true;

        else  Player.topCollision = false;

        if (Player.bottomBorder.intersects(entities[i].getTopBounds()))  Player.bottomCollision = true;

        else Player.bottomCollision = false;

        if (Player.leftBorder.intersects(entities[i].getRightBounds()))  Player.leftCollision = true;

        else  Player.leftCollision = false;

        if (Player.rightBorder.intersects(entities[i].getLeftBounds()))  Player.rightCollision = true;

        else  Player.rightCollision = false;

    }
}

```

}

Here is some of the Entity class code:

```
public class Entity {
public int renderX, renderY;
protected Sprite sprite;
protected SpriteSheet sheet;
protected Rectangle topBorder, bottomBorder, leftBorder, rightBorder;
protected int sizeX, sizeY; // sizes of entity

public Entity(int renderX, int renderY, Sprite sprite, SpriteSheet sheet, int sizeX, int sizeY) {
    this.renderX = renderX;
    this.renderY = renderY;
    this.sprite = sprite;
    this.sheet = sheet;
    this.sizeX = sizeX;
    this.sizeY = sizeY;
    setBounds();
}

public void setBounds() {
    setTopBounds();
    setBottomBounds();
    setLeftBounds();
    setRightBounds();
}

public Rectangle setTopBounds() {
    return topBorder = new Rectangle(renderX, renderY, sizeX, sizeY - (sizeY - 4));
}
public Rectangle setLeftBounds() {
    return leftBorder = new Rectangle(renderX, renderY, sizeX - (sizeX - 4), sizeY);
}

public Rectangle setRightBounds() {
    return rightBorder = new Rectangle(renderX + (sizeX - 3), renderY, sizeX - (sizeX - 4), sizeY);
}

public Rectangle setBottomBounds() {
    return bottomBorder = new Rectangle(renderX, renderY + (sizeY - 3), sizeX, sizeY - (sizeY - 4));
}

public void render(Graphics g) {
    sprite.render(g, renderX, renderY);
    g.fillRect((int)topBorder.getX(), (int) topBorder.getY(), (int) topBorder.getWidth(), (int) topBorder.getHeight());
    g.fillRect((int)leftBorder.getX(), (int) leftBorder.getY(), (int) leftBorder.getWidth(), (int) leftBorder.getHeight());
    g.fillRect((int)rightBorder.getX(), (int) rightBorder.getY(), (int) rightBorder.getWidth(), (int) rightBorder.getHeight());
    g.fillRect((int)bottomBorder.getX(), (int) bottomBorder.getY(), (int) bottomBorder.getWidth(), (int) bottomBorder.getHeight());
}

public void tick() {
}

public Rectangle getTopBounds() {
    return topBorder;
}
public Rectangle getLeftBounds() {
    return leftBorder;
}

public Rectangle getRightBounds() {
    return rightBorder;
}

public Rectangle getBottomBounds() {
    return bottomBorder;
}

```

And finally here is some of the code for my Player class, which is nearly identical to the Entity class (not properly formatted inheritance at this stage of the project, but it will be fixed later):

```
public class Player {
public static int renderX, renderY;
public static Sprite sprite;
public static SpriteSheet sheet;
public static  Rectangle topBorder;
public static Rectangle bottomBorder;
public static Rectangle leftBorder;
public static Rectangle rightBorder;
public static boolean topCollision = false, bottomCollision = false, leftCollision = false, rightCollision = false;
public static int sizeX, sizeY;

public static boolean moveUp = true, moveDown = true, moveLeft = true, moveRight = true;

public Player(int renderX, int renderY, Sprite sprite, SpriteSheet sheet, int sizeX, int sizeY) {
    Player.renderX = renderX;
    Player.renderY = renderY;
    Player.sprite = sprite;
    Player.sheet = sheet;
    Player.sizeX = sizeX;
    Player.sizeY = sizeY;
    setBounds();
}

public void setBounds() {
    setTopBounds();
    setBottomBounds();
    setLeftBounds();
    setRightBounds();
}

public void render(Graphics g) {
    sprite.render(g, renderX, renderY);
    g.fillRect((int)topBorder.getX(), (int) topBorder.getY(), (int) topBorder.getWidth(), (int) topBorder.getHeight());
    g.fillRect((int)leftBorder.getX(), (int) leftBorder.getY(), (int) leftBorder.getWidth(), (int) leftBorder.getHeight());
    g.fillRect((int)rightBorder.getX(), (int) rightBorder.getY(), (int) rightBorder.getWidth(), (int) rightBorder.getHeight());
    g.fillRect((int)bottomBorder.getX(), (int) bottomBorder.getY(), (int) bottomBorder.getWidth(), (int) bottomBorder.getHeight());
}

public void tick() {
    checkForCollision();
    setBounds();
}

public void checkForCollision() {
    if( topCollision = true) moveUp = false;
    if( bottomCollision = true) moveDown = false;
    if( leftCollision = true) moveLeft = false;
    if( rightCollision = true) moveRight = false;
}

public static Rectangle setTopBounds() {
    return topBorder = new Rectangle(renderX, renderY, sizeX, sizeY - (sizeY - 4));
}
public static  Rectangle setLeftBounds() {
    return leftBorder = new Rectangle(renderX, renderY, sizeX - (sizeX - 4), sizeY);
}

public static Rectangle setRightBounds() {
    return rightBorder = new Rectangle(renderX + (sizeX - 3), renderY, sizeX - (sizeX - 4), sizeY);
}

public static Rectangle setBottomBounds() {
    return bottomBorder = new Rectangle(renderX, renderY + (sizeY - 3), sizeX, sizeY - (sizeY - 4));
}

```

}

I think the problem arises from the logic used in the Screen class method "checkCollision()", but I am not entirely sure. I will post more code of the main Game class if necessary.

I would like some understanding as to how the collision detection only works for the last Entity of the array, otherwise my code fully works. If there is a better way of implementing this, feel free to leave feedback.

\*\[EDIT\] Added a Collision ID integer associated with the index of the Entity array used by the checkCollision() method to detect whether a collision has occurred and at which index corresponding to the tiles rendered on the Screen.

# Answer
\[SOLVED\]: Added a CollisionID attached to the "i" variable iteration of each index of the Entities array when collision has been detected. This effectively pinpoints the actual location of the collision rather than detecting if any collision had been done on any tile. The CollisionID variable is used in the .intersects(entities\[collisionID\]) line to check if the previously detected collision is no longer true, rather than resetting the Player.bottomCollision state (which affects gravitation and movement) to false by default due to other tiles not having collision.
> 1 votes

---
Tags: java, collision-detection, entity
---


# Question
Title: How do I render 2D top-down tiled, directed water flow?
I'm working on a top-down tile-based fairly graphical 2D game inspired by Dwarf Fortress. I'm at the point of implementing a river in the game world, which covers a number of tiles, and I've calculated the flow direction for each tile, as shown below by the red line in each tile.

For reference of the graphical style, here's how my game looks currently:

What I need is some technique to animate water flowing in each of the river tiles, so that the flow blends into the surrounding tiles so that tile edges are not apparent.

The closest example I have found to what I am after is described at http://www.rug.nl/society-business/centre-for-information-technology/research/hpcv/publications/watershader/ but I'm not quite at the point of being able to understand what's going on in it? I have enough of an understanding of shader programming to have implemented my own dynamic lighting but I can't quite get my head around the approach taken in the linked article.

Could someone explain how the above effect is achieved or suggest another approach to get the result I want? I think part of the above solution is overlapping the tiles (though I'm not sure in which combinations) and rotating the normal map used for the distortion (again no idea on specifics) and past that I'm a bit lost, thanks for any help!

# Answer
I didn't have any tiles handy that looked good with distortion, so here's a version of the effect I mocked up with these Kenney tiles instead:

I'm using a flowmap like this, where red = rightward flow and green = upward, yellow being both. Each pixel corresponds to one tile, with the bottom-left pixel being the tile at (0, 0) in my world coordinate system.

And a wave pattern texture like this:

I'm most familiar with Unity's hlsl/CG-style syntax, so you'll need to adapt this shader a little bit for your glsl context, but it should be straightforward to do.

```
// Colour texture / atlas for my tileset.
sampler2D _Tile;
// Flowmap texture.
sampler2D _Flow;
// Wave surface texture.
sampler2D _Wave;

// Tiling of the wave pattern texture.
float _WaveDensity = 0.5f;
// Scrolling speed for the wave flow.
float _WaveSpeed  = 5.0f;

// Scaling from my world size of 8x8 tiles
// to the 0...1
float2 inverseFlowmapSize = (float2)(1.0f/8.0f);

struct v2f
{
    // Projected position of tile vertex.
    float4 vertex   : SV_POSITION;
    // Tint colour (not used in this effect, but handy to have.
    fixed4 color    : COLOR;
    // UV coordinates of the tile in the tile atlas.
    float2 texcoord : TEXCOORD0;
    // Worldspace coordinates, used to look up into the flow map.
    float2 flowPos  : TEXCOORD1;
};

v2f vert(appdata_t IN)
{
    v2f OUT;

    // Save xy world position into flow UV channel.
    OUT.flowPos = mul(ObjectToWorldMatrix, IN.vertex).xy;

    // Conventional projection & pass-throughs...
    OUT.vertex = mul(MVPMatrix, IN.vertex);
    OUT.texcoord = IN.texcoord;
    OUT.color = IN.color;

    return OUT;
}

// I use this function to sample the wave contribution
// from each of the 4 closest flow map pixels.
// uv = my uv in world space
// sample site = world space
float2 WaveAmount(float2 uv, float2 sampleSite) {
    // Sample from the flow map texture without any mipmapping/filtering.
    // Convert to a vector in the -1...1 range.
    float2 flowVector = tex2Dgrad(_Flow, sampleSite * inverseFlowmapSize, 0, 0).xy
                        * 2.0f - 1.0f;
    // Optionally, you can skip this step, and actually encode
    // a flow speed into the flow map texture too.
    // I just enforce a 1.0 length for consistency without getting fussy.
    flowVector = normalize(flowVector);

    // I displace the UVs a little for each sample, so that adjacent
    // tiles flowing the same direction don't repeat exactly.
    float2 waveUV = uv * _WaveDensity + sin((3.3f * sampleSite.xy + sampleSite.yx) * 1.0f);

    // Subtract the flow direction scaled by time
    // to make the wave pattern scroll this way.
    waveUV -= flowVector * _Time * _WaveSpeed;

    // I use tex2DGrad here to avoid mipping down
    // undesireably near tile boundaries.
    float wave = tex2Dgrad(_Wave, waveUV,
                           ddx(uv) * _WaveDensity, ddy(uv) * _WaveDensity);

    // Calculate the squared distance of this flowmap pixel center
    // from our drawn position, and use it to fade the flow
    // influence smoothly toward 0 as we get further away.
    float2 offset = uv - sampleSite;
    float fade = 1.0 - saturate(dot(offset, offset));

    return float2(wave * fade, fade);
}

fixed4 Frag(v2f IN) : SV_Target
{
    // Sample the tilemap texture.
    fixed4 c = tex2D(_MainTex, IN.texcoord);

    // In my case, I just select the water areas based on
    // how blue they are. A more robust method would be
    // to encode this into an alpha mask or similar.
    float waveBlend = saturate(3.0f * (c.b - 0.4f));

    // Skip the water effect if we're not in water.
    if(waveBlend == 0.0f)
        return c * IN.color;

    float2 flowUV = IN.flowPos;
    // Clamp to the bottom-left flowmap pixel
    // that influences this location.
    float2 bottomLeft = floor(flowUV);

    // Sum up the wave contributions from the four
    // closest flow map pixels.
    float2 wave = WaveAmount(flowUV, bottomLeft);
    wave += WaveAmount(flowUV, bottomLeft + float2(1, 0));
    wave += WaveAmount(flowUV, bottomLeft + float2(1, 1));
    wave += WaveAmount(flowUV, bottomLeft + float2(0, 1));

    // We store total influence in the y channel,
    // so we can divide it out for a weighted average.
    wave.x /= wave.y;

    // Here I tint the "low" parts a darker blue.
    c = lerp(c, c*c + float4(0, 0, 0.05, 0), waveBlend * 0.5f * saturate(1.2f - 4.0f * wave.x));

    // Then brighten the peaks.
    c += waveBlend * saturate((wave.x - 0.4f) * 20.0f) * 0.1f;

    // And finally return the tinted colour.
    return c * IN.color;
}

```
> 14 votes

---
Tags: 2d, rendering, glsl, water, fluid-dynamics
---


# Question
Title: UI looks different between editor and in game
I am very confused about Unity's UI system.

This is how my inventory menu looks in the Editor:

And this is the view in game:

**Settings**

Can someone please explain why this happens?

# Answer
I finally solved it, I had to change the rect transform of `Panel_Slots` to stretch height:
> 2 votes

---
Tags: unity, gui, menu
---


# Question
Title: How to properly looping movement of an object
I would like to create an intelligent (universal) class to looping movement object, like sliding doors, etc.

I've thought to declare two vectors:

From To

And a Speed variable.

Then looping. I don't know how to check when current position is \>= then To and looping reverse, considering that you can have starting position (x or y or z) greater then arriving position.

Thanks

# Answer
I'd solve this by abstracting your loop phase from the position, something like this:

```
phase = phase + deltaTime/travelTime;

// Here I use a cosine wave to get a nice ease-in and -out.
// You could use a triangle wave instead for linear motion.
weight = 0.5 * (1 - cos(phase * PI))

position = lerp(From, To, weight);

```

Here when `phase` is `0`, you're at `From`, about to start moving toward `To`. At `0.5`, you're halfway from `From` to `To`. At `phase = 1.0`, the object has arrived at `To` and is about to turn around and return to `From`. At `1.5`, it's halfway back to `From`. And at `2.0` the cycle repeats (you could take `phase` modulo 2 for the same effect).
> 1 votes

---
Tags: movement
---


# Question
Title: Positioning tile sprites so they connect seamlessly
What is the easiest and the most accurate way to combine tiles into a single platform in Unity, with no gaps, overlaps, or misalignment with the already-placed tiles, so that it looks like one continuous piece?

Here is what I mean:

I would like to be able to do the combination of platforms without the dragging by mouse.

I thought about doing it through the coordinates and a little bit of small calculations, but I was not able to find the width of the game object with the respect to coordinates in the Inspector.

# Answer
> 6 votes
Using the Move tool (not the RectTransform tool)

(Image from Unity docs)

Hold the V key to enable vertex snapping, and hover over the corners of your sprite. The transform gizmo will snap to the closest vertex.

Keep holding v, and click and drag that vertex to the corresponding vertex of the rest of your chain:

In my tests, this is most precise when zoomed in.

---
Tags: unity, 2d, tilemap, platform
---


# Question
Title: How to Run a Wad file like doom with OpenGl
Hey I need A code example that allows me to run a wad file in OpenGL support.

```
// oPENGL.cpp : Defines the entry point for the console application.
//JOHN NAN

#include "stdafx.h"
#include "Windows.h"
#include "GL\glew.h"
#include "GL\freeglut.h"
#include "iostream"

using namespace std;

void changeViewPort(int w, int h)
{
    glViewport(0, 0, w, h);
}

void render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glutSwapBuffers();
}

int main(int argc, char* argv[]) {

    // Initialize GLUT
    glutInit(&argc, argv);
    // Set up some memory buffers for our display
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
    // Set the window size
    glutInitWindowSize(2560, 1080);
    // Create the window with the title "Hello,GL"
    glutCreateWindow("MT3d");
    // Bind the two functions (above) to respond when necessary
    glutReshapeFunc(changeViewPort);
    glutDisplayFunc(render);

    // Very important!  This initializes the entry points in the OpenGL driver so we can
    // call all the functions in the API.
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "GLEW error");
        return 1;
    }

    glutMainLoop();
    return 0;
}

```

# Answer
> 0 votes
What do you mean by "run"? If you mean to execute the Doom's WAD file then you just cannot. The WAD file is not an executable format, instead it's a structured file format containing textures, level geometry, etc. So instead of trying to "run" it you should read the WAD file and load all the data that it contains, and use it to generate valid data that can be fed into OpenGL. Take a look here for the WAD file format: Zdoom Wiki

---
Tags: opengl
---