# Question
Title: Synchronizing actions with animations across network
I'm working on a project which allows players to take actions in time-limited turns. All players are connected to a central server, which is authoritative. That means the server sends info that a turn for given player has started and the time remaining to take an action. This leads to problems when client-side animations are involved. Each action has an associated animation, which takes some time to complete. The player should be able to initiate the action within given time, and the next player show start his turn when any animations complete. Obviously, the server has no notion of animations, but still needs to take them into account and start the next turn at proper time point. I'm not sure how to solve this problem. Possible solutions I came up with:

**Constant animation time and built-in delay**

The server will have a built-in delay after an action has been taken, before starting the next turn. Problems:

* seems an artificial construct
* animation times need to be exact

**Not waiting for animations**

The server can simply broadcast action effects without any delay, and go to the next turn. Problems:

* will look very strange for the players since the effects will become visible before the animation completes
* possible overlapping animations across turns

**Sending actions along with animation times**

The client can send the animation time for given action, which the server will use as a delay for the next turn. Problems:

* obvious cheating possibility (players can use the delay for "extra time")

So, given above, all my ideas are simply bad. Therefore the question remains: is there an existing solution for such class of problems?

# Answer
> 0 votes
Solution 1 et 2 seems legit to me ! It goes like this :

1. **Player A** choose an action / animation starts on his client.
2. Server receive the information and send it to **Player B**.
3. **Player B** receive the information and animation starts on his client.

Even if you don't know the length of your animations, *which you should*, just wait for the animations to be over client side to know when the turn is over.

Hope this help !

---
Tags: animation, networking
---


# Question
Title: Weird issue with Member Initializers C++
I'm making a game with C++ and SDL2. I have a class called "text" and a class called "buttonObj"

The constructor of "text" is a void function that takes an SDL\_Color variable.

The first part of buttonObj looks like this:

```
string textContent;
text buttonText;
text highlighted_buttonText;

//Constructor
buttonObj(string tex, SDL_Color notHighlighted, SDL_Color highlighted) :
  textContent( tex ),
  buttonBase( img ),
  buttonText( notHighlighted ),
  highlighted_buttonBase( hI ),
  highlighted_buttonText( highlighted )
{}

```

Currently, this works, but I don't exactly know WHY it works. With a constructor initializer, the value outside the parenthesis gets assigned to the value within the parenthesis. So, how come an SDL\_Color (i.e "notHighlighted") can get assigned to a text variable? (i.e buttonText)

I assume this is because with a class, the variable inside the parenthesis is a parameter of the constructor of that class. So, since the constructor of text takes an SDL\_Color variable, the program treats "notHighlighted" as a parameter, rather than the regular one-line initializer. Right?

Speculation Aside, this works. From my console, I can see **two "text" instances are constructed**, one for "highlighted" and one for "notHighlighted". **Once the texts are constructed, they remain as they should and render as they should later on in the code.**

However, this isn't what I want... Instead of passing an SDL\_Color into the constructor and having buttonObj turn the color into text, (via constructing it) I want to load some text beforehand (elsewhere during runtime) and pass the text into buttonObj directly. Like so:

```
string textContent;
text buttonText;
text highlighted_buttonText;

//Constructor
buttonObj(string tex, text notHighlighted, text highlighted) :
  textContent( tex ),
  buttonBase( img ),
  buttonText( notHighlighted ),
  highlighted_buttonBase( hI ),
  highlighted_buttonText( highlighted )
{}

```

According to my knowledge of what one line initializers are SUPPOSED to do, "highlighted\_buttonText" should become equal to the parameter "highlighted." So "highlighted\_buttonText" is set to whatever the parameter "highlighted" is, **since they're both of type "text"**

However, this doesn't work. In my console, I see that the texts are constructed and then destructed! As if something is calling the destructor... this means that the variables don't work fine later on in the code. (And then I get a bunch of exceptions in the library I'm using for text rendering. It's a text chaching library based on SDL\_TTF called SDL\_FontCache)

I know this is a hard issue to explain and I might not be describing it well. But please, any advice would be awesome! Weird problems like this irk me...

# Answer
With your first chunk of code, you use the *initializer list* to *construct* the class variables. So in this case, a *copy* of `notHighlighted` is passed to the constructor of `buttonText` during the construction of the instance of `buttonObj`. The values are not *assigned*, they're *copied*. For trivial objects like SDL\_Color, it's not really an issue.

In your second code chunk, you get stuff deleted because the *copy constructor* of `buttonText` is called to construct `buttonText` from `notHighlighted`. Once the copy is done (i.e. once `buttonText` is constructed from `notHightlighted`), the copy (which is notHighlighted) is deleted (i.e. the destructor is called). If `notHighlighted` had references to stuff allocated by SDL, and the destructor has SDL deallocate that stuff, and the copy constructor of `text` did not make proper clones of these items, the references pointed by `buttonText` will be no longer valid.

To avoid that, you have a couple of options:

* Make sure that `text` creates appropriate copies of referenced SDL objects when copy-constructed.
* Use raw pointers and make sure you know when you should delete the text. (This is doable but requires great care to avoid memory leaks.)

```
string textContent;
text* buttonText;
text* highlighted_buttonText;

//Constructor
buttonObj(string tex, text* notHighlighted, text* highlighted) :
  textContent( tex ),
  buttonBase( img ),
  buttonText( notHighlighted ),
  highlighted_buttonBase( hI ),
  highlighted_buttonText( highlighted )
{}

```
* Use shared pointers so that the object is properly deleted when no longer in use. (This is one of the favoured methods.)

```
string textContent;
std::shared_ptr<text> buttonText;
std::shared_ptr<text> highlighted_buttonText;

//Constructor
buttonObj(string tex, std::shared_ptr<text> notHighlighted, std::shared_ptr<text> highlighted) :
  textContent( tex ),
  buttonBase( img ),
  buttonText( notHighlighted ),
  highlighted_buttonBase( hI ),
  highlighted_buttonText( highlighted )
{}

```

---

> I see that the texts are constructed and then destructed

Instead of just spamming the console with "text::ctor" and "text::dtor" when constructed and destructed, also output the address of the object (i.e. the `this` pointer) you'll see a bit more *what object* is actually being constructed and destructed.

And as always, even if outputing data to the console is one of the best way to debug, a good step-by-step debugger is very nice to have and use in such cases.
> 2 votes

---
Tags: c++, sdl
---


# Question
Title: How to generate doorways procedurally, on the fly, and guarantee acessibility
I'm currently creating a spaceship exploration game, and I have a massive problem I've been trying to solve for months, and through the rest of my group deciding to opt for a rewrite to fix some massive spaghetti.

Anyway, the problems goes as follows:

The player starts in a room, from which they can travel to some other adjacent rooms through doorways.

These doorways are stored in a map of the direction they're in, and the doorway object they reference. Each Doorway object keeps track of the two rooms it links, and will direct the player to each one when necessary.

However, all rooms need to be accessible by at least one route, and going through a doorway on the starboard side means that the other room needs to have the same doorway on the port side. I can do this by just having every wall be a door, but that gets boring to explore.

Pre-generating these proved enough of a glitchy mess for me to fail it, but now, the spec has changed. The world will be theoretically infinite, and as such, the pathing cannot be pre-generated, and instead must be done as new rooms are needed, or expected to be requested soon.

So I need to generate what is essentially a maze, with loops allowed, drawn on a grid, one square at a time, where not only is every room not directly aware the others exist, but acessible from every other. On top of this, going through a doorway on one side of a room means that the same doorway needs to be on the opposite side of the next room.

What's a good way to guarantee all these properties? I am willing to part with rooms having no knowledge of others, but would rather keep it this way for ease of re-generating a room's type later, should that become necessary.

Below is a text file ascii mockup of a 5x5 example I created https://pastebin.com/EtdAWAwD Lines are walls, Xs are doors, and the S is the player starting position.

Any advice at all is appreciated, even on alternate routes to consider for generating these.

# Answer
There's *many* ways to do this - there's even a wikipedia article on it.

Googling for stuff like "Prim's Algorithm maze", "Kruskal's Algorithm maze" etc leads to a bunch of sample code and youtube videos.

For your requirement of needing something that scales to an infinite world, I think the "recursive subdivision" method would be easiest, although there are definitely visible grid alignment if the player is looking at the map. You should be able to place the gaps in the grid through some fixed deterministic hash so that you can re-generate the same maze at the same location every time.
> 4 votes

# Answer
When your world is supposed to grow indefinitely, then Prim's Algorithm and Kruslak's Algorithm won't help you, because they operate on a field of known size.

What you can do instead is grow your maze by starting with a single room and then keep attaching new rooms randomly to the border of the maze. You do that by picking a random room which still has free edges, generate a new room bordering that edge, and connect the two rooms with a doorway.

That will generate a maze with a tree-shaped topology with the first room as its root. When you want the maze to be able to loop, you can simply check if a newly generated room also happens to borders any other rooms than the one it was generated from, roll a random number for each, and when it's high enough you also connect to that room with another door (how much is "high enough" depends on how many loops you want).
> 4 votes

# Answer
You could try that:

Whenever a room needs to be generated (say, it's in some proximity `r` and is not yet generated) at `(x,y)`

1. find all doors to the 'void' in the radius `R` from `(x,y)` (it can be in any measure). If none is found then create a door connecting to `(x, y)`
2. generate a maze starting from any position found in 1, filling the 'void' in the whole region of radius `R` around `(x, y)` (by any algorithm that guarantees connection between any two points, so for example recursive backtracing). If at any point it would create a door to a room outside radius `R` create the door but don't follow it. (So you effectively generate a whole region at once, instead of single room)
3. For the doors found in 1. force the connection from both sides.

You have to choose `R` and the metric empirically for what you need. It could even be possible to procedurally generate a bounding polygon (which is quite easy) each time and use it as the restricting region. That way you put more irregularity into the generator.

One disadvantage of that algorithm is that the shape of the maze is dependent on the order of discovery, so it is impossible to replicate solely by the seed. But I can't think of any other algorithms achieving that that wouldn't be purely probabilistic.

I'll also leave this link https://nothings.org/gamedev/herringbone/ here, maybe it can be useful somehow.
> 0 votes

# Answer
The first thing is to realize it's a graph, and since it's on a grid it mean each node has at least 4 neighbor.

1. Since you have a starting position, using a tree like structures guarantee all room are always reachable. So when generating new room, it should always link to a previous room, this simple rule guarantee there is always a path to the starting point, and since all rooms are connected to the starting room there is always a path to any rooms, because that's how tree works.
2. Now you have a tree, add randomly or using clever tricks, links to another room, and you will have cycle and it stop being a tree.
3. In order to have more maze like features, nest the grid, generate an overall graph, then inside each chunks, run any generative maze algorithm such has it links all of the opening of the master node.
4. It's a game, please don't confuse the player and offer way to understood how it navigate around lol.
> 0 votes

---
Tags: procedural-generation, maze
---


title: 2D Rivers/Lakes in infinite terrain

text:
# Question
Title: 2D Rivers/Lakes in infinite terrain
I've been looking into generating lakes and rivers for a 2D infinite tilemap but I'm stuck with how to handle them for an infinite map.

I can use noise/heightmaps for determining the lakes and the starting points for rivers but for an infinite map I can't use the "flow downhill" or "carve out" technique because the player could come across the river at any point.

If I have a river that's a max of 200 tiles long, I'd have to calculate noise/map values for 33x33 chunks (my chunks are 6x6 tiles) around the player which feels excessive and very inefficient.

I have not found a way to make noise alone work for this, rivers would always be too circular if I find a range narrow enough and they'd encircle lakes, not extend outward.

Calculating voronoi cells and putting rivers at *certain* edges, with some extra noise to make the paths more natural, *might* work.

I just can't seem to find any good examples where they aren't working with known-dimension maps.

# Answer
Take a look at this resource: http://martindevans.me/game-development/2015/12/11/Procedural-Generation-For-Dummies-Roads/

In short, I think you could treat a river in a similar manner as a road in that example. Let's say you are using simple perlin-noise as a heightfield. You can then sample that heightfield at any point to generate an uphill/downhill vector for that location in space using a formula like the one listed below, and you can then use that vector to trace out the route of a river. E.G. start at a random seed position, sample the vector field, step in the direction of the vector, iterate like this until the route has traveled a certain number of steps, or doubles back on itself, or goes uphill, or collides with another route, etc. As will all things procedural, it will take a lot of fiddling to achieve a believable result.

heightfield-to-vectorfield pseudocode:

```
float v = SampleHeightField(position);
float x = SampleHeightField(new Vector2(position.x + .5f, position.y));
float y = SampleHeightField(new Vector2(position.x, position.y + .5f));

Vector2 fieldVector = new Vector2(v-x,v-y);

```
> 1 votes

# Answer
I had this problem, my solution was to replace *causation* with **correlation**. Basically all algorithm try to *cause* a river, ie you have a mountain and you try to find a plausible river path, which is hard. But observation show that river correlate to a *the slope* of a mountain, ie it flows down.

SO why not generating the river first THEN generating the mountain that generate it? Basically the river define the slope of the mountain. It gives you much more power because you can now control events along the river path, it become trivial to add lake, bridge, waterfall, town, just like you generate barrier, lighting, etc ... along a road.

Basically all you need now, is the starting point (highest point) and the ending point (lowest point), which you can use to join river together too, and if you are smart you can also create infinite river. You can just recursively break the river in smaller intermediate segment or events, and just interpolate between them. Adjusting the width of influence to shape terrain around it.
> 0 votes

---
Tags: unity, c#, procedural-generation
---


title: rolling hills terrain generation

text:
# Question
Title: rolling hills terrain generation
I am trying to implement cartoon style terrain generation in Unity with perlin noise.

I want to create 3D rolling hills for my game like in mario

The low frequency perlin noise I leverage always gives me realistic rolling hills, but I want that very cartoony edge between elevations and the flat tops. Any ideas how this may be acheived? I suspect it may have to do with playing with some easing function between neighbouring points (non-linear quantization?).

to expand, could something like this wrapped around a sphere work (my world will be spherical with displacement).  I would setup a biome etc. but if the aforementioned would work, how would i go about generating the height map texture like the image ?

# Answer
> 3 votes
Looking at the image, it looks to me like you would want to use cylinders with hemispherical end caps on the top to produce something similar. It looks like the cylinders are x units wide and spaced 1/2 x units apart. So I would take your Perlin noise and use that for the heights of the cylinders.

# Answer
> 0 votes
Well for each chunk, spawn hills (varying paramter like size and height) at random location using a relaxed grid sampling, they will overlap and give the desired features automatically.

---
Tags: unity, procedural-generation, terrain
---


title: Why is the line not being drawn?

text:
# Question
Title: Why is the line not being drawn?
I'm trying to add a few polishing touches to my puzzle game (made in Game Maker) in the vein of Ironclad. The following code is for adding a gem object to a stack that already has at least one other object.

Everything works except the draw\_line, for some reason. At first, I thought it was because `ds_stack_top().x` didn't actually return the x value of the object on top of the stack. So, I replaced the points with random values, and those didn't work. It clearly runs past the code, since "did link" prints out.

I'm not sure what I'm doing wrong.

```
            obj_Handle_Links.Match_Length +=1; //because we're increasing the length
            image_index = 1; //this should highlight
            Linked = true; //the gem's now linked

            var start_x = ds_stack_top(obj_Handle_Links.Link_Stack).x; //get the start point of the line
            var start_y = ds_stack_top(obj_Handle_Links.Link_Stack).y; //get the start point of the line
            show_message("did link");
            draw_line(start_x, start_y, x, y);

            ds_stack_push(obj_Handle_Links.Link_Stack, id) //adds the instance to the stack

```

# Answer
> 1 votes
You want to draw the line from (0,0) to the point popped off of the stack, right? If so, then

> draw\_line(0, 0, x, y);

should be

> draw\_line(0, 0, start\_x, start\_y);

Also make sure the object drawing the lines is set to visible, otherwise it's draw events are skipped.

---
Tags: game-maker, debugging, bug
---


# Question
Title: Algorithm for "mipmapping" terrain vertex heights and normals
I am creating an engine in opengl. As the distance from the player increases, the width and height of the tiles increase by factors of 2. How can I do this? I am currently just averaging, but I miss some of the peaks and valleys, so the slopes are less intense as the tile size increases. This causes some of the textures relative to slope angle to disappear (e.g. grass isn't formed on large slopes, but at distance everything becomes grassy).

The slopes/textures and lighting are based on my vertex normal map.

Here is pseudo code for my current procedure:

```
float heightmap[layer][x][y]
float normalmap[layer][x][y]

For i=1; i<num_mipmaps; i++
    For x=0; x<(width>>i); x++
        For y=0; y<(height>>i); y++
            heightmap[i][x][y] = 0;
            For x2=x*2-1; x2<x*2+1; x2++
                For y2=y*2-1; y2<y*2+1; y2++
                    heightmap[i][x][y] += heightmap[i-1][x2][y2];
            heightmap[i][x][y] /= 9;

```

... then I just calculate all face normals and vertex normals separately for each layer.

# Answer
I've not dealt with LOD before. I will say, that I've always wondered if instead of averaging if you did some sort of minimum and maximum values for a group of vertices if that would produce better results?

However, for the bump mapping you might look into LEAN maps. In essence, for downsampling a bump map, they calculate the spread of normals in the higher res version of the map and attempt to reproduce that in the smaller versions.

> The method evaluates bumps as part of a shading computation in the tangent space of the polygonal surface rather than in the tangent space of the individual bumps. By operating in a common tangent space, we are able to store information on the distribution of bump normals in a linearly-filterable form compatible with standard MIP and anisotropic filtering hardware.
> 1 votes

---
Tags: opengl, c++, terrain, heightmap
---


title: Ogre Render Lines completely wrong

text:
# Question
Title: Ogre Render Lines completely wrong
I'm trying to render line list using indices of triangles as follow

```
float *vertices = static_cast<float *>(vertexBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD));

for (int i = 0; i < out.numberofpoints; i++)
{
    vertices[(i*3)] = out.pointlist[(i*3)];
    vertices[(i*3)+1] = out.pointlist[(3*i)+1];
    vertices[(i*3) + 2] = out.pointlist[(3*i)+2];

}

vertexBuffer->unlock();

uint16_t *indices = static_cast<uint16_t *>(indexBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD));

int  l, t;
int numTriangles = out.numberoftrifaces*3*sizeof(uint16_t);
for (l = 0, t = 0; t<numTriangles; t += 3) {
    // Each vertex has to be listed twice
    indices[l] = out.trifacelist[t];      l++;
    indices[l] = out.trifacelist[t + 1];    l++;
    indices[l] = out.trifacelist[t + 2];    l++;
    indices[l] = out.trifacelist[t + 2];    l++;
    indices[l] = out.trifacelist[t + 1];    l++;
    indices[l] = out.trifacelist[t];      l++;
}

indexBuffer->unlock();

```

The problem that ogre renders broken triangles and it's completely wrong. I'm not doing anything wrong regarding rendering the lines that the triangles are composed

I'm using ogre 1.9

# Answer
The triangles you're drawing per iteration of the loop are the triangles:

```
t, t + 1, t + 1

```

And

```
t + 2, t + 2, t

```

These are degenerate triangles, presumably you want:

```
t, t + 1, t + 2
t + 2, t + 1, t

```
> 1 votes

---
Tags: c++, ogre
---


# Question
Title: How do I implement a JavaScript interpreter into a C# game?
I'm trying to create a hacking game where players design programs and hack other people's stuff. Users write their programs in JavaScript. I'm aiming for a hackmud-style system, where user programs can interact with the host game, for example, transferring funds.

Trouble is, I don't know where to start. I'm using C# to develop my game. Everything I found online for using JavaScript in C# interprets the script as a program on the host computer. This is a problem because I don't want the user code to have access to the host computer, just the game. Is there a standard architecture for a project like this?

# Answer
> 1 votes
I would recommend using Microsoft's ClearScript. This includes an examples page that will provide the basics of setting up an interface where the script will interact with your game.

I have to admit to not having used it myself (though I have considered it in the past for a game, and have used C# scripting using Roslyn instead), but looking at the Examples and FAQTutorial pages reveal that it should be a simple task to implement a way for a users script to interact with your game.

---
Tags: c#, javascript, scripting
---


# Question
Title: How can I switch between two cameras with fading in/out when switching?
The first script is the way I'm using now to switch between cameras.

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

public class SwitchCameras : MonoBehaviour
{
    [Header("Cameras Init")]
    public Camera[] cameras;
    public Vector3[] originalPosition;
    [HideInInspector]
    public Vector3 currentCameraOriginalPosition, currentCameraPosition;

    [Space(5)]

    [Header("Cameras Switch")]
    public string currentCameraName;
    public Vector3[] lastCameraPosition;

    private int currentCamera = 0;

    void Start()
    {
        cameras = Camera.allCameras;
        lastCameraPosition = new Vector3[cameras.Length];

        if (cameras.Length >= 1)
        {
            originalPosition = new Vector3[cameras.Length];
            for (int i = 0; i < cameras.Length; i++)
            {
                originalPosition[i] = cameras[i].transform.position;
            }
        }

        if (cameras.Length == 1)
        {
            Debug.LogError("Need more then 1 camera for switching..");
        }
        else
        {
            Debug.Log("Found " + cameras.Length + " cameras");
        }

        for (int i = 0; i < cameras.Length; i++)
        {
            cameras[i].enabled = false;
        }
        cameras[0].enabled = true;
        currentCameraName = cameras[0].name;
        currentCameraOriginalPosition = originalPosition[0];
    }

    void LateUpdate()
    {
        if (Input.GetKeyDown(KeyCode.G))
        {
            cameras[currentCamera].enabled = false;

            if (++currentCamera == cameras.Length)
                currentCamera = 0;

            cameras[currentCamera].enabled = true;
            currentCameraName = cameras[currentCamera].name;

            currentCameraOriginalPosition = originalPosition[currentCamera];
        }
        lastCameraPosition[currentCamera] = cameras[currentCamera].transform.position;
        currentCameraPosition = lastCameraPosition[currentCamera];
    }
}

```

And this is a script for starting a new game:

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

public class NewGame : MonoBehaviour
{
    public void RestartGame()
    {

    }
}

```

Both scripts attached to the same GameObject. I'm calling the RestartGame method from On Click in the inspector of a button I have in the main menu.

Now in the SwitchCameras script I'm using the G key to switch between the cameras.

But now I want to do that when a new game start to fade in/out between two cameras inside the RestartGame method. I want to call some method from the SwitchCameras script that will gade in/out between two cameras.

The idea is when starting a new game or resuming a game that the first camera will fade out slowly, fade out I mean will be enabled false slowly and then near the end to enabled true the second camera slowly.

Like switching between the two cameras but slowly.

Should i use startcoroutine ?

# Answer
> 3 votes
Put black 2D planes (or UI images, better to put an image if you want extra effects) in front of your cameras. Make the first one's plane transparent and the second one's plane solid. Disable the second camera at first (along with the 2D plane). When you want to switch between, just slowly decrease the first plane's transparency (increase its color alpha), turn on your second camera, turn off your first camera and decrease the transparency of your second plane (which is on the second camera).

If you've opted for UI images, play around with fillings etc. for more effects.

# Answer
> 1 votes
If you want to cross-fade straight from one view to the other, rather than fading to black first, we can do it by capturing a snapshot of the first camera before we disable it.

Add a UI canvas to your scene, in Screenspace Overlay mode, with a RawImage that stretches to fill the whole view. It can be disabled for starters, since we'll only use it when doing the cross-fade. Then slap a script something like this on it:

```
[RequireComponent(typeof(RawImage))]
public class CameraCrossFader : MonoBehaviour {

    // Hold our render target between uses so we don't
    // have to create & destroy it repeatedly.
    RenderTexture _snapshot;

    // Call this when you want to start a cross-fade.
    public void CrossFade(Camera startCam, Camera endCam, float duration) {
        StartCoroutine(FadeSequence(startCam, endCam, duration));
    }

    IEnumerator FadeSequence(Camera startCam, Camera endCam, float duration) {
        // If we haven't made a capture target yet, or our render changed size
        // since we last used it, create a new one at our current resolution.
        if(_snapshot == null
         || _snapshot.width != Screen.width || _snapshot.height != Screen.height) {
            // If we already had a target, destroy it so we don't leak memory.
            if(_snapshot != null)
                 DestroyImmediate(_snapshot);

             // Make a new render target of the desired size & format.
             _snapshot = new RenderTexture(Screen.width, Screen.height,
                                            RenderTextureFormat.RGBA32);
        }

        // Copy the last rendered frame into this texture.
        _snapshot.ReadPixels(new Rect(0,0,Screen.width,Screen.height), 0,0);

        // Use this image as our stand-in card, and enable this object so it's shown.
        gameObject.SetActive(true);
        var image = GetComponent<RawImage>();
        image.texture = _snapshot;

        // Switch rendering to use the second camera.
        startCam.gameObject.SetActive(false);
        endCam.gameObject.SetActive(true);

        // Gradually fade our stand-in card to transparent.
        Color color = Color.white;
        for(float a = 1f; a > 0; a -= Time.deltaTime/duration) {
               color.a = a;
               image.color = color;
               // Let the game run for another frame.
               yield return null;
        }

        // Fade complete. Switch this object off until the next fade.
        gameObject.SetActive(false);
    }
}

```

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


title: Why the OnMouseEnter event never fire?

text:
# Question
Title: Why the OnMouseEnter event never fire?
I have a Camera i added and put it above the space station. The Camera name is Map Camera. I attached to it a collider Capsule collider before it tried also with Box Collider.

Also attached to the Map Camera a script name Map:

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

public class Map : MonoBehaviour
{
    public Camera mapCamera;

    private Camera[] cameras;
    private Color startcolor;

    // Use this for initialization
    void Start()
    {
        cameras = Camera.allCameras;

        GameObject levels = GameObject.Find("_Level");
        foreach (Transform child in levels.transform)
        {
            child.gameObject.AddComponent<CapsuleCollider>();
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.M))
        {
            if (mapCamera.enabled == false)
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = false;
                }
                mapCamera.enabled = true;
            }
            else
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = true;
                }
                mapCamera.enabled = false;
            }
        }
    }

    void OnMouseEnter()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        foreach (RaycastHit hit in Physics.RaycastAll(ray))
        {
            if (hit.collider.name == "Corridor_Window_Part_05")
            {
                break;
            }
        }
    }

    void OnMouseExit()
    {

    }
}

