# Question
Title: Optimizing expensive calculation for calculating touch of side of cube
I have this code:

```
someMethod(){

    for (int i = 0; i < numberOfCubes; i++) {
        for (int f = 0; f < NUMBER_OF_SIDES; f++) { // Loop over all the
            // faces
            for (int t = 0; t < 2; t++) { // Loop over the triangles per
                // face (2)
                if (checkTriangleHit(mTriangleVerticesData[i],
                        NUMBER_OF_SIDES * 4 * f + NUMBER_OF_SIDES * 2 * t,
                        depth, i)
                        && ((curFace == MINUS_ONE) || (depth[0] < curDepth))) {
                    curFace = f;
                    curDepth = depth[0];
                }

            }
        }
    }
}

public boolean checkTriangleHit(float[] vertexData, int vertexDataOffset,
                                float[] depth, int cubeNumber) {
    // This function checks whether the passed x and y coordinates hit the
    // triangle
    // passed as argument. If so, it returns true and updates the depth of
    // the hit.
    // Else, it returns false
    float[] fMVPVector = new float[12];

    for (int v = 0; v < 3; v++) {
        // Project the 3 vertices of the triangle using the Model, View and
        // Projection matrix
        Matrix.multiplyMV(fMVPVector, v * 4, mMVPMatrix[cubeNumber], 0,
                vertexData, vertexDataOffset + v * 4);

        // Perspective division
        fMVPVector[4 * v + 0] /= fMVPVector[4 * v + 3];
        fMVPVector[4 * v + 1] /= fMVPVector[4 * v + 3];
        fMVPVector[4 * v + 2] /= fMVPVector[4 * v + 3];
        fMVPVector[4 * v + 3] /= fMVPVector[4 * v + 3];

        // Convert x, y to screen coordinates
        fMVPVector[4 * v + 0] = (fMVPVector[4 * v + 0] + 1) * mWidth / 2;
        fMVPVector[4 * v + 1] = (1 - fMVPVector[4 * v + 1]) * mHeight / 2;

    }

    // Now consider only x and y coordinates and figure out whether the
    // click is in the projected view
    // Transformation matrix for an affine coordinate system
    float[] fTMatrix = new float[4];
    fTMatrix[0] = fMVPVector[4] - fMVPVector[0]; // V1x - v0x
    fTMatrix[2] = fMVPVector[5] - fMVPVector[1]; // V1y - v0y
    fTMatrix[1] = fMVPVector[8] - fMVPVector[0]; // V2x - v0x
    fTMatrix[3] = fMVPVector[9] - fMVPVector[1]; // V2y - v0y

    float det = fTMatrix[0] * fTMatrix[3] - fTMatrix[1] * fTMatrix[2];
    if (Math.abs(det) < SMALL_NUMBER) {
        return false;
    }

    // Invert now the matrix
    float[] fTInvMatrix = new float[4];
    fTInvMatrix[0] = fTMatrix[3] / det;
    fTInvMatrix[1] = -fTMatrix[1] / det;
    fTInvMatrix[2] = -fTMatrix[2] / det;
    fTInvMatrix[3] = fTMatrix[0] / det;

    // Move the touch event fit in the new coordinate sytem
    float[] touchVector = new float[2];
    touchVector[0] = x - fMVPVector[0];
    touchVector[1] = y - fMVPVector[1];

    // Calculate the affine coordinates of the point
    float[] touchAffVector = new float[2];
    touchAffVector[0] = fTInvMatrix[0] * touchVector[0] + fTInvMatrix[1]
            * touchVector[1];
    touchAffVector[1] = fTInvMatrix[2] * touchVector[0] + fTInvMatrix[3]
            * touchVector[1];

    // The new x and y coordinates must be positive and less than 1.
    if ((touchAffVector[0] < 0.0f) || (touchAffVector[0] > ONE)) {
        return false;
    }

    if ((touchAffVector[1] < 0.0f) || (touchAffVector[1] > ONE)) {
        return false;
    }

    // The vector v2-v1 is the diagonal of the spanning parallelogram
    // Check that the point lies beneath the diagonal of the parallelogram
    if (touchAffVector[0] + touchAffVector[1] - ONE > 0.0f) {
        return false;
    }

    // Calculate now the depth of the touch event in the current triangle
    depth[0] = touchAffVector[0] * (fMVPVector[6] - fMVPVector[2])
            + touchAffVector[1] * (fMVPVector[10] - fMVPVector[2])
            + fMVPVector[2];
    return true;
}

```

Which calculates whether a tap (android) has been done on a side of a cube.

It works well for one cube, but as of 2 cubes it gets slow and for four it is human noticeable (and irritating).

I plan to use eight cubes in the future so it might be handy to optimize it.

My math skills are not that good so could it be possible to maybe at least give a few hints on how to optimize this?

Thanks a lot,

S.

# Answer
> 1 votes
It's been mentioned, but you probably need to exclude cubes based on a simple bounding box test first. Also, if you are testing a touch into the projected view space, would this not be just ray cast against projected space. If so, then I would advise the following.

1. Obtain the ray cast of the touch point into your view space.
2. Loop through every cube, test bounding sphere ray cast first, cheap test.
3. if point 2 successful, then , invert a copy of the ray cast so that is now in the local space of the cube. (invert the ray using the inverse of the cube matrix).
4. Test this copy ray cast against the untransformed cube (in its local space).
5. Do a dot product test on the normal of the face of the cube to make sure the face at the least is facing the ray cast. That should bring it down to 3 faces at most to test. meaning only 6 triangles to test from what I can see.
6. if you need to get the depth of the hit, you will have to take the ray cast start from the hitpoint and create a vector, then multiply it back out by the cubes transform.

There are plenty of ray cast code samples out there, hope this helps.

---
Tags: opengl, matrix, optimization
---


title: No way to make asset store go online?

text:
# Question
Title: No way to make asset store go online?
I was trying to follow a tutorial for my first unity tests and I can't seem to convince unity that I indeed have an internet connection, short of a complete uninstall I tried about everything I could think of or find on google:

* Running unity as an admin
* Reseting my TCP-IP with a Microsoft tool
* Deactivating my firewall
* Deactivating windows 10 firewall for real and completelly (Because windows 10 sucks and I'd be using windows 7 if it weren't for docker)
* Deactivating my AV software Logging out and in from unity

The browser will open the asset store no problem, I'm on windows 10

# Answer
Apparently my account was too old and had no username associated with it (I indeed had downloaded unity a couple years ago but did nothing with it), since I was logged in through google it would log in but didn't ask me to create a new username until clicked on the cloud button and I dug around on their site.

As soon as I created the username and restarted unity it would work.

Apparently the old account and outdated version confused the IDE.
> 1 votes

---
Tags: unity, ide
---


# Question
Title: What are the ramifications for lying to the ESRB?
The ESRB Ratings Process walkthrough describes the steps to get a physical boxed game rated:

> Physical (e.g., boxed) games typically sold at retail are rated using a "Long Form" process whereby ESRB raters evaluate the content of each game in advance of its public release. In these cases the publisher must provide two key forms of content disclosure as their game is being finalized: 1: a completed ESRB online questionnaire detailing the game's pertinent content, which essentially translates to anything that may factor into the game's rating. This includes not only the content itself (violence, sexual content, language, controlled substances, gambling, etc.), but other relevant factors such as context, reward systems and the degree of player control; and 2 a video that captures all pertinent content, including typical gameplay, missions, and cutscenes, along with the most extreme instances of content across all relevant categories. Pertinent content that is not playable (i.e., "locked out") but will exist in the game code on the final game disc must also be disclosed. Once checked to ensure that all pertinent content disclosed in the completed questionnaire is reflected in the video submitted, the video is reviewed by a group of at least three trained raters who collectively deliberate about what rating should be assigned.

For digital games, the ‘Short Form’ process is similar.

Implicit in all of this is the idea that you will fill out the questionnaire honestly, and that you will submit video footage indicative of questionable game content.

But what if you didn’t? What if a game like, say, GTA ‘marketed’ itself to ESRB as an open-world life simulator, and totally left out the violence/theft/etc. when submitting their materials? When the organization found out the developers lied, what exactly would happen?

# Answer
> 1 votes
The ESRB's enforcement process is described on an adjacent page.

Broadly, the ESRBs enforcement mechanisms are financial in nature. They can refuse to work with you in the future, they can directly leverage fines against you, and they can use their relationships with retailers to limit or outright stop the sale of your game.

It's worth noting that getting your game rated by the ESRB is entirely optional.

However, many retailers (including online stores) opt to only stock titles that have been rated, and many publishers will require your game to get rated as part of the publishing deal. In addition, the ESRB ratings are trademarks of the Entertainment Software Association, and one thus requires their permission to use them.

This gives the ESRB a de facto level of bargaining power that it can deploy via contractual agreements with developers and publishers.

---

One of the more famous incidents of ESRB enforcement is the re-rating of GTA: San Andreas in the light of the sexually explicit content that found its way into the shipping game. This involved pulling existing copies of the game from stores to re-sticker them or replace them with new copies that Rockstar produced (presumably on their own dime) with the offending content removed.

Somewhat less famous is the incident where Wartune used the ESRB's "AO" rating images without permission (or actually even submitting the game to the board). Wartune's developer or publishers were threatened with legal action for it.

# Answer
> 1 votes
The short answer is: it depends on the specific context of the situation.

The general scenario you described is addressed in their FAQ under incomplete / inaccurate disclosure:

> ... Where a game or app has been assigned a rating based upon incomplete or inaccurate content disclosure, ESRB works to ensure that the rating is promptly corrected wherever it is displayed to consumers, be it a game box, an advertisement, an online or mobile storefront. For physical (e.g., boxed) games, failure to disclose pertinent content during the rating process may also be addressed via formal ESRB sanctions and penalties.

Some specific sanctions and penalties are described on the ESRB enforcement page:

> ... with digitally delivered games and apps, the prompt correction of an inappropriate rating is technically feasible and serves as an effective enforcement mechanism. However, this and other remedies are less readily applied with respect to physical (e.g., boxed) video game products, where the ESRB enforcement system allows for the imposition of harsh sanctions (e.g., fines up to $1 million, product recall, the stickering of product throughout all retail outlets) for instances of significant or egregious content non-disclosure. Less serious violations of ESRB content disclosure guidelines can result in the assignment of points, fines, and mandated corrective actions.

Specific sanctions & penalties can be found in the ESRB Enforcement System Summary. It describes a range of violations & the point system used to determine penalty levels. Here is a summary of the fine schedule:

