# Question
Title: Monogame - Screen transition with fading
I'm trying to create a fade logic with Monogame for my screen transitions. I've read tutorials online but I'd like to work with Premultiplied Alpha for the fading. I've seen people add 1x1 pixels black images to their content, scale it to the screen's width/height (depending on aspect ratio) and drawing it with the alpha value first decreasing, and then increasing (fade in, fade out). So I would like someone to give me an example code to work with, preferably, 2 methods: `FadeIn()` and `FadeOut` in something like a `Transition` class. I should be able to call these at the begging and at the end of my screen classes. Keep in mind that I'm using the following `enum` code for screen state management:

```
public enum gameStates
{
    splashScreen,
    engineScreen,
    titleScreen,
    optionsScreen,
    playScreen,
    gameOverScreen,
    creditsScreen,
}
private static gameStates currentGameState = gameStates.splashScreen;
public static gameStates CurrentGameState
{
    get { return currentGameState; }
    set { currentGameState = value; }
}
// And then switch(currentGameState) in Update() and Draw()

```

So maybe `FadeIn()` and `FadeOut()` should take an `enum` value as a parameter? So that when they are called, the value is passed and inside them the `currentGameState` is accessed through the property in `Game1` and is changed. Would this be the correct approach? Thanks!

# Answer
> 6 votes
The problem with dealing with gamestates in an enum and a big switch statement and dealing with transitions is that you want also keep track of what the previous state was. This becomes more complex is some states may be triggered at various points during gameplay (options screen, inventory screens, other special states). So to deal with transitions more easily I've structured my states a bit differently. It comes with other benefits as well, so might be worth considering.

I have implemented the gamestates as classes to isolate their own logic. I then made a gamestate manager to deal with the active gamestate. The gamestates are then handled as a stack. The main gameloop calls the update/draw functions of the top of the stack. Don't worry, I'll get to the transitions soon :-)

```
public interface IGameState
{
    void Update(GameTime gametime);
    void Draw(GraphicsDevice gd, SpriteBatch sb);
    void WakeUp();
    void Sleep();
    //some other things as initialize, reset, cleanup or dispose you may need for your game.
}

```

The WakeUp and Sleep functions contain logic that is required when something becomes active or goes to sleep again. For example my "option menu" gamestate can be pushed at any moment and just get pushed to the top of the stack. The gamestate manager looks a bit like this:

```
    private Stack<IGameState> GameStack = new Stack<IGameState>();

    public void Pop()
    {
        if (GameStack.Count > 0)
            GameStack.Pop();

        if (GameStack.Count > 0)
            GameStack.Peek().WakeUp();

    }

    public void Push(IGameState state)
    {
        if (GameStack.Count > 0)
            GameStack.Peek().Sleep();

        GameStack.Push(state);
    }

    public void Update(GameTime gametime)
    {
        if (GameStack.Count > 0)
            GameStack.Peek().Update(gametime);
    }

    public void Draw(GraphicsDevice gd, SpriteBatch sb)
    {
        if (GameStack.Count > 0)
            GameStack.Peek().Draw(gd,sb);
    }

```

It makes the main gameloop as easy as this:

```
    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        GamestateManager.Update(gameTime);
        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GamestateManager.Draw(GraphicsDevice, spriteBatch);
        base.Draw(gameTime);
    }

```

**So now to the topic of transitions:** You could do a couple of things using this mechanism.

For example, implement a fadeout effect that is triggered before a state 'pops' itself from the stack (do a fade, once it is complete, pop itself from the stack and push the next state onto the stack). On the wakeup of a state trigger a fadein effect. This would result in a fade-to-black type of fade.

Another option is on a 'sleep' draw the scene to a `RenderTarget` and use that in your transition action triggered by the 'wakeup' of a new gamestate. Use the static graphic in your transition animation. You may expand your `IGameState` with a `Texture2D GenerateTransitionSnapshot()` or something. With this you could create a crossfade or any more complex fades where the old state 'freezes' and a new scene is shown.

Another thing you could do, is call the 'update' and 'draw' function of a previous gamestate each frame (for example if you want keep things animating or something) render those to a Rendertarget and deal with the transition in your gamestate manager. This makes the gamestate manager contain a bit more logic. You wakeup and sleep functions could control wether player input is accepted or not. This would result in a fade where the old state keeps animating. Performance wise your game should be able to draw both scenes.

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


# Question
Title: How can I implement lights & shadows in a multi-layer 2d tilemap?
I am in the process of writing an isometric game from scratch, and I'd like to know how/if I can add lights and shadows.

The code I have so far can be found here, but it should be enough to know that *right now*, the maps are **simple 3d arrays of true/false values**. Here is a shot of the environment:

If it were a single layer tilemap it would be straight forward. I can understand the simple raycasting in 2d that is required.

However, given that my maps have multiple levels of height as well as cave-like areas, I don't really know how to go about doing convincing shadows for it. Perhaps a per-block solution is the only realistic way?

# Answer
> 1 votes
Can I recommend getting 2d shadows working first, even if it's just for the level that your avatar is currently on. It will be easier to start looking at the code that way and get it working.

I have implemented shadows in 2d tile maps in a couple of ways. One shadowcasting method which I found described by Eric Lippert at Microsoft works quite well.

And the other way, which I did myself first time i looked at this kind of thing was to orthogonally sweep the visible tiles and tile-edges and generate edges (and maybe corners iirc) describing the scene in the lowest number of edges. You can then cull hidden edges and form any custom shadowing features such as recessed shadows if you want to show a little bit of wall. Then create your shadow geometry (projective shadow casting ?) and render it over the top.

But if I try to take that idea to 3d, it just becomes easier to do it in 3d. While the method described by Eric Lippert could presumably be converted to 3d. But I think you'll find that doing it in 3d is expensive. Perhaps take a look at the source code for Brogue as well. It may have a more efficient implementation for 2d visibility/shadow casting.

Good luck.

---
Tags: 2d, javascript, graphics, lighting, shadows
---


# Question
Title: How to use Tiled Editor to recreate a 2D map?
Alright, to familiarize ourselves with the Tiled Editor, the teacher asked us to replicate a tile-based map of a 2D platformer.

*He gave us pretty much these two things:*

**1.) A selection of maps to copy from (Choose one map to copy)**

**2.) A folder with subfolders that contains 16x16 images on each subfolder (tiles)**

Naturally, I started by importing the images from the folders by clicking on each folder, and importing each collection, which takes a long amount of time..(also considering the tiles for the other maps are mixed in here as well)

I used the png image as a transparent backdrop to help me place the tiles, then started placing tiles, which again, took a lot of time...

More than halfway there, I realized the width I set the map when I created it wasn't enough and tried to change the option under properties but it was grayed out. I also tried creating a new map and copying and pasting from my original one but that one doesn't seem to work either.

Is there a way to speed up the process a little bit? or salvage the tmx file? Considering that he might ask us to create more maps later on, I'd like to be a bit informed...

---

I've also looked up the possibility of importing the image itself, slicing it to the desired tile size and removing duplicate tiles. This way I can simply import the map png and have the software only create tiles that are used in the level.

Can this be done?

# Answer
About resizing, as @bornander commented, there's a menu action for resizing that you need to use rather than directly changing the size in the Properties view.

---

The following article is about automating the process of creating a tile map and a tileset based on an image of a map: https://github.com/bjorn/tiled/wiki/Import-from-Image

As of now, Tiled can't do this natively, but it's something I'd like to add support for eventually.
> 2 votes

---
Tags: 2d, tiled, importing
---


# Question
Title: MonoGame 3.4 Content Pipeline Extension missing reference
I'm pretty new to MonoGame and XNA in general. So was wondering how I could import custom content and make it work on any platform. So I came across Content Pipeline Extensions wanted to do it like the documentation says but i **cant find MonoGame.Framework.Content.Pipeline**.
So I have multiple questions:

* Where is it located?
* Is there any other way i can load stuff like map data etc.?
* If yes does it work on any platform?

**Edit:**
I can simply load files without the content pipeline. I didn't expect that to work across all platforms. Thanks to Shiro for clearing this up.

# Answer
The MonoGame.Extended project loads Tiled maps using a custom content importer. I wrote a tutorial about how to create custom content importers on my blog.

Of course, as @Shiro mentioned in the comments you don't *need* the Pipeline to load your own content with MonoGame. Just be aware that to make it work across all platforms you'll need to use `TitleContainer.OpenStream`. This is by far the simplest way and if it works for you by all means do it that way.

The idea of using the Pipeline is to give you the opportunity to optimize the content at compile time. You can pre-process the data and write it out as a binary XNB file to be efficiently read into the game. The process is quite involved though:

1. Create a new project to hold your content importer, processor and writer that references the `MonoGame.Framework.Content.Pipeline.dll`. It's available as a NuGet package.
2. Implement a class that derives from `ContentImporter<T>`
3. Implement a class that derives from `ContentProcessor<T,K>`
4. Implement a class that derives from `ContentTypeWriter<K>`
5. Implement a class that derives from `ContentTypeReader<K>` (in the game project)
6. Reference the DLL from the Pipeline tool (by editing your `Content.mgcb` file)
7. Read the content into your game using `Content.Load<K>`

As you can see custom content importers can be quite daunting at first, but once you've done a few of them they are not too bad. I hope this clears some things up for you.

Finally, to answer your other question.

> Where is it \[MonoGame.Framework.Content.Pipeline.dll\] located?

If you're not using the NuGet package for some reason, the DLL lives with the Pipeline tool in a rather obscure place. On my machine it's located here:

```
C:\Program Files (x86)\MSBuild\MonoGame\v3.0\Tools

```

I found it by looking at the path set on the shortcut in the start menu.
> 8 votes

# Answer
the comment made by @Necr0 stating that "content projects are no longer necesary" is not entirely correct. Monogame no longer requires the *XNA content project*. There are still reasons to have your own content pipeline projects. You could, for example, create a content pipeline importer for your own level format. Or, if you plan to support a file format created by a tool you use (Tiled, Spine/Spriter for example). I myself made a content project that packs a bunch of images into a texture atlas, so I don't have to deal with that at runtime and I don't need to deal with that in photoshop- just save the individual files and the importer does the rest.