```

In the Start I'm adding to each child also a collider. While the game is running i tried to change the colliders set Is Trigger to be on/off but nothing helped it's never getting to the OnMouseEnter event. I used a break point.

Screenshot of the Map Camera inspector.

And this is a screenshot for example of the child Corridor\_Window\_Part\_05 while the game is running so now it have a capsule collider too.

What I'm trying to do is when the mouse cursor in the game window while the game is running will be over the child for example Corridor\_Window\_Part\_05 then get into the OnMouseEnter but it's never get to the OnMouseEnter.

The last screenshot showing for example the Corridor\_Window\_Part\_05 in the scene view and I want that in the game view while the game is running when i move the mouse cursor on one of any of the children under \_Level to get into OnMouseEnter but it's never firing the event.

Update on what I did so far:

Changed the Map script to:

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

public class Map : MonoBehaviour
{
    public Camera mapCamera;

    private Camera[] cameras;

    // Use this for initialization
    void Start()
    {
        cameras = Camera.allCameras;

        GameObject levels = GameObject.Find("_Level");
        foreach (Transform child in levels.transform)
        {
            child.gameObject.AddComponent<MapHighlight>();
            child.gameObject.AddComponent<BoxCollider>();
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.M))
        {
            if (mapCamera.enabled == false)
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = false;
                }
                mapCamera.enabled = true;
            }
            else
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = true;
                }
                mapCamera.enabled = false;
            }
        }
    }
}

```