Aggravating factors affecting judgments include gravity of offense (nature of content), willful intent, negligent actions, history of non-compliance, failure to cooperate with ESRB investigation (including fraudulent actions), and perceived damage to the ESRB system (including publicity).

This only covers the sanctions that you contractually agree to by using the ESRB system. It's possible that additional penalties may apply depending on the legal jurisdiction of the situation. When in doubt, ask your lawyer / legal team.

---
Tags: content-rating, esrb
---


# Question
Title: Can I develop Linux + Windows games using C#, .NET and OpenGL?
I want to learn to develop 3D and 2D graphics with either OpenGL or DirectX. I chose OpenGL as it's being used in webGL and works cross-platform.

I already know .NET well, and the C# language just fits my style very well and I feel secure with it.

However, I want to develop a game that works on Windows and Linux. Is this possible to do with the combination of C#, .NET and OpenGL. I know that OpenGL will not be a problem.

# Answer
I highly suggest you take a look at OpenTK. Using it with MonoDevelop has worked out great for me in the past (Though I never wrote a full on game with it). If you stick the the C# 2.0 standard, you'll have little to no problems.
> 6 votes

# Answer
Unity3D is developed using Mono, so of course you can!

Just be careful.

Like the others said: test your code as often as possible on 'the other OS' - and by that I mean daily.

Unity is available for Windows and the Mac, but since Mac essentially is unix, I guess it's only a matter of time/effort before Unity can target Linux..
> 4 votes

# Answer
In theory, yes, you should be able to develop a 3D application using C# and OpenGL on both Windows and Linux.

In practice, this is likely to be somewhat painful: you will need to restrict yourself to the subset of functionality that works for both Visual Studio and Mono, and it is likely that you won't be able to use many tools and libraries which have been targeted at only one environment.

You will need to take a very rigorous approach of converting your project files from one environment to the other, testing early and often so as to catch problems quickly, and rewriting immediately anything that proves not to be portable. This can be very frustrating at times.

In the end, ask yourself why you would want to target Linux. If learning C# and 3D development is your main goal, maybe you should concentrate on Windows instead of getting lost in the intricate details of different platforms. If your goal is to write a platform independent 3D application, many other interesting languages, such as Java or Python, might be better options in term of portability, and they are close enough to C# that you can leverage most of your experience in that domain.
> 3 votes

# Answer
Yes it's doable. If you need to check for compatibility while working with Visual Studio Mono Tools can be very helpful. But they aren't free.

Also there is always Java, which is a very similar language to C#, has great OpenGL bindings, and works virtually the same on all platforms.
> 1 votes

# Answer
SDL.NET looks like the best place to start. From their site

> SDL.NET is a set of object-oriented CLS-compliant .NET bindings for the SDL gaming library and provides high-level access to audio, keyboard, mouse, joystick, TrueType fonts, various image formats, sound mixing, MPEG-1 movies, 2D video framebuffer and 3D hardware via OpenGL.

and SDL is

> Simple DirectMedia Layer is a cross-platform multimedia library designed to provide low level access to audio, keyboard, mouse, joystick, 3D hardware via OpenGL, and 2D video framebuffer. It is used by MPEG playback software, emulators, and many popular games, including the award winning Linux port of "Civilization: Call To Power."

Qt seems to be another option for a cross platform UI.

MonoXNA and looks like a nice project, but it is still in its infancy. It may be a place for you dig in and get some great low level knowledge as the libraries come together.
> 1 votes

# Answer
Two people say yes, I'd say no.
You can do it using C# and OpenGL, but not using .NET. .NET is Windows specific.
Go with Mono and the libraries they support and you should be good. .NET framework is never fully ported (it's a hairy subject) but the base libraries are, so a lot of knowledge is applicable, but to be fact specific, no, a project developed with .NET is not guaranteed to compile or run on Linux.
Okay, edited to add, yes you can, if you don't use unported features. .NET is not fully crossplatform. I took the porting requirements stricter than what the question asked for.
> 0 votes

# Answer
In theory it is possible, but unless you have your heart set on making a game in C#, I suggest using C++ instead. Compiled code is always faster if well written and you will be writing a game that produces an executable for the platform you are developing for. if you do write a game in C# for Linux, mono will produce and executable file that of course the .net framework will run, so even though you written the game for Linux, you actually written the game for the .Net Framework that is actually able to run the game because Mono open version works on Linux. kind of like wine, so in reality, you still only written the game for windows.

If that does not bother you then I say have fun, but like everybody else has already stated, you will have to avoid the windows only functions when making your game which might require you to reinvent the wheel to get the same functionality on Linux;however,those rules would apply no mater which language you choose go with unless you use Java which would be the same boat as C# but minus Unity awesomeness.
> 0 votes

---
Tags: opengl, c#, cross-platform, .net
---


# Question
Title: Is it bad practice to use the entire map image as a tilemap?
I made a map in photoshop which I want to use as a map in my game. The question is should I try to cut it up to pieces, or is it bad (performance wise) if I use the way I made it. The picture itself is really specific without any repeatable part so I'm not sure if I can cut it up to smaller parts.

*I'm kinda new to game developement, so pls forgive me if I asked something stupid here.*

# Answer
In general you want all your textures to be big and few, usually devs, when they have multiple small sprites for a game, they combine them to one single texture (Texture Atlas), so I'd recommend to have your map in one texture.

However, it kinda depends on how big the map is. Obviously if you have a giant map of a huge open world, and you can only explore a tiny fraction of it, you don't want all of that constantly in memory. In this case, you'd probably need to separate it and load each one dynamically. Where do you draw the line of how big a map should be to do that? that's up to you to decide, depending what platforms you want to support, with OpenGL for example, max texture size can be about 2048 or 4096 or something else (depending on the hardware), if you target phones, I wouldn't be surprised if it was less than that.

If your game is simply multiple regular-sized "stages" or something like that, it's better loading the whole stage map at once, if it's an open world, you have to find a way to do it dynamically (one of the struggles of making an open world game).
> 1 votes

---
Tags: tilemap, maps, png
---


# Question
Title: A scriptManager (singleton) not storing a variable (in the same scene)
The script below is called every time I pickup an item and stores an instance of it in the array "mainInventory".

The problem is when I access the array after picking up another item its empty.

The script is on the MainCamera.

```
public class InventoryManager : MonoBehaviour
{
public static InventoryManager instance = null;
public Image inventoryPanel0;
public Image inventoryPanel1;
public Image inventoryPanel2;
public Image inventoryPanel3;
public Image inventoryPanel4;
public Image inventoryPanel5;
public Image inventoryPanel6;

private Item[] mainInventory;

// Use this for initialization
void Awake ()
{
    //Singleton
    if (instance == null)
        instance = this;
    else if (instance != this)
        Destroy(gameObject);

    mainInventory = new Item[7];
}

public void pickedUp(Item item)
{
    //Below checks which slot item belongs in
    bool positionFound = false;
    int currentPositionCheck = 0;

    while (!positionFound)
    {
        if (mainInventory[currentPositionCheck] == null)
            positionFound = true;
        else
            currentPositionCheck++;
    }

    //Adds item to slot
    mainInventory[currentPositionCheck] = item;

    //Adds image to inventory panel
    switch (currentPositionCheck)
    {
        case 0:
            inventoryPanel0.sprite = item.icon;
            break;
        case 1:
            inventoryPanel1.sprite = item.icon;
            break;
        case 2:
            inventoryPanel2.sprite = item.icon;
            break;
        case 3:
            inventoryPanel3.sprite = item.icon;
            break;
        case 4:
            inventoryPanel4.sprite = item.icon;
            break;
        case 5:
            inventoryPanel5.sprite = item.icon;
            break;
        case 6:
            inventoryPanel6.sprite = item.icon;
            break;
        default:
            Debug.LogError("Expand inventory", this);
            break;
    }

}
}

```

Item:

```
public class Item : MonoBehaviour {

public string name;
public Sprite icon;

private MessageManager messageManagerScript;
private InventoryManager inventoryManagerScript;
private bool inRange;

private void Start()
{
    //Gets managers
    GameObject managerContainer = GameObject.FindWithTag("MainCamera");
    if (managerContainer != null)
    {
        inventoryManagerScript = managerContainer.GetComponent<InventoryManager>();
        messageManagerScript = managerContainer.GetComponent<MessageManager>();
    }
    else
    {
        Debug.Log("Can't find camera containing maangers");
    }
}

// Update is called once per frame
void Update()
{
    //If in range and player presses key
    if (inRange && Input.GetKeyDown(KeyCode.F))
    {
        Destroy(gameObject);
        OnTriggerExit(new Collider());

        //Pickup item
        inventoryManagerScript.pickedUp(this);
    }

}

private void OnTriggerEnter(Collider other)
{
    inRange = true;

    //Displays pickup message
    if (other.gameObject.tag == "Player")
    {
        messageManagerScript.displayPickupMessage(name);
    }
}

private void OnTriggerExit(Collider other)
{
    //Removes pickup message
    messageManagerScript.removeDisplayMessage();

    inRange = false;
}

```

}

# Answer
> 2 votes
When you call `Destroy(gameObject)` it destroys the `gameObject` as well as the components on it, including the `Item`. Later, when you are looking for an empty spot in the list, you check for the object being null. When comparing a `MonoBehaviour` that has been destroyed to null, it returns true.

So your problem is that you are destroying the `Item`. Maybe you should just be disabling it, or putting something besides the `MonoBehaviour` into your inventory list.

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


# Question
Title: SpriteRenderer batching issue, with Z-Position and Order in Layer
I have two sprites (they look the same but with different colors):

I want them to be positioned like on the image above, so there's a feel like blue is standing on the green one. There are two ways to achieve that:

* Blue block with `Order in layer 1`, Green block with `Order in layer 0`
* Blue block with lower `Z coordinate`, so it's physically in front of the green one.

Both of the concepts appear to **break batching** between these two objects. They're on the same atlas (I've tested it by setting the same Z position and Sorting Order and batching works).

How can I achieve batching here?

# Answer
> 1 votes
No, order (be it due to different Z position, different Order in layer, etc.) doesn't break sprite batching.

The most probable cause is that those sprites are using different `Materials`: you can't batch such sprites.

---
Tags: unity, sprites, batching
---


# Question
Title: Unity gameobject design approach for item drops
In a game like Minecraft, the player could have any of several hundred types of items in their inventory. Players can drop those items into the world, but obviously how they're rendered in the world differs from how they're rendered in the inventory.

I'm trying to understand how to design for this scenario using Unity's GameObject concept.

