# Question
Title: Proper indoor lighting without directional light
I would like to know how to properly handle indoor lighting without a directional light. My scene has a room( its some kind of shop), in which the player and ai-agents can move around. I can get good results by placing long area lights at the ceiling and baking the light, and placing light probes so the dynamic objects are also affected by the baked light.

The main problem is how can i get real-time shadows for the player and the ai-agents ?

You could position a few point lights roughly where the center of the area lights would be. But i don't know if i can or even should have so many shadow casting lights in one scene. I tried placing 6 or so and i think only 4 of them would actually cast shadows.

I would really appreciate some help. For this project, i've kind of given up on it but i really want to know. Thank you.

# Answer
Static lights should use the light map (as they don't change, there is no need to use dynamic resources).

Moving lights, should use some form of real-time shadow mapping, which involves doing a sort of quick bake of a custom light map based on what it can "see". This is done by doing a depth map render before the lighting phase, for each light (spotlights do a single perspective render, directional lights do an orthographic render, and point lights do a cube map render).

Then, during the lighting phase, for each type of light. a shading pass is done which refers to the corresponding shadow map, and decides if the resulting pixel to be shaded is, or is not, in shadow. if it is, then it gets direct light, if not, then it gets nothing, or maybe just a little ambient light.

There are a few techniques out there, so I would recommend googling shadow map techniques, along with shadow volumes, in conjunction with unity, and decided what is possible, and what works best for you, and learning that.
> 1 votes

# Answer
You would have to render dynamic lighting and shadowmap for the characters/moving-objects in the first pass, then render your entire scene using your static lightmap/shadowmap and dynamic lightmap/shadowmap together in the second pass.

You can afford to have many point lights if you are only calculating light/shadows from point lights for your dynamic objects.

Also research "deferred lighting". It is a method for rendering a large number of lights with 2 passes.
> 0 votes

---
Tags: unity, lighting, shadows, lightmap
---


# Question
Title: How do I represent a 3D world-based game in a 2D Platformer/Top-Down gameview?
To imagine the question lets have the following scenario:

> We have Terraria (a 2D Platformer revolving around harvesting resources and building stuff). We have a large 3D sphere populated with resources (static) and creatures (dynamic and reactive). If the world of Terraria was 3D instead of linear 2D (with 3 layers in the 3rd dimension in total), what are the different ways one could deliver the visualization of such a world/game?

The example I have given above is for a 2D Platformer based on a 3D world. For the above case - the question is easily solved somewhat by converting the 2D platformer into a top-down planar game (Civ V to a limited extent - again represents a cylinder not a sphere; Rimworld nails the top-down solution almost perfectly, but some rasterization using tiles was required) - but lets avoid that and explore some better options.

Another example I would like to give for a top-down 2D planar game based in a 3D space:

> We have a classic Top-Down space invader shooter, in this case, space is completely flat and planar - with limited depth in the 3rd dimension. What if the depth was infinite in the 3rd Dimension? What if the dimensionality of battles in realistic 3D space games were more accurately simulated instead (attacks arriving from multiple dimensions - and not just the same plane)? Ofcourse, keeping the 2d concept of the visualization itself in mind. What are the different ways to make this possible?

And also, *is it even practical?*

This is not easily solved by turning the UI into a platformer. Homeworld tackles this only to a certain extent - but it still limits the depth and reduces the significance of the 3rd Dimension.

# Answer
The old *Roller Coaster Tycoon* game uses 2d isometric tiling.

Isometric projection is a method for visually representing three-dimensional objects in two dimensions. You can read more details on the wikipedia particle about this: Isometric graphics in video games and pixel art.
> 1 votes

# Answer
A cheap way to do something like this would be to use parallax scrolling, and show details higher than the player scrolling faster than the terrain they're crossing.

You'll also want to consider some alpha blending so you don't obscure important game objects (like the player). Note that this is a concern with isometric views as well.
> 0 votes

---
Tags: 2d, 3d, user-experience
---


title: LibGDX: How can i remove inner actors?

text:
# Question
Title: LibGDX: How can i remove inner actors?
How can I remove these(on the picture) actors if I only have access to root's Window methods `getChildren()` and `getCells()` ? I've tried somthing like this: `removeActor(getCells().get(1).getTable().getCells().get(0).getTable()...getTable());`

But it always return the root Table.

**UPDATE**

I've came to this:

```
Cell<FileChooser> cell = getCells().get(1);
removeActor(cell.getActor().getCells().get(0).getActor());

```

But now it throws nonsense Exception:

```
Exception in thread "LWJGL Application" java.lang.ClassCastException: com.kotcrab.vis.ui.widget.file.FileChooser$11 cannot be cast to com.kotcrab.vis.ui.widget.file.FileChooser

```

How class cannot be cast to its own type?

# Answer
> 1 votes
If you could keep a reference to the `VerticalGroup` when you add it then you could simply call `remove` on that `Actor` to remove it from its parent.

If for some reason you can't get a reference to the node when it's either created or added to the `Stage` `Actor` tree then you can traverse the actors using some sort of path to find the one you want to delete. For example; if you know that the "*path*" to the `Actor` that you want to remove is always

```
VisTable/VisScrollPane/VisTable/VerticalGroup

```

then you can use a helper class like this one;

```
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.Array;

public class StageHand {

    public static void removeByPath(Stage stage, Class...classes) {
        removeByPath(stage, new Array<Class>(classes));
    }

    public static void removeByPath(Stage stage, Array<Class> classes) {
        for(Actor actor : stage.getActors())
            removeByPath(actor, 0, classes);
    }

    private static void removeByPath(Actor actor, int index, Array<Class> classes) {
        Class<?> target = classes.get(index);
        if (actor.getClass().equals(target))
        {
            if (index == classes.size - 1)
                actor.remove();
            else {
                if (actor instanceof Group) {
                    for(Actor child : ((Group)actor).getChildren())
                        removeByPath(child, index + 1, classes);
                }
            }
        }
    }
}

```

And you'd call it something like this

```
StageHand.removeByPath(stage, VisTable.class, VisScrollPane.class, VisTable.class, VerticalGroup.class);

```

If you need to delete based on some other criteria (like `Actor`'s `getName` method for instance), then that would be trivial to achieve as well.

---
Tags: java, libgdx, scene2d
---


# Question
Title: Libgdx Texture Size Rounding Problem with Camera
I have a problem with with camera usage. I use camera and a virtual coordinate system because I want to scale my game screen to whatever the actual system resolution is.

If I set camera viewport size to 1200, 1600 for example and real application pixel resolution is 600x800 then this problem happens. I want to draw a 62x62 image to the horizontal center of screen. when I use draw function with x equals (1200/2 - 62 / 2) this problem happens.

600 - 31 = 569. Since i draw 62 units wide in virtual coordinate space, its actually 31 pixels in this example. The problem is 31 pixels is impossible to center on a even numbered x axis (600 actual pixels in this example). But camera tries to solve this very badly by default. It just cuts last vertical line from my image and it's rendered wrong!

Ofc in this example I can change app resolution to whatever I want but I want to focus on mobile and support many different screen resolutions and I just wanna think in virtual coordinate space and its units not the pixels resolution of the device. What's the point of using camera when I think about the resolution? How can I prevent such problems?

If I put image to elsewhere (some even number) in x axis for example x=0 the image scales perfectly well and no missing pixels. If I don't use camera at all it also scales perfectly (using only pixel based units).

If there is no solution I feel like camera and viewport classes are useless and everyone must use pixels.

Screenshot of the problem:

Code for my game class:

```
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class MyGame extends ApplicationAdapter
{
   private SpriteBatch batch;
   private OrthographicCamera camera;
   private Texture myTexture;

   @Override
   public void create ()
   {
      batch = new SpriteBatch();
      batch.enableBlending();
      batch.setBlendFunction(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA);

      camera = new OrthographicCamera(1200, 1600);
      camera.translate(camera.viewportWidth / 2, camera.viewportHeight / 2);

      myTexture = new Texture(Gdx.files.internal("circle.png"), true);
      myTexture.setFilter(TextureFilter.MipMapLinearLinear, TextureFilter.MipMapLinearLinear);
   }

   @Override
   public void render ()
   {
      Gdx.gl.glClearColor(1f, 1f, 1f, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

      camera.update();

      batch.setProjectionMatrix(camera.combined);
      batch.begin();
      batch.draw(myTexture, 569, 150, 62, 62);
      batch.end();
   }

   @Override
   public void dispose () {
      batch.dispose();
      myTexture.dispose();
   }
}

```

Code for its desktop launcher:

```
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class DesktopLauncher {
   public static void main (String[] arg) {
      LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
      config.width = 600;
      config.height = 800;
      new LwjglApplication(new MyGame(), config);
   }
}

```

Image asset I've used in this example:

# Answer
The problem isn't the location of the image -- it's the scaling of the image. The width of the graphic is 62x62. The system needs to know how to represent it as 31x31 image.

The filter that determines how to scale it is a combination of anti-aliasing and the texture filter defined as TextureFilter.MipMapLinearLinear.

You can play around with different filters, but I will add that having a higher resolution texture (e.g. 128x128) will produce better results when filtered down to 31x31.
> 0 votes

---
Tags: libgdx
---


# Question
Title: Head bone not found when importing .blend to Unity
I have created a model, rigged it(using rigify), and created several actions(animation clips) for it Blender. Everything seems to be fine. However, when I import the .blend to Unity I get a console warning that "Required human bone 'Head' not found". I know that there is a bone called "head" in my .blend. The animations work, except the head rotation does appear to not be deforming. Has anyone experienced this? Is this just a naming convention thing. Should I try to rename my "head" bone to "Head"? I just don't know the inner workings of the the import process well enough to know what to do.

# Answer
> 0 votes
I had this same problem so I went to configure it manually. When I selected the Head transform in Unity to assign it to the Avatar, it told me that the Head bone wasn't a child of the Chest bone. I changed this in Blender and when I came back, Mecanim accepted it.

# Answer
> 0 votes
The problem comes from the order you parented the bones. Make sure the Hip bone is not parented to the spine/upper legs. Instead the spine needs to be parented to the Hip (same goes for the upper legs), From there check the order of the nearby bones and correct the order you parented them.

After this Unity will be able to automatically recognize all the bones at the correct locations.

P.S for beginnings bone names are very important (Example) Hips, Spine, Left Upper Arm,Left Lower Arm,Left Hand. ect.

# Answer
> -1 votes
Select the joint as neck end where it is head

---
Tags: animation, blender, unity, bones
---


title: How do i set up 9-slicing in Opengl?

text:
# Question
Title: How do i set up 9-slicing in Opengl?
What is the ideal way to set up 9-slicing?

(for the people who don't know what 9-slicing is)

Let's say we have a quad, with a texture applied to it. 9-slicing is basically a way of dividing a texture in 9 parts. The reason why we do this is to have a quad with a texture, that can be resized without the issue of having the texture all warped. we divide the edges, the corners, and the main body of the texture:

As can be seen in the pictures, we have a quad that can be scaled without warping the texture

which would look something like this(no 9-slicing):

Now, to come back to my question: How should i set up 9-slicing? should i have a multiple quads(one for the center part, one for the right edge, one for the left edge....) but then how do i specify the different texture coordinates for each quad? Another way would be to just create the quads with their texture coordinates and relative textures and then move them all toghether like a whole object. I hope someone explain me a little more about this "9 slicing" approach, since I've never used it before. Thanks everyone for the help

EDIT: (to answer HolyBlackCat)

"Another way would be to just create the quads with their texture coordinates and relative textures and then move them all toghether like a whole object."

What i wanted to say is this: I create separate quads, attach separate textures to them, render and move them at the same time:

This is, in my opinion, the most logical way to do this. Despite that, I still want to know what would be a better, faster way to do this, without having to have too many vertices for a quad

# Answer
The 2 methods (using 1 quad or using 9 quads) is basically a trade-off between using extra CPU time (9 quads) or using extra GPU time (1 quad).

In my opinion the 1 quad method is much better, so I'm going to include it here, if you want the other solution, then I'll add that too.

So, you'll need a border width on the 9-slice texture, the border width on the GUI and the texture coordinates. Before doing anything, you'll need to project the border width of the window to the UV coordinates. This would look something like this:

```
uniform vec2 u_dimensions;
uniform float u_border;

// Later before other operations
vec2 borders = vec2(u_border) / u_dimensions.xx;

// Use borders.x for the x axis and borders.y for the y axis

```

So, you should deal with the 2 axes separately, because they are largely the same. First, if the coordinate on the current axis is less, than the width of the window's border, then you can leave it as it is. If it's less, than `1 - borders.x` if you're dealing with the x axis or `1 - borders.y` if you're dealing with the y axis, then you'll need to scale it a bit. Here's where the border size on the 9-slice texture comes into play. Basically, you'll need to map the values between `textureBorder` and `1 - textureBorder` where `textureBorder` is the width of the border on the 9-slice. And lastly, if the coordinate on the axis is more, than `1 - borders.[x/y]`, then you'll need to map it between `1 - textureBorder` and `textureBorder`. Since the map function doesn't exist in glsl, here's a replacement:

```
float map(float value, float originalMin, float originalMax, float newMin, float newMax) {
    return (value - originalMin) / (originalMax - originalMin) * (newMax - newMin) + newMin;
}

```

You use it as a traditional map function. So, together, the code would look like this:

```
// Helper function, because WET code is bad code
// Takes in the coordinate on the current axis and the borders
float processAxis(float coord, float textureBorder, float windowBorder) {
    if (coord < windowBorder)
        return map(coord, 0, windowBorder, 0, textureBorder) ;
    if (coord < 1 - windowBorder)
        return map(coord,  windowBorder, 1 - windowBorder, textureBorder, 1 - textureBorder);
    return map(coord, 1 - windowBorder, 1, 1 - textureBorder, 1);
}

void main(void) {
    borders = vec2(u_border) / u_dimensions.xx;
    vec2 newUV = vec2(
        processAxis(a_uv.x, u_textureBorder, borders.x),
        processAxis(a_uv.y, u_textureBorder, borders.y)
    );
    // Output the color
    o_colour = texture(sampler, newUV);
}

```

Quick note: if you define your GUI windows, as 3 units wide and 2 units tall and you want the border, to occupy the 1/30 of the horizontal space, then you need to pass 0.1 as the windows border width.
> 1 votes

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


# Question
Title: How can I spawn items based on probabilities?
I'm working on a game where I want to choose which object to spawn based on probabilities. Assuming the decision to spawn the object has been done by some other process, I'd like the object with the highest probability to have a higher chance of being spawned. An object with 50% spawn probability should spawn more often than an object with 15% spawn probability. I also need to account for instance where a game object has the same spawn probability

```
GameObject 1 .50
GameObject 2 .25
GameObject 3 .25

```

How can I implement this logic?

# Answer
> 2 votes
There are different ways of doing this. Here I am giving two ways of getting a weighted game object. The first one is easy but not a good practice and has a lot of issues. I have commented on the code so that you can easily understand. If you have any confusion feel free to tell me here.

```
using System.Linq;
public class RandomObject
{
  public GameObject randomObj;
  public int priority;

}

public class CumilativeSelection
{
  public List<RandomObject> objectList;
  System.Random rnd = new System.Random();
// This logic is straught forward but might not be currect always (Not a good choice)
// 1. You pick a value from 1 to 10 (or may be 1 to 100 whatever)
// 2. Probability of having 1 is 1/10, 2 is 1/10 and so on (Uniform Destribution) .So the
//    Probability of having 1 to 4 is (1/10 + 1/10 + 1/10 + 1/10) = 0.4 or 40%
// 3. Now you can spawn on a particular object with a 40% of probability.
void EasyRandom()
{

    int val = rnd.Next(1, 10);
    if(val<2)
    {
        //10% probabilty of coming to this block
        //Spawn an object which has 10% probability
        //1/10 = 0.1
    }
    else if (val < 6)
    {
        //50% probabilty
        // 1/10 + 1/10 + 1/10 + 1/10 + 1/10 + 1/10 = 5/10 = 0.5
    }
    //And so on
}

// This logic is called the Cumilative Destribution Function. More accurate and a bit
// complex. To learn more go to link: http://www.vcskicks.com/random-element.php This
// guy had made the explanation really easy. My logic is kind of similar to him with a few
// variation.

GameObject GetObjectWithMaxProb()
{
    int totalWeight = objectList.Sum(t => t.priority); // Using LINQ for suming up all the values
    int randomNumber = rnd.Next(0, totalWeight);

    GameObject myGameObject = null;
    foreach (RandomObject item in objectList)
    {
        if(randomNumber < item.priority)
        {
            myGameObject = item.randomObj;
            break;
        }
        randomNumber -= item.priority;
    }
    return myGameObject;
}

```

So, what we are basically doing here is picking a random value between zero and the total weight. Then, just checking which of the item has more priority than the random number just generated and return that game object. I have tested the second function with unity and it did a great work giving the object with most probability. I have uploaded the full project to github if you want to check. https://github.com/Shubhra22/WeightedRandom.git

# Answer
> 2 votes
In genetic programming, this is called the roulette selection function/algorithm. Here's one way to implement it:

```
int selectFromRoulette(double[] weight, Random rng) {
    double total = 0;
    double amount = rng.nextDouble();
    for(int a=0; a<weight.length; a++){
        total += weight[a];
        if(amount <= total){
            return a;
        }
    }
    return -1;
}

```

The above code takes an array of mutually exclusive probabilities (weights) and randomly selects one of them. If the probabilities sum up to less than 100%, there's a chance than none of them will get selected - in that situation, the method will return -1. It assumes that the sum of the probabilities doesn't exceed 100%. Also, keep in mind that testing for equality of floating numbers is error prone, so you probably don't want this exact solution if you're making casino games.

# Answer
> 0 votes
Yes. This is quite similar to how you do what is called a "weighted average".

Your rand() function needs to be able to take a range as floats, many do not.

OTOH, if your probabilities are always going to be percentages, consider storing them as unsigned integers instead. Once upon a time, that would have been a no-brainer, but these days floating point operations are cheap and memory access is expensive. Why when I was your age...

OTOOH, if your language frees you from such concerns, then never mind that crusty ol guy sitting in my chair.

# Answer
> 0 votes
Since your probabilities sum up to 1, you can basically loop through the objects adding the previous probability to the probability to select the object (this basically generates a probability density function). More clearly:

```
r = U(0,1) // random value drawn from a uniform distribution
if r <= p_1 // if the random value is smaller than the probability to call object 1
    obj = 1 // call object 1
else if r <= (p_1 + p_2) // else, compute probability to call object 2, and check if it applies
    obj = 2
else if r <= (p_1 + p_2 + p_3) // else compute probability 3...
    obj = 3

```

Since `r` is uniformly distributed, you will have the right proportion of object 1, 2 and 3.

Of course, in code, you would probably have a vector of gameObjects with their corresponding probabilities (make sure the probability vector sums to 1).

Example (in c#):

```
GameObject[] myGoArray = new GameObject[]{go1,go2,go3};
float[] myAssociateProb = new float[]{.5f,.25f,.25f};

float r = Random.Range(0f,1f);
GameObject selectedGo;
float currentProb = myAssociateProb[0];
for(int i = 0; i < myGoArray.Length; i++){
    if(r <= currentProb){
        selectedGo = myGoArray[i];
        break;
    }
    currentProb += myAssociateProb[i + 1];
}

```

---
Tags: c#, mathematics, random, spawning
---


# Question
Title: Calculate corner rotation to fit between 2 waypoints
I'm currently working on a system where I create a linear path by spawning waypoints, but i'm struggling to figure out how to compute the rotation needed to render the corner waypoints correctly.

if I rotate it towards (nextSegment.Coordinate - myCoordinate) it almost seems correct, most corners are behaving how I want.

but you can see the first 2 corners, and one near the end are incorrect.

if I rotate it towards (prevSegment.Coordinate - myCoordinate) it solves the rotation for the incorrect segments in the previous solution.

I know the coordinate of the next cell, and the previous cell and the cell i'm trying to rotate.

But then the other segments are incorrect. I cannot figure out the pattern on how to decide which segment to rotate towards. Any ideas?

# Answer
You cannot correctly angle the L shaped block without having the coordinate of both the previous block and next block. That being said...

The direction of the arrows is irrelevant to the problem. Each line on the L shaped block must point to a block next to it, so you only have 4 possibilities for corner shapes.

There are many ways to do it, but you could rotate it based on which quadrant the average of the coordinates of the next and previous tiles end up in. (relative to current)

```
Avg.x = (nextSeg.x + prevSeg.x)/2 - myCoord.x
Avg.y = (nextSeg.y + prevSeg.y)/2 - myCoord.y

if Avg.x > 0 && avg.y > 0
    Angle = 0
if Avg.x > 0 && avg.y < 0
    Angle = -90
if Avg.x < 0 && avg.y > 0
    Angle = 90
if Avg.x < 0 && avg.y <  0
    Angle = 180

```

Angles depend on your 0 deg position

EDIT: updated per response, multiplied by 2 to fix flooring

```
avg.x = (nextSeg.x + prevSeg.x - 2*myCoord.x);
avg.z = (nextSeg.z + prevSeg.z - 2*myCoord.z);

if avg.x > 0 && avg.z > 0
    angle = 0
if avg.x > 0 && avg.z < 0
    angle = -90
if avg.x < 0 && avg.z > 0
    angle = 90
if avg.x < 0 && avg.z <  0
    angle = 180

```
> 0 votes

---
Tags: unity, mathematics, rotation
---


# Question
Title: Destroyed GameObject but still trying to access it(C# Unity)
**EntryPoint.cs**

```
protected IEnumerator LoadAsync(string prf_path, Transform prt_tf, bool is_enable = true)
{

    ResourceRequest res_req = Resources.LoadAsync<GameObject>(string.Format(prf_path, quality));
    res_req.priority = 0; // = ThreadPriority.Low;
    yield return res_req;

    if (res_req == null || res_req.asset == null)
    {
        res_req = Resources.LoadAsync<GameObject>(string.Format(prf_path, "HIGH"));
        res_req.priority = 0; // = ThreadPriority.Low;
        yield return res_req;
        Debug.LogFormat(prf_path, "HIGH");
    }
    else
    {
        Debug.LogFormat(prf_path, quality);
    }

    GameObject prf = res_req.asset as GameObject;
    GameObject obj = Instantiate(prf);

    obj.transform.SetParent(prt_tf);
    obj.transform.localScale = Vector3.one;
    obj.transform.localRotation = prf.transform.localRotation;
    obj.transform.localPosition = prf.transform.localPosition;
    obj.name = prf.name;
    yield return new WaitForEndOfFrame();
    obj.SetActive(is_enable);
}

```

> `obj.SetActive(is_enable);` when i click the error it's pointing me here

LOBBYUI: I have an option which is Option `Rendering` and Option `Livestreaming`. Now here's the problem . When i tried to run my program for the very first time and choose Option `Livestreaming` it will work then i'll logout then it will go back to my LobbyUI and choose the Option `Rendering`. Then this error will come out

> Object of type 'GameObject' has been destroyed but you are still trying to access it.

Now when i tried this line of code

```
if (obj != null)
    {
        obj.SetActive(is_enable);
    }

```

It will point out to my object which is initiated and that's pretty weird . Any idea?

# EDIT:MORE INFO

I load my resources using this line of code:

**MC\_EntryPoint: EntryPointA**

```
 if (PlayerPrefs.GetInt(OptionPopup.LiveStreaming_) == 1)
    {
        tf = transform.Find("UI Root/FullscreenPanel/Screen3DUI/panel (depth 1~2)");
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/logo", tf));
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/card_open_window", tf));
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/ranking", tf));
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/streaming_feed", tf));

        tf = transform.Find("UI Root/FullscreenPanel/Screen3DUI/panel (depth 10~11)");
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/midterm_loading", tf));

        tf = transform.Find("UI Root/FullscreenPanel/Screen3DUI/panel (depth 12)");
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/game_result", tf));
    }
    else
    {
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/minimap_type_b (x_ 1575, 1356)", tf));
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/replay", tf));

        tf = transform.Find("UI Root/FullscreenPanel/Screen3DUI/panel (depth 1~2)");
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/logo", tf));
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/card_open_window", tf));
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/ranking", tf));
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/top_bar", tf));

        tf = transform.Find("UI Root/FullscreenPanel/Screen3DUI/panel (depth 10~11)");
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/midterm_loading", tf));

        tf = transform.Find("UI Root/FullscreenPanel/Screen3DUI/panel (depth 12)");
        yield return StartCoroutine(LoadAsync("MC_VERSION/{0}/UI/Screen3DUI/game_result", tf));
    }

    loading.SetValue(0.02f);    // 2%.

```

So it's something like . Is there any other way load some of my **UserInterface** if i'm from `Livestreaming`(which i do not load some UI) to `Rendering` (which i load some UI).

**EntryPointA:EntryPoint**

```
protected override IEnumerator Init()
{
    tzPlayInfo.Instance.BLOCK_GAME_FLOW = true;
    tzPlayInfo.Instance.MAKING_GAME_OBJECT = true;
    //start_time = Time.realtimeSinceStartup;
    loading.SetValue(0f);       // 0%.

    yield return StartCoroutine(InitSystem());
    //Debug.Log(string.Format("End InitSystem - {0}s", Time.realtimeSinceStartup - start_time));
    loading.SetValue(0.01f);    // 1%.

    yield return StartCoroutine(InitUI());
    //Debug.Log(string.Format("End InitUI - {0}s", Time.realtimeSinceStartup - start_time));
    loading.SetValue(0.05f);    // 5%.

    yield return StartCoroutine(InitGO());
    //Debug.Log(string.Format("End InitGO - {0}s", Time.realtimeSinceStartup - start_time));
    loading.SetValue(0.95f);    // 95%.

    yield return StartCoroutine(InitServerDependentInfo());
    //Debug.Log(string.Format("End InitServerDependentInfo - {0}s", Time.realtimeSinceStartup - start_time));
    loading.SetValue(0.96f);    // 96%.

    yield return StartCoroutine(Recheck());
    //Debug.Log(string.Format("End Recheck - {0}s", Time.realtimeSinceStartup - start_time));
    loading.SetValue(1f);       // 100%.
    CameraManager.Instance.TurnOnCamera(eCmr.PADDOCK_1); // 로딩이 끝나면 카메라를 켠다.
    tzPlayInfo.Instance.BLOCK_GAME_FLOW = false;

    Destroy(loading.gameObject);    // 첫로딩 UI 삭제.
    Destroy(this);                  // EntryPoint 컴포넌트 삭제.
}

```

# EDITTED QUESTION

I guess the information I provided was a bit stiff so i edited it. And i'm guessing that it is null because I destroy something??? Please enlighten me.

# Answer
I'll answer my own question . What i did here is that this line of code

```
protected IEnumerator LoadAsync(string prf_path, Transform prt_tf, bool is_enable = true)
{

ResourceRequest res_req = Resources.LoadAsync<GameObject>(string.Format(prf_path, quality));
res_req.priority = 0; // = ThreadPriority.Low;
yield return res_req;

if (res_req == null || res_req.asset == null)
{
    res_req = Resources.LoadAsync<GameObject>(string.Format(prf_path, "HIGH"));
    res_req.priority = 0; // = ThreadPriority.Low;
    yield return res_req;
    Debug.LogFormat(prf_path, "HIGH");
}
else
{
    Debug.LogFormat(prf_path, quality);
}

GameObject prf = res_req.asset as GameObject;
GameObject obj = Instantiate(prf);

obj.transform.SetParent(prt_tf);
obj.transform.localScale = Vector3.one;
obj.transform.localRotation = prf.transform.localRotation;
obj.transform.localPosition = prf.transform.localPosition;
obj.name = prf.name;
yield return new WaitForEndOfFrame();
obj.SetActive(is_enable);
}

```

Doesn't work on Android Phone . It's basically for PC Platform only . So right now currently I'm making a method for Mobile. I'll edit my answer after i finish this up. Thanks guys
> 2 votes

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


title: Need insight on item system

text:
# Question
Title: Need insight on item system
I have made an item database that takes keyed values from a database script then assigns them to an item class, then stores that item class in a List variable.

This works fine but I have come across something that I see as potentially troublesome. For every unique effect, I have to make another keyed value and apply it to all the existing collections in the database.

I want to make it such that an item can hold only 6 special values(physical damage, magical damage, armor, heal, etc) but with this method, I don't know how to tell the script which value goes to which special effect.

Below is a template item from the database file. I use GRFON for this. See how I have written down all the possible damage types but for special values, I made 7 only with 6 of them being generic. The damage types can easily be assigned but when it comes to the special values, I have a hard time assigning magnitudes to special effects.

```
{
iD: 0
name: Template
category: Null
type: Null
subtype: Null
values: {
    physical: 0, magical: 0, hot: 0, cold: 0, electric: 0, dark: 0 }
specialvals: {
    spMag1: 0, spMag2: 0, spMag3: 0, spMag4: 0, spMag5: 0, spMag6: 0, spDuration: 0 }
special: none .
properties: {
    mass: 0, durability: 0, maxdurability: 0, charge: 0, maxcharge: 0, accuracy: 0, useRate: 0, reloadRate: 0, range: 0 }
description: This is a template item.
equippable: 0
usable: 0
stackable: 0
maxStacks: 1
count: 0
rarity: 0
price: 0
uID: template
}

```

# Answer
Having variables in data structures which mean different things in different contexts is an anti-pattern. It easily leads to a lot of confusion.

What you could do instead is to store these in a list of key-value pairs.

The JSON representation would look like that in JSON:

```
specialvals: [
    { key: "fireaura_range", value: 30 },
    { key: "fireaura_duration", value: 10 },
    { key: "radioactivity", value: 10 },
    { key: "considered_contraband_during_smuggling_quest", value: 1 },
    { key: "tastefulness_in_soup_receipt", value: -590 },
]

```

On the C# layer, you would either represent this with a `Dictionary<String, Int32>`.

When your item database is an SQL database, then these special values would be stored in a database table separated from the items table with 3 columns `ItemID`, `key` and `value` with the primary key being `ItemId` and `key`.

---

A completely different approach would be a component-based architecture.

Instead of trying to represent every possible item functionality in one class, you create a bunch of "component" classes and each item can have any number of these classes.

```
   components: [
       { type: "aura_damage",
         element: "fire",
         range: 30,
         duration, 10 },
       { type: "radioactive",
         radioactivity: 10 },
       { type: "soup_ingredient",
         taste: "salty",
         value: -590 },
       { type: "smuggling_quest_contraband",
         illegality: 500 }
   ]

```

Your item would then have a list of components with 4 entries. Each entry would be a different class which inherits from a `Component` base class and has the variables applicable for that type.
> 1 votes

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


title: Entity Component System data duplicate

text:
# Question
Title: Entity Component System data duplicate
I've read some articles about Entity Component System and I like this idea of "entities" having lots of "components" to define them, so I tried to implement it. Here is an simple overview of what i've got so far:

I've a template class that will hold a list for each component type that exit

That allows me to have a collection of components by its type

Which is good because in memory components will be contiguous

Then I've a component manager that hold all these collections and allows me to retrieve a collection at any time

Also, each entity keeps tack of all components it has with a bitset

So in the final result, each index of all component containers belongs to an entity

I know that this causes a problem than, not all entities have all components, so it causes a waste of space... But for now, I can (saldy) live with it

But the **real issue** for me here is that some components will have same data, and if each entity have a component for that data, this data will be duplicated unnecessary

Even worst, it would require OpenGL to have different objects in memory that are exactly equal and having to enable those objects and disable them many times is not desirable at all.

I've been scratching my head to figure out a solution for this issue but I can't find any. Could someone give me an advice please?

If you've read this far, Thank You!

# Answer
> 1 votes
When you have a large amount of data shared between multiple game entities, then the component representing that data might be a good candidate for the flyweight pattern. Your `Mesh` component shouldn't include the full mesh data. It should only have a reference to which mesh asset is used to represent that entity (in an OpenGL-based graphic engine, this could just be the ID of the vertex buffer object), plus any entity-specific metadata which is relevant to how that mesh is applied to this particular entity. The mesh assets themselves should be stored in an own data structure separated from the entities.

Now you might be skeptical about what this means for memory locality when the mesh data is no longer close to the rest of the entity. But you need to ask yourself: if the data is shared, how often will you actually access it? Remember that you can not manipulate it while processing a specific entity, because that manipulation would also affect all other entities. There are also very few reasons I could think of to regularly access the actual mesh data. Your rendering system will just require the VBO id and the model matrix derived from your Transform component.

The only thing I could think of which could make use of the actual mesh data is collision detection, and in that case you should not use the high detail meshes used for the graphical representation. Performance will force you to use a low-detail mesh which would be small enough that data duplication isn't that much of an issue anymore.

# Answer
> 0 votes
Each of your ComponentCollection might have different constraints or ways to optimize data storage, so I would relax the design of the base class.
By doing so, the template-based ComponentCollection could be *one implementation* of the base class, used for standard component types, while your Mesh collection could store data with another structure, more appropriate to share meshes among different entities.

---
Tags: opengl, c++, entity-component
---


# Question
Title: Gamemaker Studio 2 html5 game sfx influence background music volume
When I run my game in html5 the game sound effects for shooting makes the background music less audible. It is like the volume of the bg music goes down. And when shooting is done it goes up again.

When I run my game in test everything is fine. How can I fix this?

# Answer
> 1 votes
My problem was caused by many bullets that were all fired at once with each their own soundeffect. All these sound effects together caused the problem. Now I only play the sound once and the problem is gone.

---
Tags: game-maker, sound
---


# Question
Title: Why does this code never switch back to the object at index 0?
I have two `GameObject`s in an array, and the S key is used to cycle an index referring the objects in this array.

When I run the game for the first time and press S, it changes from 0 to 1 and then to 2. After that it just cycles between 1 and 2... but it should be changing between 0 and 1 only; there are only two objects.

Why is this behavior occurring? My code is below:

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

public class SwitchObjects : MonoBehaviour
{
    public GameObject[] objects;
    public int activeIndex = 0;

    public void SetActiveObject(int aIndex)
    {
        activeIndex = aIndex;
        for (int i = 0; i < objects.Length; i++)
            objects[i].SetActive(i == activeIndex);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.S))
        {
            if (activeIndex == objects.Length)
                activeIndex = 0;
            activeIndex++;
            SetActiveObject(activeIndex);
        }
    }
}

```

# Answer
I belive your problem is here:

```
        if (activeIndex == objects.Length)
            activeIndex = 0;
        activeIndex++;

```

You set activeIndex to zero, but then increment it immediately. So the solution should be:

```
if (activeIndex == objects.Length)
    activeIndex = 0;
else
    activeIndex++;

```
> 3 votes

# Answer
```
if (activeIndex == objects.Length)
                activeIndex = 0;
++activeIndex;

```

This statement resets activeIndex to 0 then immediately adds 1, so activeIndex can never be reset to 0.
> 3 votes

---
Tags: c#
---


# Question
Title: How do you support different VR platforms?
I created an Android app for Gear VR in Java (using the GearVR framework) that I now want to port to Unity, so it can also be used for Microsoft's semi-new Mixed Reality headsets (for Windows; not HoloLens, though).

I've never worked with Unity (or C#) before, that's why I have a question:

How would you set up something like that? Can you simply create a single project and then put it on your (Android) phone/compile it on your PC depending on where you want to test it, or do you need separate projects for different platforms?

# Answer
> Can you simply create a single project and then put it on your (Android) phone/compile it on your PC depending on where you want to test it, or do you need separate projects for different platforms?

Yes, you can create a single project and build it for each platform you want to target. This is one of the major benefits / reasons to use a multiplatform game engine like Unity.

For a very simple project, this should mostly "just work" - you select your build platform from the build settings dialog and you're off to the races.

As you start using more platform-specific libraries, tools, input conventions, etc. you might need to expand on this with things like native plugins, conditional compilation, asset bundles, or custom build scripts to control what gets included in each platform, or abstraction layers to keep the bulk of your game code & content cross-platform.

Andrew Carvalho of Laundry Bear Games gave a great talk about how to do this type of platform-specific work at EGLX 2018 - I tried to capture some of the main points in a livetweet thread. Keep an eye out for the video of the session to get the whole story.

This work tends to be very bespoke for the type of per-platform adjustments a particular game needs, so if you find that you need more than what comes out of the box, you can post a new question here detailing the specific task you need to accomplish / build errors you're getting, and how you're trying to solve them, to get tailored help in making it work.
> 1 votes

---
Tags: unity, android, windows, virtual-reality, gearvr
---


title: Scene components and renderer

text:
# Question
Title: Scene components and renderer
I'm currently writing a very small game engine for learning purposes, and hit a block when trying to separate the engine's logic from the "rendering" module.

My current approach is to feed my renderer with a pointer to a "Scene", iterate through its nodes, test them with a static\_cast(yeah you read that right) to a "Renderable" object (for example a static mesh class that contains a material and a vertex array) and draw.

I'm aware that this approach is terrible but I can't think of an alternative. At this point I feel like my architecture is complete spaghetti. Any indication would be much appreciated.

# Answer
> I'm aware that this approach is terrible but I can't think of an alternative.

Design-wise, your approach is fine. A rendering interface should know how to consume objects that describe a single (or set of) drawing requests and translate those into state configuration and draw calls for the underlying graphics API. For your renderer, it sounds like your `Renderable` objects are exactly that: a representation of something to draw. So this is fine.

Implementation-wise, however, your approach has some minors flaws.

> My current approach is to feed my renderer with a pointer to a "Scene", iterate through its nodes, test them with a static\_cast(yeah you read that right) to a "Renderable" object (for example a static mesh class that contains a material and a vertex array) and draw.

It sounds like you are coupling the renderer to the scene this way (by having the renderer "know about" scene types, such as `Scene` and `Node`; it sounds like `Renderable` is a child of the latter and that the former is a broader type of scene than *just* a rendering one (that is, that you have `Node` types that are not rendering-related).

Furthermore, `static_cast` isn't a good way to "test" nodes. It will always "succeed" in performing a downcast (take a look at point #2 in under the Explanation section in the above link about `static_cast`), but using the resulting `Renderable` may result in a crash because the `Node` really *was not* a `Renderable`. `dynamic_cast` would be the right tool here.

But there's no reason to involve down-casting at all. Rather than give you renderer a `Scene` directly, just change its interface so it gets a set of `Renderable` objects, such as via a `const std::vector<Renderable*>&` parameter. Now the `Renderer` doesn't "know about" the `Scene`.

`Renderable` itself doesn't need to derive from `Node`, it can just be a base class on its own. Now your renderer is decoupled entirely from `Scene` and its related higher-level API.

In the `Scene` itself, store the array of `Renderable` objects for the scene *separately* from the nodes in the scene. You can have nodes in the scene fill this list up with `Renderable` objects they'd like to have drawn as part of the routine processing of your logic update. Then, at the start of rendering for that frame, you just give the renderer the list of `Renderable` objects that the scene has built up for that frame, and let it do its job.

The key idea here is that the "scene" is a high level concept and the renderer is a lower-level one. High level APIs can know about, and use, lower-level ones but such visibility should not go the other way. By enforcing that kind of unidirectional data flow you can keep code less coupled and simpler.
> 1 votes

---
Tags: architecture, rendering, scene-graph
---


title: Generate cave like Terrain in 2D

text:
# Question
Title: Generate cave like Terrain in 2D
I want to create 2D Terrain randomly. It should look like a connected Cave (Shown below). What is the best method or Algorithm to get similar results?

The important part is the open area(green) and that it is fully surrounded by walls(brown).

4 Examples:

# Answer
> 2 votes
1. Generate a cave map using an algorithm based on cellular automata. For example http://www.roguebasin.com/index.php?title=Cellular\_Automata\_Method\_for\_Generating\_Random\_Cave-Like\_Levels

1.1. To make the cave fully connected you can for example do an iterative method based on (1).

First generate the cave map from randomly filled area.

Identify connected regions by flood-fill.

Remove the ones with are under some arbitrary threshold.

Then discretize the cave into squares (or rectangles). I did this to reduce number of nodes (and it was needed for some other features so might as well do it there).

Then form a graph between these squares (square is a vertex, edge is between square that are connected).

Find the MST (minimal spanning tree), but treat all vertices (squares) in one connected cave region as one vertex of MST (use the region\_id for determining equality of nodes). I made a quick sketch of how it could look like:

Regenerate the cave but put some more empty cells on the path of the MST, this will make it more probable for it to be a passage there after some iterations of CA.

Do until there is only one region.

I found it quite fast for maps of the size 256x256.

That's how it should look like after a few iterations. I had more visualizations but unfortunately I can't recompile it right now and make screens.  Smaller maps should look more like on your pictures.

Also you can just force border walls after the generation.

2. Generate a noise map using for example simplex or perlin noise
3. Scale the noise map by a function of the distance to the wall so there is smaller probability of having high parts near walls.

# Answer
> 4 votes
You could generate, analyse and discard random noise fields.

Just generate thousands of them, and keep the ones that have a fully enclosing wall on the outside.

For generation, I would use Simplex Noise. Here is my implementation in C for it.

After generating a 2D field with values in range \[-1,1\], you pick a threshold value (let's assume 0.0) and define WALL as \> 0 and VOID as \<= 0.

Then you test the entire rim (x==0 || x==max || y==0 || y==max) for being WALL. If one value on the rim is not WALL, discard this cave, and generate a new one with different noise coordinates.

You can put more restrictions on it too, as: no disconnect of the cavity. To test this, floodfill from a void sample. If the set does not contain all void values, then the void is disconnected, and could be discarded.

For a little more efficiency, you could also dynamically pick the threshold value by setting it to the lowest value found on the rim. This way, a closed rim is guaranteed. (Note that you can also guarantee this using Sean's suggestion of scaling the values based on distance to the centre.)

And then examine the cave. If it is too small, or disconnected, continue to the next random field.

But the key point I am trying to make here: you don't have to specifically force your generator to satisfy constraints, it is enough if you can analyse and identify these constraints after which your filter your solution.

# Answer
> 3 votes
I think you will get similar results if you do it like this.

Start with some points in a circle around your cave area.

Jitter the points by moving each one randomly from it's starting position.

Trace the lines in between each point using an algorithm to generate thickness.

You could do this last part by checking point-to-line-segment distance on each square, or by creating a line of arbitrary thickness.

---
Tags: procedural-generation, terrain, random, noise
---


# Question
Title: The GameObject transform automatically sets to (0, 0, 0) when i apply Perlin Noise
I am learning how to use the Perlin Noise with some Documentation. So far i mostly understood quite a lot.

Here i post the codes in order:

**The Noise Code**

```
public static class Noise {

public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, float scale)
    {
        float[,] noiseMap = new float[mapWidth, mapHeight]; //We create new 2D array

        if (scale <= 0)//If input scale is 0 we will have a 0 div!!
        {
            scale = 1f;

        }

        //We loop through the noise map
        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                //Now at which point we are sampling our height values
                float SampleX = (float)x/scale; //For non integer values we divide by scale
                float SampleY = (float)y/scale;

                float perlinValue = Mathf.PerlinNoise(SampleX, SampleY);
                noiseMap[x, y] = perlinValue; //We assign the Perlin noise value to the 2D thing
            }
        }
        return noiseMap; //We return the noiseMap we generated
    }
}

