# Question
Title: Mouse look rotation not rotating object axis in Unity
So, I made a simple First Person Camera script for my game, and the way it's *supposed* to work is the camera is rotated by localEulerAngles to rotate the camera around, and then just the Y-axis rotation is also applied to the character, so that he moves in the direction of the camera.

This isn't how its working now.

I've narrowed down the two most likely problems in the scripts, and this first one is from the camera controller:

`player.transform.localEulerAngles = new Vector3(0, rotationX, 0);
cam.transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);`

Note: the camera works just fine, and rotates perfectly in all directions.

Secondly, the player movement controller, which might not be actually be moving locally? I can't tell.

`transform.Translate (new Vector3(0, 0, Input.GetAxis("Vertical") * walkSpeed));
transform.Translate (new Vector3(Input.GetAxis("Horizontal") * strafeSpeed, 0, 0));`

There you go. Right now, even though the camera moves just fine with the mouse, and, incidentally, the whole script used to work, the player moves forward on the global Z-axis with `W` and backwards with `S`, all the while acting like a shooter on rails.

Thank you!

# Answer
> 1 votes
Currently you simply add transformation based on your input value. The axis are locked. So no matter which rotation your gameobject has, it always will transform into the locked in axis based on your input.

You need to change the forward direction based on the current forward direction of your camera.

In this case, use Camera.main and get the forward postion of it and apply it to your translate.

Heres an example:

```
// Update is called once per frame

void Update () {

     Vector3 MouseWorldPosition = MainCamera.camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
     transform.LookAt(MouseWorldPosition);
     transform.rotation = Quaternion.Euler(new Vector3(0, transform.rotation.eulerAngles.y, 0));
     // Amout to move
     float inputX = Input.GetAxis("Horizontal") * PlayerSpeed *

     Time.deltaTime;
     float inputY = Input.GetAxis("Vertical") * PlayerSpeed * Time.deltaTime;
     // Move the Player
     transform.Translate(Vector3.forward * inputX) ;
     transform.Translate(Vector3.left * inputY) ;
     if (Input.GetKey("space"))
     {
         //Fire projectile
         Instantiate(ProjectilePrefab, transform.position,Quaternion.identity);
     }
 }

```

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


# Question
Title: Game Maker Studio 2: Why is my variable not being properly changed?
Ok, so in my game you have a party of four characters that you control one at a time, each of which can lose health and die independently of each other. All of the player character objects use essentially the exact same code controlling their "deaths", (just with their own object variables and flags that get set and triggered etc.), but for whatever reason identical code does not produce identical results for all of the characters.

In particular, one of the character classes, the Alchemist, absolutely refuses to either set their "dead" flag to True properly, or at the very least the sections of code that are dependent upon "dead" being true do not appear to be acknowledging that it is. I've gone over all its events several times and monitored its behaviors in-game very closely, and everything about its malfunctioning behavior can be traced to the fact that it's completely ignoring the "dead = true;" line in one of its events while still executing the remaining code that follows it. Absolutely nothing else in any of its events sets or modifies this variable outside of its initialization in the Create event; it's just this one line of code that works perfectly for every other character object refuses to do its one job for this object in particular, and everything is falling apart because of it.

Does anyone know why this might be happening? Is there some quirk of proper GML practice that I'm not using?

If it helps, here's the code that gets triggered when a character is made "dead"

```
else if(wounded and position == 0 and !dead)
{
    dead = true;
    instance_create_layer(x,y,layer,obj_alchemist_corpse);
    death_sort();
}

```

Everything else is just a series of If statements that are triggered by 'dead' being true, but again, it would appear that one object in particular is executing the code in the above statement without actually setting 'dead' to true, and I would like to know why or why not.

EDIT: Forget what I said about an alchemist; further testing indicates it's just the second character in your party line of four that isn't getting their flag properly set.

# Answer
> 1 votes
**Nevermind**

Turns out, the problem was with the way I handled generating your selected party and the fact that modifying an object in a room with Creation Code doesn't completely replace the contents of the Create event, which long story short was secretly making hidden instances of the second character in your party underneath all the correct ones and throwing everything askew. This has since been rectified and now everything works just the way it should.

---
Tags: game-maker
---


# Question
Title: How to get the ip address from the gamer?
I have an android game with one player against the other , how to get the ip address to send the positions ?

# Answer
This is kind of a tricky thing. You will certainly need a master server, which manages the players which are online and their IP's to match players. You can first search for another player, e.g. by name or matchmaking. How you do that entirely depends on how you store and manage the players on your master server.

One simple option would be to use the Google Multiplayer API. It handles matching, invitations and connection stuff for you, you only have to implement the game logic and network logic, but the connection and initiation is handled for you. This would be the most straightforward and simplest solution. I don't know which framework you are using, since you specified this to be a C# question, so it may be difficult to integrate the Google API to your project.

The second possibility is to use your own Master Server. This is significantly more complicated than using the Google API. Additionally, if you want to use a direct connection to the other player, the problem arises that, unless you are in the same network, most players will sit behind a router or are in a mobile network. It is very complicated to connect to a device behind a firewall or in a public network, if you cannot assume certain ports to be opened. Either you route your connection completely to your own servers, or you can try something like a NAT Punchthrough. Here again, the Google API will handle that for you.
> 2 votes

---
Tags: c#
---


# Question
Title: Creating a click and drag system in GameMaker Studio 2
I am attempting to create a click and drag system in GameMaker 2, for example a dress-up game or maybe a puzzle. How would I go about getting the objects to click and drag?

I'm trying to get it so I can click and drag a piece of clothing, for example, and drag it onto a character and then drag another piece of clothing on as well.

# Answer
If all your objects move at the mouse position at the same time, probably their *Step* event looks like this:

```
// Click and drag object
if (mouse_check_button(mb_left) && position_meeting(mouse_x, mouse_y, self))
{
    x = mouse_x;
    y = mouse_y;
}

```

Or at least, this is the GML equivalent of what is happening.

The code above doesn't take into account whether an instance is actually being clicked on by the user, it cares only about the button click itself.

**Step 1: Individual instance flag**

We give every instance a variable, with a starting value of `false`:

```
grabbed = false;

```

We set its value to `true` when the mouse button is pressed *and* conditions are met; and set it to false when the mouse is released. We can do this by splitting the code between *Left Pressed* event:

```
// Now instance can move
grabbed = true;

```

And *Global Left Released* event:

```
// Now instance must stop
grabbed = false;

```

Finally our *Step* event will loop like this:

```
// Move instance if selected
if (grabbed)
{
    x = mouse_x;
    y = mouse_y;
}

```

Now objects are dragged only if mouse click happened inside their collision mask.

**Step 2: Global instance flag**

The code works fine so far, except if multiple instances are overlapping when you click, they will all snap to the mouse position! To prevent this, we must make sure one instance only is 'grabbed' when clicking before dragging it. To do so, we can use a global variable instead of an individual flag to tell what instance is picked by the cursor, and move it accordingly:

```
global.grabbed = noone;

```

This variable will hold the `id` of the instance that must move around. So, instead of a `true`/`false` approach, we have a `noone`/`id` variable that specifies which particular instance is being moved around. So:

*Left Pressed* event:

```
// Check if instance can be dragged
if (global.grabbed == noone)
    global.grabbed = self;

```

*Global Left Released* event:

```
// Stop dragging
global.grabbed = noone;

```

*Step* event:

```
// Move object if currently grabbed
if (global.grabbed == self)
{
    x = mouse_x;
    y = mouse_y;
}

```

You can also use the `global.grabbed` variable to get info about what the player has picked.
> 1 votes

---
Tags: game-design, game-maker
---


title: Benefits of going full AABB?

text:
# Question
Title: Benefits of going full AABB?
By "going full AABB" I mean using only AABBs for all of your objects (both dynamic and static), with dynamic objects colliding both with each other and static objects. In what specific ways does this simplify physics calculations? Are there any special techniques that require a world made entirely of AABBs? Some way to, say, remove the need for TOI-ordering (or similar) by taking advantage of that fact that all objects are AABBs?

In particular I'm looking for specific large-scale benefits, not just small things like collision detection being slightly faster. There seem to be quite a few games that use only AABBs, like Minecraft for example, so there must be a significant benefit to it or they wouldn't be doing it. Only thing I can think of is getting to do position/velocity corrections per-axis, though I'm not sure how one would exploit that to its full potential.

# Answer
> 2 votes
The main advantage is speed.

Testing whether 2 AABB collide with each other requires 2 compares per axis. The test itself is really simple (`box1.maxX >= box2.minX && box2.maxX >= box1.minX`) however it's likely that a copy-paste-edit error gets made there.

Testing against a ray is also rather simple.

However it doesn't solve the O(n²) problem of testing each object to every other object by itself. But having fast collision check alleviates that issue somewhat, letting you some more objects being collision checked at the cost of having less precise collision.

There are ways to fix these shortcomings, the O(n²) ness can be fixed by a broadphase collision that eliminates large swaths of objects that will never collide with each other and the precision of the collision can be fixed by using a more precise collision system after testing the AABB.

---
Tags: physics, aabb
---


# Question
Title: Why do I need to offset my aim rotation angle by 90 degrees?
I have this simple code to rotate an object (gun barrel) towards a target object (rocket ship).

The gun barrel rotates towards the ship but is always 90 degrees off. I have fixed this in my code as you can see by subtracting 90 degrees from the angle but I would like to know why it is happening and if there is a more elegant solution.

I have checked the rotation of all objects involved but that doesn't seem to change anything. Any help is much appreciated!

```
using UnityEngine;

public class RotateTowardsObject : MonoBehaviour {

    public float speed = 5f;        // how fast this rotates towards the target
    public Transform target;        // target to follow

    public void Update()
    {
        Vector2 direction = target.position - transform.position;                                               // direction between this position and target position
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;                                    // calculate the angle
        angle = angle - 90f;                                                                                // ** Temporary fix(?) for rotation being +90 degrees off
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);                                     // create rotation from quaternion
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);            //  set rotation acceleration towards target
    }

```

# Answer
As per the unit circle math, angle 0 means "pointing right". Your initial orientation is up, at 90 degrees, so that's why you need to offset by 90 degrees so that your zero is at top, and -90 at right.

You can just keep doing this, or rotate your model to be oriented towards right by default. I find that the best practice, as then you can just swap content in and out of different systems. It's a good practice to make everything that needs to be rotated to face right in the future.
> 4 votes