Individually, it seems like the expectation is that:

* I would have one GameObject (with at least a `SpriteRenderer`) for every unique item that can appear in-world.
* I would have one GameObject (with at least an `Image` component) for every unique item that can appear in inventories.

With so many, I also need to come up with some sort of directory so that I can associate bulk prefab objects for use in-game.

Is this accurate? I feel like that's a lot of overhead.

Would I be able to create one GameObject with both a `SpriteRenderer` and an `Image` and maybe toggle between then based on whether its in world or an inventory?

I had also considered using one generic GameObject and replacing the sprite/image based on the item needed, but that feels like it's misusing what GameObjects are meant for. It also likely subverts the benefit of pooling them, etc.

Is there another approach I'm missing?

# Answer
> 1 votes
How about this:

* Create a struct/class, that has one `Sprite` and one `Mesh`/`Image` (depending what your items looks like in the world). Create a script that has a list of those classes. Give data to this script, in pairs, like `list.add( new MyClass(catSprite, catMesh) );` for each object that exists in your game.
* Your items have now IDs based on their index in the array, in the above example, `list[0]` would be the cat object.
* Now create two scripts, one handles an item in the world, and how it behaves (maybe when you drop it, it bounces around, or it shines to indicate it's an interactive item) and the other handles an item in the inventory (it occupies a slot, and you can move it around or interact with it either with `use` or `destroy` etc).

Now for example, when you destroy a block, or kill an enemy, and you want to summon a new item, you simply do something like `MyItemScript.SummonItem(id, location);` which would (most likely) `Instantiate` a prefab of an item, and change it's `Mesh` / `Image` to match that of that item's `id`.

Do the same for an inventory item. When you pick up an item from the floor, do something like `MyInventoryItemScript.SummonItem(id, slot);` which would `Instantiate` a prefab of an inventory item, with the sprite from the item's id and then destroy the item on the world.

Please note this is not the only way of doing this, and depends on your exact situation, but it can probably give you some vague idea of where to go next.

# Answer
> 1 votes
1. Create a prefab with a `Sprite` or `Image` component.
2. Clone/Instantiate this prefab as needed
3. Set the sprite/image to the desired image file from Resources

For example, I have this helper function that I apply directly to an Image component.

```
public static Sprite getSpriteForResource(string texName) {
    //Debug.Log(texName);
    Texture2D t = t = Resources.Load<Texture2D>(texName);
    if(t == null) {
        Exception err = new Exception("Unable to load image file '" + texName + "'");
        Configuration.writeToErrorFile("MainThreadErrors.txt", err.ToString());
        return null;
    }
    Rect size = new Rect(0, 0, t.width, t.height);
    return Sprite.Create(t, size, new Vector2(0.5f,0.5f), PIXELS_PER_UNIT, 0, SpriteMeshType.FullRect);
    //PIXELS_PER_UNIT = 100
    //Matches the ReferencePixelsPerUnit property on the Canvas
}

```

and

```
img.GetComponent<Image>().sprite = SpriteLoader.getSpriteForResource("items/" + item.name);

```

---
Tags: unity
---


# Question
Title: How can I pass an enum value to the OnClick method of a button?
I am making a UI system for my game where I want to use an `enum` to define different UI modes. But `OnClick` function on button doesn't show method which receive `enum`s.

I heard I can pass an integer value to `OnClick` method and then somehow transform it into an enum. What can I do about it?

# Answer
You can have integer as parameter to your click function and then cast it to the enum directly:

```
public void SwitchUIMode(int uiMode)
{
   UIModes currentMode = (UIModes)uiMode;
   switch (currentMode)
   {
       case UIModes.MainMenu:
       ...
   }
}

```
> 1 votes

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


title: How can I draw an outline in Unity3d?

text:
# Question
Title: How can I draw an outline in Unity3d?
I am trying to highlight a rectangle of arbitrary height. I thought the easiest way to do this would be to create a separate "box" gameobject that outlines the rectangle.

I've tried with both a MeshRenderer + Transparent Texture, and a LineRenderer to outline the four points of the rectangle. Neither are very satisfactory.

(Line renderer on in the middle, scaled cube on the right)

What's the right way to go about this? I am trying to get something like the left rectangle - a simple perimeter of fixed width through four points of my choosing.

# Answer
> 2 votes
I had this same problem creating an outline, except I needed to create the "stroke" for a 3d cube, and found a new way to do it that I've not seen anywhere else online.

In the image below there are two shapes with outlines. The one on the right is a cube constructed with LineRenderer, which builds flat faces that always turn towards the user. I found this method super glitchy, with random "strokes" appearing that mimicked the triangles that make up the face.

The one on the left is my “innovation” with 12 separate skinny cubes constructing what looks like an outline. To change the size of the “stroke” in the outline I need to increase/decrease sizes of two sides of each of the 12 skinny cubes. This would also work for 2d outlines. Just apply a material to change the color and voila!

In this image you can see a detail of structure of this cube. This could all be created at runtime but I made it by hand and used it as a prefab.

# Answer
> 10 votes
Use `GUI.Box()`.

If you only need a 2D rectangle, GUI is the way to go. Create a new GUIStyle using a simple rectangle as a texture (the inside of the rectangle should be transparent, of course), set up its `Border` value so that it is not stretched, and call `GUI.Box(new Rect(...),"",myGuiStyle);`.

You can use `Camera.WorldToScreenPoint` method if you want to outline something in world coordinates (i.e. 3D), just remember that in Unity's world coordinates y goes from bottom to top, and in GUI y goes from top to bottom.

**Code Example:**

```
void OnGUI()
{
    //top left point of rectangle
    Vector3 boxPosHiLeftWorld = new Vector3(0.5f, 12, 0);
    //bottom right point of rectangle
    Vector3 boxPosLowRightWorld = new Vector3(1.5f, 0, 0);

    Vector3 boxPosHiLeftCamera = Camera.main.WorldToScreenPoint(boxPosHiLeftWorld);
    Vector3 boxPosLowRightCamera = Camera.main.WorldToScreenPoint(boxPosLowRightWorld);

    float width = boxPosHiLeftCamera.x - boxPosLowRightCamera.x;
    float height = boxPosHiLeftCamera.y - boxPosLowRightCamera.y;

     GUI.Box(new Rect(boxPosHiLeftCamera.x, Screen.Height - boxPosHiLeftCamera.y, width, height),"", highlightBox);
}

```

# Answer
> 1 votes
Below is a non-shader approach.

Think of your 2d box as nothing more than four lines, where each line is stretched in only one dimension (the other two dimensions are the cross-section of the edge). This is much like if you were to construct a box in real-life, where you are piecing together variable lengths of wood that all have the same cross-section size.

With that in mind, you can devise a Component, say `BoxBuilder`, which when attached to a GameObject, creates and manages four child GameObjects. Each child game object is one of your box edges, and can simply be a 3d cube that is stretched in only one dimension. With a `width` and `height` defined `BoxBuilder` level, you can calculate the necessary positioning and non-uniform scale of the four child edges. It will be a lot of `pos.x=w/2`, `pos.y=h/2`, ..., `scale.x=h`, `scale.y=w`, etc. sort of code.

Though I believe you're asking for 2-d only, note that this same idea can be applied to 3d boxes if needed, where the `BoxBuilder` now must create and manage 12 child edges, but again only scaling each edge in one local dimension.

# Answer
> 1 votes
A simple way is to use a Shader with two Passes: the first Pass uses the vertex shader to scale up the object a bit and uses the pixel shader to color it to a solid color matching to the color you want the outline to have, and then the second Pass does the regular rendering.

# Answer
> 0 votes
I am currently facing the same problem, and my solution is exactly what DuckMaestro and Raven Dreamer suggested - Have a script that creates 4 child objects at runtime each of which representing a side of the border and attach line renderers to each one.

In my case I needed to constantly resize the border to keep it around my object (A text mesh \[which uses a mesh renderer\] for a custom text field) so every update I did this:

```

float width = Mathf.Max(renderer.bounds.size.x + paddingX * 2, minWidth);
float x = renderer.bounds.center.x - width / 2;
float height = renderer.bounds.size.y + paddingY * 2;
float y = renderer.bounds.center.y - height / 2;

AlterBorder(0, new Vector3(x - thickness / 2, y, 0), new Vector3(x + width + thickness / 2, y, 0)); //Bottom edge going left to right
AlterBorder(1, new Vector3(x + width, y + thickness / 2, 0), new Vector3(x + width, y + height - thickness / 2, 0)); //Right edge going bottom to top
AlterBorder(2, new Vector3(x + width + thickness / 2, y + height, 0), new Vector3(x - thickness / 2, y + height, 0)); //Top edge going right to left
AlterBorder(3, new Vector3(x, y + height - thickness / 2, 0), new Vector3(x, y + thickness / 2, 0)); //Left edge going top to bottom

```

`AlterBorder()` simply accesses the appropriate line renderer (specified by first parameter) and set its start and end to the first and second vector respectively.

Note that I used `renderer` as my reference for size, but obviously you can use any rectangle, as long as x,y is the top left corner.

From what I can tell this works really well, looks great in game because I can easily move my bordered object around in all 3 axis (Even rotate it, and since line renderers always face the camera it doesn't look weird), and is not hard to implement.

---
Tags: unity, graphics
---


# Question
Title: Unity Input.GetMouseButtonDown(0) is not working
My code to detect left mouse click is not working **Input.GetMouseButtonDown(0) and Input.GetMouseButtonUp(0)**. But same code for **Input.GetMouseButton(0)** is working.

Code:

```
void FixedUpdate()
{
  #if UNITY_ANDROID
    mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0, 0, 4f));
    mouseCameraOffset = bowlingBall.position - mouseWorldPos;

    if (Input.GetMouseButtonDown(0))
    {
        Debug.Log("last");
        lastMousePos = Input.mousePosition;
    }

```

# Answer
Mouse events might be fired and lost between two consecutive `FixedUpdate`s.

Use `Update` to make sure you capture all of them.
> 2 votes

---
Tags: unity, unityscript
---


title: Monogame - All effects in one file?

text:
# Question
Title: Monogame - All effects in one file?
I am successfully drawing all of my geometry with an AlphaTestEffect and would like to apply shaders. I've built a shader Effect from a tutorial and can't seem to find anything on the web that answers my question:

Does monogame support passing separate effects with the same geometry to the Graphics Device, or do you have to perform all Techniques you intend to apply to a model in the same effect?

# Answer
> 1 votes
After playing with my shader some more I got it working. Indeed you can run multiple effects on the same geometry. It should be similar performance to having all your techniques in the same effect but can be abstracted better.

---
Tags: c#, monogame, effect
---


# Question
Title: C++ Text RPG - Commands and their output
**Synopsis**

So far i tried to make games and most of the times i finished on having 'engines' ready. Not the games at all. I figured out that after having rendering, music, i/o handling, all that stuff ready i pretty found myself already burned out and having no idea what the game was about i wanted to write.

And in my at least 10 years of hobby gamedev i completed 10 engines but not a single game.

I got to know OpenGL, GLES, LibSDL and even low level frame buffer rendering - however that knowledge is nothing if you can't get your game out.

I wrote my own GL based UI systems, even coded my own scripting language, coded multiplayer tcp/udp client-server game system, coded level editors, model viewers, mesh exporters, ray tracers and tons of shaders. Meantime i worked on other things too - not related to gamedev (like Distributed Computing Libraries, Algotrading stuff, lot of IOT, exploits, machine learning algorithms..) and i finished them **all**, but still i come back to try to write a game and i fail.

**Why?**

After so many years i try to answer this question and i think the reason of me not being able to finish a simple game is because i always somehow focused on the engines, core but not the actual game itself.

It's like knowing all about how the game should be running so that you actually see it on your screen with top performance but when you ask me how does these two characters will fight - i would answer - you need to figure it out.

**Today**

This time is no different. I told myself i will write a game - 'simple' text RPG, no graphics at all - plain text, should be easy - no need to focus on anything but text - easy huh?

No

I just finished to build the scratch of the backend of the game, have the Rooms implemented, Entities, Parsing the input, Json loader, saveing, loading, inventory, commands interpreter and what? Well im stuck.

**Problem**

Imagine i have the following structure:

```
CEntity (base class for all entities)
CEntityItem
CEntityDoor
CEntityRoom
CEntityCreature
CEntityCreatureCow
CEntityCreaturePlayer
CEntityCreatureHorse

CCommand (base class for all commands)
CCommandLook
CCommandWalk
CCommandXXXX

```

The game 'engine' does nothing special, basically it goes endless loop asks for user input, passes the input into command and prints out the return

pseudocode

```
while(1) {
// Returns a vector of strings, users input split by ' ' space

std::vector<std::string> vCommand = GetInput();

// Go through the available commands and see which fits

for(;;;)
{

         if(m_vCommands[a]->GetCall == vCommand[0])

         printf("%s\n", m_vCommands[a]->Handle(vCommand);
}

}

```

And when a player types in (example)

```
Command: look

```

What i do is just go through the available commands, check which does it fit and pass it as

```
std::string strOutput = pCommand->Handle(std::vector<std::string>& rvstrCommandArguments);

```

A proper command object gets called out and performs action - in this example Look, returning a string that is then printed on players screen like:

```
Output: You look around and find nothing

```

Other examples of commands i am thinking on top of my head will look like:

```
fight <name>
craft <empty> - for a list of available options
craft <axe>
hide <where>

```

Just want to keep it simple to finish it this time.

But here comes the question,

Is it fair to keep the output of the command that should be displayed to the user within the command class itself (just as i do) ?

For now it's simple, but later i will add some text formatting (colors and stuff).

With my OOO approach 'everywhere' sometimes i feel i am overcomplicating things and trying to search for better solutions to problems that do not exist.

# Answer
> Is it fair to keep the output of the command that should be displayed to the user within the command class itself (just as i do) ?

Maybe. Yes in some cases, no in others. You've shared a lot about your architecture but nothing about the *purpose* so it's hard to answer with specificity. Code exists to accomplish a goal, not just to be good code, so the goal should be foremost in all your design decisions and is a critical component of asking good questions. :)

If you're concerned about hypothetical "code purity" or about "large scale maintenance" then, in one way, y is merging in two responsibilities to a single piece of code: a Command hypothetically should only be concerned with parsing input and dispatching an Action. Some other module should be responsible for consuming Actions, mutating game state, and dispatching Events. And finally, an output module should be responsible for consuming Events and producing the final output text. Note that I didn't call out specific classes or interfaces, just general concepts.

Now, here's the counter point to the above: that's all a crapload of heavily-abstracted OO code that is borderline "architecture astronauting." **If** you have a lot of complex interactions between different unrelated code modules, **if** your code is particularly large, and **if** you are working with a large team, then that kind of design can help. If you have a simple single-player text adventure game you're working on by yourself, that all would very probably be a mass of over-designed obfuscation of what should be fairly a simple input-update-output loop. One could argue in that case that what you have already even falls into that case, but it's hard to say without knowing all the details.

In terms of your question, what all that means is: use the simplest solution that will work. If outputting text in your `Command` object is simple and it works, just do it. Don't over-complicate. Don't design for problems you don't have and very possibly never *will* have.

TL;DR: make it as simple as possible but no simpler. :)