```

**The Map Generator**

```
public class MapGenerator : MonoBehaviour {

    public int mapWidth;
    public int mapHeight;
    public float noiseScale;

    public bool autoUpdate;

    public void GenerateMap()
    {
        //We will fetch the noiseMap from the Noise class
        float[,] noiseMap = Noise.GenerateNoiseMap(mapWidth, mapHeight, noiseScale);

        MapDisplay display = FindObjectOfType<MapDisplay>();
        display.DrawNoiseMap(noiseMap);

    }

}

```

**Map Display**

```
public class MapDisplay : MonoBehaviour {

    public Renderer textureRender;

    public void DrawNoiseMap(float[,] noiseMap)
    {
        int width = noiseMap.GetLength(0);
        int height = noiseMap.GetLength(1);

        Texture2D texture = new Texture2D(width, height);

        Color[] colourMap = new Color[width * height];
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                colourMap[y * width + x] = Color.Lerp(Color.black, Color.white, noiseMap[x, y]);
            }
        }
        texture.SetPixels(colourMap);
        texture.Apply();

        textureRender.sharedMaterial.mainTexture = texture;
        textureRender.transform.localScale = new Vector3();
    }
}

```

**EditorControls Code**

```
//This class controls the editor so instead of MB we use Editor
[CustomEditor (typeof(MapGenerator))]
//We have to say it is custom and the "typeof" of the class
//the custom editor is, in that case. MapGenerator