And created new script called Map Highlight:

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

public class MapHighlight : MonoBehaviour
{
    private Color startcolor;

    private void OnMouseEnter()
    {
        startcolor = GetComponent<Renderer>().material.color;
        GetComponent<Renderer>().material.color = Color.white;
    }

    private void OnMouseExit()
    {
        // Remove the white color.
    }
}

```

The Map script is attached to the Map Camera. When running the game I see on the children objects the script and the box collider i added.

I have a box collider also on the Map Camera.

But when the mouse cursor is over one of the children nothing happen. I'm using a break point on:

```
startcolor = GetComponent<Renderer>().material.color;

```

In the Map Highlight script inside the OnMouseEnter but it's never getting there.

I tried to change the Is Trigger on/off on the children and on the map camera i tried to remove the box collider from the map camera then only from one of the children and then from both nothing worked so far.

It's not getting to the OnMouseEnter.

Could be the mouse cursor is too far ?

# Answer
> 2 votes
You have to put the OnMouseEnter on the object you wish to BE moused over, so in your case, the station object.

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


title: Cannot pick up an object in Unity game

text:
# Question
Title: Cannot pick up an object in Unity game
I have a `PickupTarget` object in front of my `FirstPersonCharacter` which is used for 'holding' picked up object. Somehow, it doesn't work; when I click on the object (`Axe`) it just stays on the ground.

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

public class PickUp : MonoBehaviour {

    public Transform target;

    void Update () {

    }

    void onMouseDown() {
        this.transform.position = target.position;
        this.transform.parent = GameObject.Find ("FirstPersonCharacter").transform;
    }

    void onMouseUp() {
        this.transform.parent = null;
    }
}

```

I have added `PickupTarget` as a `target` of script in `Axe` object:

This is the structure of my `Axe` object.

# Answer
`onMouseDown()` is just a random function. You aren't calling it from anywhere in your code and Unity won't call it because it's not the MonoBehaviour event method.

You want `OnMouseDown()`.

Same goes for your `onMouseUp()`: `OnMouseUp()`

Capitalization matters.

Also make sure that the script the GameObject is attached to has its own Collider component as well.
> 3 votes

---
Tags: unity
---


# Question
Title: Which collider should I use for a bucket?
I have a bucket, and I want a ball to be able to enter it. I'm facing a problem: Unity mesh collider seems not work with concave object... is that true? How can I solve this?

# Answer
You need to use a mesh collider, set the mesh, and disable the "Convex" checkbox.
> 1 votes

---
Tags: unity, collider
---


# Question
Title: Why Are Some Foreign Characters Not Displaying Properly
I am localizing a game for the first time and I'm noticing some characters are not displaying properly. Most are fine but there is a small handful that are not correct. For example on a loading screen I display the word Loading. In German I'm displaying `Lädt`. The `ä` character is not displayed as `ä`, instead isn't displayed as shown in the image. I'm running in a standalone game. I packaged a development build to see if the problem was there too but it seem localizing is not working when I package it but I can tackle that problem later unless there is a known issues with this. To change languages I am calling Set Current Culture in blueprints.

# Answer
Apparently this is because of the font I'm using. It doesn't support some of the characters used in other languages. The answer to my question on UE4's answer hub has more details.
> 1 votes

---
Tags: unreal-4, blueprints, localization
---


title: SDL Sprite Customization

text:
# Question
Title: SDL Sprite Customization
I am currently working in C++ with SDL2. I plan on making a game that utilizes character visual customization. More specifically, equipping clothes and items changes the appearance of characters. However I don't know how to approach this situation. With that being said, how would I achieve this character customization in SDL2?

Right now I have two ideas...

1. Create a sprite sheet for every possible combination.( Way too much time).
2. Break the sprite into different rects to draw each article of clothing or item. (Not sure if this is efficient)

# Answer
> 1 votes
Choose the second option. This way you will only have the necessary parts images, which will reduce the number of assets that would probably be huge with so many specific combinations, thus leaving the final set of your game much smaller and with fewer assets to load.

And to program, use switch/case rather than if/else. Here is why. (summarizing: switch / case has more performance when it comes to many conditions)

**For example:**

```
enum Outfit
{
    HELMET,
    ARMOR,
    AXE,
    // ... bunch of enums
};

void insert_clothing(const Outfit& piece)
{
    switch(piece) {
        case HELMET:
            // ..
            break;

        case ARMOR:
            // ..
            break;

        case AXE:
            // ..
            break;

        // ... bunch of cases

        default: std::cout<<"Non-existent enum"; break;
     }
}

void remove_clothing(const Outfit& piece)
{
   // Same thing, only changing the case definition
}

```

**And when you call the functions, call using the piece you want to wear on/remove from the character:**

```
void f()
{
   insert_clothing(HELMET);
   insert_clothing(ARMOR);
   remove_clothing(HELMET);
}

```

---
Tags: c++, sprites, sdl2, character
---


# Question
Title: Implementing Turn based Combat Using Node js
I am creating a browser game that allows players to fight monsters using `Nodejs`, `Socket.io` and `Express`. However I can't seem to figure out how to implement the turns of combat.

My train of thought and workflow is as follows:

* The player declares an attack on a monster (`Client` makes a `Post` request.) - **Working**
* The `server` get's the player's stats as well as the monster's. - **Working**
* The player selects his action and attacks, then it's the monster's turn and so on. - **Can't figure this out**

How would such a functionality be implemented?

# Answer
This is just an exercise in modeling the objects you want to represent your game.

At the very least, you need a concept of the battling entities (players and creatures) and individual battles.

The **Creature / Player** will be objects that have attributes like HP and Attack power.

The **Battle** class will track things like turn count, whose turn it is, etc.

When the player initiates the battle, you should create a new battle object to track the turns.

In the following example code, I'm using javascript functions as examples, but you can map them to REST endpoints or whatever. for example, `POST /battles/new` with data `attacker_id=2&target_id=1` for `function initiateBattle`.

```
 // Starts a Battle -- could throw an exception if either combatant is already in combat.
 function initiateBattle(attacker, target) {
    var battle = new Battle(attacker, target);
    game.globalBattlesList.add(battle);
    return {battle: {
       id: battle.id,
       current_turn: {
          owner: attacker,
          number: 1,
       }}};
 }

 // Send an attack in a battle
 function attack(battle, attacker, target) {
     if (battle.current_turn.owner != attack) {
        return {result: "error", message: "It's not your turn!"};
     }

     target.HP -= attacker.ATK;

     if (target.HP <= 0) {
        ...
        game.end_battle(battle);
        return {
           status: "OK",
           winner: attacker,
           message: "${attacker.name} wins in ${battle.current_turn.number} turns!"
        };
     }

     // change turn
     battle.current_turn = {owner: target, number: battle.current_turn.number + 1};

     // does the AI have a delay?
     setTimeout(function() {
         // do_enemy_turn will choose an action for the AI
         // and set battle.current_turn back to
         do_enemy_turn(battle, target, attacker);
     }, target.attack_delay);

     return {
         result: "continue",
         message: `target is at ${target.HP} HP`
     };
 }

```
> 1 votes

---
Tags: browser-based-games, turn-based, node.js
---


# Question
Title: Preloading for level transitions in a tile-based game?
I am developing a 2D Metroidvania which consists of a series of interconnected levels. When my player gets *near* a portal which can take him to a new map, I want to pre-load the next map so that there is a seamless transition when he actually enters the portal.

Here is some background about the structure of my code.

Each level is represented by a Tiled TMX file in which I have specified where various objects of different sprite classes spawn (for example, enemies, pickups, levers, etc.). When starting a new game, loading a saved game, or changing a level, my game loop runs through the appropriate TMX file and generates all the objects in that level.

For example, here is a simplified version of my `new_game()` method.

```
level = "level_1.tmx"

def new_game(self):
    Globals.scene = "game"

    # create groups
    self.all_sprites = pg.sprite.Group()
    self.walls = pg.sprite.Group()

    # load map and spawn objects
    self.map = TiledMap(path.join(self.map_folder, level))
    self.map_name = level
    self.map_img = self.map.make_map()
    self.map_rect = self.map_img.get_rect()

    # spawn objects
    for tile_object in self.map.objects:
        if tile_object.name == 'player':
           Player(self, tile_object.x, tile_object.y)
        if tile_object.name == 'wall':
            Obstacle(self, tile_object.x, tile_object.y, tile_object.width, tile_object.height)

```

I handle level changes like this: If the `Player` object intersects a `Portal` object, a `change_map()` method is called which loads a new map (the one associated with the intersected portal) and positions the player at the appropriate position on the new map. The `change_map()` method looks very similar to the `new_game()` method above, except that it empties all the sprite groups and hangs on to the player object for repositioning on the new map.