---
Tags: unity, c#, rotation, quaternion
---


# Question
Title: Why does the object spawn only on client?
In my game I have an object, let's say food, that whoever consumes it, that player will spawn one more element. I am checking collision in Update.

The following code is working fine on server side, but the object is not spawning. Although, it is spawning on local client but it is not updating on server.

Here is my code:

```
// This function is called on Update
private void CheckForFood(Vector3 snakePartPosToBeInitialize,Vector3 headPos)
{
    if(_food != null)
    {
        if (_food.transform.position == headPos)
        {
            UiControllerCS.UI.showScore();
            GameObject obj = Instantiate(snakePart, snakePartPosToBeInitialize, Quaternion.identity) as GameObject;
            currPartOfSnake += 1;
            obj.name = "" + currPartOfSnake;
            obj.transform.parent = gameObject.transform;
            tail.Add(obj);
            NetworkServer.SpawnWithClientAuthority(obj , connectionToClient);
        }
    }
}

```

I am getting the following error :

> SpawnObject for 1 (UnityEngine.GameObject), NetworkServer is not active. Cannot spawn objects without an active server.

# Answer
> 0 votes
You can try instantiating it on the network using:

```
Network.Instantiate()

```

Here is the documentation

# Answer
> 0 votes
As a client you don't have access to NetworkServer which only exist on the server. If you want to call NetworkServer.SpawnWithClientAuthority you must call it on on the server. You do such via a Remote Procedure Call, in your case a Command.

---
Tags: unity, c#, multiplayer, unity-networking
---


# Question
Title: SMAPI add warp to existing map [Stardew Valley]
I am trying to add a warp into the existing farm map using SMAPI. I tried the following things but both didn't work.

Setting the Warp inside the map properties:

```
Map farm = Game1.getLocationFromName("Farm").Map;
farm.Properties.TryGetValue("Warp", out PropertyValue initialWarps);
farm.Properties.Remove("Warp");
farm.Properties.Add("Warp", initialWarps + "64 18 TestRoom 5 5");

```

Setting the Warp inside a Tile:

```
Game1.currentLocation.setTileProperty(64, 18, "Back", "Warp", "64 18 TestRoom 5 5");

```

I can confirm that the first approach works when you set the Warp property directly in the map file but it doesn't seem to work if you add it afterwards.

# Answer
> 1 votes
Until someone finds out how to solve this problem using the build in warp property, i came up with my own solution. It isn't as nice but i thought i am gonna share it with you if someone has the same problem.

ModEntry.cs

```
using System;
using Microsoft.Xna.Framework;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewModdingAPI.Utilities;
using StardewValley;
using xTile;

namespace StardewValleyMod {

    public class ModEntry : Mod {

        private IModHelper helper;
        private WarpManager warpManager;

        public override void Entry(IModHelper helper) {
            this.helper = helper;
            warpManager = new WarpManager();

            warpManager.add(new Warp(new Vector2(60, 15), "Farm", new Vector2(5, 5), "TestRoom"));

            GameEvents.FourthUpdateTick += warpManager.update;
        }
    }
}

```

WarpManager.cs

```
using System;
using System.Collections.Generic;
using StardewModdingAPI;
using StardewValley;

namespace StardewValleyMod {

    class WarpManager {
        private List<Warp> warps;

        public WarpManager() {
            warps = new List<Warp>();
        }

        public void add(Warp warp) {
            warps.Add(warp);
        }

        public void update(object sender, EventArgs args){
            update();
        }

        public void update() {
            if(Context.IsWorldReady) {
                int x = Game1.player.getStandingX() / Game1.tileSize;
                int y = Game1.player.getStandingY() / Game1.tileSize;

                foreach(Warp warp in warps) {
                    warp.tryToWarp(x, y, Game1.currentLocation.Name);
                }
            }
        }
    }
}

```

Warp.cs

```
using System;
using Microsoft.Xna.Framework;
using StardewValley;

namespace StardewValleyMod {

    class Warp {
        private Vector2 from;
        private Vector2 to;
        String fromMap;
        String toMap;
        private int rotation;

        private bool triggerFlag;

        public Warp(Vector2 from, String fromMap, Vector2 to, String toMap, int rotation) : this(from, fromMap, to, toMap) {
            this.rotation = rotation;
        }

        public Warp(Vector2 from, String fromMap, Vector2 to, String toMap) {
            this.from = from;
            this.to = to;
            this.fromMap = fromMap;
            this.toMap = toMap;
            rotation = 2;
        }

        public bool tryToWarp(int x, int y, String mapName) {
            if(!triggerFlag) {
                if(x == from.X && y == from.Y && mapName.Equals(fromMap)) {
                    Game1.warpFarmer(toMap, (int) to.X, (int) to.Y, (int) rotation);
                    triggerFlag = true;
                    return true;
                }
            } else if(!mapName.Equals(fromMap)) {
                triggerFlag = false;
            }

            return false;
        }
    }
}

```

# Answer
> 0 votes
This is what I bhave figured out:

```
List<Warp> warps = new List<Warp>();
warps.Add(new Warp(5, 53, "BusStop", 34, 23, false));
warps.Add(new Warp(5, 54, "BusStop", 34, 23, false));
warps.Add(new Warp(5, 55, "BusStop", 34, 23, false));

foreach (Warp warpy in warps)
{
  location.warps.Add(warpy);
}

```

---
Tags: c#, modding
---


# Question
Title: How to prepare a rigged character model to be imported as a humanoid in unity?
I want to import a character as a humanoid to be able to use masks on animation system. I used proper human structure but unity gives some errors when I want to turn it from generic to humanoid and says some bones are not in the right place or have a wrong name.

The questions is how should a rigged model be prepared in modeling program to be imported in unity as humanoid?

# Answer
> 0 votes
Unity has a doc file for this: https://docs.unity3d.com/Manual/AvatarCreationandSetup.html

By following the underlined red texts you probably find your answer but i think your problem is a bad avatar mapping: https://docs.unity3d.com/Manual/class-Avatar.html

---
Tags: unity, skeletal-animation, mecanim, rigging
---


# Question
Title: Do I have to take aspect ratio into account, when computing a direction in View Space?
I read an article about implementing a Single-Pass Volume Renderer.

After thinking about it, I have a question, which concerns the provided GLSL code snippet of the Fragment Shader.

To calculate the ray direction, the author uses the FocalLength (distance of the projection plane from view point) as Z-component, and the fragment coordinates in NDC-space as xy component. This gives a vector pointing from the view point to the pixel on the projection plane which is computed. Obviously this direction is supposed to be in View Space, because it assumes 0,0,0 as view point and the ModelView Matrix is used to convert the direction to object-local space. But I am not sure if that is correct, because isn't it that in view space the projection window isn't necessarily normalized, but has a width of twice the aspect ratio? It gets normalized by applying the projection matrix (at least in Direct3D as far as i know). So if this is true, why does this work? Why he maps the x component of gl\_FragCoord to \[-1;1\], when the leftmost pixel would have an x-coordinate of -aspectRatio in view space?

# Answer
> 2 votes
You are correct. I would suspect the author of this blogpost simply didn't notice his mistake because he happened to be using only a square aspect ratio (his example code seems to use an 800×800 framebuffer). Or he is using only square aspect ratios on purpose to avoid this issue. Either way, in general, you will have to consider the aspect ratio when going from normalized device coordinates back to view space. \\$ \newcommand{\mvec}\[1\]{\begin{pmatrix}#1\end{pmatrix}} \newcommand{\ivec}\[1\]{\left(\begin{smallmatrix}#1\end{smallmatrix}\right)} \newcommand{\mmat}\[1\]{\begin{bmatrix}#1\end{bmatrix}} \renewcommand{\vec}\[1\]{\mathrm{\mathbf{#1}}} \newcommand{\mat}\[1\]{\mathrm{\mathbf{#1}}} \\$

Anyhow, if the goal is to generate rays in a way that matches rasterization by the hardware graphics pipeline, I would personally follow a different approach. Rather than trying to construct my rays to match the way in which I expect my projection matrix to be constructed, I would simply compute the rays from a given projection matrix \\$\mat M\\$. All you need is the inverse \\$\mat M^{-1}\\$ of that projection matrix.

Given a point on the screen in viewport (pixel) coordinates \\$\ivec{x && y}^T\\$, we compute the clip-space coordinates of two corresponding points, one on the near and one on the far plane: \begin{align} \vec p''\_{near} &= \mvec{ 2\cdot\frac{x}{w} - 1 \\ 2\cdot\frac{y}{h} - 1 \\ -1 \\ 1 } & \vec p''\_{far} &= \mvec{ 2\cdot\frac{x}{w} - 1 \\ 2\cdot\frac{y}{h} - 1 \\ 1 \\ 1 }, \end{align} where \\$w\\$ and \\$h\\$ are the width and height of the viewport respectively. For simplicity, we'll ignore the fact that the viewport may be offset. It should be obvious how to account for such an offset in case that would be necessary.

Note that in OpenGL, pixel locations correspond to the centers of the cells of a sampling grid by default. Thus, the viewport coordinates of the pixel at row index \\$j\\$ and column index \\$i\\$ would be \\$x = i + \frac{1}{2}\\$ and \\$y = j + \frac{1}{2}\\$. `gl_FragCoord` will already give you the correct coordinates unless you explicitly change its coordinate system origin via layout qualifier.

We can then transform these two points back to camera-space by first multiplying with the inverse projection matrix \begin{align} \vec p'\_{near} &= \mat M^{-1} \vec p''\_{near} & \vec p'\_{far} &= \mat M^{-1} \vec p''\_{far} \end{align} and then dehomogenizing to get euclidean coordinates: \begin{align} \vec p\_{near} &= \frac{1}{p'\_{near\_w}} \cdot \mvec{ p'\_{near\_x} \\ p'\_{near\_y} \\ p'\_{near\_z} } & \vec p\_{far} &= \frac{1}{p'\_{far\_w}} \cdot \mvec{ p'\_{far\_x} \\ p'\_{far\_y} \\ p'\_{far\_z} }. \end{align}

Knowing a point on the near and one on the far plane, we can construct a view ray representing all points which project to our pixel, e.g., \begin{equation} \vec r(t) = \vec p\_{near} + t \cdot (\vec p\_{far} - \vec p\_{near}). \end{equation}

Note how this automatically also allows us to account for clipping on the near and far plane as everything behind the near plane will be behind the ray start (\\$t \< 0\\$) and everything beyond the far plane will correspond to \\$t \> 1\\$.