> With my OOO approach 'everywhere' sometimes i feel i am overcomplicating things and trying to search for better solutions to problems that do not exist.

The most important thing to remember about OOP is that objects/classes exist to model isolated functional behavior, *not* to model real-world taxonomies. If something could be a function or a simple piece of data, just do that. OOP's power comes from modular composition of complex behavioral components. OOP's weakness comes from Java-style "everything's an object stuffed full of interfaces and getters/setters" (which a lot of folks these days confuse with OOP itself and think OOP as a whole is bad; that's just as wrong).

As a complete aside: that systems-Hungarian naming scheme in your sample code is killing me. There's literally zero good reason to prefix class names with `C` or to prefix variable types with type information. Unless you're working for 1990's Microsoft, nobody wants to work with code written like that. :)
> 2 votes

---
Tags: c++, game-design
---


title: CreateGraphicsPipelineState

text:
# Question
Title: CreateGraphicsPipelineState
**Hi!**

Would someone answer my question, please? Does the title's method create the same components always or verify possible duplicates?

For exaple: I have one **D3D12\_INPUT\_LAYOUT\_DESC struct** and **two shaders** need the same IL. How many ILs will it create? (In the D3D11 one was enough). Is it possible to avoid duplicates?

*I highly appreciate the answer.*

# Answer
In DX12, you will be creating one input layout per pipeline state. This is preferable, because the driver will have all the knowledge of the shaders and input layout and it can do several optimizations with them, like inlining the vertex fetch inside the vertex shader. It can result in reduced latency when fetching a vertex buffer. Also, it can reduce traffic between VS-PS stage by omitting unused registers. And there are possibly many more opportunities to optimize. However, in your application you can share the input layout description with multiple PSOs.

Also note, that in DX11, indeed you could share input layouts between shaders and reuse one on the API side. But here the driver is deferring shader compilation until you actually use a shader and internally it can be creating multiple shader-input layout permutations behind the scenes. This can result in stuttering when the CPU can't keep up, so it is preferable to precompile these a'la DX12.
> 1 votes

---
Tags: directx12
---


# Question
Title: Is clipping done before or after projection?
Is clipping applied after projection or before?

How can it be applied after projection when a vertex is behind the camera and projected therefore mirrored?

At this time I clip the triangle before projection. For this I create _ a plane which represents the screen and check whether the sides of a triangle intersect with the plane (Basically a ray plane intersection test).

If true then I calculate the intersection point between side and plane and project this new point instead of the vertex behind the plane. This works though but I just wanted to know whether this is a wrong or right method to do it.

# Answer
The projection matrix describes the mapping from 3D points of a scene, to 2D points of the viewport. It transforms from eye space to the clip space, and the coordinates in the clip space are transformed to the normalized device coordinates (NDC) by dividing with the `w` component of the clip coordinates. The NDC are in range (-1,-1,-1) to (1,1,1).
Every geometry which is out of the clippspace is clipped.

So clipping is done on the Homogeneous clipspace coordinates after the "projection" but before the perspective divide.

The condition for a homogeneous coordinate to be in clip space is

```
-w <=  x, y, z  <= w.

```
> 2 votes

# Answer
If I remember correctly, clipping is usually done on homogeneous coordinates, so when you've transformed your vertices to a cube with a center of (0, 0, 0) and extending by 1 in all directions, because it is faster that way, since transforming vertices is very cheap to an average GPU.

This also solves the issue if one vertex is behind the camera, since you can clip on the cube, on it's side pointing towards -Z.

At the end of the day, if your method works, and it's not terrible performance-wise, there is not much reason not to use it.
> -1 votes

---
Tags: 3d, matrix, clipping
---


# Question
Title: Locking on to enemy, player can only move towards enemy, not away?
I'm working on a lock on function and so far I can lock on to the nearest enemy, but my player can't move around the enemy, i can only move towards it. I have my project setup so that the camera is always at a fixed position/rotation, and the player moves independently of the camera.

Here's my move function:

```
public void Move(float h, float v) {
    if (!lockPlayerMovement) {
        Speed = 0;
        MoveDirection.y -= Gravity * Time.deltaTime;
        if (Mathf.Abs(v) > ThumbStickDeadZone || (Mathf.Abs(h) > ThumbStickDeadZone)) {
            var lookRotation = new Vector3();
            lookRotation.Set(h, 0, v);
            lookRotation = lookRotation.normalized;

            var rotation = Quaternion.LookRotation(lookRotation, Vector3.up);
            if (lookRotation.magnitude > ThumbStickDeadZone) {
                Speed = RunSpeed;
                transform.rotation = Quaternion.Slerp(Transform.rotation, rotation, Time.deltaTime * TurnSpeed);
            }
        }
        if (Controller.isGrounded) {
            MoveDirection = Transform.TransformDirection(Vector3.forward).normalized;
            MoveDirection *= Speed * Time.deltaTime;
            //if (Input.GetButton("Fire1"))
            //      MovementProperties.MoveDirection.y = JumpSpeed;
        }
        Controller.Move(MoveDirection);
    }
}

```

Lock On Function:

```
void Update () {
    playerPosition = transform;

    if (enemyLockedOn && enemyTarget != null) {
        transform.LookAt(enemyTarget.transform);
    }
}

void ScanForEnemies() {
    int numOfEnemies = 0;

    float distanceFromPlayer;
    GameObject closestEnemy;

    List<GameObject> enemies = new List<GameObject>();

    Collider[] cols = Physics.OverlapSphere(transform.position, radius);

    foreach (Collider col in cols) {
        if (col && col.tag == "Enemy") {
            ++numOfEnemies;
            enemies.Add(col.gameObject);
            //print(Vector3.Distance(playerPosition.position, col.transform.position));
        }
    }

    if (enemies.Count > 0) {
        distanceFromPlayer = Vector3.Distance(playerPosition.position, enemies[0].transform.position);
        closestEnemy = enemies[0];
        for (int i = 0; i < enemies.Count; i++) {
            if (Vector3.Distance(playerPosition.position, enemies[i].transform.position) < distanceFromPlayer) {
                distanceFromPlayer = Vector3.Distance(playerPosition.position, enemies[i].transform.position);
                closestEnemy = enemies[i];
            }
        }

        /* Set closest enemy as the player target and lock player to that enemy (while in range -- or scan pressed again) */
        enemyTarget = closestEnemy;

        if (enemyTarget != null) enemyLockedOn = true;

        print("Closest Enemy : " + closestEnemy + " | Distance From Player : " + distanceFromPlayer);
        print("Number of nearest enemies : " + numOfEnemies);

    }
}

```

# Answer
> 1 votes
There's quite some code there, and some variables which are not explained, but I think the culprit is:

```
MoveDirection = Transform.TransformDirection(Vector3.forward).normalized;

```

This line makes the `MoveDirection` variable to move towards the +Z axis. Assuming that the code that handles this movement is changing the player's `localPosition`, this means that the player will be moving towards the direction it is pointing, in this case the locked enemy.

To move backwards, you can either use `-Vector3.forward` or `Vector3.back`, but I'm not sure what would be the best way to implement that in your project, as I can only see part of it.

Or the alternative is this line:

```
MoveDirection *= Speed * Time.deltaTime;

```

If you set `speed` to a negative values (as in, going backwards) this line will automatically make the player move backwards.

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


# Question
Title: Problem with draw distance in Unity editor 3D view
The Unity editor scene renderer is not letting me get a close-up view of anything. As the camera moves closer, the geometry closest to the camera just disappears. It's as if the draw distance has become far-sighted.

In the example above, the geometry of the green object (a car mesh) is being cut off as I pull the camera in. The floor is also disappearing, as shown by the grey cut-off at the bottom.

This is making is extremely difficult to line up colliders with render meshes, position smaller objects, and do other detailed tasks. I don't remember my Unity doing this before about a month ago, but I have no idea what changed. Is there a setting somewhere? Has anyone else seen this?

# Answer
Select the object you want to look at and press `F` to focus the camera on it. It automatically adjusts the near and far clipping planes.
> 1 votes

# Answer
Check the scaling of your objects. Chances are the objects are way too small or way too big. Adjust the scaling accordingly in the Mesh Import settings, and try to keep the model scale 1, 1, 1 in the inspector.

I don’t know of any way to adjust the clipping distance in the inspector scene view.
> 0 votes

---
Tags: unity, rendering, settings
---


title: Reverse the movement of object?

text:
# Question
Title: Reverse the movement of object?
Sorry if my title was not clear. My script needs to fix the method of movement object. In my script, the Z axis angel of main object moves with the target object on Y axis. If target goes under zero value, main object goes back smoothly. But, if target goes up from "part 2 to part 1"...it just be there.I don't know how to invert or reverse the movement. Here is my script

```
public Transform target;
public float dis, zz;

// Update is called once per frame
void Update()
{
    dis = transform.position.y - target.transform.position.y;
    transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, zz);
        // part 1
    if (dis < 0.0f && dis > -0.3f)
    {
        zz -= Time.deltaTime * 0.2f;
        if (zz <= -0.3f)
        {
            zz = -0.3f;
        }
    }
        // part 2
    if (dis < 0.31f && dis > -0.6f)
    {
        zz -= Time.deltaTime * 0.2f;
        if (zz <= -0.6f)
        {
            zz = -0.6f;
        }
    }
        // part 3
    if (dis < 0.61f && dis > -0.9f)
    {
        zz -= Time.deltaTime * 0.2f;
        if (zz <= -0.9f)
        {
            zz = -0.9f;
        }
    }

}

```

# Answer
> 1 votes
Maybe you meant to write `else if` instead of just `else` in part 2 and part 3. It’s hard to follow what it’s doing because it’s entering all 3 if statements in some cases, but it feels to me like you need those cases to be exclusive of each other.

If this is wrong please describe the exact behavior you’re trying to achieve.

---
Tags: unity
---


title: Opengl Postprocessing draws only white

text:
# Question
Title: Opengl Postprocessing draws only white
I'm currently trying to implement post processing into my project.

First I configure my framebuffer:

```
glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);

glGenTextures(1, &textureColorbuffer);
glBindTexture(GL_TEXTURE_2D, textureColorbuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, _width, _height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureColorbuffer, 0);

glGenRenderbuffers(1, &rbo);
glBindRenderbuffer(GL_RENDERBUFFER, rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, _width, _height); // use a single renderbuffer object for both a depth AND stencil buffer.
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); // now actually attach it
                                                                                // now that we actually created the framebuffer and added all attachments we want to check if it is actually complete now
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << endl;

float quadVertices[] = { // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
                         // positions   // texCoords
    -1.0f,  1.0f,  0.0f, 1.0f,
    -1.0f, -1.0f,  0.0f, 0.0f,
    1.0f, -1.0f,  1.0f, 0.0f,

    -1.0f,  1.0f,  0.0f, 1.0f,
    1.0f, -1.0f,  1.0f, 0.0f,
    1.0f,  1.0f,  1.0f, 1.0f
};

glGenVertexArrays(1, &quadVAO);
glGenBuffers(1, &quadVBO);
glBindVertexArray(quadVAO);
glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
glBindFramebuffer(GL_FRAMEBUFFER, 0);

```

Then I initialize the shader:

Vertex Shader:

```
    #version 430 core
    layout (location = 0) in vec2 aPos;
    layout (location = 1) in vec2 aTexCoords;
    out vec2 TexCoords;
    void main()
    {
        gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);
        TexCoords = aTexCoords;
    }

```

Fragment Shader:

```
    #version 430 core
    out vec4 FragColor;
    in vec2 TexCoords;
    uniform sampler2D screenTexture;
    void main()
    {
        FragColor = vec4(vec3(1.0 - texture(screenTexture, TexCoords)),1.0);
    }

```

I then set the uniform for the texture:

```
    shader.get()->use();
    shader.get()->setUniform("screenTexture", 0);

```

Then before drawing my Scene I set to draw to the framebuffer:

```
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
    glEnable(GL_DEPTH_TEST);

```

Then I draw my scene. After that I try to draw the framebuffer (after some post processing, just inverting the color to test)

```
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glDisable(GL_DEPTH_TEST);
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    shader.get()->use();
    glBindVertexArray(quadVAO);
    glBindTexture(GL_TEXTURE_2D, textureColorbuffer);
    glDrawArrays(GL_TRIANGLES, 0, 6);

```

Unfortunately the whole screen is drawn full white. When I turn on wire-frame mode, i can see that 2 triangles were drawn, which is correct.. but I don't know why it doesn't work.

# Answer
You missed to clear the color buffer and especially the depth buffer of the framebuffer (`framebuffer`) after the framebuffer is bound and before the scene is rendered. Since the depth test is enabled when the scene is rendered, the depth buffer has to be cleared right before:

```
// bind the frambuffer
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);

// clear the color attachmnet (texture) and depth buffer
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // <------ you missed this

// enable the depth test
glEnable(GL_DEPTH_TEST);

// render the scene
// ....

// bind the defualt frambuffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);

// celar the default frambuffer
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear( GL_COLOR_BUFFER_BIT );

// disable the depth test
glDisable(GL_DEPTH_TEST);

// install current program and set the texture sampler uniform
shader.get()->use();
shader.get()->setUniform("screenTexture", 0);

// bind the texture
glBindTexture(GL_TEXTURE_2D, textureColorbuffer);

// draw a quad (2 triangles ) on to the entire viewport
glBindVertexArray(quadVAO);
glDrawArrays(GL_TRIANGLES, 0, 6);

```
> 0 votes

---
Tags: opengl, c++, shaders, post-processing
---


title: Libgdx texture bleeding in tile map

text:
# Question
Title: Libgdx texture bleeding in tile map
So I am making a game in Libgdx using an isometric tiled map but when I set the texture filtering of the tiles to linear, black lines show up between all the tiles. This is caused because each tile blends with the tiles next to it.

I know many people have asked this before and the common answer seems to be add padding. I have padding but that doesn't help because then the tiles start blending with the clear pixels instead. That just turns the lines a different color.

Another option people say is to copy the pixels on the edge of each tile for padding, but unfortunately that only works for non-isometric maps. However when I use the tilemap preprocessor it works fine even with filtering, but the tilemap preprocessor causes many other issues so I don't want to do that.

How can I fix this? Somehow the tiledmap preprocessor does it fine but I'm not sure what that actually does other than adding padding. Any help is greatly appreciated!

# Answer
If you're getting transparent edge pixels, it sounds like you haven't enabled duplicatePadding. Just to be sure, these are my recommended TexturePackerSettings:

```
duplicatePadding = true
paddingX = 2
paddingY = 2

```
> 2 votes

# Answer
You should check that your spritesheet is power of two.

For example:

> 3 tiles of 64x64 = one spritesheet of 192x64 ---\> **wrong**
>
> 4 tiles of 64x64 = one spritesheet of 256x64 ---\> **right**

Even if each sprite is power of two itself.

I hope this helps you.
> 0 votes

---
Tags: libgdx, tilemap, isometric
---


title: How can I create a caption system?

text:
# Question
Title: How can I create a caption system?
I will not be voice acting my game, so I'd like to add captions/subtitles to it.

How could I achieve this?

I'm using Unity 2018.

# Answer
> 2 votes
Use an overlay Canvas with a text box. Put a MonoBehaviour subclass (eg Subtitles) on the textbox that you can use to display your text. A minimal example would be something like:

```
public class Subtitles : MonoBehaviour {
  public Text textbox;
  private static Subtitles Instance;
  void Start() { Instance = this; }
  public static void ShowText(string text) {
      Instance.textbox.text = text;
  }
}

```

Then when you want to show a message, just call `Subtitles.ShowText("my message");`

---
Tags: unity
---


title: Random NPCs - possible yet?

text:
# Question
Title: Random NPCs - possible yet?
Traditionally, non-unique game mobs and NPCs are of the cookie-cutter type. Seen one, seen 'em all, and you instantly know their behavior, stats and strong/weak points. Games however become ever more immersive, and this seems like one of the last hurdles to take in that regard.

A quick search for this shows mods like SetBody for Oblivion which allegedly gives all NPCs random bodies (lore friendly), and I've found some DnD discussions about random character creation tools for DMs, but this is only putting a random look on a predefined character. With full randomization I mean not only random looks (to an extend of course - no orc looks on elves of course), but also random abilities, random AI level, etc. I'd even go as far as e.g. random attack style (weapon choice, etc.) and AI.

On the one hand this would make games far more interesting, but on the other hand it might make them a lot harder to play. Imagine a horde shooter which traditionally would e.g. have 10 basic enemy types, each with their own unique looks, stats and attack style. In the new set-up, you wouldn't be able to know how they would react to you upfront, nor would you be able to know how to best handle them. Basically every enemy you encounter would be fresh, and you cannot rely on things anymore like "Oh, that zombie is red - it's an exploding one" or "it's obviously one of the 10 available elf body types - it'll surely attack with this-and-that spell when I get closer than this-or-that distance". It seems like it could only ever work in more strategic games where you have time to study and handle each NPC and mob individually.

Regardless of whether current gaming platforms are up to it hardware wise, would players actually like and want it due to the above? Or would it only appeal to a niche of the player base, and is it thus not more common today? And I think current hardware is up to the task; if not, then it's easy to spend say 30 seconds upfront to pre-render the mobs upfront before a level starts, and just create a strong AI with diverse parameters that can be randomly tweaked per mob to weaken its abilities in a random way (a bit weaker path finding skills, smaller alert distance, etc.).

If anyone has any example of such games: please share; I'd be nice to try it on for size :)

# Answer
(Full disclosure: I am not a game developer, and (so far) have no practical experience in game development; I'm just trying to answer your question from a theoretical point of view).

If you're talking about enemies, I don't see why this wouldn't be feasible. A few ideas off the top of my head:

* You could write a few variants of an enemy's basic AI routine that could correspond to different temperaments (for example: risk-taking and highly aggressive vs. cautious and defensive, or confident enemies who attempt to take you on alone vs. hesitent ones who try to call in reinforcements), or degrees of intelligence (such as dumb enemies that always blindly go for pure damage vs. smarter ones that take into account what weapon(s) and armor you have equipped) then assign them randomly to different enemies of the same type.
* This isn't really randomization, but you could write increasingly effective AIs for enemies as a function of their level. E.g. level 1-19 orcs will only rush you head-on, but level 20+ ones can sneak up behind you while you're busy fighting the rest of them. This would feel unexpected for most players, and force them to adapt their tactics.
* If your AI script uses fixed values (e.g. mean distance at which they detect your presence, or accuracy of their shots), you could add a random deviation from those values. This variation could be based on some measure of progression through the game (e.g. character level, number of dungeons cleared, or point of progression in the main story). You could also extend this to basic attributes like level, hit points, attack power, equipment, etc.
* Instead of making every individual encountered enemy of a given type completely identical (or conversely making every enemy entirely random), you could use a probability based system to assign attributes. For example "that zombie is red, there's a pretty high likelihood it'll explode if I let it get too near" or "this body type looks elven, there's a good chance it'll use xyz spells when I get reasonably close"; again, "too near" and "reasonably close" could also be probabilistic, making it harder for the player to predict exactly how a specific enemy is going to behave. This allows the player develop a *general* idea of how certain enemies behave, without making it deterministic.
* Using a probability distribution to determine factors like an enemy's equipped weapon, armor, spells, or even many of its other stats would mean that the majority of enemies of a given type would fall within a typical range, but still allow for a few outliers that could catch unprepared players off-guard. You'd probably still want some sort of hard upper and lower limits to prevent excessively over- or under-powered enemies, but I feel this has to potential to add quite a bit of variety and uncertainty to encounters, while discouraging complacency.

IMHO the key here is to encourage the player to get an understanding of how a given enemy type will behave, and thus how to handle them in general, while still expecting them to demonstrate a reasonable degree of improvization when dealing with individual enemies of that type. Seems to me that this would encourage players to both learn common patterns and think on their feet during fights. Things should be neither too predictable nor too unpredictable.
> 2 votes

# Answer
Rimworld gives you characters with all kinds of random traits who change as they interact with the environment. Were this done in a Bethesda game (and tamed down a bit) it'd be pretty stellar.

The main issue (which may be solved in time) is Speech. In an FPS game you prefer to hear the characters talk, even if there aren't a lot of actors, etc. The tech for speech generation is getting there, and when it is, I expect that it'd be much easier to get a few dozen actors to open things up.

With that, combined with "evolving" NPCs (such as those in Rimworld, which I'll mention is derivative of Dwarf Fortress) one could imagine that RPGs at some future date will be able to generate an interesting world (and with much less effort than before.)
> 2 votes

---
Tags: random, npc
---


title: How can I make the terrain infinte?

text:
# Question
Title: How can I make the terrain infinte?
I am making a game in Unity 5 in C# and I need to make the terrain infinite. I have tried to make it infinite but it just keeps spawning the terrain too much times and then the game crashes. Does someone know how I can make the terrain infinite? Here is my code.

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

public class TerrainScript : MonoBehaviour
{
    public Transform PlayerTransform;
    private float SpawnZ = 4139f;
    public GameObject[] prefabs;
    private float RoadLength = 2.2f;
    private int amountRoads = 6;
    private List<GameObject> roadList;

    public void Start()
    {
        roadList = new List<GameObject>();
    }
    public void Update()
    {
        if(PlayerTransform.position.z > (SpawnZ - amountRoads * RoadLength))
        {
            spawnTile(0);
        }
    }

    public void spawnTile(int index)
    {
        GameObject go;
        go = Instantiate(prefabs[index]) as GameObject;
        go.transform.SetParent(transform);
        go.transform.position = Vector3.forward * SpawnZ;
        SpawnZ += RoadLength;
    }
}

```

# Answer
> 1 votes
If the player isn’t looking at a tile then it does not need to be there, so we can use that memory for something else. Instead of creating a new tile every single time, you should create a fixed number of tiles ahead of time and move ones that are not visible into view as if they were new ones, essentially recycling the tile.

This technique is called “Object Pooling”. I’m not super familiar with Unity but a search for “Unity Object Pooling” brings up some reasonable looking resources about the subject.

---
Tags: unity, c#, models, terrain
---


# Question
Title: Trying to get events to work for drag and drop
So I’m playing around with drag and drop with Nifty and I have the drag working. I don’t have a drop set up yet as I’m just trying to get the dragging working at the moment.

For the purposes of my game the default drag and drop behavior of moving the draggable to another spot wont work. I’m working on a tower defense kind of game and when the player goes to drag a turret from the inventory into the game, I still need a copy of it to stay in the starting point. So I am trying to use the DraggableDragStartedEvent to determine when the drag starts and make a copy of the dropable to place in the UI so the player can still add more of that turret if they want to. Or is there another way of changing the default behavior so when the player drags they see the item under the mouse/finger but still leaves a copy at the starting point so it can be repeated from the same location?

Here is what I have and it doesn’t seem to be working:

The Nifty book for 1.3.2 (I just now realize JME uses 1.4.2 so this may no longer work and the docs on the github are not as in depth as this book) says to add a methid to your screen controller with the annotation @NiftyEventSubscriber(id=“elementId”) and it must have a String for the first parameter to pass in the id and the second must have an event of the type you want to listen to and its just supposed to work. But its not. I see “bind” in the log and I see “start screen” in the log but when I drag the draggable nothing gets logged. The dragging is working so I know it should be calling this event.

```
controller(new ScreenController() {
    @Override
    public void bind(Nifty nifty, Screen screen) {
        System.out.println("bind");
    }

    @Override
    public void onStartScreen() {
        System.out.println("start screen");
    }

    @Override
    public void onEndScreen() {
        System.out.println("end screen");
    }

    @NiftyEventSubscriber(id="layout")
    public void onClick(String id, DraggableDragStartedEvent event) {
        System.out.println("drag started");
    }
});

```

And my draggable:

```
control(new DraggableBuilder("chest") {{
    id("layout");
    childLayoutCenter();
    width("101px");
    height("171px");
    panel(new PanelBuilder() {{
        childLayoutCenter();
        text(new TextBuilder(){{
            text("My Cool Game");
            font("Interface/Fonts/Default.fnt");
            alignCenter();
            valignCenter();
            color(Color.WHITE);
            height("5%");
            width("15%");
        }});
    }});
}});

```

# Answer
I played around with one of Niftys standard examples for Drag'n'Drop (DragDropDemoMain) and noticed that you don't get the event when the Draggable is not associated with a Droppable. If I move a Draggable to a Droppable and *then* start to drag it from this Droppable I'll get the DraggableDragStartedEvent as expected.

I investigated this a little further and found this code in DraggableControl:

```
  private void notifyObserversDragStarted() {
    if (nifty == null || droppable == null) { // <-- THIS MIGHT BE THE REASON FOR YOUR ISSUE
      return;
    }
    String id = getId();
    if (id != null) {
      nifty.publishEvent(id, new DraggableDragStartedEvent(droppable, this));
    }
  }

```

This confirms the behaviour. If a Draggable is not on a Droppable already and you drag it then you don't get the event. I guess this is because the parameter Droppable in the DraggableDragStartedEvent is supposed to be not null.

setDroppable() at the DraggableControl class could be used to set the Draggable from code. Since most of the drag'n'drop was contributed by someone else I'm not sure if there are other things to consider tho :)

But maybe this is pointing you into the right direction to solve it.
> 1 votes

---
Tags: java, jmonkeyengine, nifty-gui
---


# Question
Title: How to reproduce this triangle filling scanline effect using a shader?
I'm writing a renderer for an old DOS game in which 3D polygons were rendered in software. I'd like to simulate, using a shader, the following material/effect, used for filling a triangle:

The fist pixel of each scanline starts with a given color (here purple) and progressively fades to another color (amber). It's like each scanline is a gradient

In a shader, is it possible to have a value between 0 and 1 which tell the position of the pixel regarding the scanline bounds? (start and end, which are `S0` and `S1` in the example)

# Answer
> 4 votes
First you need to generate a set of Barycentric coordinates for your triangle.

You can set the vertex color of each triangles to the barycentric coordinates: `(1,0,0)`, `(0,1,0)` and `(0,0,1)` (for each triangle each vertex must be set to a different barycentric coordinate, the order doesn't matter).

You can also store them in the UVs and generate z using:

```
o.barycentric.xy = i.uv.xy;
o.barycentric.z = 1 - i.uv.x - i.uv.y;

```

in the vertex shader, or store them inside the normals if you're not going to use any shading.

Then it's a question of calculating the shortest intersection on the x axis slope using the `ddx` Cg function, in both directions. Then use the total distance (add both directions) to calculate the interpolation value and find where we are on the X axis according to the closest triangle edges on either side.

```
float ci = negative_distance / max(1.0, negative_distance + positive_distance);

col.xyz = lerp(_Color1, _Color2, ci);

```

Result:

## The Unity shader:

I'm generating fake barycentric coordinates using the UVs from Unity's default cube shape for testing purpose.

Replace the part that fills in `o.barycentric` with the actual barycentric coordinates according to the way you choose to store those values into your mesh (uv, 1 color, or the normal). The Unity default cube happens to have UVs that can be converted.

This will depend on what other values you need to pass to your shader.

```
Shader "Unlit/GradientTest2"
{
    Properties
    {
        _Color1 ("Color1", Color) = (1.0, 0.5, 0, 1)
        _Color2 ("Color2", Color) = (0.5, 0, 1, 1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

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

            struct v2f
            {
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
                float3 barycentric : TEXCOORD1;
            };

            fixed4 _Color1;
            fixed4 _Color2;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);

                // generate fake barycentric coordinates from Unity's default Cube mesh UV
                // In a real application you should set and use the vertex color as the barycentric coordinates instead
                o.barycentric = float3(1-v.uv.x, v.uv.y, abs(1.0 - (1-v.uv.x + v.uv.y)));
                float3 tmp = (o.barycentric - float3(1, 1, 1));
                if( dot(tmp, tmp) == 0){
                    o.barycentric = float3(0, 0, 1);
                }

                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col;
                col.a = 1.0;

                float3 b = i.barycentric;
                float3 x = ddx(b);

                float negative_distance = 1000000.0f;
                if(x.x < 0){
                    negative_distance = min(negative_distance, b.x / -x.x); // pixel distance;
                }
                if(x.y < 0){
                    negative_distance = min(negative_distance, b.y / -x.y); // pixel distance;
                }
                if(x.z < 0){
                    negative_distance = min(negative_distance, b.z / -x.z); // pixel distance;
                }

                float positive_distance = 1000000.0f;
                if(x.x > 0){
                    positive_distance = min(positive_distance, b.x / x.x); // pixel distance;
                }
                if(x.y > 0){
                    positive_distance = min(positive_distance, b.y / x.y); // pixel distance;
                }
                if(x.z > 0){
                    positive_distance = min(positive_distance, b.z / x.z); // pixel distance;
                }

                float ci = negative_distance / max(1.0, negative_distance + positive_distance);

                col.xyz = lerp(_Color1, _Color2, ci);

                // apply fog
                UNITY_APPLY_FOG(i.fogCoord, col);
                return col;
            }
            ENDCG
        }
    }
}

```

---

## Previous solution

EDIT: kept as this matched the example image in the Question and may be useful to someone.

For the gradient effect we only need two of the coordinates `(barycentric.y, barycentric.z)` so we can encode those into one of the UV coordinate sets or the vertex color as `(uv.x, uv.y)` instead.

And one of the coordinates `(1 - barycentric.z)` need to be **reversed** in our calculation so we'll do that right inside the UVs and reverse `uv.y` (the top and right corners in the image).

Set the UV for your triangle to be (0,0) for the top "pinch" corner, (0,0) for the "left" side and (1, 1) for the "right" side then use this formula to calculate the color:

```
fixed4 col;
col.a = 1.0;
col.xyz = lerp(_Color1, _Color2, i.uv.x / max(0.001, i.uv.y));

```

The `max` operation is to avoid a division by zero.

(UVs are marked as `[x,y]`)

Full unity shader:

```
Shader "Unlit/GradientTest"
{
    Properties
    {
        _Color1 ("Color1", Color) = (1.0, 0.5, 0, 1)
        _Color2 ("Color2", Color) = (0.5, 0, 1, 1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
            };

            fixed4 _Color1;
            fixed4 _Color2;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col;
                col.a = 1.0;
                col.xyz = lerp(_Color1, _Color2, i.uv.x / max(0.001, i.uv.y));

                // apply fog
                UNITY_APPLY_FOG(i.fogCoord, col);
                return col;
            }
            ENDCG
        }
    }
}