**So, what about those references you were looking for?**

If you want to make your own content projects: Reference the `MonoGame.Framework.Content.Pipeline.Portable` package using NuGet. The NuGet package is at the moment (sept 2015) pre-release only package. Make sure you choose `Include Prerelease` at the top of the Manage NuGet Packages window.

If you're looking to make your own content format. This excellent tutorial helped me a lot by making my own first content project: http://dylanwilson.net/creating-custom-content-importers-for-the-monogame-pipeline
> 3 votes

---
Tags: c#, xna, monogame
---


title: Snake game tail

text:
# Question
Title: Snake game tail
I am working at a 2D Snake Game in Unity. This is the head of the Snake: https://i.stack.imgur.com/MeelN.png And this is the Extension of the tail of the snake. It is added everytime I eat something: https://i.stack.imgur.com/IoagT.png I made the head of the snake to move, but my question is how do I move the extensions? I tried to add these extensions as childs to the head , but when i rotate the head, it rotates the all extensions at the same time, but I want to rotate one extension at a time like a chain. I am using a C# Script

```
if (position == 1 || position == 3) {
            if (Input.GetKey (KeyCode.UpArrow)) {
                position = 2;
                rotation=90;
                transform.rotation=Quaternion.Euler(0,0,rotation);

            } else if (Input.GetKey (KeyCode.DownArrow)) {
                position = 4;
                rotation=270;
                transform.rotation=Quaternion.Euler (0,0,rotation);
            }
        } else if (position == 2 || position == 4) {
            if(Input.GetKey(KeyCode.RightArrow)){
                position=1;
                rotation=0;
                transform.rotation=Quaternion.Euler (0,0,rotation);
            }
            else if(Input.GetKey(KeyCode.LeftArrow)){
                position=3;
                rotation=180;
                transform.rotation=Quaternion.Euler (0,0,rotation);
            }
        }
        if (position == 1)
            transform.Translate (Vector3.right * movementSpeed * Time.deltaTime,Space.World);
        else if (position == 2)
            transform.Translate (Vector3.up* movementSpeed * Time.deltaTime,Space.World);
        else if(position==3)
            transform.Translate(Vector3.left*movementSpeed*Time.deltaTime,Space.World);
        else if(position==4)
            transform.Translate (Vector3.down*movementSpeed*Time.deltaTime,Space.World);
        int i;
        for (i=1; i<extensions.Count; i++) {
            extensions[i].transform.position=extensions[i-1].transform.position;
            extensions[i].transform.rotation=extensions[i-1].transform.rotation;
        }

```

# Answer
> 3 votes
In unity, you will want to child all the segments (including the head) to an empty GameObject. Then you can move/rotate each child peice, including the head.

The way it works in the classic game is that only the head actually moves. The tail piece is removed from the end and a new segment is added where the head was last time. So only two segments are being moved each frame (head and tail). Not all segments.

Eg.
1. Move the head one space
2. Remove the tail piece
3. Fill in the space where the head was, with a new body/tail segment. Since you are removing the tail segment, you can reuse that GameObject for the new (neck) segment. Unless of course if you are using a unique segment for the tail piece. Then you would need to move 3 segments each frame.

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


title: 2D animated sprite in 3d Game

text:
# Question
Title: 2D animated sprite in 3d Game
I have a model created in Blender for a character with a sprite as a child of the character that I would like to animate. I'm making a turn based strategy game in which I would like to be able to click a character and turn on a "selection circle" beneath the character, much like the way a circle appears underneath a selected unit in games like Star Craft. The selecting of the character(the circle turning on/off) works fine. However, I have a 32 sprite animation that I would like to apply to the selection circle to give it a bit more life. The steps I've take are as follows:

I put my character into the scene

I add the selection circle sprite to the character as a child

I add an animation & animator component to the selection circle

I open the animation window and create a new clip

I drag my 32 sprite sheet to the window

I make sure the "play automatically" check box is selected

When I play the animation in the editor it works fine, but at run time the animation is not present, only a single sprite appears when I select my character. I've noticed that there is warning that appears in the console that says "animation must be marked as legacy" there are about a bazillion questions on here already explaining how to fix this... I.E. Change to debug mode and change animation type to 1(Legacy). I do not see this option anywhere in the inspector when I have the sprite selected. I can change to debug mode but there is nothing under the heading or an component that resembles animation type. I'm using Unity 5. Please, any help would be appreciated.

# Answer
> 1 votes
Follow these 3 easy steps

1) Select the animation file in the project , and click on the top drop down icon in the inspector.

2) Select the Debug Mode

3) Select the legacy option

# Answer
> 1 votes
Don't use legacy animations, use the Animator component to play animations instead. Here are some examples:

http://www.youtube.com/watch?v=VG7uZAwZW2o

http://johnstejskal.com/wp/creating-2d-animations-from-sprite-sheets-in-unity3d-pt2/

---
Tags: unity, animation, sprites
---


title: LightMap not working properly

text:
# Question
Title: LightMap not working properly
I've made a chips bag model for my game:

https://i.stack.imgur.com/T9Eae.jpg

And I textured it like this:

https://i.stack.imgur.com/PmEUO.jpg

and I googled on how to make lightmaps all of them say "Smart UV project" but when I do that, texture on my model gets broken, so thats why I dont want to use smart uv project

Is there another way?, it has to be.

# Answer
1. Create a lightmap in your 3D-modeling-program (e.g. blender).
2. Load it into your game without changing the object's UV-coordinates
3. Make your game multiply the diffuse-texture with the lightmap.
> 1 votes

---
Tags: textures, uv-mapping, lightmap
---


# Question
Title: How to detect mouse over for UI image in Unity 5?
I have an image that I have setup to move around and zoom in and out from. The trouble is the zoom can be done from anywhere in the scene, but I only want it to zoom when the mouse is hovering over the image. I have tried to use OnMouseEnter, OnMouseOver, event triggers, all three of those without a collider, with a collider, with a trigger collider, and all of that on the image itself and on an empty game object. However none of those have worked...So I am absolutely stumped...Could someone help me out here!

Here is my script:

```
    private float zoom;
    public float zoomSpeed;
    public Image map;

    public float zoomMin;
    public float zoomMax;

    void Update () {
        zoom = (Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * zoomSpeed);
        map.transform.localScale += new Vector3(map.transform.localScale.x * zoom, map.transform.localScale.y * zoom, 0);
        Vector3 scale = map.transform.localScale;
        scale = new Vector3(Mathf.Clamp(map.transform.localScale.x, zoomMin, zoomMax), Mathf.Clamp(map.transform.localScale.y, zoomMin, zoomMax), 0);
        map.transform.localScale = scale;
    }

```

# Answer
> 12 votes
You can implement `IPointerEnter` and `IPointerExit` interfaces and keep boolean for 'over state':

```
using System;
using UnityEngine;
using UnityEngine.EventSystems;

public class TestOver : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public bool isOver = false;

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("Mouse enter");
        isOver = true;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("Mouse exit");
        isOver = false;
    }
}

```

# Answer
> -1 votes
You should first define a function (method) in your script, then create an event trigger for image (with PointerEnter event) and specify that function in it.

http://answers.unity3d.com/questions/783279/46-ui-how-to-detect-mouse-over-on-button.html#answer-783299

---
Tags: unity, c#, gui, image, mouse
---


title: States within a GameState?

text:
# Question
Title: States within a GameState?
I ended up coming up with having states within game states. For example:

States

* splash
* menu
* tracks
* garage
* loading
* play

What bothers me is that I now have states within the play state to handle it based on the vehicle states:

* vehicle\_flipped
* vehicle\_damaged
* vehicle\_out\_of\_fuel

Which just doesn't sound right. I was thinking of merging the play state's states with the game states, but then it feels like I am hacking when I juggle the box2d world through the game state manager to another game state.

Any ideas on how to approach this dilemma?

# Answer
In your situation, having states within states is perfectly acceptable and is often the expected architecture.

Here is something to think about: generally, during development, you could start your game directly in the "play" state (you set up a bunch of parameters that would normally be set up by the previous state), and you make the game end instead of it going to the next state (the one after "play", e.g. leader boards display, share on your social networks, etc.).

This makes your "play" state a self contained activity. Making the play states member of the game state machine would break the encapsulation of the game logic, and force you to use unclean code in state transition.
> 2 votes

---
Tags: java, android, state, jbox2d, game-state
---


# Question
Title: Is is better to have multiple smaller or one big polygon
My game has some kind of minecraft (voxel) graphic and I have the opportunity to decide whether I want to render multiple smaller polygons or one big polygon.

Which is better for performance?

# Answer
> 1 votes
"Smaller" and "bigger" are relative terms, of course.

That said, tessellating your surfaces (i.e. breaking them into smaller triangles) will usually help up to a point, and then it'll hurt.

Large triangles suffer from a number of problems. For one, any per-vertex shader calculations will result in more obvious artifacts along the edges between triangles of planar surfaces. You mentioned in a comment a problem with shadow artifacts; bigger triangles will reduce the number of areas with artifacts but will increase their severity where they do exist. Smaller triangles should reduce the artifacts' severity or even eliminate them entirely, assuming nothing else is wrong with your shadowing algorithm.

Small triangles also have problems. Mainly, they entail more vertices being transferred to the GPU and more invocations of the vertex shader than larger triangles would.

There's other considerations at play, too. If you duplicate all shared vertices on a continuous surface, you'll (probably) get much worse performance than if you use an index buffer and share the vertices. The difference is how many vertex shader invocations are required and how big your vertex buffers must be. Cubes should be hard to do poorly, but it's certainly possible.

If you want a for-sure answer, you have to actually *measure performance* for your particular game on your target hardware. For a general case, though, tessellate your cube surfaces into fourths or sixteenths.