\\$\mat M\\$ can also be a combined View-Projection or Model-View-Projection matrix to directly get the ray in world- or object-space instead.

There are many ways to construct a projection matrix. And perspective projection is not the only kind of projection. Above approach will automatically and exactly match anything you can throw at it in the form of a matrix. While it might be slightly more expensive than a specialized construction for a particular kind of projection matrix, I doubt you will be able to notice an impact on performance in practice, as ray setup is unlikely to be a bottleneck for any kind of raytracing that does something close to meaningful…

---
Tags: opengl, rendering, graphics, glsl
---


# Question
Title: Unity Failed to create decoder for ScreenSelector.png
My game works fine in the editor, but when I build and run the build the view is zoomed in, my tilemap is missing, and the camera follows a gameobject it should not.

How it should look and how it looks

I checked the logs and this is the error I am served:

> Failed to create decoder for 'C:/Users/Hamuel The First/Documents/Jetplatformer/Builds/Builds\_Data/ScreenSelector.png': 0x80070002

Further Investigation shows that ScreenSelector.png is absent from the path stated in the error. I cannot find anything that says what ScreenSelector.png is, or does. I am using the post processing stack by unity.

Any help would be much appreciated!

# Answer
I suspect you are on the beta channel. This looks like a known bug.

More details can be found here https://issuetracker.unity3d.com/issues/deployment-management-failed-to-create-decoder-exception-thrown-while-playing-development-build

This doesn't actually cause anything that I can tell and the game runs. Are you sure this is not a red herring?
> 1 votes

---
Tags: unity
---


title: Separate game engine from game

text:
# Question
Title: Separate game engine from game
I'm building a simple game engine (or mostly rendering engine) and I would like to separate the "engine" part from the "game" part. So, I've come up with an idea to build "engine" part as a library (static or dynamic) and the "game" part will link to this library. Simple.

However, there is one problem - "engine" part needs to reference some assets i.e. files with source code of builtin shaders (defualt shaders of the rendering engine).

Is there a way to include these shader files into an "engine" library? Or is there any other solution to this problem?

# Answer
All my engine's core shaders are provided as data files, and we simply expect each game to include those files as part of their game data. We load them exactly the same way we load any other game asset. Creating a new game? First thing you do is copy those default shaders into your game's asset directory. (The engine complains and refuses to start if they're not there)

I felt it was important for individual games to have the ability to modify those default shaders, which is why I wanted them to be included in the game's data, rather than in a separate "engine data" directory. I wanted it to be possible for a particular game to replace the 'default' shaders simply by changing their contents, and without needing to touch the engine itself.

With that said, I do also have a few simple rendering effects (blurs, bloom, etc) which include their own minimal shaders in static string buffers inside the engine, as they're just simple utilities; if somebody wanted something particular, they'd make it themselves rather than use the engine's simple built-in effects.
> 2 votes

---
Tags: c++, shaders, architecture, assets
---


# Question
Title: Unity Collision Doesn't Work when Two Players Instantiated
I am using Unity3D and I have a problem. I have a script which instantiates the player gameobject once you are connected to the server. I also have an attack script. When there is only 1 player on, everything works fine. When the second player comes on, the attack doesn't work! I did Debug.Log and I found out that when you clicked the other player to attack instead of attacking him, you are attacking the terrain below it.

Here is my code. Instantiate Code:

```
GameObject myPlayer = PhotonNetwork.Instantiate (
  character,
  mySpawn.transform.position,
  mySpawn.transform.rotation, 0) as GameObject;

```

Attack code:

```
using UnityEngine;
using System.Collections;

public class SendAttackInfo : Photon.MonoBehaviour
{
  public float damage = 100;

  // Use this for initialization
  void Start()
  {
  }

  void Update()
  {
    bool RMB = Input.GetMouseButtonDown(0);
    if (RMB)
    {
      RaycastHit hit;
      Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      if (Physics.Raycast(ray, out hit, 100))
      {
        Debug.Log("We arm-hit: " + hit.collider.name);

        hit.collider.transform.gameObject.GetComponent<PhotonView>().RPC(
          "ApplyDamage",
          PhotonTargets.AllBuffered,
          damage);
        hit.collider.transform.FindChild("Cube").GetComponent<PhotonView>().RPC(
          "ApplyDamage",
          PhotonTargets.AllBuffered,
          damage);
      }
    }
  }
}

```

# Answer
> 1 votes
There are a lot of unknown things to me here.

1) Is your SendAttackInfo script on both players after they spawn in? If so, you will be firing for both you and your opponent when you click since update runs on each player. Take a look at the isMine variable on Photon.Monobehaviour. It will help you write logic that will only be run for the local player.

2) What are you trying to do by searching for “cube” and calling an rpc on that after already calling the rpc on your hit target? This seems likely to be a cause of unexpected behaviour. I could also just not understand your requirements.

3) The fact that things go wrong when the second player joins is telling to me. I would look through all your scripts on the player prefab and analyze each line of code and ask yourself “do I want to run this for everyone or just the player controlling it locally?”. Also keep in mind that the ids on the PhotonViews are very important. If you somehow save a prefab with a non negative instantiation id on it’s PhotonView then photon will not dynamically assign an id at runtime and use the given id instead.

For example: if you create a prefab with a PhotonView on it and save it with view id 5 it will spawn correctly the first time photon.instantiate is called because only one view exists with id 5. Now your buddy joins and spawns a copy of the same prefab. Now there are two views with id 5 on the field. If, for example, you decided to send an rpc to a view with id 5 then you are asking photon to send the data over the network and when each client receives the data they lookup a view with id 5.... how do you think that will work when two of them exist?

The rule with photon views is as follows:

* if the photon view is saved into a scene it must have a unique id (photon handles guaranteeing the id is unique when you save).
* if the view will be spawned at runtime it must have an instantiationId of -1. Note that instantiation id and view id are two separate fields on the photon view. This gets tricky whenever you have a prefab with instantiation Id -1 that you drag and drop into a scene to edit because photon will then give it a new view and instantiation id that is not -1. This will now be saved to your prefab and will cause all sorts of issues when spawning it at runtime. You can force photon to save the proper values by not having the prefab in the scene and saving the project.

I am not near a computer at the moment to double check everything so feel free to ask questions if you have any.

I just wanted to share what I know since I have encountered these issues before. Good luck!

# Answer
> 0 votes
It sounds like you need to apply a LayerMask to your Raycast call. To do this you need to assign a different layer to your enemy object in the inspector, then in the code do something like this:

```
public class SendAttackInfo : Photon.MonoBehaviour
{
  public float damage = 100;
  private LayerMask enemyLayerMask = LayerMask.GetMask("MyLayerName");

  void Update()
  {
    bool RMB = Input.GetMouseButtonDown(0);
    if (RMB)
    {
      RaycastHit hit;
      Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      if (Physics.Raycast(ray, out hit, 100, enemyLayerMask.value))
      {
        Debug.Log("We arm-hit: " + hit.collider.name);

        hit.collider.transform.gameObject.GetComponent<PhotonView>().RPC(
          "ApplyDamage",
          PhotonTargets.AllBuffered,
          damage);
        hit.collider.transform.FindChild("Cube").GetComponent<PhotonView>().RPC(
          "ApplyDamage",
          PhotonTargets.AllBuffered,
          damage);
      }
    }
  }
}

```

The layermask variable is given the name of the layer you created and assigned to the enemy and it's value is used in your raycast so that the cast only looks for hits with the matching layer. Alternately you can expose the layermask variable publicly and the inspector will provide a dropdown where you can pick one or more layers you want to be eligible for the hit.

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


# Question
Title: Visual Studio not updating files made in Unity
In the past Visual Studio simply updated solution based on files added in Unity but now all of them have to be added manually and they are as miscellaneous when they are added. How can I fix it?

# Answer
I have run into this a few times. It is some particular workflow that causes it to happen. I usually create new files from within visual studio instead of unity and it seems to avoid the issue. If you do have files currently marked as miscellaneous, you can right click them in visual studio and exclude them from the project and then re-add them to fix the issue. You will need to show all files to re-add the file (show all files button is at the top of the solution explorer).

Hope this helps :)
> 0 votes

---
Tags: unity, visual-studio
---


# Question
Title: Stop character from moving after reach his destination?
my script is for character moving to the certain point on the terrain. To get this point I have to use mouse. When I click on the terrain, my character goes there. Now, If he reach his point and something like enemy come to push him, he moves away from his point !!? What I want is to make him stop there and no power in the world could move him.

```
private NavMeshAgent mAgent;
public Vector3 point_;
public float mark;
public bool actives;

void Start()    {
    mAgent = GetComponent<NavMeshAgent>();

}

// Update is called once per frame
void Update()    {
    Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit mousePoint;
    if (Input.GetMouseButtonDown(0))
    {
        if (Physics.Raycast(mouseRay, out mousePoint, 100))
        {
            point_ = mousePoint.point;
            mAgent.SetDestination(mousePoint.point);
            mark = Vector3.Distance(point_, gameObject.transform.position);
        }

    }

}

```

# Answer
You can use a constrain on the rigidbody https://docs.unity3d.com/ScriptReference/Rigidbody-constraints.html

Or if the external force is a physic-related one make it cinematic. https://docs.unity3d.com/ScriptReference/Rigidbody-isKinematic.html

The second one is faster to implement (a click in your rigidbody) so you can test it faster. You can also change it so its kinematic when stoppped and not kinematic when moving via script.
> 2 votes

# Answer
Could you just set isKinematic on the RigidBody to false once he reaches the destination? This would prevent the rigidbody from being effected by physics, which is kind of like preventing any force in the world from moving it :).
> 2 votes

---
Tags: unity, navmesh
---


# Question
Title: OpenGL - How can I make the edges of this textured circle smoother?
I'm building a game and I've applied a certain texture (RAW file) to a circle (GL\_POLYGON) in OpenGL. It loads correctly, with the right size and all, but the edges seem a bit jagged and I would prefer them smooth (without any evidence of a polygon being underneath).