```

---

Bonus animated Shadertoy (it's GLSL, **not Cg**) used to generate this image.

The code is different from Unity shaders due to the way Shadertoy works, I had to draw a triangle inside the quad. The last few lines are the important ones:

```
    float divider = max(0.001, (1.0 - barycentric.b));
    vec3 col = mix(left_color, right_color, barycentric.g / divider);

```

Just paste this right in Shadertoy to see the shader in action:

```
vec3 GetBarycentric(vec3 p, vec3 a, vec3 b, vec3 c)
{
    vec3 v0 = b - a;
    vec3 v1 = c - a;
    vec3 v2 = p - a;

    vec3 v0b = c - b;
    vec3 v2b = p - b;

    float d00 = dot(v0, v0);
    float d01 = dot(v0, v1);
    float d11 = dot(v1, v1);
    float d20 = dot(v2, v0);
    float d21 = dot(v2, v1);
    float i = 1.0 / (d00 * d11 - d01 * d01);

    float d00b = dot(v0b, v0b);
    float d01b = dot(v0b, -v0);
    float d20b = dot(v2b, v0b);
    float d21b = dot(v2b, -v0);
    float ib = 1.0 / (d00b * d11 - d01b * d01b);

    vec3 r;
    r.x = (d11 * d20 - d01 * d21) * i;
    r.y = (d00 * d21 - d01 * d20) * i;
    r.z = (d00b * d21b - d01b * d20b) * ib;
    //r.z = 1.0f - r.x - r.z; // we need r.z to go negative for a quick and dirty triangle

    return r;
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    // Normalized pixel coordinates (from -1 to 1)
    vec2 uv = (fragCoord/iResolution.xy) * 2.0 - 1.0;

    //triangle verts
    vec3 a=vec3(0.0,0.5,0.0);
    vec3 b=vec3(-0.5,-0.5,0.0);
    vec3 c=vec3(0.5,-0.5,0.0);

    {
        mat3 m;
        float si = sin(iTime);
        float co = cos(iTime);
        m[0] = vec3(co, si, 0);
        m[1] = vec3(-si, co, 0);
        m[2] = vec3(0, 0, 1);

        a *= m;
        b *= m;
        c *= m;
    }

    // Time varying pixel color
    vec3 barycentric = GetBarycentric(vec3(uv, 0), a, b, c);

    float alpha = 1.0;

    if((barycentric.x < 0.0) || (barycentric.y < 0.0) || (barycentric.z < 0.0)){
        alpha = 0.0;
    }

    vec3 left_color = vec3(0.5, 0.0, 1.0);
    vec3 right_color = vec3(1.0, 0.5, 0.0);

    float divider = max(0.001, (1.0 - barycentric.b));

    vec3 col = mix(left_color, right_color, barycentric.g / divider);

    // Output to screen
    fragColor = vec4(col * alpha, alpha);
}