I want to restructure my code so that when the player gets near a portal object (say, within 640 pixels), the map associated with the portal begins to load. This way, when the player enters the portal, the map will load instantly.

I was thinking that I could check to see if the player is near a portal in my game's `update()` method. If he is, I could call a `preload_map()` method. But I am unsure how this function should look and how to transition to the new map when the player enters the portal. In order to avoid a stutter when the new map loads, do I need to learn about multiple threads? Maybe I should simply load all the new map images and sprites into their own variables (suffix them with "temp" or something) and then, when my player enters the portal, I can effectuate transition with lines like `self.map_img = self.map_img_temp` and `self.all_sprites = self.all_sprites_temp`.

So my question is: **Given the structure of my code, how can I use pre-loading to achieve seamless map transitions?**

---

Here is a similar question where the poster does not specify enough information about the structure of their code.

# Answer
> 1 votes
What I would do (let's assume you have a game instance called GameStatus) is something similar to this::

1. Have a GameStatus.cached\_map that can be either None or contain a TileMap object (created by the `TileMap()` call)
2. Have a function, let's say 'load\_map', that loads the map and assign it to the .cached\_map property
3. When in your update cycle you detect the player is in range of the portal, you'll call load\_map (this will set your cached\_map from None to a valid map object)
4. In your Portal, you check if there's an available with `if cached_map:`, if it's available you assign it to GameStatus.map and finish setting it up, if not you call your usual map loading code.

This will work as a prototype: you'll test how splitting the code works before starting to fight with threading: verify you have all your variables available and handy or, if not, refactor the code maybe by creating your own Map management class, containing all the information and functions you need to manage it effectively. I do expect that doing this will block the game action (if map loading was instantaneous already, you wouldn't bother with preloading :-) ) so you'll need a background loading mechanism. Now that you know that loading work and you put all your pieces together, it'll be easier to add threading.

To do that, I'd use the threading module (unless your game engine/framework provides something similar) to start the map loading function in your update cycle (point 3 above) by launching a thread running `load_map()`, then in your Portal switch code, you'll check if there's a cached\_map available: if not, you can check if the thread is alive and if it is, wait for it to finish.

You can play around a bit in an interactive shell with the following code (that I used to check that I still remembered things correctly :D )::

```
import threading
import time

def load_map(map_level, map_path):
    print("Here I'd load map {} from {}".format(map_level, map_path))
    # GameStatus.cached_map = TileMap(map_path, map_level)
    time.sleep(10)
    print("map loaded!")
    return None

t1 = threading.Thread(target=load_map, args=("Lost Forest of Darkness", "/path/to/map.tmx"))
t1.run()
Here I'd load map Lost Forest of Darkness from /path/to/map.tmx
t1.is_alive()
True
<10 seconds pass>
map loaded!
t1.is_alive()
False

```

In your update cycle you will do something like this::

```
self.cached_map = None   # this might be better moved to load_map, if it has access to GameStatus)
t1 = threading.Thread(target=load_map, args=("Lost Forest of Darkness", "/path/to/map.tmx"))
t1.start()

```

statement, to create the thread then run it in background immediately.

When finally the player enters the portal, the portal loading function needs to check if the map is available (GameStatus.cached\_map is not None), if not it can wait on the thread calling `t1.join()` (join() will wait for the thread to end before returning, t1.is\_alive() tells you if it's running, etc. You can check https://docs.python.org/3/library/threading.html for more). You can then copy the cached\_map to the 'real' map and do the rest to activate it (or encapsulate all this in a dedicated map object, as said above some refactoring might be useful to keep things readable and simple (i.e it might be a good idea to save the thread(s) as property of your GameStatus class, and/or implement map\_load as a method of it).

P.S.

Which Python Game Engine are you using?

---
Tags: architecture, tilemap, python, loading, tiled
---


title: Device Disposing Memory leak issue

text:
# Question
Title: Device Disposing Memory leak issue
I have a memory issue after disposing all my D3D objects and lastly disposing the device. I want to free all memory and, depending on user interaction, creating a new device, but removing all memory footprint of the old device.

I traced down some Disposing issues I had to only have this left, right at the line at disposing the device:

I get this by calling:

```
mDevice.QueryInterface<DeviceDebug>().ReportLiveDeviceObjects(ReportingLevel.Summary)

```

I understand that that the DeviceDebug interface I receive to get this debug information increases the Refcount of the ID3D11Device by +1. So it should be 2 references left.

Now I wonder if I need to track down this last reference (the 2nd) in order to get the device fully released after I call .Dispose(). Or if this is a internal refernece that is handled for me.

The issue is, that I don't know how to check for remainding objects after the device disposing. I get no warnings about active objects in output anymore, them I fixed already.

My memory grows linearly by about ~15MB each creation and destruction of my window (not closing the application, just the part that needs a device).

Any help appreciated!

# Answer
> 1 votes
You probably still have objects bound to the pipeline (via a context-\>Set call) at the time you perform the final dispose. In D3D11 binding an object will cause it's reference count to be incremented, meaning that there are still references to those objects, meaning that the objects will be leaked.

One way to resolve this is to explicitly set all state objects, shaders, shader resources, buffers, rendertargets, etc to NULL before disposing, which will clear the reference counts and allow the dispose to happen clearly.

The other, more reliable, way is to make a call to `ID3D11DeviceContext::ClearState` before disposing. This will also release all outstanding references, and is more suitable for doing a full shutdown of video, where the more nuclear option is exactly what you want.

---
Tags: c#, directx, sharpdx
---


# Question
Title: Multiple rendering back ends architecture
so I've been thinking about designing a rendering engine with multiple back ends in C#.

Well, let me rephrase; I wish to design an engine that can be easily extended upon to support multiple back ends. My primary goals is to use OpenGL, but maybe later I might to add support for DirectX or a software renderer.

So i was thinking about how I might achieve this and think I've come up with a pretty decent design, here it is (in code, just cause it's best to see the design visually)

Firstly, the interfaces

```
/// <summary>
/// Defines an interface for low level rendering methods.
/// </summary>
public interface IRenderContext
{
    void Clear(bool colorBuffer, bool depthBuffer, bool stencilBuffer);

    // One a side note, should all the methods below be in some kind of resource manager???

    // Now for each type of resouce that can be used by the render context, lets
    // create and return an interface, rather than an object so that users don't have
    // to see an ugly class like "OpenGLMesh" or "DirectXRenderTarget".

    IMesh CreateMesh(Vertex[] vertices, int[] indices);

    ITexture CreateTexture(int width, int height, char[] pixelData);

    IShader CreateShader(ShaderType shaderType, string shaderSource);

    IRenderTarget CreateFrameBuffer(int width, int height);
}

/// <summary>
/// Defines an interface for high level rendering functions.
/// </summary>
public interface IRenderDevice
{
    // Lets contain the render context to make our lives easier
    IRenderContext RenderContext { get; }

    void DrawMesh(Transform transform, IMesh mesh, ITexture texture);

    // and other methods that are on more of a higher level would go here
}

```

and finally the way it would be used is like this:

```
IRenderContext renderContext = new OpenGLRenderContext();
IRenderDevice renderDevice = new OpenGLRenderDevice(renderContext);

ITexture texture = renderContext.CreateTexture(640, 480, pixelData);
IMesh mesh = renderContext.CreateMesh(vertices, indices);
renderDevice.DrawMesh(transform, mesh);

```

Is this a bad design? Am I missing something? What can I do to improve the architecture.

# Answer
Largely echoing Josh, I think this is very difficult to do. After all, if we could generalize abstractions that allow us to write code against any kind of backend while still being able to express what we want to do at the low-level of what primitives to render and so forth, we'd all be writing code against such an abstraction and there'd be little point to writing code specifically for OpenGL or DirectX or anything else.

Instead a much easier thing to do typically is abstract your game state instead of the renderer. Then you can have multiple concrete rendering backends that render such state, and such implementations would be free to do whatever since they don't have to conform to any abstraction.
> 1 votes

# Answer
It looks incomplete and/or overly-simplified. It consequently probably won't scale up very well to more complex rendering scenarios. It probably won't work well for anything but the first rendering backend you build for it, either.

Texture and buffer resources are pretty similar, conceptually, across most rendering APIs: they're the easy part. State management beyond those resources are usually where things get complicated and fiddly to port between APIs, and your abstraction doesn't account for that *at all*. Even with the resources you're not accounting for all the varied usage modes and behavioral control flags a robust API is going to want - can this be read on the CPU, can it be bound as a render target, where does it exist in GPU memory, et cetera.

It's a reasonable *start*, and continuing along this path will be very educational for you. I suggest you simply proceed, keeping aware that you'll have to refactor the design as you want to write more complex rendering code, and as you port it. I'd also suggest that if you *really* want to make this kind wrapper you immediately being implementing it in more than one backend (say, OpenGL and D3D). Pick one you like better, build parts of your API in that backend first, and then try making it work with the other backend. You should discover pretty quickly where there are interesting differences that challenge your assumptions and force you to refactor your design, and that will ultimately lead to a much better API.