public class MapGeneratorEditor : Editor {

    public override void OnInspectorGUI()
    {
        MapGenerator mapGen = (MapGenerator)target;//The object being inspected.

        //If we changed anything in the Editor, it will autoupdate.

        if (DrawDefaultInspector())
        {
            if (mapGen.autoUpdate)
            {
                mapGen.GenerateMap();
            }
        }

        if (GUILayout.Button("Generate"))
        {
            mapGen.GenerateMap();
        }

    }

}

```

This last piece of code makes a button inside the Inspector so when i press it. The whole thing runs and gives me the Perlin Noise Map displayed on a plane.

**Plane Configuration (Inspector)**

**QUESTION**

The problem i have right now is that when i press the Generate Button (see below):

The Planes Scale goes from (1, 1, 1) to (0, 0, 0) and i do not know why it does that. The only way to get back my Perlin Noise displayed on that Plane is if i manually setup the plane a Scale.

What i am missing here?

Thanks for answer.

# Answer
> 3 votes
You told it to set the scale to zero when you wrote `textureRender.transform.localScale = new Vector3();` That's because a new Vector3 is initialized to (0,0,0). Scale is multiplied, so "no change in scale" is represented by the value of 1 (not zero), so you probably meant to set the scale to (1,1,1), so you'll need to write `new Vector3(1,1,1)`.

Alternatively, the default localScale is (1,1,1) so you could just avoid assigning it a new value altogether and keep its original value of (1,1,1).

---
Tags: perlin-noise, heightmap
---


# Question
Title: Show only some parts of a point cloud. OpenGl4
I am developing an opengl 4.0 app which is showing a point cloud. In the other hand, I have an array "pos" where I have some x,y,z positions:

```
pos[number of pos][3] , where 3 refers to [0]:x [1]:y [2]:z