```

# Answer
> 1 votes
You can take a look at this project which implements a software render.

This revision shows how to draw triangles (but filled with the same color). I modified `triangle` method so that it accepts 2 colors and draws gradient.

```
void triangle(Vec2i t0, Vec2i t1, Vec2i t2, TGAImage &image, TGAColor c1, TGAColor c2) {
    if (t0.y==t1.y && t0.y==t2.y) return; // i dont care about degenerate triangles
    if (t0.y>t1.y) std::swap(t0, t1);
    if (t0.y>t2.y) std::swap(t0, t2);
    if (t1.y>t2.y) std::swap(t1, t2);
    int total_height = t2.y-t0.y;
    for (int i=0; i<total_height; i++) {
        bool second_half = i>t1.y-t0.y || t1.y==t0.y;
        int segment_height = second_half ? t2.y-t1.y : t1.y-t0.y;
        float alpha = (float)i/total_height;
        float beta  = (float)(i-(second_half ? t1.y-t0.y : 0))/segment_height; // be careful: with above conditions no division by zero here
        Vec2i A =               t0 + (t2-t0)*alpha;
        Vec2i B = second_half ? t1 + (t2-t1)*beta : t0 + (t1-t0)*beta;
        if (A.x>B.x) std::swap(A, B);
        float width = B.x - A.x;
        for (int j=A.x; j<=B.x; j++) {
            float k1 = (j - A.x) / width;
            float k2 = 1 - k1;
            TGAColor color = TGAColor(c1.r * k1 + c2.r * k2, c1.g * k1 + c2.g * k2, c1.b * k1 + c2.b * k2, 255 );
            image.set(j, t0.y + i, color); // attention, due to int casts t0.y+i != A.y
        }
    }
}