```
GLuint loadTex(int wrap){
GLuint texture;
int width, height;
BYTE * data;
FILE * file;

file = fopen( "tex.raw", "rb" );
if (file == NULL){
    std::cerr << "O ficheiro da textura não foi encontrado" << std::endl;
    return 0;
}

width = 128;
height = 128;
data = (BYTE*)malloc( width * height * 3 );//Alocação do buffer

fread( data, width * height * 3, 1, file );//Ler dados da textura
fclose( file );

glGenTextures( 1, &texture );//Nome da textura
glBindTexture( GL_TEXTURE_2D, texture );//Selecção da textura actual
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );//Parâmetros da Textura
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap ? GL_REPEAT : GL_CLAMP );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap ? GL_REPEAT : GL_CLAMP );
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, data );

free(data);

return texture;
}

void drawCircle(float cx, float cy, float r, float aspectRatio){

GLuint t = loadTex(1);
float angle, radian, x, y, tx, ty, xcos, ysin;

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, t);

glBegin(GL_POLYGON);

for (angle=0.0; angle<360.0; angle+=2.0){
    radian = angle * (M_PI/180.0f);

    xcos = (float)cos(radian);
    ysin = (float)sin(radian);
    x = xcos * r  + cx;
    y = ysin * r*aspectRatio + cy;
    tx = xcos * 0.5 + 0.5;
    ty = ysin * 0.5 + 0.5;

    glTexCoord2f(tx, ty);
    glVertex2f(x, y);
}

glEnd();
glDisable(GL_TEXTURE_2D);
}

```

Is this a problem from my texture file? Or is it from my code? I apply Line Smoothing before drawing anything (and it is being applied correctly in my lines I believe)

# Answer
> 2 votes
Just in case you never figured this out, you need to enable GL\_BLEND and set both your blend equation and blend function to use transparency.

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

```

also when you apply your texture you set the color format to GL\_RGB when it should be RGBA, also why did you use gluBuild2DMipmaps instead of glTexImage2D, for your purposes you really don't need to use gluBuild2DMipmaps, but none the less the same applies,

```
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data );