It will also make it much less daunting (and more likely that you'll actually finish) to have it work on two different rendering backends if you can develop them mostly in lockstep.

You may want to take a look at other API abstractions; sokol is in C, but it's a pretty good, minimal example you can look at. BGFX is a bit more complex.
> 0 votes

# Answer
After allot of searching, I've found something scales nicely and is quite simple to expand.

Here's a link, if you follow it you'll also a few articles on the topic and how it was designed, it's pretty much a tutorial.

https://github.com/amesgames/RenderDevice/tree/develop
> 0 votes

---
Tags: c#, opengl, rendering, opentk
---


# Question
Title: Add picture in the Hierarchy view in Unity
How can I add a picture in the Hierarchy view in Unity? For example, Dragon bones does it automatically. Here it is :

As you can see there is a picture on the right of the gameObject name.

# Answer
> 3 votes
They are hooking into the `EditorApplication.hierarchyWindowItemOnGUI` event. In their case they are storing a single icon texture within their editor script, and then checking the type of the object in the hierarchy, exiting the routine as soon as they've either decided there's nothing to do or they've found a specific icon to show.

I've linked to their code above (it's all open source), but something like this:

```
[InitializeOnLoad]
public class YourIcons : Editor
{
  static Texture2D yourIcon;
  static bool isInited = false;

  static YourIcons()
  {
    Initialize();
  }

  static void Initialize()
  {
    if (isInited)
    {
      // Only do this once.
      return;
    }

    // Find the current path we're running in
    DirectoryInfo rootDir = new DirectoryInfo(Application.dataPath);

    // Search the directory for this file
    FileInfo[] files = rootDir.GetFiles("YourIcons.cs", SearchOption.AllDirectories);

    // rework our file path into the Assets path
    string editorPath = Path.GetDirectoryName(files[0].FullName
                                .Replace("\\", "/")
                                .Replace(Application.dataPath, "Assets"));

    // Add the name of the folder with your icon
    string editorGUIPath = editorPath + "/GUI";

    // Load the icon
    yourIcon = AssetDatabase.LoadAssetAtPath<Texture2D>(editorGUIPath + "/yourIcon.png");

    EditorApplication.hierarchyWindowItemOnGUI -= HierarchyIconsOnGUI;
    EditorApplication.hierarchyWindowItemOnGUI += HierarchyIconsOnGUI;
    isInited = true;
  }

  static void HierarchyIconsOnGUI(int instanceId, Rect selectionRect)
  {
    GameObject go = (GameObject)EditorUtility.InstanceIDToObject(instanceId);

    if (!go)
    {
      // If this isn't a GameObject, then stop processing
      return;
    }

    // create a rectangle to hold the texture.
    Rect rect = new Rect(selectionRect.x - 25f, selectionRect.y + 2, 15f, 15f);

    // Check to see if the GameObject is one we care about
    if (go.GetComponent<YourComponent>())
    {
      // Position the rectangle off to the right of list, 15px in from the edge
      rect.x = selectionRect.x + selectionRect.width - 15f;
      GUI.Label(rect, yourIcon);
      return;
    }
  }
}
/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2012-2017 DragonBones team and other contributors
 *
 */

```

---
Tags: unity, image, hierarchy
---


# Question
Title: Unity: how intercept Mouse Click on UI and not fire "shoot"?
I've a classic

```
void Update() {
   if(Input.GetMouseButtonDown (0))
      Fire();
}

```

What i want to do is that if I click on a UI button , the `Fire()` routine not will be called.

How to do to say Unity `if InputGetMouseButtonDown(0) && !UI clicked` ?

# Answer
> 5 votes
So, first, stop using `Input.GetMouseButtonDown(0)`, use `Input.GetButton("Fire1")`. This allows your player to remap the controls. It won't fix your problem, but this is still something you should do.

Onto your problem, you have a few options:

* When the UI is up, set some global variable (eg. `gamePaused`) that when true, your game logic doesn't execute. This includes shooting.
* Ask the event system: `EventSystem.current.IsPointerOverGameObject()`
* Check if your mouse is in a region of the screen (eg. over/not over the UI) and if over the UI, don't fire.

# Answer
> 0 votes
Another option is that when you click on the UI button, you should enable / disable the script that has the Fire().

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


# Question
Title: Change center point and size with the help of the Matrix in Unity
Let us suppose I have an array of `Vector3`, it contains vertices. Now I want to scale the vertices and/or change the center point of the texture (move texture relatively).

I have a `Vector3` which is a new center point and I have a `Vector3` which is vector for scaling along x, y and z.

How can I construct a needed matrix in Unity?

I am very new to all this, so, please, in case of any misunderstanding ask me about it.

Here is what I was able to find on my own. The problem with it, though, is that I can not infer what I need from it. I need a little bit more peculiar thing.

# Answer
Why use a matrix for this at all?

```
Vector3 ScaleAndShiftVector(Vector3 v, Vector3 shift, Vector3 scale) {
    return Vector3.Scale(v, scale) + shift;
}

```

You could do this with a matrix,

```
var matrix = Matrix4x4.TRS(shift, Quaternion.identity, scale);
var transformed = matrix.MultiplyPoint3x4(v);

```

but that does more calculations than you need, since it's accounting for rotation too which you're not using.
> 1 votes

---
Tags: unity, matrix, vertex, scale, pivot
---


# Question
Title: Disable automatic expansion of folder/parent when dragging objects into?
I'm organizing a large scene. I have a few subfolders like Trees, Flowers, etc. When I drag a tree into the Trees folder, it expands the folder and scrolls to the bottom (where it added them). Is there *any* way to disable this behavior? I immediately have to scroll back up and collapse it so I can see the structure again.

# Answer
Not a solution, but after dragging if I hit ,  it collapses the folder. Nice workaround.
> 1 votes

---
Tags: unity
---


title: Default Controller Mapping?

text:
# Question
Title: Default Controller Mapping?
It seems like different controllers have their buttons mapped differently. I was wondering if there was some sort of standard. X is the first button, then A, then B, then Y. I looked and couldn't find any standards anywhere.

EDIT: I'm specifically talking about controllers used with computers. Usually with 2 joysticks, a hat, 4 letter buttons, 2 triggers, and 2 bumpers.

# Answer
There is no completely universal standard.

Anyone could make a USB gamepad that looks outwardly like a standard Xbox controller, for example, but reports its buttons to the PC in a completely arbitrary order that doesn't match up to any other device. Even the same controller can report its controls in a different order depending on the host platform & driver.

The Rewired project includes an attempt to fit a wide array of common PC gamepads to a shared template. While they cover many devices, it's still not a universal standard, but it's the most comprehensive standardization attempt that I know of.
> 2 votes

---
Tags: input
---


# Question
Title: How can I color/un color object that don't have renderer and material?
I have a simple object:

I want to create a highlight effect.

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

public class Map : MonoBehaviour
{
    public Camera mapCamera;
    public Text objectWasHit;

    private Camera[] cameras;
    private GameObject mouseOvered;

    // Use this for initialization
    void Start()
    {
        cameras = Camera.allCameras;

        GameObject levels = GameObject.Find("_Level");
        foreach (Transform child in levels.transform)
        {
            child.gameObject.AddComponent<Renderer>();
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.M))
        {
            if (mapCamera.enabled == false)
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = false;
                }
                mapCamera.enabled = true;
            }
            else
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = true;
                }
                mapCamera.enabled = false;
            }
        }

        bool rcHit = false;
        Vector3 mouse = Input.mousePosition;
        Ray castPoint = mapCamera.ScreenPointToRay(mouse);
        RaycastHit hit;
        Debug.DrawRay(castPoint.origin, castPoint.direction * 1000, Color.magenta);
        if (Physics.Raycast(castPoint, out hit, 1000))
        {
            rcHit = true;
            if (mouseOvered != hit.collider.gameObject)
            {
                mouseOvered = hit.collider.gameObject;
            }
            objectWasHit.text = mouseOvered.name;
        }

        if (!rcHit && mouseOvered != null)
        {
            //do your thing to undo the material change
            mouseOvered = null;
        }
    }
}

```

First I'm not sure if white color is the right way for highlighting. Second there is no startcolor since the object don't have any renderer or material at the first time. Then how can I make the highlight effect ?

# Answer
When the object would have no Renderer, then it would not have an appearance in the game, so it would not make sense to highlight it.

However, it might be possible that the renderer which visualizes the object is not on the object itself but in one of its child-objects. To get the first renderer in the children of the object, use `GetComponentInChildren<Renderer>()`. This, however, might give you the wrong one if there are multiple children with renderers.

If the object has multiple sub-objects with their own renderers, you might want to use `GetComponentsInChildren<Renderer>()` (plural). This will give you an array with all the renderers of all the children of the game object.

Now regarding trying to highlight something with `renderer.material.color = Color.white`: Pure white is the default color of most renderers. So unless the renderer's color was manually changed to something else, this line won't have any visible effect except removing a different coloration you set before.

The simple solution to just see something for now and prove that your code works, would be to use a different color like `Color.red`. You can also create a custom color which is "whiter than white" to render the object brighter than usual:

```
private static Color OVERBRIGHT = new Color (2.0f, 2.0f, 2.0f);