```

Value k1 is the position of current pixel regarding the scanline bounds.

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


title: Loading a web page in unity

text:
# Question
Title: Loading a web page in unity
Hello I need to open a page in unity and save some of it's contents but I have absolutely no idea how I should do it.

Thanks for help.

# Answer
You could use this plugin. A few on the asset store are a little pricey when it comes to embedded browsers (as I'm assuming that's what you want to display the web page) but this one is free and open-source. https://bitbucket.org/vitaly\_chashin/simpleunitybrowser

It also appears to have settings to save web page data. If you don't mind me asking, what data do you need to save? If it's user data, there are more elegant ways of solving this particular problem, i.e. https://gamedevelopment.tutsplus.com/tutorials/how-to-save-and-load-your-players-progress-in-unity--cms-20934

If not, then this seems like your best bet.
> 2 votes

---
Tags: unity, web
---


# Question
Title: Overcoming fill rate and generation bottlenecks in voxel engine
I decided to make a voxel engine using octrees. I am instancing entire cubes and sending the sizes and positions to the vertex shader.

I currently have 2 major problems:

**Problem 1** \- Because the cubes are instanced I can't remove hidden faces which means that some pixels are being overwritten lots of times. I have backface culling enabled but it doesn't fully help - also I noticed depending on the direction I look the lag is more / less which means sorting it might help, but then I don't really want to be sorting my cubes every frame.

**Problem 2** \- A 64\*64\*64 octree takes around 1/2 a second to fill and compress which is too slow, probably needs to be 1/10th of that speed. My method for that is as follows:

I have a generation function `bool isCube(glm::vec3)`. Then, I create a full octree and fill up the base nodes with 0 or 1 depending what `isCube` returns for that given position. Finally, I compress it by checking if all leaves are the same, remove them, and store that value in the node above.

For reference the current `isCube` function looks like this:

```
bool isCube(glm::vec3 pos)
{
    if (glm::length(pos) < 300)
        return true;
    return false;
}