```

this should fix your problem with your code, sorry this is 4 years late, but still hope it helps (=

# Answer
> 1 votes
It should be either from the image file itself, or from a shader which rejects all perfectly white pixels, or something like that, but since the shader isn't the simplest thing to implement, I'll bet it's the image file. I'll also bet you made or found this image with a white background, then tried to delete that white to make the background transparent. Unfortunately you deleted the pixels that are perfectly white, but the edge isn't perfectly sharp, and you missed some partially white pixels.

Those are the more certain bets I can make. Now I'll make another less certain bet: that you're using GIMP. If you're not, maybe you can adapt the instructions for another program.

You want to experiment with the tolerance on the selection wand, as well as selection feathering, and the color erase mode of the fill tool. Find whatever works best. Maybe take your current image with the transparent background, do alpha to selection, shrink selection by 1px, invert, then color erase white.

# Answer
> 0 votes
The problem is not you texture, this should be solved when you put something in background, like texture or geometry, I had similar problem.

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


# Question
Title: Creating color texture from greyscale heightmap in shader
I'm trying to create a shader that takes a grayscale map as input, and returns a colored albedo that I want to use as texture for my PCG planets, I think that the code below should work, but it only produces flatly white objects.

I'm a total shader noob, so I'm terribly sorry if I'm missing something obvious here.

```
    Shader "Custom/Planet" {
    Properties{
        _height("HeightMap", 2D) = "white" {}
    }
    SubShader{
        Tags { "RenderType" = "Opaque" }
        LOD 200

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

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

        struct Input {
            float2 _heightMap;
        };

        float minHeight = 0;
        float maxHeight = 1;

        float inverseLerp(float a, float b, float v) {
            return saturate((v - a) / (b - a));
        }

        //UNITY_INSTANCING_CBUFFER_START(Props)
        //UNITY_INSTANCING_CBUFFER_END

        void surf (Input IN, inout SurfaceOutputStandard o) {
            float hv = inverseLerp(minHeight, maxHeight, IN._heightMap);
            o.Albedo = hv;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

# Answer
You've probably already figured it out, but just in case. If you want to remap your height values to the colours from the texture gradient, this should do the job:

`void surf (Input IN, inout SurfaceOutputStandard o) {
 // map height to [0, 1] values
 float hv = inverseLerp(minHeight, maxHeight, IN._heightMap);
 // create UV from height
 float2 uv = float2(hv, 0.0);
 // sample gradient texture
 o.Albedo = tex2D(_GradientTexture, uv);
}`

Note that I used 2D texture for gradient, but you can use 1D texture instead, or use 2D texture and pack different gradients, then u-coordinate will be as usual (normalized height value), and v-coordinate can select graient type. E.g.

`int planet_type = ...; // from 0 to textue_height-1`

`// this math is used so vertical coordinate will fall exactly at the pixel center, so 2 horizontal gradient lines will not be mixed if you are using bilinear filtering to sample _GradientTexture
int v = 0.5/textue_height + (float)planet_type/textue_height;`

`o.Albedo = tex2D(_GradientTexture, float2(u, v));`

Beside the color you can alse generate normals from height map to get more details for lighting, you can look e.g. here or here. Take care about different scale values for height(Z) and XY
> 0 votes

# Answer
To Creating color texture from grayscale you can use HSL or HSV color.

> HSL (Hue, Saturation, Lightness) and HSV (Hue, Saturation, Value) are two alternative representations of the RGB color model, designed in the 1970s by computer graphics researchers to more closely align with the way human vision perceives color-making attributes. https://en.wikipedia.org/wiki/HSL\_and\_HSV

```
Shader "Smkgames/HSBC" {
    Properties {
        _MainTex ("Texture", 2D) = "white" {}
        _Hue ("Hue", Range(0, 1.0)) = 0
        _Saturation ("Saturation", Range(0, 1.0)) = 0.5
        _Brightness ("Brightness", Range(0, 1.0)) = 0.5
        _Contrast ("Contrast", Range(0, 1.0)) = 0.5
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows

        #pragma target 3.0

        sampler2D _MainTex;
        fixed _Hue, _Saturation, _Brightness, _Contrast;
        float4 _Color;

        struct Input {
            float2 uv_MainTex;
        };

        inline float3 applyHue(float3 aColor, float aHue)
            {
                float angle = radians(aHue);
                float3 k = float3(0.57735, 0.57735, 0.57735);
                float cosAngle = cos(angle);

                return aColor * cosAngle + cross(k, aColor) * sin(angle) + k * dot(k, aColor) * (1 - cosAngle);
            }

            inline float4 applyHSBCEffect(float4 startColor, fixed4 hsbc)
            {
                float hue = 360 * hsbc.r;
                float saturation = hsbc.g * 2;
                float brightness = hsbc.b * 2 - 1;
                float contrast = hsbc.a * 2;

                float4 outputColor = startColor;
                outputColor.rgb = applyHue(outputColor.rgb, hue);
                outputColor.rgb = (outputColor.rgb - 0.5f) * contrast + 0.5f;
                outputColor.rgb = outputColor.rgb + brightness;
                float3 intensity = dot(outputColor.rgb, float3(0.39, 0.59, 0.11));
                outputColor.rgb = lerp(intensity, outputColor.rgb, saturation);

                return outputColor;
            }

        UNITY_INSTANCING_CBUFFER_START(Props)
        UNITY_INSTANCING_CBUFFER_END

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 startColor = 1-tex2D(_MainTex, IN.uv_MainTex) + float4(1,0,0,1);
            float4 hsbc = fixed4(_Hue, _Saturation, _Brightness, _Contrast);
            float4 hsbcColor = applyHSBCEffect(startColor, hsbc);

            o.Albedo = hsbcColor;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```
> 0 votes

---
Tags: unity, shaders
---


# Question
Title: Is there an upgrade path from Asset Store to package manager for TextMesh Pro?
A little while back I used the Asset Store to install TextMesh Pro after following a tutorial. The version I got was 1.2.2. I have since then had it pointed out to me that the newest version is now available through the Package Manager. The version there is 1.2.3.

I have tried changing which version i am using but have had no luck. I did quite a bit of work with adding texts and do not want to redo all of it. Simply deleting the package from my app, and then installing it from the package manager does not work. All text scripts end up not linked.

Is there anything I can do to switch my project over from the app store to the package manager?

# Answer
> 5 votes
Yes, upgrading to the new package manager version of TextMesh Pro requires the use of a utility tool to convert these existing projects to use the new sets of GUIDs and FileIDs. Using this tool will ensure that your text scripts remain linked.

See this Unity official forum thread: TextMesh Pro & Unity 2018.1. As explained there, here are the steps:

> This new version of TMP will be made available via the new Unity Package Manager (also part of Unity 2018.1). These new Unity Package Manager (UPM) packages are shared between all projects. This new version of TMP includes source code and uses the new Assembly Definition feature introduced in Unity 2017.3.
>
> Due to how this package manager works, it is important to understand this new version of TextMesh Pro will be using a completely different / unique set of GUIDs and FileIDs which was necessary to make sure it did not conflict with the current sets of GUIDs and FileIDs used by the source code and DLL only versions of TMP currently out there. As such project files and assets created with previous versions of TMP will require the use of a utility to convert these existing projects to use the new sets of GUIDs and FileIDs.
>
> During the beta period for 2018.1, I would love to get your feedback and most importantly assistance to test this project conversion utility to make sure it correctly handles the conversion process.
>
> My suggested upgrade steps are as follows but expect these may change based on your feedback.
>
> 1. Before installing Unity 2018.1, open your project in your current version of Unity and close all scenes you might have opened. Using "File -\> New Scene" will close current scenes. In this step we are trying to avoid having any TMP resources or DLLs loaded when you first open Unity 2018.1. Failing to do so will just confuse the crap out of Unity and make the upgrade process more complex.
> 2. As usual, please backup your project before upgrading to this new version of TMP and Unity 2018.1.
> 3. Install Unity 2018.1. Personally, I always install new major versions of Unity in separate folders which allows me to use multiple versions of Unity for testing and what not.
> 4. Open Unity 2018.1 and expect to see lots of error messages since the older version and new versions of TMP are present thus resulting in class conflicts. This could be avoided by deleting the "TextMesh Pro" folder in step (1) but it isn't necessary as once the previous version of TMP is removed by deleting the "TextMesh Pro" folder these errors will go away. That is provided you did close any open scene using TMP in step (1). Once the "TextMesh Pro" folder is deleted, Unity will go through an Assembly Reload and the new version of TMP will finally be loaded.
>
> Note that I could have used a new namespace for this new version but this would have required updating all the scripts referencing the "TMPro" namespace which given these errors only show up during this upgrade process, going thru all the scripts to change the namespace would have been more complicated in my opinion.
>
> 5. Now we need to import the Essential Resources that TextMesh Pro needs. These are the default font asset, sprite asset, stylesheet, shaders, etc. You can add these to your project by going to the "Window - TextMeshPro - Import TMP Essential Resources" menu. These resources will be added to your project in the "TextMesh Pro" folder.
>
> Note: These resources could have been contained inside the new TMP UPM package but these would have be hidden and given they would be inside a Resources folder to make it possible to access them at runtime, they would have been part of any build whether or not TMP is used. As such I thought it would be better to make those visible to users by adding them into the local project and giving you control over them.
>
> 6. Lastly, since this new version of TMP uses a new set of GUIDs and FileIDs, we will need to convert your existing project files and resources to use this new set. To convert the project, go to "Window - TextMeshPro - Project Files GUID Remapping Tool". This will open the new Project GUID Remapping Tool which will enable you to Scan the Project to find the resources and files than need to be converted and then if you chose convert them to the new set of GUIDs and FileIDs used by this new version of TMP. Please be sure to following the instruction provided in the tool and to have made a backup of your project first.
>
> Please provide feedback on this process and most importantly let me know if you run into any unforeseen issues. I have run through this process many times with various projects and it worked fine. On the other hand, "Murphy's Law" is always in full force so provided you backed up your project first, we'll be able to iron out whatever issues and make sure we get all these projects converted over nicely.

---

EDIT: For reference, see below for an example of an error message before taking the steps to upgrade. As explained above, these error messages are due to the older version and newer version of TMP both being present. (I got this error message while upgrading to Unity 2018.2 from 2017.3.)

```
Assets/TextMesh Pro/Examples/Scripts/FloatingText.cs(86,30): error CS0121: The call is ambiguous between the following methods or properties: `TMPro.TMPro_ExtensionMethods.Compare(this UnityEngine.Vector3, UnityEngine.Vector3, int)' and `TMPro.TMPro_ExtensionMethods.Compare(this UnityEngine.Vector3, UnityEngine.Vector3, int)'

```

---
Tags: unity
---


title: Removing duplicate vertices on a mesh

text:
# Question
Title: Removing duplicate vertices on a mesh
I have a set of vertices and another set of indices. Sometimes I find that I have duplicate vertices in my mesh.

I tried at first to check if two identical vertices were in the array of vertices but that didn't work because I remembered that more that if one vertex represents multiple edges then the vertex would be validly represented as multiple vertices in the vertices array.

Then I remembered that the indices help represent how the vertices are structured but I didn't know how to use them. So I came here to ask how to use them to detect duplicate vertices in a mesh.

# Answer
> 0 votes
First you'll need a lookup structure to look up vertices you've processed so far. This could be, for example, a dictionary keyed on the position of your vertices, or an octree/k-d tree/etc. Each entry will hold the updated index of the de-duplicated vertex at that position.

(If you're using this for display meshes, you'll want to count vertices with different normals/UVs as distinct, but if I recall correctly you're working on collision meshes so we can ignore this detail and treat vertices as pure positions)

Next you'll need a re-indexing list the same size as your initial list of vertex positions. This will hold the new index of each vertex after de-duplication.

Initialize a vertex count to zero. Iterate over your list of vertices, checking to see if each position (or one within a small rounding tolerance) is already in your lookup collection.

* If there's no vertex recorded yet at that point, set the current vertex's new index to your current vertex count, and increment that count. Write this vertex and its new index into your lookup structure.
* If you already have a vertex recorded at that point, set the current vertex's index to that recorded index and do not increment the vertex count.

Either way, write the new index you've chosen for this vertex into the re-indexing list.

At the end, or as you go, you can build your new vertex list, using only the first vertex with each new index.

Then you need to update your index list. For each entry in the list, replace it with the corresponding new index looked from your re-indexing list. ie. `indices[i] = reindex[indices[i]];`

Lastly, check to see whether any triangles have become degenerate (two or three indices all pointing to the same vertex) - if so, you can delete that whole triangle. (Swapping 3 indices from the end of the list, or moving the rest of the indices back 3 spaces to fill the gap)

---
Tags: java, algorithm, geometry, mesh, vertex
---


title: GLSL shader time uniform freezed?

text:
# Question
Title: GLSL shader time uniform freezed?
I have a simple fragment shader to simulate "falling water". I'm using Ogre3D and opengles2, this is my code:

```
#version 130

uniform sampler2D valveTex;
uniform sampler2D noiseTex;
uniform float time;

uniform vec3 sprayColor;

varying vec2 uv;
varying float rand;

    void main()
    {
        gl_FragColor.w = texture2D(valveTex, uv).w;
        float noiseW = texture2D(noiseTex, uv + vec2(rand, -time)).x;
        gl_FragColor.w *= noiseW + noiseW;
        gl_FragColor.xyz = sprayColor;
    }

```

The shader works well and I see the animation happening, but after some time running the animation stops like if the variable `time` stopped updating, and the water stream looks still. What can be causing this?

**Edit1:** variable `time` is derived from Ogre's `time_0_1`.

# Answer
> 2 votes
It sounds like your `noiseTex` you're looking up into might be configured with wrapping mode `CLAMP_TO_EDGE` \- once your `time` uniform gets large enough to take it outside the \[0, 1\] texture coordinate range, texture samples start just repeating the same values they had at the edge of the texture.

Ensure your texture is a power of two in size and configured with wrapping mode `REPEAT`.

---
Tags: opengl, shaders, opengl-es2, ogre
---


# Question
Title: How do I deal with closely coupled systems in a game engine?
Let's say a game engine had a central game class as well as multiple systems (as objects) that are stored within it. These systems (such as input, rendering, sound, etc) would also be updated by this main game class. What if the input manager detects that the close button on the window if pressed. It would cause the game to shutdown by, say, calling a quit method inside the game class. This would be an example of a closely coupled system which is typically not good for future expansion of these systems. How would a closely coupled system like this be dealt with in order to make it more loosely coupled?

# Answer
Events would help for this.

Take your InputManager example in the method where you detect the close button has been pressed instead of referencing the game class and calling the quit method you would fire an event lets say "OnWindowClosed" and then have your game class subscribe to that event.

That way you could theoretically have any class that needs to know the game is shutting down subscribe to the event and do whatever it needs to do when OnWindowClosed is triggered.

This way the subscriber (Game class) doesn't need to know anything about the publisher(Input Manager) other than it did something it may want to "respond" to.

Here is an example from my project, the ActorManager needs to listen for the OnMapLoad Event Triggering from MapManager in order to spawn the Actors into the scene after its been generated.

```
public class EventManager
{
    //define a delegate signature, the variables need to match up the event trigger
    public delegate void OnMapLoad(Vector3 mapSize, Dictionary<Vector3, Tile> currentMap);
    //define the event generally prefixed with "On"
    public static event OnMapLoad OnMapLoadCallBack;

    //and here's the event trigger itself
    public static void TriggerOnMapLoad(Vector3 mapSize, Dictionary<Vector3, Tile> currentMap)
    {
        //check to see if OnMapCallBack has subscribers
        if (OnMapLoadCallBack != null)
        {
            //if it does trigger the event with params (or without if you dont define any above)
            OnMapLoadCallBack(mapSize, currentMap);
        }
    }

}

public class ActorManager : MonoBehaviour
{

    public int teams = 2;
    public int teamMembers = 1;
    public GameObject toonPrefab;
    public GameObject aiPrefab;
    public List<Team> teamsList = new List<Team>();
    public Vector3 teamOneSpawn = new Vector3(0, 0, 0);
    public Vector3 teamTwoSpawn = new Vector3(0, 0, 0);
    //I'm using unity and you always want to be sure to subscribe and unsubscribe from events otherwise they will cause memory leaks, I'm simply doing it when the gameobject is instantiated and when it's disabled/removed
    void OnEnable()
    {
        //here I'm subscribing to the event and assigning the function Init to fire when the event is triggered, notice again the parameters must match the delegate you define
        EventManager.OnMapLoadCallBack += Init;
    }

    void OnDisable()
    {
        //unsubscribing here
        EventManager.OnMapLoadCallBack -= Init;
    }

    void Init(Vector3 mapSize, Dictionary<Vector3, Tile> currentMap)
    {
        CreateTeams(mapSize);
    }

public class MapManager : MonoBehaviour
{
    public void GenerateMap(BiomeData biome)
    {
        CreateFloor(biome);
        AddDecorations(biome);
        AddTrapTiles(biome);
        AddEnviroment(biome);

        //this is where I call the event from the Map Manager to let the Actor Manager know the map has finished loading
        EventManager.TriggerOnMapLoad(mapSize, currentMap);
    }
}

```
> 1 votes

---
Tags: architecture, game-loop
---


# Question
Title: How can I generate the smallest enclosing sphere from a mesh?
I have a polygon which is defined by a set of vertices and I need the smallest sphere encompassing the mesh.

The spheres are defined by a position vector (x,y,z) and a radius.

Is there an algorithm that given a solid collision mesh with no holes generates the smallest sphere that encompasses a solid collision mesh with no holes in all cases

---

This is not a duplicate of this question because the question is only about a sphere encompassing a polygon soup a. I'm asking if there is an algorithm that given any solid collision mesh with no holes generates the smallest sphere that encompasses a solid collision mesh in all cases.

# Answer
## Solving the bounding sphere problem

Computing the bounding sphere for a set of given vertices means solving the minimum covering circle problem in three dimensions. There're many algorithms out there to find such a bounding sphere, like Welzl's algorithm (at this page you can find an implementation in Java), and many others. You can also check out Fischer's exact solver the open source Miniball algorithm is based on.

The minimum enclosing sphere problem can be solved with an average algorithmic complexity of *O(n4)* for a naive algorithm working on free vertices, down to an easy *O(nk)* where *k* is the number of vertices of the equivalent convex hull of your starting mesh.

**Edit:** such linear-time solution is optimized for a convex set of vertices *only*, because further assumptions can be made due to geometric properties of convexity. A mesh with just no holes isn't *necessarily* convex; for example, a *C*-shaped mesh has no holes, but it isn't convex either – you can connect its two edges with a segment, and part of it will lie outside the shape. A solid mesh may have fewer vertices to compute compared to a "holed" counterpart (and the CPU will be happy about it), but solidity doesn't imply convexity. Thus such mesh isn't eligible for the optimized algorithm mentioned above.

## Consideration: exact vs. approximate solutions

As developers, we should be aware of many aspects in our games. Highly-detailed simulations (e.g. physics) or rich graphics imply a greater workload on CPU/GPU; on the other hand, prioritizing performances excessively may lead to a poor game experience due to low quality of simulation.

As **coders**, we must not waste resources when possible; we can optimize some operations in order to spend spare resources elsewhere if needed. As **designers**, we must define the minimum requirements for our game without being too greedy: a side-scrolling platformer will *never* need the same precision of physics simulation we expect from a top-quality racing game.

We need tradeoffs between results expected and resources required; every CPU clock is precious. If we can sacrifice some little realism without having the player noticing it and gain overall performances, this is a good way to go in my opinion.

## An approximate, efficient algorithm

Having already aswered your question, if you don't really need the smallest sphere possible and an approximation of it is good enough, you can go with this algorithm.

```
algorithm MiniBall
    input: set V of points in space
    output: enclosing sphere in the form [center, radius]

    B = AABB(V)                // AABB from vertices
    C = mean(B.max + B.min)    // centroid of box B
    for each v in V:
        r = max(r, dist(C, v))        // distance to furthest point
    return [C, r]

```

The main idea is:

* Consider the axis-aligned bounding-box, and use its centroid as *origin*. This ensures the sphere center will be always amongst the vertices;
* Find the distance from the centroid to the furthest vertex, and use such distance as *radius*. This ensures that no points will lie outside of the sphere, *at most* on the sphere surface.

The complexity of this algorithm is *O(n)* where *n* is the number of vertices: you first read all vertices to find the bounding box corners, then you compute *n* distances between centroid and individual vertices.

It's quite fast, and may be more suitable for a real-time application with average precision requirements, such as a videogame.

**Bonus:** you can tweak the code line computing distance, and use the criterion that better suits your needs:

* **Max distance:** no points outside of the sphere, at least one on the surface;
* **Min distance:** no points inside the sphere, at least one on the surface (not really recommended in most cases);
* **Average distance:** compute both the larger and smaller radii, and use `mean(minR, maxR)` as sphere radius. On average the sphere will split the vertices set into two halves. Some points may be inside the sphere, others outside of it, some can lie on the surface.
> 7 votes

# Answer
Here is what I came up with after some feedback from @nwp.

> * set the radius to 0
> * set the center to the first vertex.
> * add the radius incrementally to the absolute distance between the first point and each point on the mesh.
> * add the center incrementally to the radius halved.
> * add the entities position to the mesh.

For more info see this thread on chat.
> 0 votes

---
Tags: 3d, algorithm, mesh, sphere
---


# Question
Title: Loading sprite resources from nested folders
This is how I try to load my sprite images:

```
 sprite Sprites[];

 void Start() {
    ...
    Sprites = Resources.LoadAll<Sprite>("Card/AnimalImages");
    Debug.Log("Sprite name: " + Sprites[8].name);
    ...
 }

```

But it gives me the error that you can see in the picture below. Note that in the same figure there is a hierarchy of folders on the right side. I put two ellipsis in the code because it is actually much longer than what I posted, but I assure you that the script is correctly attached to the object and it generally works.

The problem is that it doesn't load the sprites as I expect: the debugger hangs at the point where the `Debug.Log(...);` is executed (precisely when it tries to access the Sprites vector which is probably empty).

It's the first time in Unity3D where I need to load the sprites in that way. I tried to look in some previous posts, probably I will have missed someone, but in those found until now no one has helped me.

Can someone help me to understand how to load the sprites and especially where is my mistake?

---

> Update

I tried to check if could be a problem of static/dynamic arrays, but it seems not to be a problem of this type, in fact following code:

```
    Sprites = new ArrayList(Resources.LoadAll<Sprite>("Card/AnimalImages"));
    Debug.Log("Size of dynamic array: " + Sprites.Count);

```

prints:

*Size of dynamic array: 0*

# Answer
> 2 votes
When in doubt, always read the docs for the methods you're using:

> ## Description
>
> Loads all assets in a folder or file at path in a **Resources folder**.
>
> If path refers to a folder, all assets in the folder will be returned. If path refers to a file, only that asset will be returned. The path is relative to any **Resources folder** inside the Assets folder of your project.

(Emphasis added)

So when you call `Resources.LoadAll<Sprite>("Card/AnimalImages")`, Unity looks for files in a folder path like `Assets/.../Resources/Card/AnimalImages`. Because you have no such path in your project, it finds nothing, and gives you an array of zero length.

If there are assets that you want to load dynamically through code, you need to put them under a folder called `Resources` so that Unity knows to package them up into the built game, even if it doesn't see them referenced in any scenes.

# Answer
> 0 votes
Since you don't know the amount of sprites in the folder (i'm assuming you are not checking that). I would recommend to use a Dynamic array instead of a regular one, this comes at the cost of little bit performance but as long as that's ok I see no benefit of having a normal array over a dynamic. With dynamic you can add and remove sprites as you please and it also makes it easier to search etc.

Edit: could also be that the images is not imported as sprites and the Resources.LoadAll finds 0 elements

---
Tags: unity, sprites, loading, filesystem
---


# Question
Title: Find extreme points of a rotated ellipse function on a given axis
How to find the points where it is most extreme on the X and Y axis?

For example lets say I have an equation that describes an ellipse that is rotated:

```
(x * RadiusX * Rx + y * RadiusX * Ux)^2 +
(x * RadiusY * Ry + y * RadiusY * Uy)^2 = RadiusY^2

```

How can I find the points where it will be most extreme on each axis

Please keep in mind the values for variables RadiusX, RadiusY, Rx, Ry, Ux, Uy are known.

An example with values:

```
((x * 1 * 0.70711) + (y * 1 * -0.70711))^2 +
((x * 1.414213 * -0.70711) + (y * 1.414213* -0.70711))^2 = 1.414213 * 1.414213

```

# Answer
> 1 votes
A trick I find often helps with ellipses is to think of them as stretched/rotated copies of the unit circle.

By reversing the transformation, we can map the problem back onto the unit circle, where the math is usually easier, then run the answer back through the transformation to answer our original question about the ellipse.

To roughly outline the steps:

1. Find the transformation matrix that maps the unit circle to your ellipse, then compute its inverse
2. Apply its inverse to vectors along the horizontal and vertical axes (1, 0) & (0, 1) - these give you the directions of the edges of the blue bounding box, after it's been squashed to a diamond.

Our extreme points in our original coordinate system map to where these slanted lines are tangent to the circle.
3. Take the perpendiculars of these transformed directions (green lines in the diagram above) and normalize them to unit length to snap them onto the unit circle. These are the points of tangency.
4. Apply your transformation matrix to these tangent points to map them back to the extremes in our original coordinate system.

# Answer
> 2 votes
The general equation of an ellipse centered at the origin is:

$$(ax+by)^2+(cx+dy)^2=r^2$$

Expand w.r.t x and y:

$$(a^2+c^2)x^2+(b^2+d^2)y^2+2(ab+cd)xy=r^2$$

An horizontal line has equation y=k. Either it intersects with the ellipse in two points, or it intersects in only one point (it's tangent), or it doesn't intersect at all. We find the intersection by solving the trinomial (in x):

$$(a^2+c^2)x^2+2(ab+cd)kx+(b^2+d^2)k^2-r^2=0$$

There is only one intersection when the discriminant is zero, hence you want to find k such that

$$4(ab+cd)^2k^2-4(a^2+c^2)(b^2+d^2)k^2+4(a^2+c^2)r^2=0$$

Expand and simplify:

$$\left(a^2b^2+c^2d^2+2abcd-a^2b^2-a^2d^2-b^2c^2-c^2d^2\right)k^2+(a^2+c^2)r^2=0$$

$$(2abcd-a^2d^2-b^2c^2)k^2+(a^2+c^2)r^2=0$$

$$(ad-bc)^2k^2=(a^2+c^2)r^2$$

$$k=\pm\frac{r\sqrt{a^2+c^2}}{|ad-bc|}$$

The positive k is the maximum value of y, the negative the minimum value. By symmetry of the ellipse, they are opposite.

---

The extreme values of x can be found the same way, using a vertical line x=l. The same computation will lead to

$$l=\pm\frac{r\sqrt{b^2+d^2}}{|ad-bc|}$$

The positive l is the maximum value of x, the negative the minimum value. Again, by symmetry of the ellipse, they are opposite.

---

The expressions found are not defined when ad=bc, but then the two squares in the original equation are proportional and the conic is degenerate (the equation leads to two parallel lines).

---
Tags: geometry, linear-algebra, graph
---


# Question
Title: Need help understanding ms to fps for a Unity animation
I'm trying to create an animation in Unity (2018.1.1f1) and can't understand how to proceed.

I have a 3 sprites which I need to order like so : 1 2 3 2 (then repeat). The first and third sprites should have a 640ms delay and the second sprite should be 80ms.

In the animation window, I don't understand how to translate that into fps on the animation timeline.

What sample should I choose and where I need to put each sprites on the timeline to get the 640 and 80ms specified?

# Answer
# Frame rate is a nebulous thing

First thing to understand: the frame *rate* is going to be "however many frames the game can manage in the specified time interval." Typically games try to achieve 60 frames per second, though others aim for 30 for one reason or another.

And any given frame may not occur with the exact same time taken as the previous or the next frame. For example, to achieve 60 frames per second, each frame would need to compute and render in 16.666 milliseconds. But if one frame takes 15, and the next two take 17, then...well, your average across those three frames is 16.666, everything's fine.

Fine, except for your "it has to be exactly 80ms" animation, which would be visible for 4.8 frames, not 5 frames, as that would be 83ms: 3ms too long. You're just going to have to live with this. Also, 80ms is *really short.* I suspect that most people won't even recognize this middle frame unless they actively pay attention to the sprite. Its slow enough to be visible, (ie. below the Flicker Fusion Threshold) but too fast to notice at a glance and react to.

In any case, lets look at this window:

The timeline across the right there is timed out in *seconds,* so your animation will start and finish in about a second and a half (1440ms).

So, measuring things out, you want your transition points about here:
> 1 votes

---
Tags: unity, 2d, animation, sprites, frame-rate
---


title: Sobel Edge Detection on Depth Texture

text:
# Question
Title: Sobel Edge Detection on Depth Texture
I'm currently trying to implement contour shading via edge detection on a depth texture.

I'm rendering the color and depth information onto two textures. In my post processing shader I do the following:

```
out vec4 FragColor;
in vec2 TexCoords;
uniform sampler2D colorTexture;
uniform sampler2D depthTexture;
uniform float far;
uniform float near;

```

Then the matrices for the sobel filter:

```
mat3 sobel_y = mat3(
     1.0, 0.0, -1.0,
     2.0, 0.0, -2.0,
     1.0, 0.0, -1.0
);

mat3 sobel_x = mat3(
     1.0, 2.0, 1.0,
     0.0, 0.0, 0.0,
    -1.0, -2.0, -1.0
);

```

The function to linearize the Depthvalue

```
float LinearizeDepth(float z)
{
     float n = near;
     float f = far;
     return (2.0 * n) / (f + n - z * (f - n));
}

```

In the main I'm filling the matrix to calculate the gradients and then substract the result of the diffuseColor to get Black if the gradient is high (an edge) and just output the diffuseColor if the gradient is low.

```
void main()
{
    vec3 colorDiff = texture(colorTexture, TexCoords).rgb;
    mat3 I;
    vec3 texel;
    for (int i=0; i<3; i++) {
        for (int j=0; j<3; j++) {
            float depth = LinearizeDepth(texture(depthTexture, TexCoords + vec2(i-1, j-1)).r);
            I[i][j] = depth;
        }
    }

    float gx = dot(sobel_x[0], I[0]) + dot(sobel_x[1], I[1]) + dot(sobel_x[2], I[2]);
    float gy = dot(sobel_y[0], I[0]) + dot(sobel_y[1], I[1]) + dot(sobel_y[2], I[2]);

    float g = sqrt(pow(gx, 2.0)+pow(gy, 2.0));

    FragColor = vec4(colorDiff - vec3(g), 1.0);
}

```

My problem is that g is always 0 since i just the the normal color as output.

If i just output the depth values it does look correct:

Any Idea what I'm doing wrong here?

# Answer
Here's your problem:

```
for (int i=0; i<3; i++) {
    for (int j=0; j<3; j++) {
        float depth = LinearizeDepth(texture(depthTexture, TexCoords + vec2(i-1, j-1)).r); I[i][j] = depth;
    }
}

```

Texture coordinates are usually in the range 0...1, where 0 on the x axis is the left edge of the texture and 1 is the right edge, regardless of the resolution of the texture.

So when you add/subtract 1 from the texture coordinate, you're not nudging the sample over by one pixel, you're jumping the entire width of the texture. If the wrap mode is set to repeat, then you're wrapping all the way around the texture and back to the same spot.

So naturally your Sobel filter doesn't find an edge: it's presented with a grid of 9 identical samples, the same as it would see in a field of a single flat colour.

Instead, you'll want to offset your samples by ±1/(texture size) to move only one pixel over.
> 5 votes

# Answer
I'm not sure I entirely understand your question, but I think you can take the gradient of the depth that you've calculated in `g` and use that as an overlay for the color you sampled from the color channels. Perhaps something like this (untested):

```
float inkAmount = g / kMaxGradientValue;

```

Then mix the color texture with black (or whatever color your outline ink is) via something like this:

```
FragColor = mix(colorDiff, inkColor, inkAmount);

```

In the above `kMaxGradientValue` is the maximum value that the gradient can have. It's been a while since I've worked with Sobel operators, but I think the max is something like `sqrt(18) = ~4.24`, assuming your R, G, & B are all in the 0-1 range.

You might need or want to adjust the white and black points of the ink amount to deal with noise and small variations in the gradient.
> 0 votes

---
Tags: opengl, shaders
---


# Question
Title: Does pausing the canvas draw restores the FPS to higher value in a HTML5 game?
I set Frame Per Second of 60 for my game. But after 1 minute it gets to a significantly lower value - around 8 FPS.

Does pausing the canvas drawing restores the FPS to higher value? If it does, how much time is enough to pause the game in order to get 60 FPS again?

# Answer
> 1 votes
I don't think you have the proper approach to your issue.

Typically, if a game starts to go slower and slower, it's because you add stuff to it over time and it's not able to process everything in a timely fashion. If there is too much stuff from the beginning, the frame rate will be low but constant from the beginning.

Even if "pausing" a game to "let the frame rate catch up" or to "restore the FPS" seems to work to solve your current issue, it will not fix the underlying problem. It is not a good solution and your players will really not like that.

I suggest you use a JavaScript profiler (I did not test this one myself, but it could be useful to you) to inspect the behaviour of your code, and from there determine what's causing the issue.

# Answer
> 0 votes
It does restore(very slowly) the FPS but it wasn't the correct approach to my problem. The correct approach is to use webgl in order to utilize GPU.

---
Tags: javascript, html5, css, easeljs
---


# Question
Title: OpenGL Array Texture generates black texture
I am creating a game using OpenGL that has many textured cubes. I am trying to use an Array Texture to load multiple textures from one file. I tried to setup my texture atlas; however, all that renders is a black texture. I'm not sure what exactly I am doing wrong.

Here is the texture loading code:

```
    // Load image
    stbi_set_flip_vertically_on_load(true);
    unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0);
    // Generate texture object
    glActiveTexture(GL_TEXTURE0);
    glGenTextures(1, &textureId);

    glBindTexture(GL_TEXTURE_2D_ARRAY, textureId);

    // Actually load texture
    if (data) {
        glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, width, height, 0, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        //glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
    } else {
        std::cout << "Failed to load " << path << " texture" << std::endl;
    }

    // set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    // Free memory
    stbi_image_free(data);

```

Here is my fragment shader

```
#version 330 core
out vec4 FragColor;

in vec2 TexCoord;

uniform sampler2DArray my_sampler;

void main()
{
    FragColor = texture(my_sampler, vec3(0, 0, 1)) * vec4(1.0f);
}

```

Here is my texture file:

Does anyone know how I can solve my issue?

# Answer
> 2 votes
That's just not how array textures work. You can't load a texture atlas as an array texture; how would OpenGL know where one array layer ends and the next begins?

2D array textures have 3 dimension: width, height, and number of layers

Also, you're getting a blank texture because your `glTexImage3d` call passes *zero* for the number of layers. Which produced an OpenGL error that you didn't notice.

But more than that, 2D array textures are sequences of 2D images, not a single 2D image with subrectangles in it. So you are expected to upload pixel data with "number of layers" worth of *separate* 2D images.

So you need to readjust your texture data. You have to break it up into distinct images, and then transfer them into the array texture (either all at once in a big 3D buffer, or each one individually with multiple `glTexSubImage3d` calls).

# Answer
> 0 votes
First thing you wanna do when things don't work in OpenGL (or any API really): check whether some operation raised an error. In OpenGL, this is done by calling `glGetError()`.

Starting with OpenGL 4.3, there's also a mechanism to get debug messages from the graphics driver, which will give you more detailed information about what's going on and, particularly, what's going wrong. You need to have a debug context to get debug messages. If you do not handle context creation yourself but use a library such as, e.g., GLUT or GLFW, consult the documentation of that library to find out how to have it create a debug context for you (may not be supported by all such libraries). Assuming you have a debug context, you can register callbacks to receive debug messages. For example (APIENTRY is needed on Windows):

```
void APIENTRY OpenGLDebugOutputCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam)
{
    std::cout << message << std::endl;
}

// ...

glDebugMessageCallback(OpenGLDebugOutputCallback, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);

```

Now to your actual problem: My first guess would be that `glTexImage3D()` simply doesn't do anything because you specify a depth of 0, which means your array texture image has no layers. Apart from that, it should probably be pointed out that your fragment shader ignores the texture coordinates and will simply sample the lower left corner of layer index 1 (also: layer indices start at 0). Finally, I'm not sure what exactly you are planning to use an array texture for. Your image looks like a traditional texture atlas, which you would usually store in a normal 2D texture and select subregions from via texture coordinates. If you want to put subregions of this larger image into separate layers of an array texture, you will generally have to make sure to provide the data to OpenGL accordingly, i.e., one image per layer.

Some other notes concerning your code: I would suggest to be explicit and use a sized internal format such as, e.g., `GL_RGBA8` rather than a generic base format like `GL_RGBA`. Assuming that your image data is sRGB encoded (seems most likely as it comes from a file), I would suggest using `GL_SRGB8_ALPHA8` as internal format. In this case, you will most likely also want to `glEnable(GL_FRAMEBUFFER_SRGB);` to get the colors right. Furthermore, you probably want to at least make sure that the number of channels in the data loaded from the file using `stbi_load()` actually matches the input data format you specify in your call to `glTexImage3D()`.

---
Tags: opengl, c++, textures, rendering
---


# Question
Title: Unity3d 2017 trail renderer behaving weird
Please see the screenshot I attached, I am trying to make skid marks using trail renderer, but one side of trail is going upwards just after it renders, it was working fine Unity 5.4, but when I upgraded it to 2017, it is behaving like this.

# Answer
> 2 votes
What worked for me was to put a script on the trail gameobject, and in `start()` just write:

```
myTrails = gameObject.GetComponent<TrailRenderer>();
myTrails.Clear();

```

That's it. Trails will start fresh when they appear!

# Answer
> 1 votes
Most likely this happens because your object starting point is `(0,0,0)` (world origin), hence the trail is being rendered from that position too.

You should create your object to a given position rather that creating it at the origin and then moving it to another place: this way the origin will not count as a valid coordinate for trail rendering.

If that doesn't work, you can use a different approach: when the object is created, its trail has a `Time` value equal to 0. Next step, you can set `Time` to a desired value, for the very first coordinate (world origin) will not count as timing out in respect of the `Time` value, but the next will because the timer will be greater than 0.

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


# Question
Title: Native crashes on UE4 android game only in distribution build
As I build my game for development mode and install it directly from apk file to my device, it runs without errors and doesn't crash, there are in-game ads and it is able to get variables from game-saves.

But once I build with `Shipping` and `Distribution` tags and upload it to Google Play I get errors on all devices that it is tested. (Installing directly through apk also crashes it.)

Here are backtraces-

```
*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
Build fingerprint: 'motorola/harpia/harpia:6.0.1/MPI24.241-2.35-1/1:user/release-keys'
Revision: 'p1b0'
ABI: 'arm'
pid: 14791, tid: 14855, name: Thread-932  >>> com.MadElectron.FarmPlanet <<<
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0
    r0 00000000  r1 00000000  r2 00000001  r3 00000000
    r4 000084fa  r5 95bd3280  r6 00000000  r7 00002888
    r8 9dbb5fd4  r9 980edb20  sl 96d7f100  fp 9dbb5f88
    ip a274d504  sp 9dbb5f60  lr 9fd0eed4  pc a162ad24  cpsr 20070010
backtrace:
    #00 pc 0344dd24  /data/app/com.MadElectron.FarmPlanet-1/lib/arm/libUE4.so (_ZN22FSessionServicesModule13StartupModuleEv+72)
    #01 pc 01b32058  /data/app/com.MadElectron.FarmPlanet-1/lib/arm/libUE4.so (_ZN14FModuleManager27LoadModuleWithFailureReasonE5FNameR17EModuleLoadResultb+432)
    #02 pc 01b31e98  /data/app/com.MadElectron.FarmPlanet-1/lib/arm/libUE4.so (_ZN14FModuleManager10LoadModuleE5FNameb+76)
    #03 pc 0196bee8  /data/app/com.MadElectron.FarmPlanet-1/lib/arm/libUE4.so (_ZN11FEngineLoop4InitEv+1752)
    #04 pc 0196aa10  /data/app/com.MadElectron.FarmPlanet-1/lib/arm/libUE4.so (_Z11AndroidMainP11android_app+2568)
    #05 pc 0196e618  /data/app/com.MadElectron.FarmPlanet-1/lib/arm/libUE4.so (android_main+108)
    #06 pc 01981bc8  /data/app/com.MadElectron.FarmPlanet-1/lib/arm/libUE4.so
    #07 pc 00041acb  /system/lib/libc.so (_ZL15__pthread_startPv+30)
    #08 pc 00019355  /system/lib/libc.so (__start_thread+6)

```

# Answer
Transfering to 4.19.2 solves the problem
> -1 votes

---
Tags: android, unreal, google-play
---


# Question
Title: OpenGL ES 2.0 cannot understand how to use 2D ortho projection and shaders
I am migrating an app that draws on OpenGL ES 1.0 to OpenGL ES 2.0.

The app used to draw multiple 2D triangles, as a vertex array, where the vertices matched the pixels on screen.

I made a sample project to reproduce the problem.

The data

```
static ShortBuffer provideData() {
    final ByteBuffer data = ByteBuffer.allocateDirect(12 * BYTES_PER_SHORT);
    data.order(ByteOrder.nativeOrder());

    final ShortBuffer floatData = data.asShortBuffer();
    floatData.put(new short[]{
            351, 22, 361, 22, 361, 32, 351, 22, 351, 32, 361, 32
    });

    return floatData;
}

```

OpenGL 1.0: **works as expected**:

```
final class FirstGenRenderer implements GLSurfaceView.Renderer {

    private static final int VERTICES_PER_PARTICLE = 6;

    private final ShortBuffer coordinates = DataProvider.provideData();

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();

        final int color = Color.DKGRAY;
        gl.glClearColor(
                Color.red(color) / 255f,
                Color.green(color) / 255f,
                Color.blue(color) / 255f, 0f);

        final int particleColor = Color.WHITE;
        gl.glColor4f(
                Color.red(particleColor) / 255f,
                Color.green(particleColor) / 255f,
                Color.blue(particleColor) / 255f, 0f);
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        gl.glViewport(0, 0, width, height);
        gl.glOrthof(0, width, 0, height, 1, -1);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

        coordinates.position(0);

        gl.glVertexPointer(2, GL10.GL_SHORT, 0, coordinates);
        gl.glDrawArrays(GL10.GL_TRIANGLES, 0, VERTICES_PER_PARTICLE);

        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    }
}

```

The output: clear color and a small white square at the bottom

The same implementation on GL 2.0: **does not produce desired results**:

```
package com.doctoror.ortho;

import android.graphics.Color;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.support.annotation.NonNull;

import java.nio.ShortBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public final class SecondGenRenderer implements GLSurfaceView.Renderer {

    private static final int COORDINATES_PER_VERTEX = 2;
    private static final int VERTICES_PER_PARTICLE = 6;

    private static final String VERTEX_SHADER_CODE =
            "uniform mat4 uMVPMatrix;" +
                    "attribute vec4 vPosition;" +
                    "void main() {" +
                    "  gl_Position = uMVPMatrix * vPosition;" +
                    "}";

    private static final String FRAGMENT_SHADER_CODE =
            "precision mediump float;" +
                    "uniform vec4 vColor;" +
                    "void main() {" +
                    "  gl_FragColor = vColor;" +
                    "}";

    private final ShortBuffer coordinates = DataProvider.provideData();

    private final float[] mvpMatrix = new float[16];
    private final float[] projectionMatrix = new float[16];
    private final float[] viewMatrix = new float[16];

    private int program;

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        final int vertexShader = loadShader(
                GLES20.GL_VERTEX_SHADER,
                VERTEX_SHADER_CODE);

        final int fragmentShader = loadShader(
                GLES20.GL_FRAGMENT_SHADER,
                FRAGMENT_SHADER_CODE);

        program = GLES20.glCreateProgram();
        GLES20.glAttachShader(program, vertexShader);
        GLES20.glAttachShader(program, fragmentShader);
        GLES20.glLinkProgram(program);

        final int color = Color.DKGRAY;
        GLES20.glClearColor(
                Color.red(color) / 255f,
                Color.green(color) / 255f,
                Color.blue(color) / 255f, 0f);
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES20.glViewport(0, 0, width, height);

        Matrix.orthoM(projectionMatrix, 0, 0f, width, 0f, height, 1, -1);

        Matrix.setLookAtM(viewMatrix, 0, 0f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f);
        Matrix.multiplyMM(mvpMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        GLES20.glUseProgram(program);
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

        final int positionHandle = GLES20.glGetAttribLocation(program, "vPosition");
        checkGlError("glGetAttribLocation");

        GLES20.glEnableVertexAttribArray(positionHandle);
        checkGlError("glEnableVertexAttribArray");

        coordinates.position(0);

        GLES20.glVertexAttribPointer(
                positionHandle,
                COORDINATES_PER_VERTEX,
                GLES20.GL_FLOAT,
                false,
                0,
                coordinates);

        checkGlError("glVertexAttribPointer");

        final int colorHandle = GLES20.glGetUniformLocation(program, "vColor");
        checkGlError("glGetUniformLocation");

        final float[] color = new float[]{1f, 1f, 1f, 1f};
        GLES20.glUniform4fv(colorHandle, 1, color, 0);

        final int mvpMatrixHandle = GLES20.glGetUniformLocation(program, "uMVPMatrix");
        checkGlError("glGetUniformLocation");

        GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false, mvpMatrix, 0);
        checkGlError("glUniformMatrix4fv");

        GLES20.glDrawArrays(GL10.GL_TRIANGLES, 0, VERTICES_PER_PARTICLE);
        checkGlError("glDrawArrays");

        GLES20.glDisableVertexAttribArray(positionHandle);
    }

    private static int loadShader(final int type, @NonNull final String shaderCode) {
        final int shader = GLES20.glCreateShader(type);

        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);

        return shader;
    }

    private static void checkGlError(@NonNull final String glOperation) {
        int error;
        if ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
            throw new RuntimeException(glOperation + ": glError " + error);
        }
    }
}