Note that when I say "tessellate" I mean it in the general geometric sense, not necessarily tessellation shaders. Whether or not you want to use tessellation shaders to automatically sub-divide your cube surfaces is a bigger topic, and not one I'm qualified to answer (I have no experience with them).

---
Tags: textures, performance
---


# Question
Title: Compile cocos2d-x Windows games without Visual Studio
I want to use cocos2d-x to make a Windows game. I used the cocos console:

```
cocos compile -p WIN32

```

And apparently it needs Visual Studio.

Is there an alternative to build the Windows game without Visual Studio? Anything more lightweight? I am hesitant to use Visual Studio because I actually work on many different machines and they all have somewhat limited memory.

Any other smaller IDE would do. Or even better, some sort of command line tool.

# Answer
> 1 votes
You can use Qt Creator (with MinGW) to compile cocos2d-x on Windows, here's a step by step guide by Martell on the official forums:

http://discuss.cocos2d-x.org/t/setup-fastest-setup-for-cocos2d-x-on-windows-with-qt-creator-debugging/15177

Qt Creator/Qt is a Cross-Platform IDE and application framework. Download it here:

http://www.qt.io/download-open-source/

---
Tags: cocos2d-x, windows, visual-studio
---


# Question
Title: How do I make a racing car turn more smoothly when traversing waypoints?
In a racing game, I have set up waypoints for the player to follow.

I have added many waypoints to give an illusion of curved movement.

However, the player car turns instantaneously when passing each point, which is especially jarring because the camera is following their rotation.

How can I make the player's movement a more natural curve?

---

I'm using C# in Unity.

# Answer
You basically have an ordered list of segments, making the segmented path you have described of that road. To smooth it up, you could simply take the centers of the segments and the points connecting them to create Bézeir curves from them.

Read here for a detailed explanation of how it's done.

Once you describe the path as connected Bézeir curves, it's already smooth. Now you just need to configure the vehicles to follow that path. The easiest way to do that is by generating enough points on the path at run time so you basically get many tiny segments. You can also do a kind of binary search on the curve with the `t` variable, by starting with a small increment and then doubling it until it's too far off and then doing a regular binary search over between the too far off value and half of it. Obviously, generating the spline is more cost efficient amortized.
> 1 votes

# Answer
Well I don't know much about way points but there is another way to rotate your objects on the circular track.

You can use unity iTween by which u will have to take few nodes and will be able to place them as u want and then one script is there for iTween which u will apply on the gameobject then I think it will work.

Here u go... http://itween.pixelplacement.com/index.php
> 0 votes

# Answer
You can use iTween Visual Path editor. Its a nice tool to move object on a particular path. I usually use it for cinematic camera movement. Also many of the parameters regarding the path will be exposed to the user. You can start and end at any point on the path, need not be from start point to end point. Also can force the look at angle of the moving object according to the path nodes.

Link- http://pixelplacement.com/v2/2010/12/03/visual-editor-for-itween-motion-paths/

If you want to make a car racing game its more appropriate to make a Car AI system.

Here is a nice tutorial:- https://www.youtube.com/watch?v=HeQ89e27ehc
> 0 votes

# Answer
As solution, without other tools, you can consider to start (smoothely) turn to next waypoint before you reach the current target waypoint.

Hope the image clarify my idea. When you reach the green circles (the size can depend on waypoints distances) start to turn versus next waypoint
> 0 votes

---
Tags: interpolation, curves, waypoints
---


# Question
Title: Continuous weighted random distribution, biased toward one end
I am currently contributing to a particle system for our game and developing some emitter shapes.

My uniform random distribution along a line or along a rectangular area works fine - no problem.

But now I would like to have something like a 1 dimensional gradient in this distribution. This would mean for example lower values are more common than higher values.

I don't know what would be appropriate mathematical terms for this problem, so my search skills are rather useless with this one. I need something that is computationally simple, as the particle system needs to be efficient.

# Answer
> 45 votes
Take a look at this picture:

It shows the process of mapping a (random) value to a curve. Suppose you generate a uniformly-distributed random value X, ranging from 0 to 1. By mapping this value to a curve - or, in other words, using f(X) instead of X - you can skew your distribution in whatever way you like.

In this picture, first curve makes higher values more likely; second makes lower values more likely; and the third one makes values cluster in the middle. The exact formula of the curve is not really important, and can be chosen as you like.

For example, first curve looks a bit like square root, and second - like square. Third one is a bit like cube, only translated. If you consider square root to be too slow, first curve also looks like f(X)=1-(1-X)^2 - an inversion of square. Or a hyperbole: f(X)=2X/(1+X).

As a fourth curve shows, you can simply use a precomputed lookup table. Is looks ugly as a curve, but will probably be good enough for a particle system.

This general technique is very simple and powerful. Whatever distribution you need, just imagine a curve mapping, and you'll devise a formula in no time. Or, if your engine has an editor, just make a visual editor for the curve!

# Answer
> 9 votes
A longer explanation:

If you have a desired probability distribution such as the gradient @didito asked for, you can describe is as a function. Let's say you want a triangular distribution, where the probability at 0 is 0.0, and you want to pick a random number from 0 to 1. We might write it as y = x.

The next step is to calculate the integral of this function. In this case, it's \\$\int x=\frac{1}{x^2}\\$. Evaluated from 0 to 1, that's ½. That makes sense — it's a triangle with base 1 and height 1, so its area is ½.

You then pick a random point uniformly from 0 to the area (½ in our example). Let's call this z. (We're picking uniformly from the cumulative distribution.)