```

You could also look at the material of the object and see if its shader has any additional color properties which might give you the effect you are looking for. The Standard shader for 3d meshes, for example, has the Emissive color property which causes the object to get illuminated in addition to its illumination from light sources.

```
renderer.material.SetColor("_EmissiveColor", Color.white);

```

(note: the "Emission" checkmark in the material properties needs to be set in order for "\_EmissiveColor" to have any effect)
> 3 votes

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


# Question
Title: Is it more efficient to add scripts to each GameObject or to a single parent object?
Does a C# script added to a parent object work more efficiently and effectively (in terms of both memory and performance) on all objects, in my case lighting, or adding script components to each lighting/GameObject object? This goes for other GameObjects parented in the hierarchy.

# Answer
There is some amount of overhead to invoking each script's `Update()` and other methods, compared to maintaining a list of objects and updating them all at once from a single entry point.

So, if you maintain a list of multiple objects to update, you may see some runtime efficiency wins by iterating over them from within a single script instance. Just note that if you're searching for instances to update using `FindObjectsOfType` or `GetComponentsInChildren`, the search cost will likely outweigh the savings of not invoking each one's Update separately. So look for ways that you can persist the list across frames rather than re-building it continuously.

In practice, I haven't experienced noticeable slowdowns from having dozens and dozens of instances of simple scripts updating independently, so I recommend profiling first before adding complexity to your project - it may be premature optimization for many applications.

You should also weigh whether your developers may gain iteration efficiency by keeping the instances separate. This can make it easier to individually select & tweak a single instance or group of instances, or make use of prefabs and object references. These operations can get more complicated if the needed methods & data are tied up in a higher-level manager script.

Which pattern makes more sense for a particular feature will depend a lot on the specifics of what you're trying to accomplish, what workflows your team likes to use, and what your performance profiling looks like.
> 3 votes

# Answer
Well, the stuff that are exampled may or may not be benefits depending on what people like doing but there are some definite benefits in my opinion.

For example, I could have as much as 50 (maybe more) planet game objects in my game. They all had attractors attached to them (this didn't occur to me as a problem at first) and I wanted them to turn around themselves slowly.

At first I had attractors and the picture of the planet on the same game object and I noticed a significant increase in CPU usage when there were too many planets. After investigating the issue further, I found out that the physics calculations were taking an immense amount of time every frame. It then occurred to me that, turning attractors and rigid bodies every frame could be the culprit.

I've removed the planet picture from the game object prefab then I made a child object which had only the picture. There it was, I was no longer turning physics objects for a simple turn animation. Suddenly, physics calculations were down to just about 1% - 0% per frame from a whopping 80% on levels with many planets.

So, yeah, there are benefits to having a container object for all your other objects, but the implementation is what really matters. Nothing is ever a "fit all and do all" kind of solution.

In your case, there might not be any improvement from iterating over every single light in a parent script to putting scripts on each light. As far as I know, Unity will use separate threads for separate objects in game. The single container object with a single script will not be automatically threaded, so you will need some effort on your part to properly thread that one.
> 0 votes

---
Tags: unity, c#, gameobject, hierarchy
---


# Question
Title: Why is depth test not working properly in my code?
http://jsfiddle.net/w9WqJ/31/

When rotating the camera, some pieces that are supposed to be hidden are displayed. Should I create more triangles or what did I do wrong here?

# Answer
> 1 votes
Your vertex shader has some bad maths in it. You have this:

```
    float newZ = pos_.z * .5 + .5;
    gl_Position = vec4(pos_.x, pos_.y, -newZ * .00001, newZ);

```

But you actually just want to be doing this:

```
    float newZ = pos_.z * .5 + .5;
    gl_Position = vec4(pos_.x, pos_.y, pos_.z, newZ);

```

(Also, 'newZ' is probably a bad name for that variable; what you're really calculating is 'w' in homogenous space; not a new 'z' coordinate.)

Basically, you were mangling your z-coordinate such that the depth buffer can't tell what's closer or further away any more.

It's also worth noting that as you get further into GL stuff, you're going to stop doing explicit maths this way, and will instead probably start using `mat4` matrices to represent rotations and projections into homogenous space, at which point you won't have to do any special maths like these; just multiply by the matrix(es) and assign the result to gl\_Position, and you're done.

All this stuff gets easier, once you're working that way instead of hand-rolling your own maths! So stick with what you're learning; you're pretty close to reaching the point where it gets easier! :)

---
Tags: webgl
---


title: Canvas enabling is not working

text:
# Question
Title: Canvas enabling is not working
I have a canvas with two buttons in it and I want to enable it on the button click, but when I try to enable it, it doesn't work. However, when I try to disable it on button click it does work. Here is my code:

```
 public GameObject mycanvas;
  public  void onClick() {
     mycanvas.SetActive(true);
}

```

Can someone please tell me what I am doing wrong?

# Answer
If the enable button is a child of the canvas, and the canvas is disabled, the button is disabled too, so you can't click it.

Moreover, are you using the `On Click ()` callback of the Button itself, by feeding it your `OnClick` method? I mean something like this:
> 1 votes

---
Tags: unity, 3d
---


# Question
Title: how to modify multiples BoxCollider on a same game object?
I have an game object with multiples BoxCollider attached to it, is there a way to get all the BoxCollider to an array so that I could modify their value individually ?

# Answer
`GetComponents()` will do what you need.
> 1 votes

# Answer
I made the `BoxColliderArray` public just so you can see it in the inspector.

```
    public BoxCollider[] BoxColliderArray;

    // Use this for initialization
    void Start ()
    {
        BoxColliderArray = GetComponents<BoxCollider>();

    }

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

        //TODO: Do something with the BoxColliderArray

    }

```
> 1 votes

---
Tags: unity, c#, unityscript, collider
---


# Question
Title: Why is a baked normal map more efficient to render than additional physical detail?
I was just contemplating about why I improve performance by baking additional details into the object rather than just rendering the more detailed model. How does the GPU get to take a shortcut to render potentially the same amount of detail on screen, just because the detail is represented in a different way?

# Answer
Reading the comments I think I've understood what @Viziionary was asking, and that's my answer:

First one of your assumption is wrong: normal mapping gives us just an approximation which is clearly visible on edges for examples, like @Sidar said, and like any other approximation is easy to compute.

Second the real point of the answer: 4M vertices will always be 4M vertices (which are more than the pixel on a 1080p screen) and each of them needs to be computed every frame, in the vertex shader. Instead the amount of pixel being drawn may vary a lot (they're generated in the rasterizer stage given the size of the triangles, which change with the distance, on the screen) but to reach the order of milions you need to draw you're model on the whole screen, thing that, in games, nether happens... So with normal maps you're computing only the information (level of detail) you need (the light on the visible pixels) based on the resolution of you're screen/distance of objects/visibility..., while with a detailed mesh you're always computing all the vertices, even if two of them are so close they will be rendered in the same pixel.

Not to mentions that if you move the work on you're pixel shader you can take advantage of things such early-Z (don't remember if this is its name) and other gpu/programming optimisations.

Sorry for the bad english. Hope I've been clear enough.
> 3 votes

# Answer
The problem is that the density of your mesh needs to be higher. Which requires more computational power and memory ( also think of lower end targets/devices ). Additional not ideal for rigged meshes. Normal maps contain surface direction per pixels, the perpendicular direction of the position on the surface ( hence the name normal maps ). Each pixel represents a unit vector, not a color ( it makes a color but that isn't the intend ). With this information it's possible to fake light shading and give the illusion of depth/height similar to a dense mesh while keeping the mesh low poly.

It's fairly cheap to calculate the math in the shaders to get the final result affected by a normal map. Add on top that your mesh is actually pretty low poly in comparison it's a win win for your GPU.

To get a nice effect from your normal map your mesh still needs to have enough density. Normal maps don't curve well on hard edges and completely destroys the illusion.

Edit: I'm assuming you are using a lower poly version of your mesh. If not, that ain't right. Pretty much defeats the purpose otherwise.

Edit2:

https://en.wikipedia.org/wiki/Normal\_mapping

4 million triangles vs 500 triangles. That's 0.0125% of the original.
> 3 votes

---
Tags: normal-mapping
---


# Question
Title: why does a type alias to engine specific header violate encapsulation?
In a class called Sprite.h my teacher asked this question which I don't fully understand.

A generic interface has to include an engine specific header in order to expose different sprites. This violates encapsulation between framework and specific engine.
How would you solve this?

Could anyone elaborate what the problem with this is and why this is not advised?

```
#include <Overlord/Engine.h>
using Sprite = Overlord::Engine::Texture;

```

# Answer
> 3 votes
It *sounds* like your teacher is referring to the fact that to use `Sprite` in this case (which is an `Overlord::Engine::Texture`) you must depend on the "Engine.h" header from Overlord, thus preventing whatever file has that code snippet you posted from completely encapsulating its dependency on Overlord. Any code that needs to depend on the header containing your posted code snippet *must also* depend on "Overlord/Engine.h."

I don't really see this as a problem for *that specific* code snippet, personally. You cannot hide every dependency, and if that code is in your game (that uses the Overlord engine) or in the Overlord engine itself, this is basically not worth worrying about.

This kind of header dependency bleed is usually more of an issue when you're hoisting dependencies up through many layers of encapsulation. For example, if that snippet of code was from the Overlord engine itself (say, maybe it's in "Overlord/Sprite.h") and instead looked like this

```
#include <d3d11.h>
using Sprite = ID3D11Texture*;