```

The output: a clear color.

Expected output: as with GLES10, above.

# Answer
> 0 votes
I have accidentally copy-pasted `GL_FLOAT` instead of `GL_SHORT` for my `glVertexAttribPointer`.

```
GLES20.glVertexAttribPointer(
    positionHandle,
    COORDINATES_PER_VERTEX,
    GLES20.GL_FLOAT, // With the sample data, SHOULD BE GL_SHORT
    false,
    0,
    coordinates);

```

---
Tags: opengl-es, opengl-es2
---


# Question
Title: Renderer.material assignment not working
I have a fairly simple question: I am trying to change an object's material via code with the line

```
rend.material = NewMat;

```

where `rend` is of type `Renderer` (`MeshRenderer` to be specific) and `NewMat` is of type `Material`. Both variables are public and assigned in the inspector and both are not null.

When I now try to assign the material, nothing happens. I don't event get any error. When I look into the inspector I can see that under Materials on my MeshRenderer the material doesn't even change. The line

```
Debug.Log(rend.material == NewMat);

```

outputs `false`.

What am I doing wrong?

# Answer
Are you absolutely sure that you're using `rend.material` when trying to change the material?

I'm asking because, if you do something like this:

```
using UnityEngine;

public class ChangeMaterial : MonoBehaviour {
    public Material NewMat;
    public Material ObjMat;
    public Renderer Rend;