```

I would like to show only the points of the point cloud which are inside of a sphere of radius R for any of the positions I have in the array pos. I was thinking in sending the array pos to the vertex shader that draws my cloud point and there, do a loop for each position and check if the distance between any of the positions and the vertex is less than a radius R. If so, I put an alpha colour of 1.0. If not, an alpha colour of 0. Something like:

Vertex:

```
#version 460

uniform mat4 viewMatrix, projMatrix;
uniform float Radius;

in vec4 position;
in vec3 pos[N];

in vec3 color;

float d;

out float Color;
out float AlphaC;

void main()
{
    Color = color;
    AlphaC = 0.0;

    for ( int i = 0; i < pos[i].length; i++ ) {
        d = distance(vec4(pos[i],1),position);
        if (d<Radius) {
            AlphaC = 1.0;
            break;
        }
    }

    gl_Position = projMatrix * viewMatrix * position ;
}

```

Fragment:

```
#version 460

in float Color;
in float AlphaC;

out vec4 outColor;

void main()
{
    outColor = vec4(Color, AlphaC);
}

```

But I am not sure how to send this pos array since this matrix is an Nx3 with N depending in the file of positions that I am using. Any idea? Does N has to be defined before compiling?

# Answer
It sounds like you want to have points that are more than a certain distance from all other points not be drawn, right? If so, I would recommend using something like an Octree data structure to store your points.

With an octree you generate a bounding box around all your points. You then break that up into 8 smaller boxes (cutting the big box in half along each axis). You continue cutting the boxes in half until it gets down to the size of the maximum allowed distance between points.

Next you insert your points into the octree. Each point gets filtered down into the smallest box that contains it. Once all the points are in, you can walk the tree. For each leaf box in the tree, if it contains more than 1 point, then all points in that box should be added to the list of points to draw, because they are by definition all within the maximum allowed radius.

For leaf boxes that contain a single point, you need to compare that point to the points in the neighboring 26 leaf boxes to see whether it's within the maximum allowed distance. As soon as you find 1 point that it's close enough to, you know to include that point in the list of points to draw.

Finally draw only the points in the list you built.
> 1 votes

---
Tags: opengl, alpha-blending, point-cloud
---


# Question
Title: How can I get the vector3's names to gameobject name?
```
void DrawBox()
    {
        SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color);
        SpawnLineGenerator(v3FrontTopRight, v3FrontBottomRight, color);
        SpawnLineGenerator(v3FrontBottomRight, v3FrontBottomLeft, color);
        SpawnLineGenerator(v3FrontBottomLeft, v3FrontTopLeft, color);

        SpawnLineGenerator(v3BackTopLeft, v3BackTopRight, color);
        SpawnLineGenerator(v3BackTopRight, v3BackBottomRight, color);
        SpawnLineGenerator(v3BackBottomRight, v3BackBottomLeft, color);
        SpawnLineGenerator(v3BackBottomLeft, v3BackTopLeft, color);

        SpawnLineGenerator(v3FrontTopLeft, v3BackTopLeft, color);
        SpawnLineGenerator(v3FrontTopRight, v3BackTopRight, color);
        SpawnLineGenerator(v3FrontBottomRight, v3BackBottomRight, color);
        SpawnLineGenerator(v3FrontBottomLeft, v3BackBottomLeft, color);
    }