```

then *this* might be more of a concern. Now end-users of Overlord are forced to be aware of D3D11, forced to have it included in all their files depending on this Overlord header, and potentially forced to deal with linking the correct D3D11 libraries.

You can use information-hiding techniques like PIMPL or similar compile-time polymorphism tricks to keep `#include`s of lower-level dependencies like your specific graphics or physics APIs out of your public-facing headers. This can significantly simplify the use of your library, in some cases; in other cases it's simply a stylistic preference on the part of the library author.

By way of example, you could eliminate the D3D header in my example by doing:

```
struct Sprite {
private:
  struct Implementation; // Note: forward declaration
  Implementation* implementation;
};

```

In the `.cpp` file for `Sprite`, you'd write

```
#include <d3d11.h>

struct Sprite::Implementation {
  ID3D11Texture* texture;
};

Sprite::Sprite()
: implementation(new Implementation)) {
  implementation->texture = ...
}

```

and so on. This prevents the type information for `ID3D11Texture` from being needed in the public header, and thus prevents you from including D3D headers in your own public headers.

Based on the context I'm inferring from your question though, I don't think this is something you'd want to bother with for your specific scenario.

---
Tags: c++, design-patterns, oop
---


# Question
Title: Libgdx Resizing Textures for Different Platforms
I'm using viewports to handle different screen resolutions to support multiple platforms (desktop, android, etc.) in my libgdx powered game. I made all image assets for Full HD resolution and thought it will be easy to scale down them for lower screen resolutions. The thing is when I resize them (scale up or down) they are pixelated very badly. **I tried to use TextureFilter.Linear and TextureFilter.MipMapLinearLinear (enabled mipmaps). The result is still not satisfying.** Then I came across this post made by an administrator on libgdx forums:

http://badlogicgames.com/forum/viewtopic.php?p=107267#p107267

He says it scales the texture 60 times a second.

1-) Does it really gets scaled 60 times a second? If so why isn't it scaled only one time at program start? How can i do this?

2-) Since all games which support multiple platforms somehow need to achieve the rescaling, what is the best way to do it? My image editor program can resize it without pixelating so I think there should be a way.

# Answer
This answer explicitly refers to libgdx, but likely applies to other frameworks/engines.

1) It depends on what you consider “scaling” to entail. Can the mip-map level change each frame? Yes. However, the different mip-map levels are generated when the texture is created and uploaded to the GPU internally. Libgdx is not running a reconstruction algorithm each frame.

2) Some games ship with multiple sized source textures. However, many others rely on dynamically resizing content. For those methods, there are better mip-mapping filters than Linear. For example, the Mitchell-Netravali Cubic Filter or Catmull-Rom Cubic Spline Filter - two of the “top tier” filters among many others. You can find implementation details on all of the major reconstruction algorithms here.

For example, this graphic was downsampled from 2380x3360 to 260x400; a massive 1:11 ratio*.

*After downsampling the graphic was upsampled again with a linear filter to more easily compare the effects.
> 1 votes

---
Tags: libgdx
---


# Question
Title: Collision detected at different times depending on speed?
Imagine a scenario where there are four cubes. Two blacks that do not move, one red moving at a constant speed of **two (2)** straight and the other blue moving at a constant speed of **five (5)** also straight.

They all have equal bounding boxes.

By doing a test, I realized that if I put a command so that as soon as the red cube strikes against the black it turns left, the command does not run as soon as they collide ...

With the blue he wanted him to turn right as soon as he hit. The command takes longer to happen, I think because it is faster than red ...

Illustration of the incident:

It seems that the faster the object is, the longer it responds to the collision command. I would like you to give me a solution to this problem.

I've already moved with some bounding box options, but nothing that has given the desired result.

I also moved at the speed of the room, but it did not work either.

Sorry for any translation error. Thanks in advance!

# Answer
> 2 votes
The reason coloured cubes behave this way is because of how you treat collision check - it's not a bug, it's about setting up collision checking system.

***Predicting collisions* vs *computing actual collisions***
Imagine a cube with `speed` equal to 1; it will move one pixel forward each room step, until collision with a black cube occurs.

Since you moved the cube pixel by pixel onto collision, it will snap with the black cube *one* step before the actual collision occurs.

Let's say step *tn* is the time (in room steps) the moving cube snaps with the black one, without actually colliding with it; this is represented in the above image. Then the next step, we call *tn+1*, is the very moment the moving cube is overlapping with the black cube even if for a single pixel.

The highlighted area (intentionally exaggerated) is the result of overlapping sprites when collision is detected, but there are no countermeasures for correcting coordinates.

When you **predict** a collision (e.g. `place_meeting(objID,x+a,y+b)`, where arguments are current coordinates plus speed values), you want to know if the next position implies *overlapping* (not snapping) of objects sprites.

On the other hand, computing a collision on the current coordinates (e.g. `place_meeting(objID,x,y)`) you are asking the engine if the object is hitting a given object already: so the collision as we mean it has already happened. Before going on with game logic, you should carry the object away from the other one so that it doesn't seem it kept moving forward before collision actions occurred.

If the cube moves faster, there may not be a moment when the moving cube snaps the fixed cube; it is a bunch of pixels in front of the still cube, and the next step it is overlapping the other, or even be moved beyond if travelling at very high speed!

**Possible solution**
Try to check for collision *before* moving the cube; if a collision is detected at next position, before changing the cube direction, use `move_contact_solid()` to snap the moving cube to the fixed one, right before the actual collision occurs. *Then*, apply the speed direction variation to turn the cube around.

**Remember:** such solutions are always independent from `room_speed` or other time variables, it's only on the order actions are performed in your game logic.

---
Tags: collision-detection, game-maker
---


# Question
Title: How to make a shattering effect similar to Housemarque's Nex Machina?
After playing Nex Machina for a while, the shattering effect which turns monsters and scenes into cubes really fascinated me and I can't hold my curiosity to explore how they made it. I have tried to google some relevant material but I only found a video which introduces the game engine theory of Nex Machina and a blog post which briefly shows and introduces how they made the effect.

According to the information I have gathered, this shattering effect is achieved via ray tracing and morphing technique, but I don't know how exactly they implemented this. I have found a "Ray-tracing morph" solution here but obviously, it can not achieve the "Cube" effect in Nex Machina.

Since no GDC talk or technical blog is found from Housemarque, we can only guess how they implemented this. Any discussion is welcomed!

# Answer
> 1 votes
According to its wikipedia page, Nex Machina uses Signed Distance Fields.

In the video you linked, the graphics programmer says that their world is actually defined with voxels (and presumably rendered by raymarching it.)

Because their world definition is already volumetric, it is easier to spawn particles inside those volumes.

If you have conventional 3D models that are represented by its boundary as polygons, you would have a harder task. You could convert your boundary representation mesh into voxels, and then use that for a particle simulation. But it wouldn't be able to do it on the impressive scale that Nex Machina does it.

Only partly related to your question, but the most impressive (2D) real time shattering I've seen is in the mobile game "Smash Hit." Its author blogged about the technology behind that one.

---
Tags: rendering, graphics, particles, raytracing, effect
---


# Question
Title: Is there a way to get native resolution of device window/display on android?
When change the framebuffer resolution by calling

```
Screen.setResolution(1920,1080)

```

`Screen.currentResolution, Screen.width, Screen.height` reports back the new resolution 1920x1080.

`Screen.resolutions` gave me empty array (tested on real android device).

I am unable to get back the original resolution which was a native resolution of the device. Do I have to remember the native resolution or is there a way to get that through unity API ?

# Answer
> 3 votes
Old question, but it now has a canonical answer.

From a recent QA on SO:

> `Display.main.systemHeight` and `Display.main.systemWidth`

# Answer
> 0 votes
If you're testing in the editor, then Screen.resolutions could return an empty array since it's not really running in a screen. If you make a build and then test it, then it should give you the correct resolutions and the highest one is your best bet for a native resolution. Now, the better way of doing this, is by a static variable (assuming you're running C#).

Just make a new script named `StaticVariableHolder` (or something like that so you can remember it) and it should go something like this:

```
public class StaticVariableHolder : MonoBehaviour {

 public static Resolution nativeResolution;
 // Use this for initialization
 void Start ()
 {
     DontDestroyOnLoad(gameObject);
     nativeResolution = Screen.currentResolution;
     //print(nativeResolution); //debug line to see if it actually sets the resolution
 }
}

```

Now, add the script to some object like `StaticVariables` (as I have done). This object will now persist through ALL scenes because it's not destroyed on level loads (so be sure to put this in one level only, it shouldn't matter if that level is loaded several times but I'm not sure). Anyway, to get this variable later on you need to some line like this:

```
 Resolution nativeRes = StaticVariableHolder.nativeResolution;

```

Remember, you have to make sure the object is never lost (where the `DontDestroyOnLoad` part comes in) and you have to make sure the variable is public and static, otherwise it won't be accessible unless you search for the object (we don't want that because using Find calls in Update calls will be a huge performance hog).

---
Tags: unity, android, resolution
---