    private void Awake() {
        Rend = GetComponent<Renderer>();
        ObjMat = Rend.material;
    }

    private void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            ObjMat = NewMat;
        }
    }
}

```

the material won't change, but it will if you use:

```
private void Update() {
    if (Input.GetKeyDown(KeyCode.Space)) {
        Rend.material = NewMat;
    }
}

```

(and note that in this case, `ObjMat` won't change in the Inspector, this is because `ObjMat = Rend.material` will pass the material by value and not by reference).
> 0 votes

---
Tags: unity, materials
---


# Question
Title: Does GL Memory model guarantees that late Depth Testing accesses depth buffer values in same draw call
Suppose I issue a draw command that draws 3 overlapping triangles (T1, T2, T3). Fragment shader assigns Depth = 3 to T1 fragments, 2 to T2 and 1 to T3 fragments. Depth Buffer is cleared to 0 before draw call. GL Test is set to GL\_Less.

Now, when pixels for triangle 2 are depth tested by the hardware, is it guaranteed that hardware will read the latest written values i.e 3 (by T1 fragments)?

# Answer
> 1 votes
OpenGL doesn't have a "memory model", that's implementation-dependent (i.e. up to the driver).

However, the specification states (page 9):

> Commands are always processed in the order in which they are received...

Therefore if you issue three draw calls, the three draw calls are processed in the order in which you issue them.

Furthermore, individual vertices in each single draw call are also processed in the same order they appear in your source buffers, again from the specification but this time page 8:

> Data such as positional coordinates, colors, normals, texture coordinates, etc. are associated with a vertex and each vertex is processed independently, in order, and in the same way.

Note that some drivers may be a little "creative" about this, and behave *as if* commands or vertices were processed in order; typically this would be a performance optimization (e.g. for parallel processing) and anything you may do that depends on them *actually* being in order might disable that optimization. How much of a factor that is would vary from application-to-application and from driver-to-driver so general guidance can't really exist.

---
Tags: opengl, graphics-programming
---