```

And the gameobjects name:

```
    void SpawnLineGenerator(Vector3 start, Vector3 end, Color color)
    {
        GameObject myLine = new GameObject();
        myLine.name = start.ToString();

        myLine.transform.position = start;
        myLine.AddComponent<LineRenderer>();
        LineRenderer lr = myLine.GetComponent<LineRenderer>();
        lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
        lr.startColor = color;
        lr.endColor = color;
        lr.startWidth = 0.03f;
        lr.endWidth = 0.03f;
        lr.SetPosition(0, start);
        lr.SetPosition(1, end);
    }

```

The method SpawnLineGenerator get two vector3 and a color:

```
SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color);

```

In the SpawnLineGenerator i'm setting a name for each gameobject:

```
 myLine.name = start.ToString();

```

This give me the name for example: (-2.1, 3.4, 4.9) Nut I want it be the name like this format:

```
v3FrontTopLeft (-2.1, 3.4, 4.9)
v3FrontTopRight (-1.1, 3.4, 4.9)

```

The problem is if there is a easy way to get the names v3FrontTopLeft and v3FrontTopRight and the rest from the method DrawBox instead typing each one.

I want to know that (-2.1, 3.4, 4.9) are the coordinates for v3FrontTopLeft

# Answer
> 2 votes
While there is a way to get the name of a variable in C# (I do not recommend this), you'd still have to perform that stringification *before* calling `SpawnLineGenerator()`, at which point you may as well just do this:

```
SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color, "v3FrontTopLeft");

```

So no, I don't think there will be a way for you to achieve what you want the way you want to achieve it.

# Answer
> 2 votes
As Draco18s mentioned, with your current code you'll need to get the string before calling `SpawnLineGenerator()`. If you're using C# 6, the `nameof` expression will get this name, but if the names shown are all the names needed, you can try another approach by defining an enum:

```
public enum BoxSides
{
    v3FrontTopLeft,
    v3FrontTopRight,
    ...(and so on)
}

```

Then you can change the signature to:

`void SpawnLineGenerator(BoxSides side, Vector3 start, Vector3 end, Color color)`

This will allow you to get the name you want like so:

```
myLine.name = side.ToString() + start.ToString();

```

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


# Question
Title: change random number into specific range using resolution
I am having a simple mathematical problem that i would like to scale a randomly created decimal points using `numpy` , then apply a formula to align this decimal points to range

range \\$:\\$- \\$x\_\min : x\_\max\\$

number of points of the interval \[xmin : xmax \] : ***M***

number of points to be created : ***N***

$$ \\resolution = \frac{(x\_\max-x\_\min)}{M}$$

equation if found \\$:\\$-

\\$t\_s\\$ \\$:\\$- *first point*

$$ \\ t\_s = { random * ( x\_\max\ - x\_\min\ - N\*resolution)}\ $$

i would like to understand this equation

# Answer
If you just want to get a random decimal number selected uniformly from the range \[min, max\], you can use `random.uniform(a, b)`

> `random.uniform(a, b)`
>
> Return a random floating point number N such that `a <= N <= b` for `a <= b` and `b <= N <= a` for `b < a`.
>
> The end-point value b may or may not be included in the range depending on floating-point rounding in the equation `a + (b-a) * random()`.
> 1 votes

---
Tags: mathematics
---


# Question
Title: The name `FB' does not exist in the current context
I am trying to allow the user to share the final game score on their FaceBook timeline. I am following FaceBook tutorial and examples. When I try to download and import the FaceBook SDK package (7.11-2.0) in Unity (2017.3) I get the error:

> error CD1704: An assembly with the same name 'FaceBook.Unity.Settings' has already been imported. Consider removing one of the references or sign the assembly Library/FacebookSDK/FaceBook.Unity.Settings.dll (Location of the symbol related to previous error)

I read on other posts that the latest version of Unity may have the Facebook SDK already integrated, and will not require importing the package manually.

I therefore removed the from my project. The error disappear, but when I try to initialize the Facebook SDK for Unity using the code below, I get the error:

> The name \`FB' does not exist in the current context

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

public class ShareOnFaceBook : MonoBehaviour {

    // Use this for initialization
    void Awake () {

    if (!FB.IsInitialized) {
        // Initialize the Facebook SDK
        FB.Init(InitCallback, OnHideUnity);
    } else {
        // Already initialized, signal an app activation App Event
        FB.ActivateApp();
    }
}

```

# Answer
> 1 votes
Assuming you are following this: https://developers.facebook.com/docs/unity/examples

Unity 2017.1.0f3 without the Facebook SDK installed leads to this error:

> Error CS0246: The type or namespace name 'Facebook' could not be found (are you missing a using directive or an assembly reference?) (CS0246) (Assembly-CSharp)

Once Facebook SDK is installed, the script works (as long as you include all of the code:

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

public class ShareOnFaceBook : MonoBehaviour {

    // Use this for initialization
    void Awake () {

        if (!FB.IsInitialized) {
            // Initialize the Facebook SDK
            FB.Init(InitCallback, OnHideUnity);
        } else {
            // Already initialized, signal an app activation App Event
            FB.ActivateApp();
        }
}private void InitCallback ()
{
    if (FB.IsInitialized) {
        // Signal an app activation App Event
        FB.ActivateApp();
        // Continue with Facebook SDK
        // ...
    } else {
        Debug.Log("Failed to Initialize the Facebook SDK");
    }
}

private void OnHideUnity (bool isGameShown)
{
    if (!isGameShown) {
        // Pause the game - we will need to hide
        Time.timeScale = 0;
    } else {
        // Resume the game - we're getting focus again
        Time.timeScale = 1;
        }
    }
}

```

I can't find proof that FB SDK is included with newer Unity versions. Perhaps it is offered in the installer.

I speculate that your Unity or C# environment (MonoDevelop) is bugging out and might be "fixed" by a restart. Alternatively it could be that you only partially removed the FB SDK or have various versions of it conflicting with itself.

Also: perhaps your "FB"-related error refers to another script.

To verify, start a new project, import the FB SDK .unitypackage and try out above C# script. It should work.

---
Tags: unity, facebook
---


title: Wait until a method finish

text:
# Question
Title: Wait until a method finish
I'm using Firebase Realtime Database and I'm trying to compare if a name is available to other user. The problem is the method finish before the Firebase's method finish its execution. Here is the code:

```
private bool IsNameAvailable (string nick)
{
    bool available = false;
    FirebaseDatabase.DefaultInstance.GetReference ("users").OrderByChild ("name").EqualTo (nick).GetValueAsync ().ContinueWith (task => {
        if (task.IsFaulted) {
            Debug.LogError ("A error encountered: " + task.Exception);
        } else if (task.IsCanceled) {
            Debug.LogError ("Canceled ...");
        } else if (task.IsCompleted) {
            DataSnapshot snapshot = task.Result;
            available = (snapshot.GetValue (true) == null);
        }
    });
    return available; //This line executed before the Firebase's method end.
}

```

What can i do?? Thanks in advance.

# Answer
> 3 votes
Preventing that method from continuing until the Firebase database has returned a value would be a bad idea, because it would freeze the whole game process. So a function `bool IsNameAvailable (string nick)` is simply not going to work when it needs to access a remote resource. You will have to work with asynchronously called callback-methods in this case. There is really no good way around it.

That means you don't have a `IsNameAvailable` method which returns `bool`, you have one which returns `void` and receives a method as an additional parameter which gets called as soon as it got a result from the database.

So instead of this code:

```
 if (IsNameAvailable (nick) ) {
    textlabel.text = "Name is available";
 } else {
    textlabel.text = "Name is already taken";
 }

```

You will have to pass a callback-method to `IsNameAvailable` which gets executed as soon as the database is finished:

```
 IsNameAvailable (nick, NameCheckCallback);

 /*...*/

 private void NameCheckCallback(bool success) {
     if (success) {
        textlabel.text = "Name is available";
     } else {
        textlabel.text = "Name is already taken";
     }
 }

```

Your `IsNameAvailable` function would then look like this:

```
private void IsNameAvailable (string nick, Action<bool> callbackFunction)
{
    FirebaseDatabase.DefaultInstance.GetReference ("users").OrderByChild ("name").EqualTo (nick).GetValueAsync ().ContinueWith (task => {
        if (task.IsFaulted) {
            Debug.LogError ("A error encountered: " + task.Exception);
        } else if (task.IsCanceled) {
            Debug.LogError ("Canceled ...");
        } else if (task.IsCompleted) {
            DataSnapshot snapshot = task.Result;
            callbackFunction(snapshot.GetValue(true) == null);
        }
    });
}

```

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


title: Camera and multiple shaders

text:
# Question
Title: Camera and multiple shaders
What is the best way to handle a moving camera inside many shader programs?

I believe most games need to have one common projection matrix inside all shader programs to use a moving camera. Currently my approach will be to make one global camera object, with which I update every shader program.

I would imagine this gets a bit tedious and possibly heavy once I actually have many programs which to update every movement. So I'd like to construct the program well right away and avoid problems down the road.

What have you done about this, if anything? Do you try to share shader programs between objects?

# Answer
A nice way is using Uniform Buffer Objects (OpenGL) which buffer uniform variable information which can be shared across multiple programs. Inside every shader one will declare an uniform block, which has the layout of the uniform buffer.

For example:

```
// Vertex shader:
#version 150 core
in vec3 position;

uniform mat4 Model;

layout (std140) uniform Camera{
    mat4 View;
    mat4 Proj;
} Cam;

void main(){
    gl_Position = Cam.Proj * Cam.View * Model * vec4(position, 1.0);
}

```

Then use a struct to fill a layout (C/C++):

```
typedef struct Something{
    glm::mat4 View;
    glm::mat4 Proj;
} Layout;

```

and to create the buffer the usual way:

```
GLuint ID;
Layout layout{glm::mat4(1.0), glm::mat4(1.0)};
glGenBuffers(1, &ID);
glBindBuffer(GL_UNIFORM_BUFFER, ID);
glBufferData(GL_UNIFORM_BUFFER, sizeof layout, &layout, GL_DYNAMIC_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, 0, ID);

```

How to set and update the data:

```
void *data = glMapBuffer(GL_UNIFORM_BUFFER, GL_READ_WRITE);
memcpy(data, &layout, sizeof layout);
glUnmapBuffer(GL_UNIFORM_BUFFER);

```

To every shader program you must bind the location:

```
GLuint camloc = glGetUniformBlockIndex(programID, "Camera");
glUniformBlockBinding(programID, camloc, 0);

```

See the documentation for additional information about the functions and parameters.
> 1 votes

---
Tags: opengl, shaders, camera, performance, projection
---


# Question
Title: Setting object-specific uniforms in a render queue
I am currently trying to write a (very simple) queued renderer using OpenGL. My current idea looks like this:

```
struct RenderCommand {
    GLUint  vao;
    GLUint  texture;
    GLUint  shader;
    GLInt   zOrder;
};

void Renderer::addCommand(const RenderCommand& cmd) { /* add to queue */}

void Renderer::render() {
    /* sort the command queue to try and z-sort, batch textures, etc. */

    for(const auto& cmd: queue_) {
        // Bind shader/vao/texture when necessary, issue draw calls
    }
}

```

Now my problem is this: for sprites for example, I only have one set of quad vertices on the GPU, and I send the sprite vertex shader the sprite size using a uniform. Same goes for the model transform matrix for literally any object. That's okay when render calls issued when iterating over scene objects, but becomes a problem when everything is queued: since most sprites will use the same shader, how do I set the uniform?

I've had a few ideas for solutions, but none of them feels right:

* Add data in `RenderCommand` for size, model matrix, etc. The big problem with that is flexibility: it supports the engine's default sprite (or 3D model or text) shader, but custom shaders with other uniforms won't work.
* Add a custom data pointer to `RenderCommand` to point to uniform data to send before rendering. This is probably the most flexible option.
* Add a `UniformCommand` type, which only uploads a uniform to the currently bound shader. It'll have to be handled carefully when the queue is sorted, to ensure it stays contiguous with whatever shader and model it corresponds to, but that sounds feasible.

# Answer
> 1 votes
This code suffers from over-generalization, the sensibility that you need to account for *every* possible rendering task. This is not useful from a performance perspective.

For example, take your VAO here. Each rendered object gets its own VAO. Why? Lots of rendered objects share the same vertex format, and many of them will share the same bound buffers. When rendering such objects, you *shouldn't* change the VAO between them.

Consider your sprite example. You create a single quad, and render different sprites via separate uniforms. This is terrible from a performance standpoint; that's dozens if not hundreds of draw calls per-frame, with state changes between the draws. You'll get better performance by just writing each sprite's data to a buffer object (using appropriate streaming techniques, of course), and then rendering them all at once with a single draw command. Oh sure, each sprite will have duplicate color information for its four vertices. But so what? Even a 16MB double-buffer (8MB per buffer) should be able to store 400,000+ sprites.

You shouldn't be sticking all objects into a queue. You should be separating your rendering into hard-coded *types* of objects: skinned meshes, non-skinned meshes, sprites, lines, etc. Each type of object has its own effective queue, and each queue has its own kind of data.

For example, all sprites should source any texture data from a single texture atlas, and they should all render with the same shader. As such, there doesn't need to be any individual per-sprite data; that's all stored in the buffer object. So the only thing the sprite queue needs to know is which part of the buffer to read from and how many vertices the rendering command ought to have.

# Answer
> 1 votes
Option A) is not flexible enough for real cases. Option C), depends on the current OpenGL context status, which I think that is what you were trying to remove on the first place.

Therefore, I would go for option B). You may also want to look at https://www.khronos.org/opengl/wiki/Uniform\_Buffer\_Object With UBOs you can switch all the uniform data with just one OpenGL call.

However, are you sure you want to implement this kind of generalized queued renderer? Keep in mind that there are many OpenGL state that you are currently omitting: bound framebuffer, multiple textures, culling, clipping, Z testing, Z writing, blending...

For real applications I wouldn't write a generalized queue renderer. Although I would sort objects of the same type by their center Z to reduce pixel shader invokations by taking advantage of the early Z test. However, this is not always possible, for example, with transparency.

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


# Question
Title: Significant 2D SmallTalk/Squeak Game? Smalltalk/Squeak vs. C#
Prompted by this question about becoming a faster programmer, I'm curious to know if anyone has made a significant-sized 2D game in SmallTalk or Squeak.

And if so, how does it compare to C#? I'm using C# with FlatRedBall for my graphics/physics stuff, and I find it pretty easy to make whatever I want to make. Also, how is Squeak/SmallTalk as far as automated testing?

It's not clear from the Squeak site how the games work; are they download-and-play? I prefer in-browser (via a plugin, like Flash/Silverlight).

# Answer
Squeak has a plugin. I'd be reluctant to use it for a game, although there is a ton of cool stuff done in Scratch (http://scratch.mit.edu/), which is built on Squeak.

SUnit is as good as NUnit or JUnit. Some recent work has been done with Hudson/Jenkins with Pharo and Squeak (check the mailing list archives if you're interested).

If you're happy with C# and your physics engine stick with that. Smalltalk is a bit of a niche and it can be frustrating if you're used to modern IDEs with code completion and whatnot. OTOH, it's pretty powerful when you consider that the entire environment is written in itself, and to make a change you can just tweak a method while everything is running, there's no need to "build".

Hope this helps. Steve
> 1 votes

# Answer
Take a look at OpenCobalt http://www.opencobalt.org for what can be done with squeak. Cobalt is being ported to squeak 4.2 so that it can run on the Cog JIT VM which makes it MUCH faster than the older version running on squeak 3.8. There are things that can be done with Squeak + OpenGL that aren't being done with any other platform as far as I know because it is just too hard/slow to develop the code in a C/C++/C# based system.

E.g. 3D portals, graphical control of objects through said 3D portals, programmatic control of multiple virtual worlds using external scripting, etc. All those are of course doable with any programming system, but squeak + Cobalt and the Teatime architecture make them easy to implement over a weekend rather than spending months to reinvent teatime using a different language.

YMMV of course, depending on the specifics of what you want to accomplish.
> 1 votes

# Answer
Look at http://www.planet-plopp.de or http://www.impara.de/projekt\_pirates\_engl.html

Impara used the portable Squeak Smalltalk to build these games.
> 0 votes

# Answer
There are also videos on how Dolphin Smalltalk (Win32 only) can be used to build games http://www.object-arts.com/support/videos\_files/21163c4401ba2928d4e0c1ca319c04c7-1.html
> 0 votes

# Answer
Etoys is a squeak fork, is better than scratch in every way imaginable except community support and has choices of multiple web plugin players with varying results impacting speed.
> 0 votes

---
Tags: c#
---


# Question
Title: How can I build DOOM (SDL-Version) with MinGW?
I have recently been trying to build this source code here. I am building the original port with SDL infused, not the linuxdoom port and I’m having some issues.

What I have tried first:

* I've installed Mingw
* I've `make install`ed SDL v1.0.1
* I've set the enviroment variables to the path of the SDL-Config file

But when I load up the windows command prompt and go to the source directory and use .\configure the script outputs the following error:

```
loading cache ./config.cache
checking for a BSD compatible install… /usr/bin/install -c
checking whether build environment is sane… yes
checking whether make sets ${MAKE}… yes
checking for working aclocal… found
checking for working autoconf… found
checking for working automake… found
checking for working autoheader… found
checking for working makeinfo… found
checking whether make sets ${MAKE}… (cached) yes
checking for gcc… gcc
checking whether the C compiler (gcc ) works… yes
checking whether the C compiler (gcc ) is a cross-compiler… no
checking whether we are using GNU C… yes
checking whether gcc accepts -g… yes
checking for a BSD compatible install… /usr/bin/install -c
checking for sdl-config… /c/Program Files (x86)/SDL_MINGW32/SDL-1.0.1/bin/sdl-config
checking for SDL - version >= 1.0.1… configure: line 1181: /c/Program: No such file or directory
configure: line 1182: /c/Program: No such file or directory
configure: line 1185: /c/Program: No such file or directory
configure: line 1187: /c/Program: No such file or directory
configure: line 1189: /c/Program: No such file or directory
no
*** Could not run SDL test program, checking why…
*** The test program failed to compile or link. See the file config.log for the
*** exact error that occured. This usually means SDL was incorrectly installed
*** or that you have moved SDL since it was installed. In the latter case, you
*** may want to edit the sdl-config script: /c/Program Files (x86)/SDL_MINGW32/SDL-1.0.1/bin/sdl-config
configure: error: *** SDL version 1.0.1 not found!

```

Here is my config-log file that it generates to give more info on what the issue is…

This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake.

```
configure:563: checking for a BSD compatible install
configure:616: checking whether build environment is sane
configure:673: checking whether make sets ${MAKE}
configure:719: checking for working aclocal
configure:732: checking for working autoconf
configure:745: checking for working automake
configure:758: checking for working autoheader
configure:771: checking for working makeinfo
configure:787: checking whether make sets ${MAKE}
configure:816: checking for gcc
configure:929: checking whether the C compiler (gcc ) works
configure:945: gcc -o conftest conftest.c 1>&5
configure:942:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
main(){return(0);}
^
configure:971: checking whether the C compiler (gcc ) is a cross-compiler
configure:976: checking whether we are using GNU C
configure:985: gcc -E conftest.c
configure:1004: checking whether gcc accepts -g
configure:1047: checking for a BSD compatible install
configure:1142: checking for sdl-config
configure:1177: checking for SDL - version >= 1.0.1
configure:1259: gcc -o conftest -g -O2 conftest.c 1>&5
configure:1206:21: fatal error: SDL/SDL.h: No such file or directory
compilation terminated.
configure: failed program was:
#line 1201 “configure”
#include “confdefs.h”

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <SDL/SDL.h>

char*
my_strdup (char *str)
{
char *new_str;

if (str)
{
new_str = malloc ((strlen (str) + 1) * sizeof(char));
strcpy (new_str, str);
}
else
new_str = NULL;

return new_str;
}

int main ()
{
int major, minor, micro;
char *tmp_version;

system (“touch conf.sdltest”);

/* HP/UX 9 (%@#!) writes to sscanf strings */
tmp_version = my_strdup(“1.0.1”);
if (sscanf(tmp_version, “%d.%d.%d”, &major, &minor, &micro) != 3) {
printf("%s, bad version string\n", “1.0.1”);
exit(1);
}

if (( > major) ||
(( == major) && ( > minor)) ||
(( == major) && ( == minor) && ( >= micro)))
{
return 0;
}
else
{
printf("\n*** ‘sdl-config --version’ returned %d.%d.%d, but the minimum version\n", , , );
printf("*** of SDL required is %d.%d.%d. If sdl-config is correct, then it is\n", major, minor, micro);
printf("*** best to upgrade to the required version.\n");
printf("*** If sdl-config was wrong, set the environment variable SDL_CONFIG\n");
printf("*** to point to the correct copy of sdl-config, and remove the file\n");
printf("*** config.cache before re-running configure\n");
return 1;
}
}

configure:1303: gcc -o conftest -g -O2 conftest.c 1>&5
configure:1296:21: fatal error: SDL/SDL.h: No such file or directory
compilation terminated.
configure: failed program was:
#line 1293 “configure”
#include “confdefs.h”

#include <stdio.h>
#include <SDL/SDL.h>

int main() {
return 0;
; return 0; }

```

So, whats the issue that I am missing here?

# Answer
**Steps to bring sdldoom to compile and run on Windows/MingW with gcc-6.3.0**

Downloads:

**http://www.mingw.org/**

* MingW: Install packages mingw32-base, msys-base, mingw32-gcc-g++

**https://www.libsdl.org/projects/doom/**

* doom1.wad.zip
* sdldoom-1.10.tar.gz

**https://www.libsdl.org/release/**

* SDL-1.0.1.zip

**Installation**

1. Unzip SDL-1.0.1.zip and run ´./configure; make; make install\` in the new SDL-1.0.1 directory
2. Untar sdldoom-1.10.tar.gz to a new folder named sdldoom
3. Running `./configure` will fail because the test in the configure script apparently uses the 'wrong' main function, which does not match the prototype defined in SDL\_main.h. Just change the line 1224 from `int main ()` to `int main (int argc, char * argv[])`
4. ./configure should now run without errors
5. When running `make`, it will fail with a complaint about conflicting types: `typedef enum {false, true} boolean;` is the statement which defines the boolean type in the sdldoom-source. To fix that, we can find and replace all Occurences of "boolean" in the sdldoom-source: Run `find . -name *.[ch] -print0 | xargs -0 sed -i '' -e 's/boolean/Boolean/g'` inside the sdldoom folder to replace all `boolean` with `Boolean`.
6. Next, make will complain about an undeclared `IPPORT_USERRESERVED`. Just copy a `#define IPPORT_USERRESERVED 5000` at the beginning of the file `i_net.c`
7. Now it should compile, but the linker will throw an error about undefined references. In the `Makefile` add the library `ws2_32` to the `LIBS` variable: `LIBS = -L/usr/local/lib -lmingw32 -lSDLmain -lSDL -luser32 -lgdi32 -lwinmm -mwindows -lws2_32`
8. Run the linker with `make` again, and the `doom.exe` will be created. Now extract the `DOOM1.WAD` to the sdldoom folder, and the game is ready to run.

The installation in this way is certainly a little bit hacky, but then again the source is nearly 20 years old.
> 0 votes

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


# Question
Title: Are there any game engines for developing in C?
I cant find any game engines which use C, mostly just Java, Anyone know any good engines that support 2d Development in C?

ALso I have an additional question how hard is it to write your own game engine? How would one go about it I'm really curious about how they work.

# Answer
I don't know any Engine for C language.

But for the other part of the question, well... Even the simplest Engine is a bit hard to make **BUT** not impossible, it is not something that you will accomplish in one day and without scratching your head.

If you want to make games, then don't bother yourself by making an Engine. But if you have some time, I would recommend you at least to try to make one, it is really challenging and fun at the same time. Besides, it is really rewarding making games with your own Engine.

## EDIT

You have tons of tools online that could help you to create an Engine.

* SDL - Allows you to open a window and manage all that window stuff (drawing, input, etc.). You can learn SDL basis here
* OpenGL - Allows you to create cool effects to you're 2D Engine. This is the best online tutorial about openGL.
* SDL\_Mixer - Allows you to manage some sound (it's really basic though).

These are all libraries written in C (although the tutorials are in c++ but can be easily translated)
> 1 votes

---
Tags: 2d, game-design, c
---


# Question
Title: How can I generate terrain like SimCity 3000 does?
Are there any tips anywhere on generating terrain such as is used in SimCity 3000? I have used World Machine before, but I want something low-fidelity. I think there are only a few allowed vertical "steps" in SC3K, as well as a maximum slope. Thanks.

\[edit\]

Here are some screenshots.

Several more pics here.

# Answer
> 5 votes
Sim city uses a an XY grid, and the heights are discrete. In addition to this, the slopes seem to be limited to one "step" up or down.

So just handle all possible cases for a grid-cell.

Each cell has four corners: N0, N1, N2 and N3.

Let's designate the height at N0 as "nominal."

Then for each for the remaining corners (N1,N2,N3) there are three cases each:

1. Nx is at same level as N0. (=)
2. Nx is at lower level than N0 (-)
3. Nx is at higher level than N0 (+)

So you need to handle all 3\*3\*3, or 27 cases. I have drawn four of the 27 cases to give you an idea.

Is your game sprite-based? Then you need to draw *all* 27 sprites.

Is your game using 3D polygons? Then you only have to model a few of those, as many are variants of each other, under rotation.

Note that you need to offset each cell you draw with the absolute height of N0.

So to recap: Sim City defines the terrain heights at the **corners** of the cell, those heights are discrete, and neighbouring corners can only step +1, -1 or stay level.

---
Tags: sprites, terrain
---


# Question
Title: Physics2D.Raycast not hitting any colliders
I am making a topdown 2d game and want to get the x,y of mouse clicks so I can move the character to that location.

I am writing a CharacterController script which performs the mouse-click check and raycast in the Update function:

```
void Update () {
    if (Input.GetMouseButtonDown (0)) {
        RaycastHit2D hit = Physics2D.Raycast(Input.mousePosition, -Vector2.up);
        if (hit.collider != null) {
            Debug.Log (hit.point);
        }
    }

```

This runs whenever I click the mouse, but the `if(hit.collider != null)` condition is never met.

I've looked around for other solutions, such as Unity - Raycast not hitting to BoxCollider2D objects, but when I change my code to the one used in that answer:

```
RaycastHit2D hit = Physics2D.Raycast(
  Camera.main.ScreenToWorldPoint(Input.mousePosition),
  Vector3.back
);

```

then the `if(hit.collider != null)` block is *always* true, even if I click on empty space, and it always returns the same coordinate. To illustrate this, here is a video of me clicking the game view. The green area has a 2d box collider that is very closely mapped to its boundaries. You can see that the logged `hit.point` is always the same.

video is here - https://i.stack.imgur.com/jzXk4.jpg

screenshot -

# Answer
> 4 votes
From the video link you gave, it seems to me that your camera setting is Perspective. In a perspective camera mode if you convert the "ScreenToWorldPoint" it will not work as expected because it takes the "z" axis into account. This issue has been described nicely in this question. https://answers.unity.com/questions/331558/screentoworldpoint-not-working.html

Moving on to your actual question. You can do either of these two things.

1. ***Change your camera to orthographic*** and use the following code. (Similar to yours one)

```
if(Input.GetMouseButton(0))
{
    // this will take the mouse position in screen co-ordinate(left down corner 0,0 and top up corner screen resolution
    // then convert it to a worldpoint co ordinate (Transform.position)
    Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero);

    //if anything is collided
    if (hit.collider != null)
    {
        print(hit.collider.name);
    }
}

```
2. You can ***change the z value of your mouse input*** manually from code (if you use the perspective camera.) as mentioned in the link I have shared above

N.B: Also make sure that you are using 2d collider instead of the 3d collider. Otherwise, RaycastHit2D won't work.

Hope that helps

---
Tags: unity, c#, 2d
---


# Question
Title: Making a gameobject move back and forth in Unity
So i have this enemy gameobject and i want it to move in a certain pattern like a patrol. So i want him to move from A to B to C then Back to B to A. The script I worked out makes him go from C to A directly but I dont want that. Can someone please help . The Length of PatrolPoint Array in 3 \`using UnityEngine; using System.Collections;

public class EnemyPatrol : MonoBehaviour {

```
public Transform [] patrolPoints; // An Array of path points to be followed
private int currentPoint ;
public float enemySpeed ;

void Start()
{

    currentPoint = 0;
    transform.position = patrolPoints[ currentPoint].position; // Starting Point
}

void Update()
{

    if(transform.position == patrolPoints[currentPoint].position)
    {
        currentPoint ++ ;
    }

    if(currentPoint >= patrolPoints.Length)
    {
        currentPoint = 0 ;
    }

    transform.position = Vector3.MoveTowards(transform.position , patrolPoints[currentPoint].position , enemySpeed*Time.deltaTime);

    }

```

} \`

# Answer
> 0 votes
Currently you have it loop back to the first point with `currentPoint = 0;`. You will need to decrement it each time by one, much like how you were incrementing it before. Perhaps use a condition to check whether to go forward or backward through the points:

```
private bool backtracking = false;
...
void Update() {
    if (transform.position == patrolPoints[currentPoint].position) {
        if (backtracking)
            currentPoint--;
        else
            currentPoint++;
    }

    if(currentPoint >= patrolPoints.Length) {
        backtracking = true;
    }
    ...
}

```

# Answer
> 0 votes
I know it's a bit late but I'm going to post my code with some comments to help anyone else that may be stuck in this situation. This is for 3D, apply Vector2 if using 2D.

```
private bool left; //I set a boolean named left so that when true the object moves left

void Start () {
    left = true; //I set left to true so it would move left first
}

void Update () {
    if (transform.position.x >= 6.9f)
        left = true; //So if my X position is more 6.9 or more, left is set to true
    if (left)       //If Left is true it shall move 1 space to the left
        transform.Translate(-1f*Time.deltaTime,0f,0f);

    if (transform.position.x <= -6.9f)
        left=false;
    if (!left)    //But if its false (declared false on the above line) move right by the same speed
        transform.Translate(1f*Time.deltaTime,0f,0f);

}

```

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


# Question
Title: A* pathfinding takes too long, shortcuts needed
So I have a game where the player can move on a grid 108 X 192 large. It uses a simple A\* path-finding algorithm to move. Unfortunately, After 0.03 seconds, it would have only looked at about 300 nodes, meaning that if the end node is blocked from passage, it would take about 2 seconds for it to realize this (A\* without optimizations returns failed when the open list is empty, when it has inspected every path and realized there was no solution). And I want at least 20 fps!

I have not used any optimizations, and each point in the grid is a boolean blocked or unblocked. Any ways to speed it up?

For example, in Dota 2 (a popular MOBA), the map is full of trees and cliffs, and is 15,000 game units by 15,000 game units big, but the character starts moving as soon as you click where you want it to go. How do they do that, and is it a simple thing I am missing?

# Answer
As you yourself have stated, you still didn't have resorted yet to optimizations. So yes, there are many ways to speed that up.

But since you were talking in general terms, I will stick with what I think is the best general guidance for improving path-finding performance: decrease the size of the problem. Or in other words, search less and search smaller.

1a) On the one hand, searching less means assuring that only some agents search paths at a time. But I guess by your answer that you are not struggling with many agents path-finding, so...

1b) ... on the one hand, to search in smaller areas means reducing the possible paths that have to be evaluated in a path-finding step. For that, spatial partitioning is often used. The scene is divided in areas so that the path-finding can be performed in smaller search-spaces at a time. Also, there are search algorithms such as the HPA\* and the HAA\* that implement inherently a hierarchical path-finding, by partitioning the scene.

The idea of partitioning the space is the following. You will cluster the map into regions. When the agent has to find a path, it will first do path-finding at the higher level, i.e. find from which region to which region it should go. Them, it will find its path within the current region it is in. When it changes the region, then another within-region path-finding will be performed.

For more on that and a nice visualization, see one of the answers to the following question: What is the most appropriate path-finding solution for a very large proceduraly generated environment?
> 4 votes

# Answer
300 nodes in 0.03 seconds means only 10,000 nodes per second, which seems rather slow. Before implementing more complicated approaches such as hierarchical partitioning, the first thing I'd do is to optimize the code.

1. Run the **profiler** to find out which functions are using the most time. It is often surprising where the time goes, and it is a waste of your time to optimize something you think is slow when it turns out not to be the slow part after all.
2. Check the **data structures** being used. *You should have no loops through the open/closed sets!* The open set is a priority queue, and should use a priority queue data structure, which can find the best node without searching the entire data structure. I usually use a binary heap. The closed set can either be implemented as an internal structure, as a boolean flag on each node, or as an external structure, as a set (hash table or array). I have sample code in C++ and Python (and incomplete C# code) if you want to take a look.
3. If the end node being blocked is a common problem, connected components (“island id”) is extremely simple and fast to implement. You preprocess the map once. Loop over each node. If it already has an island id, then skip it. If it does not have one, run breadth or depth first search from that node, and mark all visited nodes with the new island id. When you run A\* you will first compare island ids. If they are different, you will know right away that there is no path. (Note: this only is useful if all edges are two-way. One-way edges complicate this.)
4. Only if you're already using good data structures and the system is still too slow would I suggest investigating hierarchies or waypoints or contraction hierarchies or more advanced techniques. A 15000x15000 map may need such things but your 108x192 grid should not.
> 3 votes

# Answer
The quickest way to vastly speed up A\* is:

The algorithm frequently tests whether a node is in **OPEN** or **CLOSED** set. It is vital that this test is O(1). You do not want to traverse the entire set to see if it is in there or not.

Much faster is two booleans for each node, which will tell you if a node is in **OPEN** or **CLOSED** set.

This change alone will make your implementation of A\* many times faster.

But yes, you do make a good point: if the goal is not reachable, then every node that *is* reachable will be traversed unfortunately. So unreachable nodes are the most expensive to pathfind for.
> 0 votes

# Answer
My implementation of A\* in C++ finds path to closest position on grid map 256x256 in 26 ms worst case.

You can try Jump Point Search (JPS). It also checks every cell, but works surprisingly about 4 times faster. In my case 7.5 ms.

JSP+ precalculates jump points for every cell on grid map and finds closest path to unreachable position on my map in 0.5 ms.

Also Dota 2 uses wall/obstacle tracing for short paths. It works in continuous space and founded paths are not guaranteed be shortest, but in most cases resulted path looks good. My version finds short paths in just 0.1 ms.

All tests were running on Macbook with i5-4258U. Code can be found here
> 0 votes

---
Tags: performance, path-finding, lag
---