```

---

What sort of measures can I take to reduce fillrate?

What is the best way to go about generating landscape with octrees?

# Answer
> 4 votes
The overhead of instantiation on the GPU is huge relative to those 12 triangles in each cubes. GPUs don't like small (12-triangles) batches. The faster the GPU the worse this overhead gets compared to the raw amount of triangles it can render.

Instead bake everything into larger "chunks" of geometry VBOs. You can even bake-in ambient occlusion/shadows (Eg: under the trees and mountain shade).

This way you can eliminate hidden faces.

For the rendering itself there is no need for an octree-structure, a simple list of active chunks VBOs that can be quickly traversed to render is sufficient.

An Octree comes in handy when processing visibility (or collisions): which chunks to add/remove from the active list but not for the rendering loop itself.

Separating the two has multiple advantages. One is that you may need to queue loading and geometry generation of chunks according to visibility to be run in separate thread(s).

This means they're visible but not ready to render.

You don't want to burden the render loop with this "Is my chunk ready?" check as you need to do the check to start loading (and unloading) anyway.

For VR (two eyes, similarly located) you can create a frustum box that encompasses both eyes and only does 1 visibility check instead of two. There will be some unnecessary GPU render commands for each eyes but the percentage is so small that avoiding the check CPU-side for an entire eye is more beneficial.

---
Tags: opengl, procedural-generation, voxels
---


title: Send id<MTLTexture> from ios to unity

text:
# Question
Title: Send id<MTLTexture> from ios to unity
I'm writing a plugin for unity, I need to send a texture from ios to unity. There is a `UnitySendMessage` function which takes `char*` as parameter, but I didn't find a way to convert `id<MTLTexture>` to `char*`.

How can I send `id<MTLTexture>` from ios and receive it in unity?

My current code :

```
//ios side ...
_texture = CVMetalTextureGetTexture(texture);
UnitySendMessage(CALLBACK_OBJECT, CALLBACK_TEXTURE_READY,_texture);//error
//...

//unity side
private void OnTextureReady(string texture_str)
{
   IntPtr texture = new IntPtr(Int32.Parse(texture_str));
   int width = 256;
   int height = 256;
   rawImage.texture = Texture2D.CreateExternalTexture(width, height,
   TextureFormat.ARGB32, false, false, texture);
}

```

# Answer
> 1 votes
Don't try to cast string to IntPtr. char\* is just pointer and any pointer(char\*, void\*,...) coming from native side unity treat it as IntPtr.

```
id<MTLTexture> tex = yourTexture;
char* ptr = &tex;

```

And now you have a ptr from native side

---
Tags: unity, ios, plugin
---


# Question
Title: How to orient a layer to connect 2 points AND facing the camera
here is my question, which I hope will be in general interest:

If you have got 2 Points in 3D space and want a plane to connect those, you can quite easily use a function similar to "lookAt" to orient the layer pointing with its x-axis from one point to the other. But how can you at the same time make sure the layer is rotated in the way so that the layer is facing the camera (the maximum amount possible, of course it cant be orthogonal to the camera)? The x Axis from the resulting plane should face from the one point to the other.

# Answer
> 2 votes
Take the vector pointing from the first point to the second and also the vector from the first point to the camera position, take their cross product. This creates a vector perpendicular to the other ones. Take this vector and the one pointing from the first point to the second and take their cross products too and normalize it. This gives you the normal of the plane that contains both point and is looking at the camera as much as possible.

Let's say the 2 points are A and B and the camera is C:

```
n1 = cross(B - A, C - A)
normal = normalize(cross(B - A, n1))

```

---
Tags: 3d, mathematics, rotation, three.js, orientation
---


title: JVM for PS4 Console

text:
# Question
Title: JVM for PS4 Console
can i take an open source JVM for java and modify it to make java games to be executed by consoles like PS4, Xbox one or Switch?

edit: the license of JVM have to let me do as i want with the JVM, i have seen there is an openJDK JVM that we can download, but i ignore if i can take this to start working.

# Answer
> 1 votes
In the interest of giving this question a concrete answer:

There's no fundamental/technical limitation that would prevent a Java virtual machine or any other program from being developed/ported to run on a modern game console. They're general-purpose computers, so in principle anything that you can do on your desktop you could convince a console to do, with enough porting effort to make up for the differences in the environment and available dependencies/etc.

The bigger obstacle is whether you would be allowed to publish this general-purpose virtual machine software, or games depending on it, on those platforms. Software running on consumer versions of these consoles typically needs to be approved by the first party (Microsoft, Sony, Nintendo) and digitally signed so that it has permission to run. That means the software must be developed according to their specifications.

It's not uncommon for first parties to restrict the use of general-purpose virtual machines on their platforms. VMs let you run new code that wasn't part of the executable that was reviewed & approved when the software was published - maybe even code from an untrusted third party - so we can't make very good guarantees about its safety or reliability. A bug or security vulnerability in the VM could open their users up to harm from poorly-vetted VM scripts, or deliberate attacks from hackers using the VM to compromise their system or extract personal data.

A virtual machine could also let users bypass the signing checks that are supposed to ensure only approved, non-pirated software (of which the platform-holder gets a cut) runs on the device, directly threatening their business model.

So, while this may be technically feasible, there are good reasons why the makers of these consoles might refuse permission to publish software that contains this kind of general-purpose virtual machine.

The details of what each platform-holder will or won't accept are specific to their developer agreements, which might change at any time and are not necessarily public information, so this Q&A format isn't the best way to learn about those specifics. Instead, I'd recommend reaching out to the first parties themselves when signing up to develop on their platforms, and they'll be able to give you the most accurate and up-to-date policies that apply.

---
Tags: java, playstation4
---


# Question
Title: Why are Mac versions of games larger in filesize than Windows versions?
I have browsed many games mainly on itch.io and many developers offer a Mac version of their game along with the Windows version. The Mac version of all those games is significantly larger in file size than the Windows version. Why is that?

# Answer
I'd suspect that many of these games are using Unity, as it's a popular choice for indie developers on itch.io (my own itch games included)

Scripting in Unity uses Microsoft's .NET framework, a managed environment that makes it easier to write safe code that can run on many different devices. This includes runtime software to manage memory and interface with platform-specific features, a just-in-time compiler to translate IL bytecode into a form the machine it's running on will understand, and numerous libraries to support common tasks.

On Windows, all this is available as part of the OS, so it doesn't need to be included in the game executable. On other platforms, it's replaced by Mono, a cross-platform version of the .NET framework. But Mono isn't built into the OS on Mac or Linux, so we can't count on it being there, and need to package it up within the game download itself to make sure it will work out of the box.

Similar patterns may repeat with all sorts of underlying tech. Windows has historically been a popular environment for game development, so when bringing games to new platforms it's often easier/more reliable to bring along a piece of Windows-like behaviour to build on as the common bedrock rather than change the games' foundations.
> 2 votes

# Answer
I can't say for sure why this is happening, but in the past I've downloaded games for linux, and inside the project (even though I downloaded the "linux specific" folder, and not a has-it-all folder) I could find windows-specific files like `.bat` or even `.exe`.

So the only reason I can find, is that most developers focus on windows, and only support other platforms barely enough to have a playable project. So they make a "normal" project for windows, including only files they need, and when it comes to support other platforms they just add a few files, probably for emulation or for converting some files from one platform to another.

It is not the proper way to do it, but as long as the result can be played there's not a big issue.
> 0 votes

---
Tags: windows, macos
---


# Question
Title: Unity3d - How to use controller joystick to look around?
I try to use my xbox controller as input device for a game targeted to run on windows. However the documentation fails to explain how to set it up. E.g. how can I use the right stick from my xbox controller to look around, like in any 3D game? Even such a common task is not documented.

I found a very old wiki entry where the xbox controller is briefly described, I was able to find out that the **Y-Axis** of the right analog is called `5th axis (Joysticks)` and the **X-Axis** is called `4th axis (Joysticks)`. I post the images below, in case the link get's dead.

## Linux

**Note:** wired controllers only support axises for the d-pad, while the wireless controller only supports buttons for the d-pad, refer to the table above for the wireless controller configuration.

I figured out that the name of a control is responsible for the action which the button, stick, key, pedal etc. does. But it is not documented how the control has to be named for looking around vertically or horizontaly like you can do in an 3D game to look around with the camera by using the right joystick (e.g. witcher 3)

How can I control the camera by using the right joystick?

# Answer
I was able to figure it out.

You have to name the Y-Axis Control `Mouse Y` and the X-Axis Control `Mouse X`.
> -3 votes

# Answer
for the axis's set the dead to 0.009 each then for the camera use this

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

public class CamerLook : MonoBehaviour {

    public float lookSenitivity = 5;
    public float lookSmoothDamp = 0.1f;
    public float xRotation;
    public float yRotation;
    public float xRotationV;
    public float yRotationV;
    public float currentXRotation;
    public float currentYRotation;
    [HideInInspector]
    public float lStickHorizontal;
    [HideInInspector]
    public float lStickVertical;
    public float lStickV;
    public float lStickH;

    public void Update()
    {
        lStickHorizontal = Input.GetAxis("LeftStickHorizontal");
        lStickVertical = Input.GetAxis("LeftStickVertical");

        lStickH = lStickHorizontal;
        lStickV = lStickVertical;

            xRotation += Input.GetAxis("LeftStickVertical") * lookSenitivity;
            yRotation += Input.GetAxis("LeftStickHorizontal") * lookSenitivity;

            xRotation = Mathf.Clamp(xRotation, -90, 90);

            currentXRotation = Mathf.SmoothDamp(currentXRotation, xRotation, ref xRotationV, lookSmoothDamp);
            currentYRotation = Mathf.SmoothDamp(currentYRotation, yRotation, ref yRotationV, lookSmoothDamp);

            transform.rotation = Quaternion.Euler(xRotation, yRotation, 0f);

            transform.position = transform.position;
    }
}

```
> 0 votes

---
Tags: unity, controllers, joystick, gamepad, xbox-controller
---


# Question
Title: Swapping in game currency for virtual goods. Client vs server. Best practice
I currently use a server back end to verify my managed in app currency purchases and update the user's `coin` value.

But what's the best practice to then deal with "in game purchases" where players swap their `coin` for virtual goods such as power ups etc.

I just realised that if I do it in the app then potentially a hacker could just remove the code so that they can buy some coins once then just perpetually buy whatever virtual goods they want.

Should I let my server back end deal with this instead, which would definitely solve the problem. Is this the best practice?

# Answer
I would prefer you to have the code executed on the server side. Then it would be less likely to be hacked.
> 0 votes

---
Tags: in-app-purchase
---