The next step is to go backwards, to find what value of x (we'll call it x̂) corresponds to an area of z. We're looking for \\$\int x=\frac{1}{x^2}\\$, evaluated from 0 to x̂, being equal to z. When you solve for \\$\frac{1}{x̂^2}=z\\$, you get \\$x̂ = \sqrt{2z}\\$.

In this example, you pick z from 0 to ½ and then the desired random number is \\$\sqrt{2z}\\$. Simplified, you can write it as \\$\sqrt{rand(0, 1)}\\$ — exactly what eBusiness recommended.

# Answer
> 5 votes
You'd probably get a close approximation to what you want by utilizing an exponential system.

Make the x based on something like 1-(rnd^value) (Assuming rnd is between 0 and 1) and you'll get a few different behaviors of left to right skewing based on what you use. A higher value will get you a more skewed distribution

You can use an online graphing tool to get some rough ideas on the behaviors different equations will give you before placing them in, or you can just fiddle with the equations directly in your particle system, depending what style is more to your tastes.

**EDIT**

For something like a particle system where CPU time per particle is very important, using Math.Pow (or language equivalent) directly can lead to a decrease in performance. If more performance is desired, and value isn't being changed in run-time, consider switching to an equivalent function such as x\*x instead of x^2.

(Fractional exponents could be more of an issue, but someone with a stronger math background than I could probably come up with a good way to create an approximation function)

# Answer
> 4 votes
The term you are looking for is `Weighted Random Numbers`, most of the algorithms I have seen use trig functions, but I think I figured out a way that will be efficient:

Create a table/array/List(whatever) that holds a multiplier value for the random function. Fill it out by hand or programatically...

```
randMulti= {.1,.1,.1,.1,.1,.1,.2,.2,.3,.3,.9,1,1,1,}

```

...then Multiply `random` by a randomly chosen `randMulti`and finally by the max Value of the distribution...

```
weightedRandom = math.random()*randMulti[Math.random(randMulti.length)]*maxValue

```

I do believe that this will be much faster than using `sqrt`, or other more computationally complex functions, and will allow for more custom grouping patterns.

# Answer
> 2 votes
I think what you ask for is the distribution achieved using a square root function.

```
[position] = sqrt(rand(0, 1))

```

This will give a distribution in the single dimension field `[0, 1]` where the probability for a position is equivalent to that position, i.e. a "triangular distribution".

Alternate squareroot-free generation:

```
[position] = 1-abs(rand(0, 1)-rand(0, 1))

```

A square root in optimal implementation is just a few multiplication and sum commands with no branches. (See: http://en.wikipedia.org/wiki/Fast\_inverse\_square\_root). Which one of these two functions are faster may vary depending on platform and random generator. On an x86 platform for instance it would take only a few unpredictable branches in the random generator to make the second method slower.

# Answer
> 1 votes
Just use a Beta distribution:

* Beta(1,1) is flat
* Beta(1,2) is a linear gradient
* Beta(1,3) is quadratic

etc.

The two shape parameters need not be integers.

# Answer
> 0 votes
Even simpler, depending on the speed of your random generator, you can just generate two values and average them.

Or, even more simple, where X is the result of the rng, first `double y = double(1/x);`, `x = y*[maximum return value of rng];`. This will weight numbers exponentially to the lower numbers.

Generate and average more values to increase the likelihood of getting values closer to center.

Of course this only works for standard bell curves distributions or "folded" versions thereof\*, but with a fast generator, it might be faster and simpler than using various math functions like sqrt.

You can find all sorts of research on this for dice bell curves. In fact, Anydice.com is a good site which generates graphs for various methods of rolling dice. Though you are using an RNG, the premise is the same, as are the results. So it is a good spot for seeing the distribution before even coding it.

\*Also, you can "fold" the result distribution along an axis by taking the axis and subtracting the averaged result then adding the axis. For example, you want lower values to be more common, and lets say you want 15 to be your minimum value and 35 to be your max value, a range of 20. So you generate and average together two values with a range of 20 (twice the range you want), which will give a bellcurve centered on 20 (we subtract five at the end to shift the range from 20 to 40, to 15 to 35). Take the generated numbers X and Y.

Final number,

```
z =(x+y)/2;// average them
If (z<20){z = (20-z)+20;}// fold if below axis
return z-5;// return value adjusted to desired range

```

If zero is your minimum, even better, do this instead,

```
z= (x+y)/2;
If (z<20){z = 20-z;}
else {z = z - 20;}
return z;

```

---
Tags: mathematics, random, distribution
---


# Question
Title: How to compile with OpenGL ES on Windows?
I downloaded OpenGL ES 3.1 sdk here.

But when I tried to run (or compile and run) the executable in "samples" directory, I got the following message:

> The program can't start because libGLESv2.dll is missing from your computer. Try reinstalling the program to fix the problem.

This sounds strange, because the sample program is directly linked with *libGLESv2.lib*, so it shouldn't even look for dll files.

But when I wanted to install dll files (libGLESv2.dll and libEGL.dll), I got the following error:

```
regsvr32 libGLESv2.dll

```

> The module "libGLESv2.dll" was loaded but the entry-point DllRegisterServer was not found.
> Make sure that "libGLESv2.dll" is a valid DLL or OCX file and try again.

So it looks like these dll files are kind of invalid.

Is the problem from my dll files? Or did I miss something in installation process?

# Answer
It seems like you're having several points where you're confused, so I'll go one by one:

* Not all LIB files are self contained. It depends on how the DLL is compiled and linked, but it is possible, and very common for some LIB files to simply contain stubs to the necessary functionality, which is provided by a DLL. This seems to be the case.
* The error as you see it, tells you everything you need to know. The DLL file cannot be found by Windows. The places where Windows looks for DLLs is not trivial, but if you want to make sure a specific DLL is loaded with your program, your best bet is to put the DLL file in the same folder as the executable file.
* Make sure you use a DLL with the same architecture (32-bit or 64-bit) as the target program. In the case of the sample you sent, the executable is 32-bit, so copy both libGLESv2.dll and libEGL.dll into the folder which has GLESSample.exe.
* regsvr is meant to register COM components, so in this case it is completely unrelated.

Once you copy the program, it runs, but then, at least in my PC, it ends with an "Failed to link program" error. This is an OpenGL error, so this most likely means that there are no OpenGL-ES drivers in my computer.

As you know, OpenGL-ES is a subset of OpenGL, meant for mobile devices. If there are OpenGL-ES drivers for my video card, I would have to install them to get it to run. The steps to get this to work are dependent on the video card vendor, and it seems that these samples are meant for AMD Radeon™ HD, AMD Mobility Radeon™ HD, and AMD FirePro™ graphics cards.
> 3 votes

# Answer
I suggest you save yourself a lot of pain and grab the ARM Mali OpenGL ES Emulator, or the PowerVR Graphics SDK v3.3. This way you will be ready to roll in minutes. This of course assumes that you do not need your ES setup to run natively on Windows machines, e.g. when your game goes to market.

If you do need to the code to run natively on Windows, you could look at Google Angle (difficult) which translates GL calls into DirectX calls on the fly, or use the full OpenGL ES 2.0 API available under desktop OpenGL 4 (though I assume you specifically want the GLES 3.0 API, so these options may not help). I've done the latter and it works fine.
> 5 votes

---
Tags: opengl-es, windows, opengl-es3
---


# Question
Title: How to properly rotate towards a local point (a local LookAt)?
I am having a nightmare trying to make a child object rotate towards a given point of its parent object, similar to what is possible at the world level when using LookAt.

The problem is that most functions related to rotating in Unity do not work for local level. In the description of function `transform.Rotate` one can have the impression that it allows that, trough passing the `Space.Self` parameter. However, to use that function one has to know the 3 angles between the 2 points of interest. And there is no function that allows such calculation.

Anyone could please help implementing a local LookAt?

# Answer
This should do it:

```
void LookAtPointInParent(Vector3 parentSpacePoint)
{
    Vector3 parentSpaceDirection = parentSpacePoint - transform.localPosition;
    transform.localRotation = Quaternion.LookRotation(parentSpaceDirection);
}

```

If you want, you can add a second parameter to Quaternion.LookRotation() to control the roll of the object. For instance, you could use...

```
Vector3 localUp = transform.parent.InverseTransformDirection(Vector3.up);

```

to keep the object's up vector roughly aligned with the world up vector (y+) whenever possible (ie. when not looking directly up/down)
> 1 votes

# Answer
Assuming you know father position and local point position:

```
GameObject tmp = new GameObject("tmp"); //empty gameobject declared outside update() for performance

//inside update...
tmp.transform.position = new Vector3(fatherPos.x+localx
        , fatherPos.y+localy, fatherPos.z+localz);
transform.LookAt(tmp);

```
> 0 votes

---
Tags: unity, camera, geometry, rotate
---


title: Problem with animations from Blender

text:
# Question
Title: Problem with animations from Blender
I have a model that I made in Blender and also I have a gun reloading animation, the model has a rig. So it appears that the animation of the rigged model is devided into 25 different animations but in Unity I can't play all of them at once, if I play only one animation from 25 it will only animate one object (eg. hands) not the magazine or anything else. My question is how is it usually done to play animations from Blender in Unity properly or make animation properly in Blender.

# Answer
> 1 votes
It seems like you have many different meshes in the model you're exporting. Typically when you export a model, there will be a **single mesh** even though it may have physically separate parts. The crux of your problem being that animations work on a per mesh basis, so because you have 25 different meshes you're given 25 different animations. Take a look at this post to join all your meshes into one. Hopefully it won't ruin your animation.

# Answer
> 0 votes
Did you export it to Autodesk FBX from Blender? What options are showed in the animation tab when you select the imported model in Unity?

---
Tags: unity, animation, blender, rigging, export
---


# Question
Title: Separating Game Engine from game code in similar games, with versioning
I have a finished game, that I want to decline in other versions. These would be similar games, with more or less the same kind of design, but not always, basically things might change, sometimes little, sometimes big.

I would like the core code to be versioned separately from the game, so that if say I fix a bug found in game A, the fix will be present in game B.

I am trying to find the best way to manage that. My initial ideas are this:

* Create an `engine` module/folder/whatever, that contains everything that can be generalized and is 100% independent from the rest of the game. This would include some code, but also generic assets that are shared among games.
* Put this engine in its own `git` repository, which will be included in the games as a `git submodule`

The part I am struggling with is how to manage the rest of the code. Let's say you have your menu scene, this code is game-specific, but also most of it tends to be generic and could be reused in other games. I can't put it in the `engine`, but re-coding it for each game would be inefficient.

Maybe using some sort of git branches variation could be effective to manage that, but I don't feel like this is the best way to go.

Anyone has some ideas, experience to share or anything about that?

# Answer
> Create an engine module/folder/whatever, that contains everything that can be generalized and is 100% independent from the rest of the game. This would include some code, but also generic assets that are shared among games.
>
> Put this engine in its own git repository, which will be included in the games as a git submodule

That's exactly what I do and it works very well. I've an application framework and a rendering library, and each of these are treated as submodules of my projects. I find SourceTree is useful when it comes to submodules, as it manages them well and won't let you forget anything, e.g. if you updated the engine submodule in project A, it will notify you to pull the changes in project B.

With experience comes the knowledge of what code should be in the engine vs. what should be per-project. I suggest that if you are even mildly unsure, that you keep it in each project for now. As time goes by, you will see amongst your various projects what remains the same and then you can gradually factor that out into your engine code. In other words: duplicate code until such time as you are close to 100% certain that it is not changing discretely per project, then generalise it.

**Note on Source Control and Binaries**

Just remember that if you are expecting your binary assets to change often, you may not want to put these in text-based source control like git. Just sayin'... there are better solutions for binaries. The simplest thing you can do for now to help keep your "engine-source" repository clean and performant is to have a separate "engine-binaries" repository that holds only binaries, which you also include as a submodule in your project. This way you mitigate the performance-damage done to your "engine-source" repository, which is changing all the time and on which you thus need fast iterations: commit, push, pull etc. Source control management systems like git operate on text deltas, and as soon as you introduce binaries, you introduce massive deltas from a text perspective - which ultimately costs you dev time. Another solution may be GitLab Annex. Google's your friend.
> 12 votes

# Answer
At some point an engine MUST specialise and know stuff about the game. I will go off on a tangent here.

Take resources in an RTS. One game may have `Credits` and `Crystal` another `Metal` and `Potatoes`

You should use OO concepts properly and go for max. code-reuse. It's clear that a concept of `Resource` exists here.

So we decide resources have the following:

1. A hook in the main loop to increment/decrement themselves
2. A way to get the current amount (returns an `int`)
3. A way to subtract/add arbitrarily (players transferring resources, purchases....)

Notice that this notion of a `Resource` could represent kills or points in a game! It isn't very powerful.

Now lets think about a game. We can sort of have currency by dealing in pennies and adding a decimal point to the output. What we cannot do are "instantaneous" resources. Like say "power grid generation"

Lets say you add a `InstantResource` class with similar methods. You're now (starting to) pollute your engine with resources.

---

## The Problem

Lets take the RTS example again. Suppose player whatever donates some `Crystal` to another player. You want to do something like:

```
if(transfer.target == engine.getPlayerId()) {
    engine.hud.addIncoming("You got "+transfer.quantity+" of "+
        engine.resourceDictionary.getNameOf(transfer.resourceId)+
        " from "+engine.getPlayer(transfer.source).name);
}
engine.getPlayer(transfer.target).getResourceById(transfer.resourceId).add(transfer.quantity)
engine.getPlayer(transfer.source).getResourceById(transfer.resourceId).add(-transfer.quantity)

```

However this is really quite messy. It's general purpose, but messy. Already though it imposes a `resourceDictionary` which means now your resources have to have names! AND it is per player, so you cannot have team resources any more.

This is "too much" abstraction (not a brilliant example I'll admit) instead you should hit a point where you accept that your game has players and crystal, then you can just have (for example)

```
engine.getPlayer(transfer.target).crystal().receiveDonation(transfer)
engine.getPlayer(transfer.source).crystal().sendDonation(transfer)

```

With a class `Player` and a class `CurrentPlayer` where `CurrentPlayer`'s `crystal` object will automatically show the stuff on the HUD for the transfer/sending of donations.

This pollutes the engine with crystal, the donating of crystal, the messages on the HUD for current players and all that. It is both faster and easier to read/write/maintain (which is more important, as it isn't significantly faster)

---

## Final remarks

The resource case isn't brilliant. I hope you can still see the point though. If anything I have demonstrated that **"resources do not belong in the engine"** as what a specific game needs and what is applicable to all notions of resources are VERY different things. What you will usually find are 3 (or 4) "layers"

1. The "Core" - this is the textbook definition of engine, it's a scene graph with event hooks, it deals with shaders and network packets and an abstract notion of players
2. The "GameCore" - This is pretty generic to the type of game but not to all games - for example resources in RTS or ammunition in FPSs. The game logic starts to seep in here. This is where our earlier notion of resources would be. We've added these things that make sense for most RTS resources.
3. "GameLogic" VERY specific to the actual game being made. You'll find variables with names like `creature` or `ship` or `squad`. Using **inheritance** you'll get classes that span all 3 layers (for example `Crystal` *is a* `Resource` which *is a* `GameLoopEventListener` say)
4. "Assets" these are useless to any other game. Take for example the combine AI scripts in half life 2, they're not going to be used in an RTS with the same engine.

---

## Making a new game from an old engine

This is VERY common. Phase 1 is to rip out layers 3 and 4 (and 2 if the game is a TOTALLY different type) Suppose we are making an RTS from an old RTS. We still have resources, just not crystal and stuff - so the base classes in layers 2 and 1 still make sense, all that crystal referenced in 3 and 4 can be discarded. So we do. We may however check it as a reference for what we want to do.

---

## Pollution in layer 1

This can happen. Abstraction and performance are enemies. UE4 for example provides a lot of optimised cases of composition (so if you want X and Y someone wrote code that does X and Y together really fast - it knows it is doing both) and as a result is REALLY quite large. This isn't bad but it is time consuming. Layer 1 will decide things like "how you pass data to shaders" and how you animate things. Doing it the best way for your project is ALWAYS good. Just try and plan for the future, reusing code is your friend, inherit where it makes sense to.

---

## Classifying layers

LASTLY (I promise) don't be too afraid of layers. Engine is an archaic term from the old days of fixed function pipelines where engines pretty much worked the same way graphically (and as a result had a lot in common) the programmable pipeline turned this on its head and as such "layer 1" became polluted with whatever effects the developers wanted to achieve. AI was the distinguishing feature (because of the myriad of approaches) of engines, now it is AI and graphics.

Your code shouldn't be filed in these layers. Even the famous Unreal engine has MANY different versions each specific to a different game. There are few files (other than like data structures maybe) that would have gone unchanged. This is fine! If you want to make a new game from another it'll take longer than 30 minutes. The key is to plan, to know what bits to copy and paste and what to leave behind.
> 6 votes

# Answer
My personal suggestion for how to handle the content that's a mix of generic and specific is to make it dynamic. I'll take your menu screen as an example. If I misunderstood what you were asking for, let me know what it was you wanted to know and I'll adapt my answer.

There are 3 things that are (nearly) always present on a menu scene: the background, the game logo and the menu itself. These things are usually different based on the game. What you can do for this content is make a MenuScreenGenerator in your engine, which takes 3 object parameters: BackGround, Logo and Menu. The basic structure of these 3 parts are also part of your engine, but your engine does not actually say how these parts are generated, just what parameters you should give them.

Then in your actual game code, you create objects for a BackGround, a Logo and a Menu, and you pass this to your MenuScreenGenerator. Again, your game itself does not handle how the menu is generated, that's for the engine. Your game only needs to tell the engine what it should look like and where it should be.

Essentially, your engine should be an API that the game tells what to display. If done properly, your engine should do the hard work and your game itself should only tell the engine what assets to use, what actions to take and what the world looks like.
> 1 votes

---
Tags: architecture, software-engineering, design-patterns
---


# Question
Title: Textures rendering upside down and small with Pixel Shader in Mono Game but not XNA
I'm new to HLSL, attempting to use MonoGame to do some simple post processing effects.

Here is my HLSL file, taken from one of rbwhitaker's xna tutorials (I would post the link, but can't post more than two with my current reputation).

```
//------------------------------ TEXTURE PROPERTIES ----------------------------
// This is the texture that SpriteBatch will try to set before drawing
texture ScreenTexture;

// Our sampler for the texture, which is just going to be pretty simple
sampler TextureSampler = sampler_state
{
    Texture = <ScreenTexture>;
};

//------------------------ PIXEL SHADER ----------------------------------------
// This pixel shader will simply look up the color of the texture at the
// requested point, and turns it into a shade of gray
float4 PixelShaderFunction(float2 TextureCoordinate : TEXCOORD0) : COLOR0
{
    float4 color = tex2D(TextureSampler, TextureCoordinate);

    float value = (color.r + color.g + color.b) / 3;
    color.r = value;
    color.g = value;
    color.b = value;

    return color;
}

//-------------------------- TECHNIQUES ----------------------------------------
// This technique is pretty simple - only one pass, and only a pixel shader
technique BlackAndWhite
{
    pass Pass1
    {
        PixelShader = compile ps_4_0 PixelShaderFunction();
    }
}

```

The only line I've changed is the compiler version from ps\_2\_0 -\> ps\_4\_0, since MonoGame needs 4.0 (I think?)

I'm using MonoGame 3.4, and I've changed nothing from the initial project template except the following:

```
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);
    // TODO: use this.Content to load your game content here
    BlackAndWhiteEffect = Content.Load<Effect>("BlackAndWhite");
    Image = Content.Load<Texture2D>("smiley");
}

private Effect BlackAndWhiteEffect
{
    get;
    set;
}

private Texture2D Image
{
    get;
    set;
}

protected override void Draw(GameTime gameTime)
{

    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, BlackAndWhiteEffect);
    //spriteBatch.Begin();

    spriteBatch.Draw(Image, GraphicsDevice.Viewport.Bounds, Color.White);

    spriteBatch.End();

    base.Draw(gameTime);
}

```

Here is the result of the code executing in monogame:

And here is the result from an identical project created in XNA (except for ps\_2\_0 in the shader, as mentioned before):

Would appreciate any help. I can upload both solution files if needed.

# Answer
> 3 votes
I have solved my problem, although I am not sure why exactly this solves the problem. This post was helpful to me: http://www.software7.com/blog/monogame-hlsl-shader-example-for-a-post-processing-blur-effect/

Here is my working shader:

```
//------------------------------ TEXTURE PROPERTIES ----------------------------
// This is the texture that SpriteBatch will try to set before drawing
texture2D ScreenTexture;

// Our sampler for the texture, which is just going to be pretty simple
sampler TextureSampler = sampler_state
{
    Texture = <ScreenTexture>;
};

//------------------------ PIXEL SHADER ----------------------------------------
// This pixel shader will simply look up the color of the texture at the
// requested point, and turns it into a shade of gray
float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 texCoord : TEXCOORD0) : SV_TARGET0
{
    float4 color = ScreenTexture.Sample(TextureSampler, texCoord.xy);

    float value = (color.r + color.g + color.b) / 3;
    color.r = value;
    color.g = value;
    color.b = value;

    return color;
}

//-------------------------- TECHNIQUES ----------------------------------------
// This technique is pretty simple - only one pass, and only a pixel shader
technique BlackAndWhite
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_3  PixelShaderFunction();
    }
}

```

Here's what I did: used Texture2D instead of Texture, changed the arguments of PixelShaderFunction (some of which I don't use, but seem to be required), used Texture.Sample instead of tex2D, and changed to ps\_4\_0\_level\_9\_3

The rest of the code remained the same.

If anyone knows why this works, I'd be happy to hear the explanation.

Edit:

For anyone experiencing this problem in the future, here is the explanation. All of the parameters are needed for the PixelShaderFuction for registers to be mapped correctly. See the post here:

http://www.software7.com/blog/pitfalls-when-developing-hlsl-shader

# Answer
> 0 votes
You should add address mode on your texture sampler:

```
sampler TextureSampler = sampler_state
{
    Texture = <ScreenTexture>;

    AddressU = WRAP;
    AddressV = WRAP;
};

```

I'm not sure why that's necessary on monogame and not XNA but I guess it's because DX9 did things a bit different. The flipped UV coordinate puzzles me, I hope someone else can shed any light on this.

---
Tags: c#, xna, glsl, hlsl, monogame
---


title: PNGs on a plane

text:
# Question
Title: PNGs on a plane
I am trying to make a chain link fence using planes and a .png image as the texture, I am importing the whole environment from blender however this problem keeps on appearing, the plane gets the .png file and you can see through the fence only on one side, if you turn to the other side then the plane disappears completely. However this doesn't happen in blender when I render the image. I have tried importing the .blend file to unity and using an .fbx file however it still appears that way. Any idea on how to fix this problem?

# Answer
I think you actually mean a quad. A quad consists of 2 triangles, even if blender doesnt show that. A triangle - and with that - a quad, has a normal. Consider it to be the front of the quad. Usually, we dont draw the back of a quad because we don't need to. Rendering is roughly twice as fast when we dont draw the triangles that face the other way, and you usually dont see that we cull them, because they're normally occluded by other triangles. In this case, it is a little more difficult. We need to duplicate the quad, and make the copy face the other way. In blender, select your quad (or plane, if you want to keep calling it that). Shift-d to duplicate the vertices. Just move it slightly away to the side that you cant see in the other program. Press w. Click flip normals. Save and export. Im not sure if this is what the problem is but it sounds like it.
> 1 votes

---
Tags: materials, importing
---


title: Creating three-dimensional biomes

text:
# Question
Title: Creating three-dimensional biomes
I have an idea for a space-based game where there are different sectors of control. These would be set up in a manner similar to terrain biomes, where there will be clusters with limited space between them where there are 'mixed' biomes or even no biomes whatsoever, indicating no 'side' has control over that region.

There are a plethora of articles on the web these days about how to create two dimensional biome maps, but I have seen none about making three-dimensional maps. Has anyone done any coding like this before? My Google-fu is strong but I haven't found any significant pages on it.

I will continue to work on it solo, but as a beginning, solo programmer I expect I will be quite slow on it. I was just wondering if anyone had done this already.

# Answer
I suggest using Voronoi subdivision. I gave similar answer here for a map (2d) biomes. You may generalize it in 3d.

Then asociate a value to each point that results (in the example image) in different color for each cell
> 2 votes

---
Tags: c#
---


title: Where to begin in game developing?

text:
# Question
Title: Where to begin in game developing?
I have no experience with development, I have played many games and have great ideas but don't know where to start other then storyboards and ideas. I want to know what I'll need and how to start learning so one day I can make a game that I can be proud of.

# Answer
Learn about games. Play games you enjoyed again and try to figure out how they work and how they do what they do and why. Many game developers have blogs and web sites and Twitter streams. Subscribe to those and read what they've written in the past years. Search StackExchange here and just read any topic that talks about things you will need for whatever the simplest game idea you've had so far would need. Use your favorite web search engine and just type in any questions you have and see what interesting stuff you find.

This will give you a better idea of how game developers out there work, what tools they use etc. Then learn about those tools. Depending on what parts of game design you want to do, learn those disciplines (there are lots of non-game-development resources and tutorials about programming, graphics design, animation, sound design, UI design etc.).

There are also books about lots of game design topics.

In the end, it's not important where you start, just *that* you start. Find out how to program your computer or how to install a development environment specific to games and start doing a few simple games, and keep trying things out, keep learning. Build a few to throw away, and thereby learn on the go.
> 1 votes

---
Tags: video
---


# Question
Title: the object of type 'GameObject' has been destroyed but you are still trying to acess it
the object of type 'GameObject' has been destroyed but you are still trying to access it .your script should either check if it is null or you should not destroy the object

my script is in c#

```
    w = brick[0].GetComponent<SpriteRenderer>().bounds.size.x;
    h = brick[0].GetComponent<SpriteRenderer>().bounds.size.y;
    x = brick[0].transform.position.x - w/2;
    y = brick[0].transform.position.y - h/2;
    xp = ball.transform.position.x;
    yp = ball.transform.position.y;
    if (ptobcollision(x,y, w, h, xp, yp)) {
        ball.GetComponent<Ball>().YDirection = 1;
        //Debug.LogError("now Error");
        Destroy(brick[0]);
    }

```

# Answer
```
xp = ball.transform.position.x;
yp = ball.transform.position.y;

if (brick[0] != null)
{
    w = brick[0].GetComponent<SpriteRenderer>().bounds.size.x;
    h = brick[0].GetComponent<SpriteRenderer>().bounds.size.y;
    x = brick[0].transform.position.x - w/2;
    y = brick[0].transform.position.y - h/2;

    if (ptobcollision(x,y, w, h, xp, yp)) {
        ball.GetComponent<Ball>().YDirection = 1;
        //Debug.LogError("now Error");
        Destroy(brick[0]);
    }
}

```
> 1 votes

---
Tags: c#
---


title: OpenGL vertex data per index

text:
# Question
Title: OpenGL vertex data per index
Usually, vertex data is assigned to a particular vertex, like this:

```
[data]    [vertices]
[1.31] -> [1, 13, 5]
[84.3] -> [5, 8, 12]
[.095] -> [8, 3, 10]

```

Then, you would typically have an array saying which order to draw the vertices in:

```
[indices]
[   0   ]
[   2   ]
[   1   ]
[   2   ]

```

Using this, the first vertex would be drawn first, then the third vertex, then the second one, then the third one again. My question is if it is possible to assign vertex data to the index array rather than to the vertex array, like this:

```
[data]    [indices]
[1.31] -> [   0   ]
[84.3] -> [   2   ]
[.095] -> [   1   ]
[30.1] -> [   2   ]

```

So that when it draws each vertex from the index array, it uses that particular value.

Please note that I am dealing with a lot more vertices than are shown here. (17^3 to be precise) The examples I shown above wouldn't be useful by themselves, but it would make a significant difference in performance in my program if this was possible.

# Answer
> 5 votes
No it is not.

The input to the shader pipeline expects a "*stream*" of vertices. So say you're using `DRAW_TRIANGLES` (or whatever it is) what actually happens is this:

> 1. Create 3 buffers (these are your `varying`s) of sufficient size
> 2. **Fetch vertex** (attributes) and put them in the input to the vertex shader
> 3. Run the vertex shader
> 4. Transfer varyings output into the 1st buffer
> 5. **Fetch vertex** and put them in the input to the vertex shader
> 6. Run the vertex shader
> 7. Transfer the varyings output to the 2nd buffer
> 8. **Fetch vertex** and put them in the input to the vertex shader
> 9. Run the vertex shader
> 10. Transfer the varyings output to the 3rd buffer
> 11. Interpolate the varyings buffers over the resulting triangle and run the fragment shader for each "fragment" (pixel/sub-sampled pixel basically)

I've put the important bit, "fetch vertex" in bold because this could mean anything. OpenGL doesn't specify how this must actually be done (because of course it belongs to the implementation) but this is where indexed arrays come into play.

---

## Buffers, arrays and indexed arrays

**Buffers:**
The most primitive form of storage is a `Buffer` \- this doesn't know what it stores, it is simply a chunk of bytes.

**Arrays:**
Next we have arrays, arrays are not actually blocks of memory. They contain 4 bits of information:

1. Which `Buffer` they are an array on. (a `BufferId` or `Buffer*` perhaps)
2. What data type they're supposed to be (eg 3 floats, 2 ints, 16 floats (for a 4x4 matrix)...)
3. An offset (call this `o`)
4. A step (call this `s`)

When you ask for the `i`th member of an array you actually get `Buffer[si+o] - to - Buffer[si+o+sizeof(data type)]` back. So if its floats, 4 bytes, you get these 4 bytes: `Buffer[si+o]`, `Buffer[si+o+1]`, `Buffer[si+o+2]` and `Buffer[si+o+3]` back

**Indexed arrays:**
This is an array of some integer data type (so it's a buffer + the array structure on top that returns numbers).

---

## Vertex streams

If you're using arrays, NOT indexed ones the fetch vertex step looks something like this:

```
For each attribute:
     attribute.array[i]
i++;

```

Or

```
For each attribute:
    attribute.buffer[attribute.array.step*i+attribute.array.offset]
i++;

```

With **indexed arrays** it does this:

```
For each attribute:
     attribute.array[Index[i]]
i++;

```

Or

```
For each attribute:
    attribute.buffer[attribute.array.step*Index[i]+attribute.array.offset]
i++;

```

In some sort of pseudo code.

As you can see indexes are not "complex" enough to do anything more than provide a lookup table mapping vertices to the data they're supposed to have.

---

## In the industry

Suppose you have vertex positions and normals, technically you can have buffers like this:

```
Buffer 1: xyzxyzxyz.....
Buffer 2: uvwuvwuvw.....

```

However this is bad because it means the implementation will (at some level) have to read something from buffer 1, then jump to buffer 2 and read some more, then back to buffer 1 and so forth and so forth. This is bad.

What you should do is something like:

```
Buffer 1: xyzuvwxyzuvwxyzuvw.....

```

This would just be a bigger step on the arrays. The implementation will likely optimise things like this so it just has to read it right away (with minimal transposing)

**Indexing is bad as it can result in rather random reads** at least with arrays it is predictable, so it is possible to do some hardware magic that can speedily read from multiple buffers, indexes however are not a simple `ax+b` formula, they can literally be random.

> *as such unless the cardinality (number) of indexes differs hugely from the length of the array* implementations often unpack the indexed array.

That is to say if you have an index of 3 million but only 12 vertices, it'll use the index. If you have 15k index and 15k vertices it will not and it'll just unpack it.

---

## Final note

The usefulness of indexed arrays is limited by the fact that MOST of the time vertices in the same position will have different surface normals, consider for example a cube. Take any corner, that vertex will have 3 distinct normals. I think this is what you're trying to do. You've realised that they have the same position, but your `data` can still vary.

---
Tags: opengl, vertex, index-buffer
---


title: Syncing items between server and client

text:
# Question
Title: Syncing items between server and client
I'm doing this game of mine, and I want to add the items to it.
I'm already familiar with the basic concept of syncing data between server and client,
Usually using sync state, that's what i've done with my friends in our previous game.
This game is sort of a recreating of the previous one, but written better.

---

The problem we had with items is that every item we created in the server was basically a Subclass of a class that is a subclass of Item, for example:

`EmeraldStaffOfTheExiledMonk : Weapon : Item`

When we wanted to have the item in the client side, what we had to do is to create an item class, which would hold the necessary information we need to have of an item, and have some sort of an initialization of an ItemPool.
Now, to sync that, we obviously have to sync the IDs of each item, assuming we have them.
My question to you guys is, is there any good way to actually sync items across client and server, without having any hard-code of those items in the client side?

---

What I eventually want is to have an ItemPool that would be generated in the client when you connect to the server, and the only thing the client would really need to have is the assets of that item(textures, and so on)

# Answer
Several approaches:

1. Serialize your objects, i.e. write out binary or XML data identifying the class (e.g. the class name, or a number representing the class) and all its interfaces. Then write some code that takes this data and de-serializes it again. Of course this means that you need to have all classes on both the client side and the server side.

But you don't need a class for each object, you just need classes for similar objects. So e.g. a class for a "staff" which then lists what amount of damage a staff does with its primary and secondary attack, and maybe what bonus it gives to certain kinds of magic or whatever. That part is the "data-driven" design that @Byte56 mentions in the comment.
2. Like 1, but just have one very complicated 'weapon' class instead of individual subclasses. This is a fully data-driven approach, and you'd need a way to tell the game that an item has or doesn't have a certain ability (e.g. set secondary attack damage to 0 to indicate there is no secondary attack). This makes it easier to update game state on the server without having to update the client, but also makes your code harder to maintain
3. Proxies. I.e. *everything* happens on the server, and your local object is just a cache/forwarder. It maybe has a name and an image, but whenever players perform an operation on it, you send a message to the server, which then replies with messages indicating what animations to play on your player/target, and how the actors' health numbers have changed. This is what many MMOs use (also as a way to prevent cheating, as all the logic happens on the server). Downside of this is that there is a lot more network traffic and a bad connection makes the game lag more.
4. Combinations of the above. E.g. basically 3, but with some of 2 or 1 for implementing caching, so you can start playing an animation because you know from your local data that the primary attack is 10 fire damage, and if the connection is slow, the game will mostly behave right by anticipating the info that comes in late. But it'll still be cheating protection because the canonical store of information is the server's, not the client's.
> 2 votes

# Answer
The usual way to handle this is having just a base-class `Item` and optionally generic classes for item sub-categories like `Weapon`. But all specific weapons would each use an instance of the class `Weapon` and differ by the properties of that class.

When the number of items in your game is small and fixed, you could transfer a list of items and their properties on login or have such a list as a file and treat it like any other asset.

When the number of items is very large or not fixed (for example, because you have procedural generation of items), you should send item information on demand. Either send the information whenever the client encounters an item, or implement a request/response protocol which allows the client to request the details of a specific item-id from the server.
> 0 votes

---
Tags: c#, client-server, synchronization
---


# Question
Title: DirectXTK Model : How to draw with custom vertex & pixel shader?
Here is the code I use to render a `.cmo` (from `.fbx`) mesh :

```
void Render()
{
    assert(g_d3dDevice);
    assert(g_d3dDeviceContext);

    Clear(Colors::LimeGreen, 1.0f, 0);

    //g_d3dDeviceContext->VSSetShader(g_d3d_GEOM_VertexShader, nullptr, 0);
    //g_d3dDeviceContext->VSSetConstantBuffers(0, 3, g_d3dConstantBuffers);

    g_d3dDeviceContext->RSSetState(g_d3dRasterizerState);
    g_d3dDeviceContext->RSSetViewports(1, &g_Viewport);

    //g_d3dDeviceContext->PSSetShader(g_d3d_GEOM_PixelShader, nullptr, 0);
    //g_d3dDeviceContext->PSSetShaderResources(0, 1, &g_SkyboxShaderRessourceView);

    g_d3dDeviceContext->OMSetRenderTargets(1, &g_d3dRenderTargetView, g_d3dDepthStencilView);
    g_d3dDeviceContext->OMSetDepthStencilState(g_d3dDepthStencilState, 1);

    // Draw ship
    std::unique_ptr<CommonStates> states(new CommonStates(g_d3dDevice));
    DGSLEffectFactory fx(g_d3dDevice);
    auto testMesh = Model::CreateFromCMO(g_d3dDevice, L"media/meshes/space-frigate/space_frigate_6.cmo", fx, false);
    testMesh->Draw(g_d3dDeviceContext, *states, g_WorldMatrix, g_ViewMatrix, g_ProjectionMatrix);

    Present(g_EnableVSync);
}

```

What puzzles me :

1. How do I use my own vertex / pixel shaders instead of the auto-generated ones ? Notice I commented the line where I set the shaders and it works just as well...
2. What is the `CommonStates` object and what is it used for ? It doesn't seem to do anything even when adding i.e. `states->Wireframe();`
3. Why is an `DGSLEffectFactory` required and what is it used for ?
4. Why does the Z-test fail in the 2nd image ?

All in all : should I write my own mesh loader instead to rely on custom vertex / pixel shaders ?

# Answer
> 2 votes
You shouldn't be loading the model every frame. Just load it once and render it over and over as needed. Also, you should create the `DGSLEffectFactory` and `CommonStates` once and reuse it.

1. The design is for you to implement your own `IEffectFactory` and then you can return your own custom `IEffect` for custom shaders. You can also control the individual subset drawing instead of calling `Model::Draw`. See ModelMesh for details.
2. The `CommonStates` object is a factory for 'stock' states. The `Model` drawing uses it to set the default states. You can use it directly. For example, to set a wireframe rendering mode: `g_d3dDeviceContext->RSSetState(states->Wireframe());` It's a helper object so you don't end up creating lots of redundant states for common combinations.
3. The `IEffectFactory` interface you pass to the `Model` loader is the abstraction for creating `IEffect` instances (i.e. shaders) and for loading textures. The default ones also handle 'material and texture sharing' so you don't create unique instances for every single model's material.
4. I can't tell exactly what's wrong based on our snippet, but a common thing to have go wrong is right-handed vs. left-handed view coordinates vs. the winding of the model. You can try passing a 'true' at the end of the loader to see if that worked.

The general model of DirectX Tool Kit is to provide you a solid starting point. You can then replace portions as you want. That said, it's best to really understand how it works before moving on your own solution. I suggest you take the time to work through the DirectX Tool Kit tutorials for a comprehensive introduction to using Direct3D 11 and the library.

---
Tags: directx11, 3d-meshes, fbx
---


title: balance productions and consumes

text:
# Question
Title: balance productions and consumes
I am looking into whether there is a way to balance the production and consumption of resources in a game over time, with the aim to allow both production and consumption to increase as various buildings and entities level up (or across various difficulty levels). For example a classic resource would be stone, wood, etc. I am not looking for the initial values for building (those I suppose are set by testing it) but is there a formula or a logical process to calculate the increasing amount?

For example, at level 1 the "mine" produces 100 stone per hour and a “house” needs 120 stone to build. How should the production level increase for a mine at level 2-3-4-etc compared to the cost of building a level 2-3-4-etc house? Also, mine level 2 will cost more than level 1 obviously.

My problem is how to balance the game (starting with costs-productions).

# Answer
You hit the nail on the head in your own question, the best way to work out the production / consumption balance is to set the game to certain levels and test it to see how it feels. There are some guidelines that can be followed however, for example say your level 1 mine produces 100 stone per hour and your house costs 100 stone, then it would make sense if a level 2 mine produces 200 stone the house should cost 200 stone.

The key is the percentage increase and making sure that one level 5 mine wont provide far more stone than you would ever need for 10 level 5 houses, that being said you would probably want to build in some reason to level up the production so you could increase production to 200 stone but the cost of the house to 190 (10% improvement). Again the actual values you set will depend entirely on your specific game and will need testing to confirm they don't lead to unbalanced play but these effects can be minimised by ensuring that everything is increasing by a similar percentage at each level.

EDIT:

Just as a note, the overall idea that you would like to implement can be planned and in fact should be! You should have an idea of how the building should upgrade over time and the effect this should have on game play but the initial numbers you guess will likely give different results from expected so testing is the only way to find the best final numbers.

A number of comments to this answer also have insight such as increasing the upgrade by only a percent of the initial building capacity so that it is not always the best case to upgrade etc. but I will leave it to others to go more in depth in these areas if they see it is required!
> 2 votes

# Answer
I'd start by deciding on what resources will be used, all of them, including time, space, etc, and seeing which ones have what kind of limits based on the logical consequences of the game type. For example Clash of Clans style game will have limited build area which makes the space consumed factor more valuable.

Also consider that resources like gold are pass through, the player gets some, has it for a while, then when they spend it, it is gone forever. Space is set in that there is a set amount in the game and once it is all used, they need to either take more space from other entities in the game, or destroy something of theirs to gain the space needed for new stuff. \[edit:clarify\] This doesn't mean that a set resource can't be variable in a fashion other than direct character choice. I.E. a game with a number of people available as a prime resource might allow extra people to be gained at preset points regardless of how many the character has, such as at the end of certain story missions. Fallout Shelter treats people partially as pass through resource, but it is a good example of more complicated resource management (in it's handling of people, not so much the power/food/water)\[/edit\]

Pass through is hard to balance because there are no natural controls and thus balance issues develop because of the commonly used increase in scale. At level one peple are dealing with 100s, while at level 10 they are dealling with thousands, and at level 20 they are dealing with millions.

Many games use this increasing scale, but it eventually leads to one of two outcomes, either the game "breaks" because player with millions vs player with 100s is no contest, or it becomes a strategy match amongst those at max level, while all those lesser find it next to impossible to get to max level if they are not on board at the start of the game or server.

Instead, I suggest forgoing the increasing scale and focus on new resource types with new tiers of play and low overall increase in power, instead giving more established players more options, and playing to economy management. Thus a max level mine might only produce two to four times the resources of a level one mine, but having more mines takes away from the space that might otherwise go towards factories. \[edit\]In other words, grow more in versatility than in power. Gaining new defense or attack types that overcome other attack or defense types. Guns are good compared to swords, not so much because of how much damage they deal, but because they can't be dodged, they pierce extremely well, and they redifine rapid fire. A sword will deal more damage than any bullet, well anything less than a fifty cal.\[/edit\]

As a player advances, they can start drilling for oil, which can be used for fuel, which allows for a new set of vehicles, which are better in some ways, but not in others, for example tanks might be more powerful, but horses can travel through terrain that tanks can't, ensuring that strategy of the player allows even low level players to not be automatically stomped by high level ones.

High level smelters might refine metal ore into not just iron, but also aluminium, which allows the construction of aircraft, changing the dynamic of strategy.
> 1 votes

---
Tags: balance, economy
---


# Question
Title: Rotating a 4D matrix about the Y axis with an X-Z vector
I should mention that I'm pretty new to Matrices and will probably need a layman's answer to my question.

I have a 4D matrix which represents the rotation of an object in 3D space. I have a normalized 2D vector which represents the direction i want the object to be facing by rotating the Y axis.

I need to be able to change the Y axis rotation of the object only, by applying some sort of calculation to the XZ vector i have. What do i need to do to make this work? And if possible, can any answers come with an explanation of the process so that i can do it again on my own in the future!

# Answer
I depends on the format of your 4d matrix. I'm guessing the orientation is in there somewhere. This is a way to recreate a matrix given a z & y

pseudocode...

```
 Vector2d my2d; // assuming this is your 2d vector with x,z components.

 Vector3 z = new Vector3( my2d.x, 0, my2d.z);   // looking dir
 Vector3 y = new Vector3( 0,1,0);               // we'll make an upward y dir
 Vector3 x = y.cross(z);                        // y cross z gives us perpendicular to y&z

```

You then need to insert the xyz vectors into your matrix. I'm not sure of your matrix format but i guess they will be described as rows or columns depending if it is left/right handed coords.

The order of the cross product depends on left or right handed also. If you find that its not working try

`x = z.cross(y);`
> 1 votes

---
Tags: matrix, vector
---


# Question
Title: How to determine vertex index using Shader Model 3 or lower?
I need something like SV\_VertexId (added in Shader Model 4) in HLSL shader to determine which vertex is currently handled. Unfortunatelly, I can compile only vs\_3\_0 or lower.

The objective is to change position of one specific vertex using HLSL. I can't edit the mesh and can't pass any data from game engine, my capabilities are limited by HLSL shader.

Shader is writing only for one mesh (humain face), I need to change it's shape a bit (for example, close an eye or make it smiling). I already tried to locate vertex by TEXCOORD, but had no idea how to separate it from other triangles verticles connected to it (placed at the same point where many triangles are met).

```
if ( VS.TC[0] > 0.8828125 && VS.TC[1] > 0.6328125  && VS.TC[1] < 0.671875 ) {
    // Upper lip center
    VS.Position += VS.Normal * uUpLip;
}

```

Could you, please, give me any advice how to identify / move only one specific verticle in HLSL? I need something like moving verticle in Blender's Edit Mode (wytn neighbour triangles are still connected in one point), but my attempt with TEXTCOORD makes them moving in different directions

Thanks

# Answer
> 2 votes
You can easily add custom fields to your vertex data, one of which could be a vertex ID. You could also place those IDs in a separate vertex stream so you can use them with any mesh.

The standard way to animate a face (or any other 3D model) would be to use some sort of skeletal animation (also called skinning) which generally means that each vertex stores the index of one or more bones, along with some weights.

There are also other techniques like morphing available.

Note that without a geometry shader you can only move existing vertices. You can't change the way the vertices are connected to each other.

---
Tags: shaders, hlsl, 3d-meshes, vertex, shadermodel3
---


title: Bounding Volumes for Empty Space

text:
# Question
Title: Bounding Volumes for Empty Space
I'm creating an Android game that relies heavily on collision detection for a couple of players (at least up to 4). I researched hierarchical structures that could speed up the process. Because I have worked with hierarchies of axis aligned bounding boxes for ray tracing in uni, the sweep and prune algorithm is currently my favorite choice.

However, I had the idea to use bounding boxes not only for the obstacles in a level, but also some boxes containing as much of the free space in the scene as possible. If the player's character stays within one of those during his movement between two frames no further intersection tests should be necessary. Could this approach reduce the number of intersection checks where a player's character intersects one or more axis aligned boxes but not the objects within?

I highly doubt I am the first person who thought of this, yet I didn't find something like it online. So, is there a good reason not to do this? My best guess for why it isn't done is that there is no good rule to find applicable bounding boxes for empty spaces in between. But if they are precomputed before the game I don't see this as a problem. Maybe they could be bounding spheres instead. Those could be grown from an obstacle's surface until it touches obstacles in at least three points, like so:

Any advice would be greatly appreciated

# Answer
You're talking about *broad-phase collision detection*—a system that lets you return early when clearly no collision is happening. I've previously written this overview of collision optimisation.

Such systems typically use a spatial indexing scheme. Popular choices in games include grid-based spatial hashing, quadtrees and k-d-trees. All make different efficiency tradeoffs, so the right choice depends on your needs.

For example, here is an illustration of *N*'s grid-based partitioning, as detailed in Metanet Software's excellent tutorial:

<sup>ⓒ Metanet software (source page)</sup>

All moveable and immoveable objects in their system occupy a square tile. Only objects contained within the same square tile need to be checked for collision. They also describe the tradeoffs of their approach in section 3.

---

I'd recommend against your particular idea, unless circle-shaped empty spaces are of special importance in your game. I don't know of (and can't imagine) a useful spatial indexing scheme based on circles that could easily be partitioned recursively. Circles also tend to be expensive to compute with, as related equations involve trig and square roots.
> 3 votes

---
Tags: collision-detection, bounding-boxes, bounding-spheres
---


# Question
Title: Memory-Efficient, Optimized Terraria-Like 2D Lighting
I am working on a terraria-clone and I am aiming for it to be able to be run on most Android devices. I am able to generate a world, jump around, etc but I am not looking to add in some efficient lighting. In the past I have tried doing a tile-based lighting system but the project quickly came to an end after that because it dropped performance hugely. In that demo I was drawing a transparent black square over each tile and setting the alpha value dependent on surrounding lights. I envision that this will not be efficient on mobile so I don't even know if I want to go down that road. I don't need the shadows or anything like that (as of right now), I just need the lighting portion implemented. I have also looked at the other suggestions on the page here but am not sure which is the best option.

If tile-based lighting is the way to go I'd have to think of the best way to go about it. I don't think that it would be a problem to just have it work with a torch giving off light and only updating light values when a light source is added/removed, but when entities are incorporated I also have to think about how will I efficiently update an entities light value based off of surround light values. I have optimized the game a lot so far, with a world of 1,620,000 tiles being contained within it and getting a stable, smooth 30 fps even on mobile. I haven't attempted creating larger worlds than that but I don't see why, at this rate, it wouldn't be able to become any larger. I am trying to keep it as optimized as possible throughout development of the entire game so coming up with an efficient, optimized lighting system is essential.

Any suggestions are greatly appreciated.

# Answer
> 5 votes
One option would be to load lighting information only as it appears on the screen. You would get one performance hit at the beginning as the full screen lighting is calculated, but from there you could cache the information and (as you mentioned) update it only when a light is flagged as modified. As you move across the world, you could calculate a short distance ahead so the player doesn't run into a dark area when it should be broad daylight.

For tile shading, I would recommend tinting/multiplying the tile color by the lighting percentage as this doesn't require adding an additional draw call for a shading square.

Terraria now has a mini-map feature that gradually fills out as you visit areas, and I suspect you could save your lighting information in a similar way.

Two other options, which could be overlapped with my suggestion above, include multithreading or offloading the lighting computations to the GPU. If these features are supported on Android, which I would certainly assume to be true.

---
Tags: 2d, tiles, lighting, optimization, memory-efficiency
---


# Question
Title: Tournament ranking for card game bot fights - how to try new bot against existing ranking?
Let's say we run a tournament for 10 bots playing 1-1 fights in card game with significant randomness influence. To measure bot skills level we run round-robin with 10k matches per each pair. Ranking shows that bots #3, #4 and #5 have very similar result.

Some time later 11th bot is developed. **What is the best strategy to rank it honestly?**

* Re-run whole tournament? Bots with similar results can come out on different positions.
* Run all ranked bots against new one? Again, those results could re-rank previous positions, if taken into account.
* something different?

CPU time is not limited and tournaments are run offline.

# Answer
This sounds a lot like a problem in Genetic Algorithm with AI Natural Selection.

But if this game is a tournamen, it depends on how you approach it.

For example. If you do the tree tourney style, where you climb up a tree to the very top, obviously you are going to have problems.

However, if you run it through an array set up where everyone fights everyone. You can get better results. Think of Yugi-Oh and Magic tournaments.

The number of times the fights have been made can also have a drastic effect on results. Best of three, best of four, best of five, etc.

Then... if lower level placing actually matters. You can have them dual one another for their places.
> 1 votes

# Answer
If rank is a normalized score, you can run all ranked bots angainst the new one. If not you have to ask why the score was not normalized and then re run the tournment.
> 0 votes

---
Tags: card-game, ranking, bot, tournament
---


# Question
Title: Pixel thin lines appearing between sprites on camera move
I'm going to apologize in advance for the lack of screenshots, but this was a very hard thing to capture, but very obvious to see.

I'm using LibGDX to create a tile base rogue-like. Everything is going alone smoothly and working well, but there is one graphical glitch that is very bothersome. I have the camera LERPing towards the player, but this smooth movement causes very small gaps to appear for about a frame between the floor tiles that's quite distracting.

The tile rendering code looks something like this:

```
for(int y = 0, i = 0; y < mHeight; y++) {
    for(int x = 0; x < mWidth; x++, i++) {
        batch.draw(mTiles[i].textureRegion, x * TILE_SIZE, y * TILE_SIZE);
    }
}

```

Where `mTiles` is a 1D array representing the 2D dungeon, `batch` is the main SpriteBatch used for rendering, and `textureRegion` is the TextureRegion of the tile.

The camera code looks like this:

```
pos = mEntity.getPosition();
mCam.position.x = MathUtils.lerp(mCam.position.x, pos.x * TILE_SIZE, delta);
mCam.position.y = MathUtils.lerp(mCam.position.y, pos.y * TILE_SIZE, delta);

```

The problem is solves if I cast the result of the LERP to an int, forcing the camera to line up with the tiles, but it's not ideal. I also tried creating a new texture of the entire dungeon floor from the texture regions that make it up, but there doesn't seem to be any elegant way to do this.

Anyone else face a similar situation? I'll try and capture some screenshots and post them later.

# Answer
So many of the responses given by Fuzzy Logic boiled down to either adding padding around the textures, or rounding the camera values to whole numbers. Due to the pixel art style of my game, rounding the values worked the best. Here's the updated camera code:

```
GridPoint2 pos = mEntity.getPosition();
mCam.position.x += (int) ((pos.x * TILE_SIZE - mCam.position.x) / 2 + TILE_SIZE / 2) / 8;
mCam.position.y += (int) ((pos.y * TILE_SIZE - mCam.position.y) / 2 + TILE_SIZE / 2) / 8;

```

This also has the side effect of there being a buffer region where the player can move but the camera does not. Personally I like this, but I'm sure there's a way to avoid it if you don't.
> 2 votes

---
Tags: java, libgdx, rendering, tilemap, roguelikes
---