title: Levels Map terminology

text:
# Question
Title: Levels Map terminology
I wonder if this thing exists and how is it called?

What I mean is not "level editor", but a kind of cover map, where you select, which level you want to play and your character symbol moves to the place accordingly. An example of such a map is here:

or this one:

Here all you have is a basis image, levels, represented by some image or animation, a character, that is being moved from one position to another and so on.

I'd like to know how this concept is called? I google all the things that pop up into my mind, but none of them is correct.

# Answer
> 2 votes
This concept is usually referred to as an "overworld". Bear in mind that the term "overworld", as DMGregory mentioned, could refer to two concepts.

The screenshots you show fall in the category **overworld menu**. In this category, there's pretty much just a background with multiple icons you can click, resembling levels.

A concept that can easily be confused with this is the **overworld map**, which consists of a map the player can actually walk around on, like in older JRPGs. Take for instance Final Fantasy IV:  In this concept, players walk across a map, and come across cities, dungeons, etc. When entering such a point of interest, the city map or dungeon map loads, creating the feeling of seamless gameplay (while there is obviously a seam).

I just want to mention that these two concepts are not exactly black and white. There have been games in the past that show it's perfectly possible to meet in the middle. Take a look at mario 3:

---
Tags: maps, levels, terminology
---


title: Making a Fall Trigger Game Over

text:
# Question
Title: Making a Fall Trigger Game Over
I have been struggling with this fairly basic issue: To make a game over menu appear upon death.

I am making a 3D game in Unity, where you, the player, must control a sphere with the basic controls: `W`, `A`, `S`, `D` and , , , . It is a game where you must "drive" the ball and pass a broad variety of obstacles, where you must lead the ball to fall into a confined box where, if within it, you ultimately win the game.

I have already implemented the Main Menu, Pause Menu and the fundamental gameplay components. I just need to figure out how to make it so the player can actually lose the game. The most important aspect of a game.

I have not a clue on how I can make this.

The player is on a platform, as are the obstacles etc. I have made in my game 2 bridges you must cross over, on which below it is nothing. So, if you slide off a bridge, you will basically die, as there is nowhere else to go upon falling. I want to make it so that when you fall from the actual platform, or the map, falling into the "abyss", you will die, on which I would like a game over screen to appear, there being a play again button, and a button that will quit the game.

I basically have no clue how to make any of this a reality. If possible, I would be delighted if anyone could develop a script for this. Java Script or C#, doesn't matter. If you can assist me in anyway, please do.

# Answer
According to your comments you want to detect when the player-character leaves the playing area and do something.

This is easily done by creating a new game object with a large `BoxCollider` representing the play-area. Set the "Is Trigger" to on, so it doesn't have any physical interaction and instead is completely scripted.

Then attach a new script to that game object and implement the OnTriggerExit function. This function will be called whenever an object leaves the `BoxCollider` attached to this game object. Remember that this applies to *all* game objects which have `Collider`s, not just to the player, so have your implementation check if it's actually the player before showing the game over screen.

Alternative solution: Instead of just one "life" box collider which kills the player when they leave, you can also have one or more "death" box colliders which kills the player when they enter. You can do that by implementing `OnTriggerEnter` instead. But when you place such a collider below your play area, make sure it is large enough that the players can't miss it. Keep in mind that games with rigid-body physics can become quite unpredictable and might launch objects out of the playing area with very high speeds.
> 2 votes

---
Tags: unity, c#, javascript, gui
---


# Question
Title: Check if a vector element exists using std::find?
I need to know how to check if a element (object) inside a vector exists.

I've heard of std::find but the I don't understand how to use it (even though I've read multiple answered questions here, and on other forums).

```
find(_InIt _First, _InIt _Last, const _Ty& _Val)

```
* What are all the parameters?
* What does the function return?

I couldn't find any good posts that explain this (or at least, didn't explain it good enough for me to understand).

---

Example : (this is the return type)

> An iterator to the first element in the range that compares equal to val. If no elements match, the function returns last.

(taken from std::find documentation) This makes no sense at all to me.

---

Examaple of how I would like to use it :

```
if (texts[index]) == does exist)
    do something
else
    do something else

```

---

This is how I'm currently using it, which is wrong.

```
std::vector<Text*>::iterator result;
result = find(texts.begin(), texts.end(), texts.begin() + index);

if (result != texts.end())
    std::cout << "Element removed" << std::endl;
else
    std::cout << "Element not found in texts, won't remove." << std::endl;

```

It gives me this error : (just parts of it, scroll down if you need the entire error...)

```
error C2679: binary '==': no operator found which takes a right-hand operand of type 'const std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Text *>>>' (or there is no acceptable conversion)

```

Full error :

```
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\system_error(379): note: could be 'bool std::operator ==(const std::error_condition &,const std::error_condition &) noexcept'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\system_error(371): note: or       'bool std::operator ==(const std::error_condition &,const std::error_code &) noexcept'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\system_error(363): note: or       'bool std::operator ==(const std::error_code &,const std::error_condition &) noexcept'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\system_error(355): note: or       'bool std::operator ==(const std::error_code &,const std::error_code &) noexcept'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\exception(341): note: or       'bool std::operator ==(const std::exception_ptr &,std::nullptr_t) throw()'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\exception(336): note: or       'bool std::operator ==(std::nullptr_t,const std::exception_ptr &) throw()'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\exception(331): note: or       'bool std::operator ==(const std::exception_ptr &,const std::exception_ptr &) throw()'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility(3134): note: while trying to match the argument list '(Text *, const std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Text *>>>)'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility(3153): note: see reference to function template instantiation '_InIt std::_Find<_InIt,_Ty>(_InIt,_InIt,const _Ty &,std::false_type)' being compiled
1>          with
1>          [
1>              _InIt=Text **,
1>              _Ty=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Text *>>>
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility(3162): note: see reference to function template instantiation '_InIt std::_Find<Text**,_Ty>(_InIt,_InIt,const _Ty &)' being compiled
1>          with
1>          [
1>              _InIt=Text **,
1>              _Ty=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Text *>>>
1>          ]
1>  c:\users\myname\desktop\c++ projects\sfml_game\sfml_game\main.cpp(93): note: see reference to function template instantiation '_InIt std::find<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Text *>>>,std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Text *>>>>(_InIt,_InIt,const _Ty &)' being compiled
1>          with
1>          [
1>              _InIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Text *>>>,
1>              _Ty=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Text *>>>
1>          ]

```

---

**Edit**, updated my code, now looks like this but when I run it, it prints "Could not remove element, it does not exist!".

```
void RemoveText(unsigned int index)
{
    std::vector<Text*>::iterator result;
    result = find(texts.begin(), texts.end(), texts[index]);

    if (result >= texts.end())
        texts.erase(texts.begin() + index);
    else
        std::cout << "Could not remove element, it does not exist!" << std::endl;

}

```

# Answer
> 1 votes
# This should work

```
std::vector<Text*>::iterator result;
result = find(texts.begin(), texts.end(), thing_I_want);

```

## Explanation of iterators

`texts.begin()` returns an *iterator* which points to the first element in text. Iterators have a special property, that adding a number to them will increment the index they reference.

More clearly, `*(texts.begin())` is the first element of texts. `*(texts.begin() +1`) is the second element of texts. `*(texts.end())` is the last element of texts.

## Explanation of std::find

```
result = std::find(

arg1 // iterator pointing to where we should start searching

arg2 // Iterator pointing to where we should stop searching

arg3 // Thing to search for in container

)

```

It will return another iterator, this one pointing to the element that matched. If you'd like to recover the index, you can do either

```
int index = std::distance(Texts.begin(), result)

```

Or

```
int index = result - Texts.begin()

```

## What went wrong

When you did `index + texts.begin()`, the result of the addition was an iterator, for which there isn't a comparison operation to your text type. That makes sense, because the third argument to `std::find` is what we're looking for, so we (in the worst case) need to compare that to all of the elements in the range we're searching. If we don't have a defined comparison between the thing we're searching for, and the elements of our vector, then there must be no way we can search for it.

---
Tags: c++
---


# Question
Title: How to design a server for a multiplayer game?
I'm trying to write a multiplayer game where players join small matches with other players. What I also want is a way for players to login and go online. How would I design the a server that could handle logging in, matchmaking and the actual running of the match? I'd like to have multiple threads on the server to handle input from all the players, but I'm not exactly sure what I want to put in a single process and what I want to split apart. How would I set up the sockets for something like this?

I'd probably end up having this run on Amazon EC2 or something similar if that makes a difference.

I was planning on making the game a MOBA where there would be a small number of players (6-10) and latency would be relevant.

# Answer
> 6 votes
Depending on what language you are using, the answer can vary.

However, if you know any Java, or can at least get the gist of it, here's some old code I wrote to handle something like this.

https://github.com/TheDudeFromCI/WraithEngine/tree/5397e2cfd75c257e4d96d0fd6414e302ab22a69c/WraithEngine/src/wraith/library/Multiplayer

Basically it works like this. First, on your server, wherever it's being hosted, you have it open a socket on a port you choose. This should go on a dedicated thread, and handle ONLY this task. This should always be open, and listening for anyone trying to connect. When someone finally does connect, create a new dedicated thread, with a socket connecting to that client. When that client loses connection, (logs off, or force quits) kill the thread.

For the client, it's even simpler. Just have 1 thread, and have it try to connect to the server ip, (if you have only one server, hard code it in. If multiple, then you can have the player type it in.) And use the same port as you chose for the server. If a socket is able to be opened, connect, and that thread will be dedicated with chatting with the server. If you want to avoid delays in gameplay, this should not be your main thread, but in addition to. Then when a message is sent or received, pass it asynchronously to the main thread. To avoid stalling, make sure the main thread is never "waiting" on the server thread. (A waiting screen is fine for times where waiting is needed, because it doesn't cancel rendering events, or input events. So the program won't be marked as unresponsive.)

Now you should be able to handle an infinite number of new clients trying to connect.

Now, each thread is a seperate client. So keep these all in a list. Most likely in some kind of thread wrapper to handle easier packet sending and receiving. If you want some security, use a handshake packet. This means that the server "asks a question" sort of speak, and if the client doesn't answer, or answers incorrectly, it kicks them. Also, banned ips should be kicked before even the handshake.

Now, in your list of clients, wait for a match request to be called, however you want to do that, then take those clients that request it to be moved into a queue. Once you have enough players, start a match with that list of clients. When a packet is received, send it back to all other players in the list. For example, a player moves, a packet is sent, the server receives it, and sends it to all other players in the list, the render the move, and poof. If that's not fast enough, you can have players actually act like mini servers, and connect to each other fully. This will make pings twice as fast, but may be harder to detect hacking. So be careful.

Once the match is over, send a packet to the clients saying the match has ended, and make their clients render a game over screen when that packet is received.

I hope all of that makes sense.

# Answer
> 1 votes
Assuming you want to design the server in Java, I would like to add in few more points or suggestions using one of my old answer.

Firstly you will require to learn `Java Sockets`. It is through which you can connect various clients to the server and exchange data. Once you are done learning the basics of Java Sockets, then you can go on and use a library like `Kryonet` or `Netty`.

**Kryonet** allows you to send data using Serialization which it achieves by Kryo serializer. Let's say if you are making bomberman and you want to send x, y location of your player to the server. You can create a class called `Position` with x, y variables and send an object of the class to the server. When `Server` receives the object you can then send it to other Clients connected on your game Server. You can store connected clients into a static List or some other data structure. I use HashMaps.

Now let's say you do some other action like shooting or anything you will create an object of the relevant class and send it to the Server. Then you can code your server on how to process these class objects.

Also let's say 100 clients are connected to your game server. You don't want to process events from every client on a new Thread. This won't scale well. You will also have to learn about Blocking and Non Blocking IO where you will understand how to handle so many clients at the same time. (Kryonet does that using Non Blocking IO)

You will also have to decide what kind of protocols you are going to use like TCP or UDP etc. It is a vast topic but for starters I would say that you should start simply by first Learning Java Sockets and creating a basic Chat Server and Chat clients and then proceed from there on. Firstly build it using Blocking IO and then using Non Blocking IO.

As far as **Netty** is concerned it is very vast and has a steep learning curve so you can ignore it for now.

**Multiplayer games are not easy and there is a steep learning curve**

You can read articles on this website for more information. Gaffer on Games

Here is a tutorial on Blocking vs Non Blocking IO

Here is a tutorial on Java Networking

Tutorial on Kryonet

---
Tags: networking, server, client-server
---


title: Show 3D elements on 2D background

text:
# Question
Title: Show 3D elements on 2D background
I'll make a navigation menu in my game and had the good idee to this the enemies to start games or go to the gun store. The problem is when I look in game mode, the enemy named `ZomBear` in hierarchy and gun are away.

The `ZomBear` and the gun are 3D elements that I will show on a canvas named `StartScreen` in hierarchy. How Can I do that?

<sup>(Click on image to see full size)</sup>

Notes by the hierarchy:

* Everything that begin whit `Btn` are button elements.
* `StartScreen`, `PlayButtons` and `LevelButtons` is a panel
* `Gun` and `ZomBear` are 3D elements form the `Prefab` folder.

Here you have also a screen from aside:

# Answer
> 1 votes
You should be able to modify the setting on your canvas to a more desirable render mode. The canvas provides three options: screen space overlay, screen space camera and world space.

From what I understand, you would want to use world space, as it allows you to place a canvas freely in the world without it automatically obscuring the rest of the scene.

# Answer
> 1 votes
In most cases 3D elements are always behind the UI elements. If you want to do so, then you have to place your background on `Quad` rather then any GUI element.

* Place a unit size `Quad`.
* Drop your image on that `Quad`.
* Resize `Quad` according to screen size.

//\*****OR\*****//
* Simply place a sprite in screen.

With either of these two techniques you will achieve your goal.

# Answer
> 1 votes
I would add an additional `Camera` to handle the UI 3D elements. Create a new layer (UI3D!?) and make sure your 3d ui elements uses that. Finally set the Camera to render only the new layer using the culling mask.

> Using the camera’s culling mask, you can selectively render objects which are in one particular layer. To do this, select the camera that should selectively render objects.

http://docs.unity3d.com/Manual/Layers.html

---
Tags: unity, 2d, 3d, game-design
---


title: Fixing the size?

text:
# Question
Title: Fixing the size?
My app isn't compatible with all screen sizes. When testing on a small size, my textview overlaps with my button. So, as suggested on the Android Documentation, and **many** stack overflow pages, I created a new `Android Resource Directory`:

In my `layout-small,` I copy and pasted one of the xml layouts of a layout that was overlapping in small screen size. So now, it looks like this:

My layout, `activity_finished_before_timer.xml`, was just copied from the regular layout to the small layout. Now, in my manifest, I specified the following. I don't know if this is necessary, but after spending hours online searching for the answer, I added it just in case:

```
<supports-screens
        android:smallScreens="true"
        android:normalScreens="true"
        android:largeScreens="true"
        android:xlargeScreens="true"
        android:anyDensity="true" />

```

After doing **everything** I could find for **hours and hours,** the layout is still overlapping. By overlapping, I mean that my textview is under my button on a small screen. It looks fine on a regular screen though.

**I have got some advice** to do something where I create a layout resource file, but instead of titling the resource file as `layout-small`, I should title it with the dp size at which my app stops working:

`layout-swp365dp`

This would mean (**In coding terms:**)

```
if (screen size > 365dp) use default;
else use default-adjusted.

```

Now, how do I get the screen size then? On my emulator, the size is given like this:

How do I get the size in `dp` then? For this method, I would just need to hit and try different screen sizes until I find the one that doesn't work. How do I do that? Is there an easier way?

**So, now I am lost** I would really appreciate **any** feedback on how to resolve this issue of why the layout is **still** being overlapped. It is very odd, since I have done everything I needed to according to all of the sources I looked at. Please help me in figuring out how to make my layout flexible enough for multiple screen sizes. Although I am frustrated at this issue, I am more eager to learn out of it, as it is my first android game.

# Answer
> -1 votes
The smart thing to do would be to create a method, like getScreenRes to get the screen resolution in pixels.

```
private static int WIDTH = 1280;
private static int HEIGHT = 720;

public static void createDisplay() {

    try {
    Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT)); //Use your code, but change these variables!
    Display.create(new PixelFormat(), attribs);
    Display.setTitle("Aincrad Online ALPHAV.4.1");
    } catch(LWJGLException e) {
        e.printStackTrace();
    }

}

```

Use the method you created to get the screen resolution to change the WIDTH and HEIGHT variables in the code. Of course, you should translate all the code to the language you are using

---
Tags: java, 2d, android, graphics
---


# Question
Title: Which Sprite would be rendered out of two overlapping sprites in a 2d world?
For example, in a 2d setting, I have two sprites(one of green color and other of blue) of same size and y-axis and are at some distance apart from each other in x-axis. If there distance is gradually decreased and they overlap, will I see the blue sprite or green?

# Answer
This depends on the details of your rendering setup, but here are the most common out-of-the-box behaviours:

## 1. Painter's Algorithm

Many 2D frameworks simply layer sprites in the order they are drawn (so you need to draw your background before your foreground). In this case, whichever sprite occurs later in your drawing (ie. drawn from a later command, or from a later index in a batch) will overlap the earlier one.

If you're triggering your drawing through code, you can usually explicitly sequence your drawing calls to get the result you want. A graphical editor like Unity or Flash will usually have some concept of "layers" or ordering within layers, which allows you to control the drawing order. Other tools might have no explicit ordering control, so the drawing order is decided arbitrarily by the engine and might change at runtime.

## 2. Alpha Test With Depth Buffer

In frameworks with 3D capabilities, 2D sprites are sometimes drawn using a technique called Alpha Testing. In this case, any pixel with alpha below some threshold (often 50%) is skipped, while the rest are drawn fully-opaque in the frame buffer *and their depth is recorded in the depth buffer*.

This depth information can change what happens with subsequent sprites:

* If the depth test is set to `less-than-or-equal`, the results for sprites at the same depth will be the same as the painter's algorithm - the latter sprite will draw over the earlier one.
* If the depth test is set to `strictly-less`, then when the second sprite tries to draw, it will find another sprite already present at the intended depth, and those pixels will be skipped. This gives the opposite outcome to the painter's algorithm: the *first sprite will overlap later sprites* at the same depth. (or potentially z-fight with them, depending on your camera & bias settings)

## 3. y-Sorted

Some frameworks & scripts for developing 2D games will automatically sort sprites by their y-coordinate, on the assumption that you're using an oblique or isometric map, where sprites at the top of the screen represent more distant objects, and those at the bottom of the screen represent closer objects.

(Example from this devblog on sprite sorting, although this case also includes a layer system)

It looks like this might be what's happening in the animated gif Jon has linked in the comments above. In this case, which sprite ends up on top depends on the particulars of the sorting algorithm used, and whether the two sprites are truly at exactly the same y-coordinate, not differing by a tiny fraction through rounding errors.

---

Of course, the fastest way to figure out what happens in your framework/engine of choice is to try it!
> 3 votes

---
Tags: textures, sprites
---


title: scaling problem with some resolutions

text:
# Question
Title: scaling problem with some resolutions
So I made a scaling system for different resolutions, and I got very weird results.

I have an old "scaling" system where you can choose which `scaleSize` you want (for testing with the old 800 x 450 resolution) and you can choose between 1 and 2. I made a new scaling system after this that makes a scale with a matrix.

(old scaling system with `scaleSize` is just for making the textures/collision boxes bigger/smaller, not resolution dependent)

```
int currentWidth;
int currentHeight;
int preferredWidth;
int preferredHeight;
float scaleWidth;
float scaleHeight;

public Matrix scale;
GameWindow Window;
ContentManager Content;
GraphicsDeviceManager Graphics;
GraphicsDevice GraphicsDevice;

public ScreenSize(GraphicsDevice graphicsDevice, GraphicsDeviceManager graphics, ContentManager content, GameWindow window)
{
    Window = window;
    Content = content;
    Graphics = graphics;
    GraphicsDevice = graphicsDevice;
    LoadContent();
}

public void LoadContent()
{
    Graphics.PreferredBackBufferWidth = 1920;
    Graphics.PreferredBackBufferHeight = 1080;

    currentWidth = GraphicsDevice.Viewport.Width;
    currentHeight = GraphicsDevice.Viewport.Height;

    preferredWidth = 800;
    preferredHeight = 450;

    scaleWidth = currentWidth / preferredWidth;
    scaleHeight = currentHeight / preferredHeight;

    scale = Matrix.CreateScale(scaleWidth, scaleHeight, 1.0f);

    this.Graphics.IsFullScreen = false;

    Graphics.ApplyChanges();
}

```

I add the `scale` to my `spriteBatch.Begin()` and the textures are scaled. It works fine when the `scaleSize` is 2 but not when the `scaleSize` is 1.

The `ScaleSize` scales the collision box and the textures (not with the resolution, but just when you need (for example) a texture that's 2x bigger, then you use the `scaleSize` of 2. See an example below.

```
public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch, Color color, float scaleSize)
{
    spriteBatch.Draw(textureImage, position, new Rectangle(
    (currentFrame.X * frameSize.X),
    (currentFrame.Y * frameSize.Y),
    frameSize.X, frameSize.Y),
    color, 0, Vector2.Zero, scaleSize, SpriteEffects.None, depth);
}

```

But the problem is that, when I use the scaleSize of 1, then the pixels in-game are not the same size (for resolutions that are not the default resolution (800 x 450)). But they are when `scaleSize` is 2. In my first code block I use the resolution 1920 x 1080. When the `scaleSize` is **2**, then it looks **good**. When the `scaleSize` is **1**, then it looks **bad** (**in fullscreen it looks good** for some reason).

example: (left is good, right is wrong)

I ask this question because I want the textures in-game smaller. (`scaleSize` = 1)

**EDIT**: scaleSize 2 doesn't look good on some resolutions (like 1440 x 900). Do I need another `preferredWidth` and `preferredHeight`?

example:

**summary**: Everything looks/works fine with `scaleSize` 2, but doesn't with 1. -\> edit: scaling doesn't work well.

# Answer
> 0 votes
The effect you encounter is probably due to rounding errors in the scaling. Note that the rectangle is all integers while the vectors and matrices are in floats.

Instead of scaling each Draw call, you can provide a transformation matrix in the Spritebatch.Begin() (see MSDN spritebatch).

Like so:

```
float _scaleSize = 0.5f; //scale to half size.
Matrix _scaleMatrix = Matrix.CreateScale(
               _scaleSize,
               _scaleSize,
                       1f);

spriteBatch.Begin(SpriteSortMode.Immediate,
                  BlendState.AlphaBlend,
                  null,
                  null,
                  null,
                  null,
                  _scaleMatrix);

```

From that point the sprites drawn in the batch will use the scale matrix (so for both positions and size parameters).

Now you have two dimensions; the "real" screen and your "virtual screen". Suppose the user has a screen of 1920x1080 (backbuffersize) while your game is made for 1280x768 (virtualsize).

So you can calculate the scale factor using these resolution to upscale your game graphics. However the aspect ratios are different so you may need to adjust your viewport so it centers (pillarbox or letterbox). To achieve this you need to adjust your viewport.

You can control the viewport (basically where the 0,0 coordinate is and the width and height of the drawable area) using GraphicsDevice.Viewport. This code puts the drawable screen in the center of the screen:

```
        Viewport viewport = new Viewport();

        viewport.X = (GraphicsDevice.PreferredBackBufferWidth / 2) - (virtualwidth / 2);
        viewport.Y = (GraphicsDevice.PreferredBackBufferHeight / 2) - (virtualheight / 2);
        viewport.Width = width;
        viewport.Height = height;
        viewport.MinDepth = 0;
        viewport.MaxDepth = 1;

        GraphicsDevice.Viewport = viewport;

```

You could start each draw call by clearing the screen black for borders, set the virtual viewport and start drawing using the matrix in your spriteBatch.Begin() for a resolution independant game. All scaling is done using the matrix so no code should concern what resolution the client is viewing.

Bonus, if you need the mousepointer, use the inverted scale matrix like so:

```
Matrix invertScaleMatrix = Matrix.Invert(_scaleMatrix);
Vector2 mouseposition = Vector2.Transform(screenposition, invertScaleMatrix);

```

Another thing I've noticed when for example drawing a tilemap is that sometimes scaled sprites rendered have a rounding error on the edges of each tile. To fix this set the samplerstate to `SamplerState.PointClamp` in the `spriteBatch.Begin();` statement.

For a complete sample with code, *David Amador* wrote code that employs these concepts here: XNA 2D independent resolution rendering

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


title: Shader change alpha depending on light

text:
# Question
Title: Shader change alpha depending on light
I use Unity, and I need a shader a bit special. Unfortunatly my skills about shaders are very limited and I need this shader quickly.

So I want a shader to display a unlit texture on a plane, and when a light affect the plane, instead of make the lighting on the plane, I want that the light change the alpha to make the "lighted" surface transparent.

I think that it's not very hard for someone who know how to make shaders, so if you can help me to do this, it can be very useful for me!

---

Edit:

Ok, maybe it's not very clear.

I speak about a light, but it's not necessary a light, it can be with an other type of object, or just a position.

What I want is to have an unlit image, with a movable circle zone on this texture which make the zone transparent, like the white circle on this picture (imagine that the with is just the transparency).

The border shouldn't be necessarily with smooth border, it will be also fine with an hard border.

I have thought about a spotlight, because it's like move a spotlight on the picture, but instead of doing the lighting, I want to set the "lighted" pixel transparent (but it's not lighted, it's just to explain what I want), a,d it's not necessary with a light

And yes, the unlit shader can't do this I think, I probably need a custom shader but I don't know how to this (I have thinked about take a basic lighting shader, and use the computed intensity of the light on the pixels to set the alpha instead of use it to set the intensity of the pixel, but I don't know exactly how to do this)

# Answer
> 3 votes
This looks like an XY problem.

What you've asked for is a material which changes opacity based on lighting. This is doable, but somewhat needlessly complex to get working well:

This hacked example is accomplished with this surface shader:

```
Shader "Custom/LightToAlpha" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
        _ALightThreshold("Light Threshold", float) = 0.0
        _ALightContrast("Light Contrast", float) = 1.0
    }
    SubShader {
        Tags { "RenderType"="Transparent" "Queue"="Transparent" }
        LOD 200

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

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

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        half _ALightThreshold;
        half _ALightContrast;

        void surf (Input IN, inout SurfaceOutputStandard o) {
            // Albedo comes from a texture tinted by color
            fixed4 c = (fixed4)1.0f;
            o.Albedo = c.rgb;
            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }

        void alphaLight(Input IN, SurfaceOutputStandard o, inout fixed4 color)
        {
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            color.a = 1.0f - saturate(c.a * saturate(dot(color.rgb, fixed3(1.0f, 1.0f, 1.0f) / 3.0f) - _ALightThreshold) * _ALightContrast);
            color.rgb = c.rgb;
        }

        ENDCG
    }
    FallBack "Diffuse"
}

```

But from your clarification, what it seems like you really want is to be able to make a movable circular hole in an image. This doesn't require all the complexities of lighting at all, and can be accomplished much more simply & robustly:

This shader exposes a vector parameter whose x, y, z correspond to the worldspace position of the hole, and whose w is the worldspace size of the hole. You can rig up a script to set these parameters from the transform of a hole object for ease of editing/animating.

```
Shader "Unlit/TextureHole"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _HolePos ("Hole Position & Size", vector) = (0, 0, 0, 1)

    }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent" }
        LOD 100

        Blend srcAlpha oneMinusSrcAlpha
        ZWrite Off
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
                float3 worldPos : TEXCOORD1;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float4 _HolePos;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.worldPos = mul(_Object2World, v.vertex).xyz;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = tex2D(_MainTex, i.uv);
                float3 offset = _HolePos.xyz - i.worldPos;
                float range = dot(offset, offset) / (_HolePos.w * _HolePos.w);
                range = 1.0f - saturate(range);
                range *= range * 5.0f; // this multiplier controls the sharpness of the fade around the hole.
                col.a *= saturate(1.0f - range);
                return col;
            }
            ENDCG
        }
    }
}

```

---
Tags: unity, shaders
---


title: Checkpoints in a racing game?

text:
# Question
Title: Checkpoints in a racing game?
The game would be a race from A to B through several checkpoints. I think there are two approaches for the concept of time.

1. The game starts with some time and player has to make it to the finish before it runs out. Extra time is granted at the checkpoints. Time left at the finish is counted as a score.
2. The time at the start is 00:00 and the stopwatch is halted at the finish. Player still has to go through checkpoints.

Opinions about these? I think the option 1 is more common but I find it frustrating for beginners.

# Answer
> 5 votes
The first option is more common because of racing games' origins in arcades, where you want play length to grow as a function of skill and credits. Since you're not trying to get quarters out of players (I assume), just recording times at each checkpoint is less frustrating for players, and gives the same numerical results.

# Answer
> 1 votes
For a particular game, option 1 might be best, for another game, option 2 might be best. I like option 1 in games because of the stress it gives me when I'm down to the wire wondering if I'm going to make it to the checkpoint in time and it adds to the exhilaration of the game when I do. I believe it adds value to the game. It's fun to get that rush of accomplishment and then have to suppress it because you are still racing and have to concentrate to not screw up the next segment. But, of course, it would not be appropriate for a real world sim games like PGR or Forza.

# Answer
> 1 votes
I'd say option 1 is actually far better for beginners.

With option 2, if you're supposed to finish in 2 minutes and you finish in 3:00 instead, you may not know where you did wrong.

With individual checkpoints the game tells you at which part of the course you're doing below average. That allows learning and improving play specifically in these parts, and encourages trying alternate approaches such as breaking before a hairpin.

With individual checkpoints you also only fail a little if you fail, say you miss the deadline by 2 seconds, or because of one avoidable crash. That way you improve on each try and as a gamer you notice visible progress as you manage to clear more and more checkpoints - getting from 3 out of 15 checkpoints to 4 out of 15 checkpoints is way more encouraging than driving 2 whole laps and improving your time from 3:00 to 2:55 if the target is 2:00.

Once the player manages to finish the course in reasonable time, i.e. clears all checkpoints, and the beginner has learned how to drive the course, then is the time to take actual time into account. At that point you'll start handing out more stars for better times, or have a best time that compares online with your friends.

---
Tags: game-design, timer, racing
---


title: How can I make a world?

text:
# Question
Title: How can I make a world?
I'm making a game, and have the screen done. but now, I want to make a world. But I don't know how to make the world larger than the screen. My screen is 800x600, I want the worldsize about 3x that.

# Answer
The question itself is a little vague, but it looks like what you're asking is "How do I create elements beyond the boundaries of my screen?"

A common way is to implement a camera system, and using the position of this camera to determine what is being rendered on screen and where it is located. In this system, all objects in-world are positioned using world coordinates (where the object is in world), and the camera is positioned using these same coordinates. Then during your rendering method, you determine which objects exist within view of your camera, and translate them to view coordinates (where the object exists on screen) to draw them.

Some psuedocode on draw:

```
for each object in allObjects
{
    if (camera.contains(object))
    {
        drawObject(object.x - camera.x, object.y - camera.y)
    }
}

```
> 3 votes

---
Tags: java
---


# Question
Title: How does a car earn nitrous in racing game?
Take the case of Need for Speed, why would a car earn nitrous gas by drifting or by flying in the air?

What's the rule of collecting nitrous in other racing game?

Is there a general formula within these?

Does it base on real vehicle engineering or aerodynamics?

# Answer
> 15 votes
The accumulation of nitrious oxide in games has no real life counterpart. In real cars a limited number of capsules filled with NO2 have to be filled at the start of the race. In that way it is similar to fuel which you can't 'earn' during a race (except for a pitstop ofcourse).

The reason this mechanic in games exist is to encourage risk-reward gameplay. It appeared in games as the Burnout series where driving in oncoming traffic, drifting etc. earned 'boost'. In the Need for Speed Undergound series boost was translated to NO2 (probably since it was featured in movies such as "The Fast and the Furious" so the general public were familiar with it).

It has since become a staple way of introducing the risk-reward challenge in arcade racers as it works really well (as a gameplay device).

# Answer
> 2 votes
Boost mechanics in games have no basis in real life.

You give out boost to:

* Help players further in the back to catch up faster, by giving them more boost.
* Encourage aggressive play (ramming, jumping), which to some people makes the game more fun.

Boost mechanics are for action racers, where all cars should constantly be on top of each other (sometimes literally), always pushing and shoving and occasionally wasting each other. The racing games which see themselves as more serious, where any form of contact can permanently damage your car and destroy any chance of winning a race, almost never use boost mechanics.

# Answer
> 0 votes
As others said, you can't just teleport additional "doses" of nitrous into a car that's earned it. But if you're looking for a realistic explanation, say you have enough "charges" in the car for the maximum number of times they can be awarded in every car at the beginning of the race, and the additional charges are simply locked until the car reaches a certain air time duration or something.

---
Tags: physics, game-design, racing
---


# Question
Title: What's the difference between UnityEngine.Random and System.Random?
What's the different between this

```
int randomNumber = UnityEngine.Random.Range(0, 10);

```

and this

```
// on top of the class
private System.Random _rnd = new System.Random();

// inside a methode of the same class
int randomNumber = _rnd.Next(0, 10);

```

I know `System.Random` must always be initialized on the top of your class what's by `UnityEngine.Random` is not needed. I know also that `System.Random` works with a intern "clock" and the "random" number is based on that.

My question is now are there some other difference between `UnityEngine.Random` and `System.Random` and witch code is better to use for an Unity project?

# Answer
Arguably the most important difference is that Unity's `Random.Range` is slightly easier to use, being static. The C# base class library `System.Random`, however, offers you more *control* and isolation.

It's possible they also use different under-the-hood implementations (although my guess would be that Unity's `Random` is just implemented in terms of the system `Random`), but that's probably not a notable concern. Fundamentally they're both likely the same *kind* of random number generator: a pseudo-random generator based on iterating a sequence defined by some seed).

The control issue is more relevant, because in some contexts you may want to use different random streams for different things. For example, in a lock-step networking networking context, you may want to fix the seed used to generate random gameplay-affecting events across all players in the game, but you may not care so much about the stream of random numbers used for purely visual events and can allow that stream to be seeded in a more traditional fashion (with the system uptime at game launch, for example).

Similarly, if you are going to be generating random numbers in multiple threads you may want to use distinct random objects for each thread in order to prevent race conditions. This may come up if your game logic runs across many threads and you also have a gameplay replay system, for example.

In the end, it's not necessarily *better* to use one or the other in general, rather there are pros and cons. When you need to isolate the sequence of numbers from other potential random sequences that may be happening, or when you need localized control over the seed of the sequence, use an instance of `System.Random`. If you just need a quick-and-dirty random value for a throw-away use or some other non-impactful scenario, Unity's simplified `Random` is probably fine.
> 24 votes

# Answer
UnityEngine.Random has a few ease of use advantages:

* Static/globally accessible — you don't need to create an instance for each object or system that needs randomness. Most or all of your scripts can share this resource.
* Convenience methods — you can use Random.Range(), Random.insideUnitSphere, Random.rotationUniform, Random.ColorHSV() to get nicely-distributed random values of various useful types without needing to roll your own math.

(I have not found any confirmation about whether UnityEngine.Random provides any cross-platform consistency guarantees different from the Mono implementation of System.Random - they might or might not be the same under the hood)

You can of course build your own class that uses System.Random (or another library, or your own PRNG) to do this, but the nice part is you don't need to — Unity's implementation is meant to give you a good baseline for random behaviour out of the box.

That said, there are cases where you'll want to use other sources of randomness:

* If you're using multiple threads, each thread should have its own source of pseudorandomness to avoid contention (UnityEngine.Random is only accessible on the main thread)
* If you need a deterministic pseudorandom sequence (eg. for a seeded level generator) you'll probably want that system to have its own source of pseudorandomness that no other script can access, so that differences in order of execution don't cause it to skip numbers and break the determinism you were counting on. For more info, there's a great post on the Unity blog about seeded random numbers.
* if you need cryptographically strong randomness for security, gambling, or generating unique IDs, you should use specialized libraries for this purpose. Neither UnityEngine.Random nor System.Random provide sufficient quality guarantees.
> 11 votes

# Answer
UnityEngine.Random is static. If you wanted to create multiple instances of a random number generator, then you would want to use System.Random.

There is no way to look up the source code for the Unity Implementation, however, Microsoft provides the source for System.Random.
> 6 votes

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


title: Unity 5 Animation attaching

text:
# Question
Title: Unity 5 Animation attaching
I have created the walking and idle animation for my fps player. I've added a JavaScript script to access it, but when I run it and press button(w), it stops and says that the animation is not attached to the object.

When I drag the walking/idle animation and drop to that object, it creates an animation controller. Again I run it, still same error. I can't find where to attach the animation

Here's my script:

```
function Update ()
{
  if(Input.GetKeyDown("w"))
  {
    GetComponent.<Animation>().Play("walk_anim2", PlayMode.StopAll);
  }
  if(Input.GetKeyUp("w"))
  {
    GetComponent.<Animation>().Play("idle_anim2", PlayMode.StopAll);
  }
}

```

Where do I need to attach the animation?

# Answer
You are using an `Animator` component but you are referencing `Animation` in your script. You can see in the error it says `MissingComponent`. You should use `Animator` component.

Here is the link for relevant API page: http://docs.unity3d.com/ScriptReference/Animator.html
> 2 votes

---
Tags: javascript, animation, unity
---


# Question
Title: Click event doesn't trigger when clicking
I've made some buttons on my screen to navigate to other scenes of my Unity project but the `Click(string command)` method doesn't trigger. I've placed a breakpoint on the bold line in code below, but the pointer never hits that point.

```
public class GameNavigation : MonoBehaviour
{
    public void Click(string command)
    {
        **switch (command)**
        {
            case "again":
                Application.LoadLevel(Application.loadedLevel);
                break;

            case "go_to_menu":
                Application.LoadLevel("Navigation");
                break;

            default:
                break;
        }
    }
}
```

Here are also some screenshots form my Unity project.

What did I wrong?

---

**Note one:** I've made also this code that is called after the scene ends. the parameter `command` is always an empty string.

```
public void RestartLevel(string command)
{
    switch (command)
    {
        case "again":
            Application.LoadLevel(Application.loadedLevel);
            break;

        case "go_to_menu":
            Application.LoadLevel("Navigation");
            break;

        default:
            break;
    }
}

```

If I place it in a comment, I get this error:

> 'Player' AnimationEvent 'RestartLevel' has no receiver! Are you missing a component?

---

**Note two:** I also use a mouse down event for when the player must shoot.

---

**Update one:** by a comment below I've made this code:

```
public Button btnAgain;
public Button btnMenu;

public void Start()
{
    btnAgain.onClick.AddListener(() => {
        Application.LoadLevel(Application.loadedLevel);
    });

    btnMenu.onClick.AddListener(() => {
        Application.LoadLevel("Navigation");
    });
}

```

The `Start()` method is always called, no problems with it. But the `Application.LoadLevel(...)` code never executes when I click on the methods. However `btnMenu` and `btnAgain` aren't null.

---

**Update two:** I've upload a zip file on my SharePoint that you can access. Start a game and choose level 01. You navigating to a new scene. On that scene you have on the right below side you have two buttons, these are the buttons that doesn't work. If you can find the problem, please give me the solving of the problem. Other bug fixes are also welcome. 😉

# Answer
Here's the process to figuring out what's causing the issue.

1. Confirm that the `Clicked` method is run. I suggest just putting a `Debug.Log()` statement there. `Debug.Log(command);` would be perfect, because it also lets you know the command.
2. If your `Click` method isn't being run, most likely something else is taking that click. Look for other objects that might be intercepting the click in front of it (Might not be visible).
3. If the correct command is received, then you should probably use `.equals()` for comparison. For instance, `command.equals("again")`
4. You might consider using separate functions for each. There's a proposal to use enums, but so far as I know, that's not accepted yet.
> 1 votes

---
Tags: unity, c#, ui-design
---


# Question
Title: c++ text based duel game, buggy turn mechanic
so ive checked this code 100 times for mistakes and everything checks out and should be working, I've tried everything I can think of but for some reason nothing works, this makes the movement super buggy and none of my attack works

this is a snippet from my initiation class

```
Frame();

Counter = 1;
//Player One's turn
while (Counter == 1)
{

    Map::Movement();
    Attack::Playerattack();
}
//Player two's turn
while (Counter == 2)
{
    Map::Movement2();
    Attack2::Playerattack();
}

```

part of my movement class

```
int ch;
switch (ch = _getch())
{
    //Player 1 movement
case KEY_W: //up
    if (Player::posy != 1)
    {
        Player::posy--;
        DisplayMap();
        Start::Counter++;
    }
    break;

case KEY_S: //down
    if (Player::posy != 20)
    {
        Player::posy++;
        DisplayMap();
        Start::Counter++;
    }
    break;

case KEY_A: //left
    if (Player::posx != 1)
    {
        Player::posx--;
        DisplayMap();
        Start::Counter++;
    }
    break;

case KEY_D: //right
    if (Player::posx != 20)
    {
        Player::posx++;
        DisplayMap();
        Start::Counter++;
    }
    break;

```

1st attack class

```
int ch;
switch (ch = _getch())
{
    case KEY_1:
        if (((Player::posx == Player2::posx) && (Player::posy == Player2::posy + Player::roa1)) || ((Player::posx == Player2::posx) && (Player::posy == Player2::posy - Player::roa1)) || ((Player::posy == Player2::posy) && (Player::posx == Player2::posx + Player::roa1)) || ((Player::posy == Player2::posy) && (Player::posx == Player2::posx - Player::roa1)))
        {
            Player2::hp = Player2::hp - Player::doa1;
            std::cout << "You have used: Attack 1" << std::endl;
            std::cout << "Player 2 HP is now: " << Player2::hp << std::endl;
            Start::Counter++;
        }

//if enemy is in range of attack 2 below the monster
    case KEY_2:
        if (((Player::posx == Player2::posx) && (Player::posy == Player2::posy + Player::roa2)) || ((Player::posx == Player2::posx) && (Player::posy == Player2::posy - Player::roa2)) || ((Player::posy == Player2::posy) && (Player::posx == Player2::posx + Player::roa2)) || ((Player::posy == Player2::posy) && (Player::posx == Player2::posx - Player::roa2)))
        {
            Player2::hp = Player2::hp - Player::doa1;
            std::cout << "You have used: Attack 2" << std::endl;
            std::cout << "player 2 HP is now: " << Player2::hp << std::endl;
            Start::Counter++;

```

2nd Attack class

```
int ch;
switch (ch = _getch())
{
    case KEY_K:
        if (((Player2::posx == Player::posx) && (Player2::posy == Player::posy + Player2::roa1)) || ((Player2::posx == Player::posx) && (Player2::posy == Player::posy - Player2::roa1)) || ((Player2::posy == Player::posy) && (Player2::posx == Player::posx + Player2::roa1)) || ((Player2::posy == Player::posy) && (Player2::posx == Player::posx - Player2::roa1)))
        {
            Player::hp = Player::hp - Player2::doa1;
            std::cout << "Player 1 HP is now: " << Player2::hp << std::endl;
            Start::Counter--;
        }

    case KEY_L:
        if (((Player2::posx == Player::posx) && (Player2::posy == Player::posy + Player2::roa2)) || ((Player2::posx == Player::posx) && (Player2::posy == Player::posy - Player2::roa2)) || ((Player2::posy == Player::posy) && (Player2::posx == Player::posx + Player2::roa2)) || ((Player2::posy == Player::posy) && (Player2::posx == Player::posx - Player2::roa2)))
        {
            Player::hp = Player::hp - Player2::doa1;
            std::cout << "player 1 HP is now: " << Player2::hp << std::endl;
            Start::Counter--;

```

if anyone has ANY ideas what im doing wrong or have overlooked please tell me and I will try it, I'm working in visual studio 2012.

# Answer
> 0 votes
First of all you lack a break in the attack class, without it the code will fall through and execute every other case.

Secondly and more importantly a player can move and attack in the same turn and and increment/decrement the counter by two. I'm assuming you're going for an either/or situation in which case try this:

Initiation

```
//Player x's turn
ch = _getch()
while (Counter == x)
{
    Counter += Map::Movement(ch);
    if (Counter == x)
    {
        Counter += Attack::Playerattack(ch);
    }
}

```

Then modify the movement and attack classes to use the parameter and return 1/-1 if value has been changed.

# Answer
> 0 votes
Ok so if anyone was wondering in the movement and attack classes i set the counter exactly to what i wanted instead of using increments and that seemed to fix the problem

---
Tags: c++, turn-based, text, visual-studio, text-based
---


title: GLSL shaders in a program

text:
# Question
Title: GLSL shaders in a program
I obviously don't want the client to be able to view/modify my glsl code. Does this leave me with only one option, and that's to hardcode it in my cpp files? How do you deal with this issue?

# Answer
> 1 votes
If someone really wants to edit or see your shader code, that person will find a way... With that out of the way:

There are several options to somewhat prevent curious eyes:

1. You can save the files with names and extensions different from what usually is done with shaders (for example prog001.dat, shining.prog, etc). That will make some people think it is something better left untouched.
2. You can save all your shaders in a custom container with some random magic numbers at the beginning so that all of them reside on a single file, you then implement a lookup and on-demand loading functionality.
3. You can save everything on a zip or rar file, rename it to have a different extension and then open that on your code and do something similar as #2.

There may be other more creative ways to do this, the point is you just need to think outside the box and keep in mind that this is not meant to keep the code completely safe. Look in the files of any AAA game and you will probably find the shader code in plain text somewhere around there.

---
Tags: shaders, glsl
---


# Question
Title: Random numbers with a left or right biased skew
Within Java I have a table of objects ranging from horrible (1%) to wonderful (100%) from which one is randomly selected. This is simple enough and appears on a bell curve with a normal distribution and the average at the 50% mark. But at various stages I wish for this distribution to shift left or right meaning that you are more likely to generate a less pleasant item or at other stages, generate a more pleasant one. The table ranges from 1 to 100.

How do I generate a random number that is biased to one end of the table and not the other, while still being able to, in this case in a bad situation, randomly come up with a 100%? I have looked at `Random.nextGaussian()`. But this doesn't seem to quite do it, if I am reading it correctly.

# Answer
There's a couple of solutions and I'll touch on them briefly. They can also be combined.

**Option 1: Add a flat value**

`rand(max-min)+min`

This produces the entire bell curve shifting left (or right! if supplied a negative min value). While it will exclude items at one and of the range, or the other, this may be beneficial (imagine a scenario where the high/good stuff needs to be common at some point and the maximum increased: during high level play you actually *want* to exclude the lower value items entirely!)

**Option 2: Roll Twice, Pick Better**

D&D 5th uses this type of mechanic with regards to advantage/disadvantage: roll twice and pick the higher (advantage) or lower (disadvantage). It has an on-average effect of being the same as adding +5 to a d20 (so about 20% better) but still generates values across the whole continuum (the bell curve gets squished to one side).

**Option 3: Inverse Gausian**

While this *may not* be the best solution *for you* there is in fact an Inverse Gaussian Distribution (or "Wald Distribution") which happens to look like an extremely squished bell curve (smashed up against the lower bound of 0) but the exact curvature can be tweaked to one's desires (but the maximal probability will occur towards the 0-end unless you do a `1-random`). I use this one currently in a game I am working on so that things are *very consistent* with extremely rare deviations, but those deviations, when they occur, are very wild1. Code for how to compute this distribution *can* be located, though you'll have to piece it together from various sources (it relies on the "error function" which you have to look up independently).

1This means that the player will largely be able to rely on their skills, provided that they are evenly matched +/-1 with the enemies, but still face occasional failures, while as the disparity grows, things become more and more tenuous very rapidly. At +0 the player has a 98% chance of success. At -1, it drops to 92%. At -2, 80%, -3 50%. If the player plays smart they can still survive at a -3 disadvantage (conversely, at a +3 *advantage* their success rate only rises to only 99.5% or so! So still not a guaranteed success, although it will be very easy).
> 3 votes

# Answer
You can add another number, from a pre-selected range, to your first number.

Suppose that we're getting `50` on average but want to move that up to 65, you'd add a random number between `0` and `(65 - 50) * 2` to your first number.

The formula for shifting the distribution (this is added to each result you generate), therefore is: `(target percentage to be the peak - 50) * 2`
> 0 votes

# Answer
`Random.nextGaussian()` should still work for you if you shift the results. Any real number (to float precision) is technically possible using this method as the constraints are simply that it's 0-centered and has a standard deviation of 1 (ie, a standard normal distribution). All that means is that you just need to shift it (with addition) to wherever you want to position the center and multiply to set the width (standard deviation). All values along the number line are still possible, so you'll also need to restrict it to \> 0 and \< 101.
> 0 votes

---
Tags: java, random
---


# Question
Title: Do matrix manipulations for 3D graphics ever produce singular matrices?
A singular matrix is a matrix that cannot be inverted. The vecmath library, for example, throws a SingularMatrixException if you try to invert a singular matrix.

I think I understand what singular matrices are. But there are plenty of matrix operations that I don't understand, so I'm not sure what might produce one. **Are singular matrices ever produced *accidentally* when manipulating 3D graphics transforms,** the way gimbal lock can be? If so, are there any strategies for avoiding singular matrices, and/or what can you do about them if you encounter one?

# Answer
> 9 votes
The simplest way this can happen is if you shrink an object until its local scale in one or more axes is 0 (flattening it to a plane, line, or point). You can avoid this by disallowing scales below a certain magnitude on any axis.

(If your system allows hierarchical nesting of transforms, you'll also have to watch out that no chain of parented matrices result in a scale below this threshold, even if each scale individually checks out. It won't reach zero, but it might get close enough to make your matrix inversion code behave badly)

The subtler way this can happen is through rounding errors.

A common first attempt at an object renderer or scene graph will store object transforms as a matrix, and perform each change by overwriting the matrix with its concatenation by some incremental transformation (eg. rotating n degrees per frame). In psuedocode:

```
Rotate(object, angle, axis)
{
    object.matrix = CreateRotationMatrix(angle, axis) * object.matrix;
}

```

Because the matrix is used in the calculation of its own successor, any errors in the current matrix propagate into the next, accumulating and snowballing over time. This can cause the scale or orthogonality of the matrix to become distorted (the object can squash, stretch, or shear unintentionally).

In extreme cases the scale can get rounded to 0 along one axis, or one axis can become coplanar with the other two, resulting in a singular matrix.

There are two main ways to keep these rounding errors from accumulating:

1. Store the transformation in terms of its constituent parts (translation vector, rotation quaternion or angles, local scale triple). When any aspect changes, the matrix is recomputed from scratch using these validated inputs. This guarantees it is orthogonal and (if you disallow near-0 values in your scale triplet) invertible, and prevents repeated changes to one parameter (eg. rotation) from causing drift in another (eg. scale). This also lets you distinguish rotation by 180 degrees from reflection along two axes, in case that's useful for your transform UI. ;)
2. Apply error correction after each step to prevent runaway error accumulation. To correct for wandering axes, orthogonalize the resulting matrix. To correct scale errors you'll still need a reference uniform scale value or local scale triplet stored separately, so you can scale each column/row (depending on your multiplication convention) to the right length.

Both of these assume you never want to deliberately introduce shear into your transformation matrices, though you could store additional shear information to maintain a non-orthogonal matrix.

---
Tags: matrix, transformation
---


# Question
Title: How to solve Sweep and prune false positives concerning large floor plane
I am developing a 3d sweep and prune module for a project, and it is producing false positives.

The pair generation code is as follows:

```
    for (unsigned int i = 0; i < mXExtents.size(); i +=2)
    {
        if (mXExtents[i]->mOwner->getID() != mXExtents[i + 1]->mOwner->getID())
        {
                tempXPairs.push_back(new Pair(mXExtents[i]->mOwner, mXExtents[i + 1]->mOwner));
        }
    }
    for (unsigned int i = 0; i < mYExtents.size(); i +=2)
    {
        if (mYExtents[i]->mOwner->getID() != mYExtents[i + 1]->mOwner->getID())
        {
                tempYPairs.push_back(new Pair(mYExtents[i]->mOwner, mYExtents[i + 1]->mOwner));
        }
    }
    for (unsigned int i = 0; i < mZExtents.size(); i +=2)
    {
        if (mZExtents[i]->mOwner->getID() != mZExtents[i + 1]->mOwner->getID())
        {
                tempZPairs.push_back(new Pair(mZExtents[i]->mOwner, mZExtents[i + 1]->mOwner));
        }
    }

```

Where each object has a unique ID in the world. This works fine with small objects, but I have encountered a problem, where, If the ground is represented by a finite (albiet large) axis aligned plane, false positives and negatives are generated, preventing the Narrow-phase from doing it's job.

As you can see, each axis list is traversed in sets of 2 elements, and the unique ID's are compared. If they do not match, then a pair is generated for that axis.

Without the ground plane, The order of each list would be Amin, Amax, Bmin, Bmax etc. which would not generated false positives. However, with the addition of the ground plane, the order becomes Pmin, Amin, Amax, Bmin, BMax, PMax.

Even if A and B are far away from one another on the axis in question, the pair is still generated. Additionally, If there is a genuine overlap on that axis, eg. Pmin, Amin, Bmin, Bmax, Amax, Pmax, then genuine intersections are missed.

Also, I've just encountered another problem: Even when traversing the lists one element at a time, In the case of objects stacked on an axis, collisions can be missed. The following image illustrates this:

If anyone else has encountered this problem, I'd like to hear how they solved it.

# Answer
> 1 votes
I came up with a solution:

In order to record all possible intersections on a given axis, You must record a pair for every possible overlap. The code I posted wasn't doing this. Instead, my new code traverses the the list one at a time, and for each endpoint which is marked as a minimum, search the remaining elements until you find the max endpoint for the same object and generate a pair for all elements in between:

```
    for (unsigned int i = 0; i < mXExtents.size()-1; i++)
    {
        //if the endpoint is a minimum
        if (!mXExtents[i]->mMax)
        {
            //search remaining elements for the max endpoint
            for (unsigned int j = i + 1; j < mXExtents.size(); j++)
            {
                //objects only have two endpoints, so this is the max one.
                if (mXExtents[j]->mOwner->getID() == mXExtents[i]->mOwner->getID())
                {
                    break;
                }
                else
                {
                    //between min and max is an intersection of AABB on this axis
                    tempXPairs.push_back(new Pair(mXExtents[i]->mOwner, mXExtents[j]->mOwner));
                }
            }
        }
    }

```

As each object has only two endpoints, min and max, once you reach it, it can be inferred that the other end point is the maximum extent, therefore beyond it, no further intersections are possible, and so no further traversing is necessary. Naturally, this does increase complexity, but as the checks are very simple integer/integer, and boolean checks, It shouldn't have too much of an impact on performance.

---
Tags: c++, collision-detection, algorithm
---


title: Buy or make assets

text:
# Question
Title: Buy or make assets
As an indie developer, I don't know if I should make my own models or buy them from the asset store (unity engine). I do know basic modeling in Blender, but I also have spare money that I can use to buy assets.

Another doubt I have is that if I decide to make my own models or assets. Is it good to sell them in the asset store (unity engine) or just keep the assets to myself?

# Answer
> 1 votes
It depends entirely on what you want.

Any answer but that would probably be subjective, but I'll try to elaborate anyhow:

I enjoy making games because it lets me get creative. I can make my own models, animate them, and place them in a 3d world. I like being able to say I made the entire game. But if you find it difficult to do all that, or just think it takes too much time while you'll never make something as beautiful as the asset you found (believe me, I know that struggle), there's nothing wrong with using assets.

Also, if you are good at modeling, texturing, animating, but realize your games don't work out because you're a terrible programmer, you could sell your models as assets. Your models would help other people finish their games, and seeing your models out there in the real world, in a finished game, is awesome.

Bear in mind that there have been made so many poorly written games created solely with assets from unity's store, that whenever you make an asset-filled game, people get hesitant. Their first idea will most likely be that it's probably terrible. Don't think buying assets will allow you to release your game sooner. Buying assets will allow you to spend more time on gameplay, story, and all other things you're making by yourself.

# Answer
> 0 votes
It's a simple cost-benefit analysis.

* How much money per hour do you value your worktime?
* How many hours will it take you to create asset X?
* How much money will it cost you to buy asset X?

This, of course, assumes that you:

1. have the skills to create the asset yourself in the desired quality and
2. that you find an asset in the store which is exactly what you want.

If only one of these is true, the choice is obvious. If neither is true, there is a third option: Hire an artist to create it for you.

---
Tags: unity, blender, 3d-modeling
---


# Question
Title: How can I make a ball glow and cast light?
I want to make my ball glow and cast light on other objects in the scene. The scene is generated at run time so I believe baking is out of the question. Emission materials work only when the object casting the glow/light is static.

# Answer
You can't use the emmisive property alone, that will simply cause the object to appear. If this is something you are positive you want (And realize that it may affect your FPS, especially if you have a large number of these objects), I would use a combination of two techniques:

1. Use the emissive property. This will make the object appear lit even in a dark scene.
2. Attach a light source to the object. Make sure to use the same color as the emissive property.
3. You might need to turn down the albedo of the object as well.

Here's an example of me doing just this. Note the wall behind is black, I turned off the skybox illumination, and it is the only light source enabled.
> 6 votes

---
Tags: lighting, unity, glow
---


# Question
Title: Rendering sprites on a Mali-400 MP device
I started developing a small cross platform game engine using OpenGL, I am working actually on a sprite batch renderer.
Everything is working fine on OS X, iOS, Win32, and some Android Devices. Here is the Results :
The image on the left show the correct result, and was tested on Samsung galaxy S1, Galaxy J5, Galaxy S3, Galaxy Tab 3. The device that give these weird results on the right is a Samsung Galaxy Core 2, With a Mali-400 MP renderer.
I start getting that weird result when I use more than one texture.
Here is my Sprite Batch class :

```
Glyph::Glyph(const maths::vec2 &position, const maths::vec2 &dimensions, const maths::vec4 &uvRect, GLuint texture, unsigned int color, float zOrder) :
textureID(texture) {

    a_zOrder = zOrder;

    topLeft.m_color = color;
    topLeft.setPosition(position.x, position.y + dimensions.y);
    topLeft.setUV(uvRect.x, uvRect.y + uvRect.w);

    bottomLeft.m_color = color;
    bottomLeft.setPosition(position.x, position.y);
    bottomLeft.setUV(uvRect.x, uvRect.y);

    bottomRight.m_color = color;
    bottomRight.setPosition(position.x + dimensions.x, position.y);
    bottomRight.setUV(uvRect.x + uvRect.z, uvRect.y);

    topRight.m_color = color;
    topRight.setPosition(position.x + dimensions.x, position.y + dimensions.y);
    topRight.setUV(uvRect.x + uvRect.z, uvRect.y + uvRect.w);
}

//SpriteBatch
ORendererSpriteBatch::ORendererSpriteBatch(): m_vboID(0), m_vaoID(0)
{
    Init();
}

ORendererSpriteBatch::~ORendererSpriteBatch()
{
    if (m_vboID != 0) {
        glDeleteBuffers(1, &m_vboID);
    }

    if (m_vaoID != 0) {
        glDeleteVertexArrays(1, &m_vaoID);
    }
}

void ORendererSpriteBatch::Init()
{
    createVertexArray();
}

void ORendererSpriteBatch::Begin()
{
    m_renderBatches.clear();

    // Makes _glpyhs.size() == 0, however it does not free internal memory.
    // So when we later call emplace_back it doesn't need to internally call new.
    m_glyphs.clear();
}

void ORendererSpriteBatch::Submit(const OSprite* renderable)
{
    m_glyphs.emplace_back(renderable->GetPosition(), renderable->GetSize(), renderable->GetUV(), renderable->GetTID(), renderable->GetColor(), renderable->GetZOrder());
}

void ORendererSpriteBatch::End()
{
    // Set up all pointers for fast sorting
    m_glyphPointers.resize(m_glyphs.size());
    for (size_t i = 0; i < m_glyphs.size(); i++) {
        m_glyphPointers[i] = &m_glyphs[i];
    }

    sortGlyphs();
    createRenderBatches();
}

void ORendererSpriteBatch::Flush(OLayer2D *layer)
{
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    ORendererFactory::OShader_Simple2D->bind();
    glActiveTexture(GL_TEXTURE0);
    ORendererFactory::OShader_Simple2D->setUniform1i("u_diffuse", 0);
    ORendererFactory::OShader_Simple2D->setUniformMat4("u_MVP", layer->getCamera()->getCameraMatrix());
    glBindVertexArray(m_vaoID);

    for (size_t i = 0; i < m_renderBatches.size(); i++) {
        glBindTexture(GL_TEXTURE_2D, m_renderBatches[i].texture);

        glDrawArrays(GL_TRIANGLES, m_renderBatches[i].offset, m_renderBatches[i].numVertices);
    }

    ORendererFactory::OShader_Simple2D->unbind();
    glBindVertexArray(0);
}

void ORendererSpriteBatch::createRenderBatches() {
    // This will store all the vertices that we need to upload
    std::vector <VertexData2D> vertices;
    // Resize the buffer to the exact size we need so we can treat
    // it like an array
    vertices.resize(m_glyphPointers.size() * 6);

    if (m_glyphPointers.empty()) {
        return;
    }

    int offset = 0; // current offset
    int cv = 0; // current vertex

    //Add the first batch
    m_renderBatches.emplace_back(offset, 6, m_glyphPointers[0]->textureID);
    vertices[cv++] = m_glyphPointers[0]->topLeft;
    vertices[cv++] = m_glyphPointers[0]->bottomLeft;
    vertices[cv++] = m_glyphPointers[0]->bottomRight;
    vertices[cv++] = m_glyphPointers[0]->bottomRight;
    vertices[cv++] = m_glyphPointers[0]->topRight;
    vertices[cv++] = m_glyphPointers[0]->topLeft;
    offset += 6;

    //Add all the rest of the glyphs
    for (size_t cg = 1; cg < m_glyphPointers.size(); cg++) {

        // Check if this glyph can be part of the current batch
        if (m_glyphPointers[cg]->textureID != m_glyphPointers[cg - 1]->textureID) {
            // Make a new batch
            m_renderBatches.emplace_back(offset, 6, m_glyphPointers[cg]->textureID);
        } else {
            // If its part of the current batch, just increase numVertices
            m_renderBatches.back().numVertices += 6;
        }
        vertices[cv++] = m_glyphPointers[cg]->topLeft;
        vertices[cv++] = m_glyphPointers[cg]->bottomLeft;
        vertices[cv++] = m_glyphPointers[cg]->bottomRight;
        vertices[cv++] = m_glyphPointers[cg]->bottomRight;
        vertices[cv++] = m_glyphPointers[cg]->topRight;
        vertices[cv++] = m_glyphPointers[cg]->topLeft;
        offset += 6;
    }

    glBindVertexArray(m_vaoID);

    // Bind our VBO
    glBindBuffer(GL_ARRAY_BUFFER, m_vboID);
    // Orphan the buffer (for speed)
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(VertexData2D), NULL, GL_DYNAMIC_DRAW);
    // Upload the data
    glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.size() * sizeof(VertexData2D), vertices.data());

    glBindVertexArray(0);
    // Unbind the VBO
    //        glBindBuffer(GL_ARRAY_BUFFER, 0);

}

void ORendererSpriteBatch::createVertexArray() {

    // Generate the VAO if it isn't already generated
    if (m_vaoID == 0) {
        glGenVertexArrays(1, &m_vaoID);
    }

    // Bind the VAO. All subsequent opengl calls will modify it's state.
    glBindVertexArray(m_vaoID);

    //G enerate the VBO if it isn't already generated
    if (m_vboID == 0) {
        glGenBuffers(1, &m_vboID);
    }
    glBindBuffer(GL_ARRAY_BUFFER, m_vboID);

    //Tell opengl what attribute arrays we need
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);

    glVertexAttribPointer(0, 2, GL_FLOAT,         GL_FALSE, sizeof(VertexData2D), (void *)offsetof(VertexData2D, m_vertex));
    glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE , sizeof(VertexData2D), (void *)offsetof(VertexData2D, m_color));
    glVertexAttribPointer(2, 2, GL_FLOAT        , GL_FALSE, sizeof(VertexData2D), (void *)offsetof(VertexData2D, m_uv));

    glBindVertexArray(0);

}

void ORendererSpriteBatch::sortGlyphs() {

    std::stable_sort(m_glyphPointers.begin(), m_glyphPointers.end(), compareFunction);

}

bool ORendererSpriteBatch::compareFunction(Glyph* a, Glyph* b) {
    if (a->a_zOrder == b->a_zOrder) {
        return (a->textureID < b->textureID);
    }
    return (a->a_zOrder < b->a_zOrder);
}

```

And here is how I call that class :

```
    m_CurrentRenderer->Begin();

    for (const OSprite* renderable : m_Renderables)
        if(m_Camera->isBoxInView(renderable->GetPosition(), renderable->GetSize())){
            renderable->Submit(m_CurrentRenderer);
        }

    m_CurrentRenderer->End();
    m_CurrentRenderer->Flush(this);

```

Any suggestion about what might cause that bug is welcome.

# Answer
> 1 votes
Since the rendering glitch shows tiles and half-tiles that might hint at a texture format or encoding/decoding issue (lack of ETC2 support?).

Make sure the textures are square, power-of-twos and try with different sizes and formats.

The other thing I'd try is adjust the vertex format to be padded to a multiple of 16 and not cross 16-byte boundaries.

eg: if it is arranged `v[4,4],c[4],uv[4,4]` (numbers=bytes) this cuts the uvs at the 16byte boundary. It's unlikely to be the issue but this may force the driver to CPU-copy the vertex buffer to re-arrange the attribute order and pad the vertex to a size that the GPU supports natively.

I'd try rearranging it `v[4,4,4],c[4],uv[4,4],pad[8]` with a valid Z value in the vertex just in case there's an issue in the CPU-copy function and it may run faster on some GPUs.

Since it renders fine on some but not the other(s) if those suggestions don't fix the problem I'd keep looking into driver/GPU limitations that may cause this.

---
Tags: 2d, android, opengl-es2, spritebatch
---


# Question
Title: What threading strategy does a game like Transport Tycoon use?
Transport Tycoon is a simulation game where you control a transport company, place railroad tracks and trains, airports, bus depots, boats etc. Now the game is about 15 years old and I remember running it on a 486sx25 with 4Mb of RAM without any problems.

I was recently thinking about modern simulation game requirements and how high they are for relatively little increase in graphics and gameplay, so how did they managed to pull it with so little resources back in the day?

Does each train car have a thread, that moves it every 100ms, sleeps, wakes, recalculates position and does crash detection, and goes back to sleep?

Or is it one thread that moves every 100ms? What happens if there is too much work to do in each 100ms interval?

# Answer
> 8 votes
The real question is, how does modern games use so much memory?

I have very sparse knowledge of Transport Tycoon, so the following is only a generalisation of how such games would be made at that time.

The game would be single threaded, split into two primary portions, game logic, and rendering.

In game logic elements are represented as only a few bytes each, the map is probably a 2D array, implemented as a flat space of memory with the implicit mapping that each tile is stored in position `Xcoordinate + mapWidth*Ycoordinate`, with probably just a single byte for each tile signifying one of up to 256 possible combinations of terrain and structures. Stuff like trains is a bit more complex, they'd have X and Y coordinate, possibly using 16 bit integers for each getting pixel perfect or better positioning, then there is cargo, speed, rotation, route and possibly some other stuff, but all things that you can express using a few integers.

On each update the game will use a simple loop to go through all trains, move them, increase or decrease speed as required, for collision detection either a simple double iteration over the array of trains will be used, or an array will be filled with with train positions thus requiring some memory to be cleared for every update but avoiding a costly double iteration.

The rendering part will go through the part of the map array that is currently in view, for each tile it will copy the image corresponding to the value of that tile to the output buffer in video card memory. Then the trains in view will be blitted onto the output buffer.

Depending on how the game is written it will if there is not enough processing power to do all the required tasks either simply slow everything down, or skip some of the rendering, thus lowering the framerate but keeping the game itself running at constant speed.

---

There are some thing from this example that can be used in modern programming:

You do not need fancy stuff like multi threading and events, you should try programming without them, not because they are bad tools, but learning the alternatives broadens your toolbox and helps you to better pick the right tool for the job.

One of my favourites, you can actually count memory use. Some modern languages makes it a bit harder by using a lot of memory that doesn't correspond directly to the resources you use, but it doesn't make it impossible. If you make one 32 bit integer, that is 4 bytes, if you make an array of 1024 such integers that is 4 kB, if you load a 640x480 image into memory as a 32 bit ARGB texture, that is 1200 kB. People should in general count memory use way more that they do, it's a great tool for planning.

Game logic typically doesn't need a lot of memory, some games use a lot anyway because they can, but often that simply means the developers then have to deal with representing all this information in a way that makes it easy to understand for the player. The big memory spender is always graphics, if not you are probably doing something wrong.

---

And finally to justify my own question, let's count memory use for my description of a game like Transport Tycoon. Let's say for a period typical example, the game use 8 bit colour, the tiles are 16x16 pixels, the biggest map supported is a whooping 256x256, there are 16 different locomotives and 32 different carts, the trains can go 8 different directions, thus 8 images for each locomotive is needed, and 4 for each cart is needed as they look the same rotated 180 degrees, that is 256 images, plus 256 blit masks. All these images are 16x16 pixels. This gives a total of 768 16x16 pixel 8 bit images, thus a total of 192 kB memory for storing all graphics assets.

The map use 64 kB.

Supporting up to 255 stations and 255 trains, with up to 32 stations on each trains route, all will need 16 bytes for a name. The stations will need 2 bytes for coordinates and 32 bytes for stocks of goods, thus 50 bytes total for a station. The trains have up to 6 carts each need 1 byte for type of cart, 1 for amount of content, 4 bytes for position and 1 for rotation. The train need 1 byte for type of locomotive, 32 bytes for route, 1 byte for next stop on route, 1 byte for speed, 4 bytes for position and 1 byte for rotation. 98 bytes total for a whole train. All this sum up to less than 37 kB for trains and stations.

the output buffer is 320x200 pixel at 8 bit per pixel, thus 62.5 kB of video memory, 125 kB to implement switching buffers.

Assume 90 kB of code and we are right around the ½ MB mark total. I have surely forgotten something in this count, but probably nothing major, and it is very typical for a period game to stay below the 640 kB mark, thus avoiding having to deal with expanded or extended memory and the possible problems this would cause for users.

If you do the numbers for a modern game you'd probably end up wondering why PC games need so much memory, indeed the modern consoles seem to do pretty well with only 512 MB of memory, there can be A LOT of textures in that space when you start to think about it.

# Answer
> 1 votes
Multi core machines became a thing in consumer machines one generation after Pentium 4, that's 4 generations after 486 machines.

When there was only one CPU, using multiple threads to operate on the same data set and having to worry about synchronizing data was just plain stupid, because there was absolutely no benefit at all. Keep in mind that the threading libraries and support for thread safe data structures were awful at that time.

If the work finishes before your 100ms interval ends, you sleep (or busy-wait) until the start of the next interval. If you run out of time, you finish work normally and just start the next frame immediately, slowing the game down. You might consider time that passed since the last frame, so if you're behind you calculate what happens in the next 150ms instead, but I doubt they did that.

Regarding memory, many of today's non-managed programs require less than 4 MB, if you disregard the GUI layer. A pretty high resolution GUI requires a lot of memory, and even more because we can easily waste a couple megabytes to make programming easier. Also keep in mind, in those times we usually worked with 16 bit, not 32 bit.

---
Tags: architecture, design-patterns, multithreading
---


# Question
Title: How to detect collision only in non-transparent texture?
I am developing a game using `libGDX`. I am trying to detect the collision between bee and tube. I am using the following code to detect the collision.

```
if(player.getBounds().overlaps(boundsBot)){

}

```

`player` is a bee and `boundsBot` is `Rectangle` of tube. Since there is some transparency in bee image, this returns `true` even if it doesn't seem to collide. I understand the reason why this is returning true.

I read this solutions. I understood the theoretical concept to the solve the problem but I couldn't achieve it using `libGDX`.

Here is what I tried,

```
if(Intersector.intersectRectangles(player.getBounds(), boundsBot, rectangle)) {
    //Gets the intersected rectangle
    System.out.println("Rectangle Bottom: " + rectangle);

    //Converting texture to pixmap
    Texture texture = player.getTexture().getTexture();
    if (!texture.getTextureData().isPrepared()) {
        texture.getTextureData().prepare();
    }
    Pixmap pixmap = texture.getTextureData().consumePixmap();

    //Trying to find transparency.....
    System.out.println("Format: "  + pixmap.getGLFormat());
}

```

How can I solve this issue?

Thank You!

# Answer
I had faced similar problem, when I was building a tower defense game.Where I needed to check for collision between tower boundary (ellipse) and enemies (rectangle),

**first method :** I have used the condition for checking if these points exist inside the ellipse like

```
if(ellipse.contains(point1X,point1Y)||ellipse.contains(point2X,point2Y)...)
{
    System.out.println("attack");
}

```

I picked those points that was in the boundary and that will collide with boundary most often.And I had 20 to 25 enemies rendered onto screen at same time and 3 to 5 forts checking for above condition whether any enemies are inside fort,My game was successful and had frame rate between 55fps and 60fps.

what you can do is check for condition if bee collided with the wall like

```
if(rectangle.contains(point1X,point1Y)||rectangle.contains(point2X,point2Y)...)
{
    System.out.println("bee collided with wall ");
}

```

**Second method:** You can also solve this using another approach ie using polygons and Intersector,for this you have to plot a polygon over the bee and wall. Like this

create polygons for bee and also for the wall

For bee

```
float[]verticesForBee=new float[]{-20,-20, -20,20,-10,20,-10,30,10,30,10,20, 20,20, 20,-20 };
Polygon beePoly=new Polygon();
beePoly.setVertices(verticesForBee);

```

For Wall

```
float[]verticesForWall=new float[]{-10,-20, -20,20,-30,20,-300,30 };
Polygon wallPoly=new Polygon();
wallPoly.setVertices(verticesForWall);

```

Now using Intersector.overlapConvexPolygon() method check if the polygons overlap with each other

```
if(Intersector.overlapConvexPolygons(beePoly, wallPoly))
{
    System.out.println("bee got collided with the wall");
}

```
> 4 votes

---
Tags: libgdx, collision-detection, transparency
---


# Question
Title: Lights appear when run in the player although Editor playmode seems to be dark enough [Unity 5]
I've removed all the lights in my scene and the ambient lighting. It works fine in the editor play mode but when I run it on my Android or as a standalone player a light source appears. The light source seems to be ambient in the PC standalone version and directional in the Android version.

Are there any other options that I have to look at?

# Answer
Yeah I figured it out. I hadn't added the right scene to the builder.
> 0 votes

---
Tags: lighting, unity
---


# Question
Title: Monogame resolution problem (without scaling sprites)
So I'm working on a project and started working on a scaling system for different resolutions.

I know if you change the monogame resolutions, that the texture won't scale but I noticed deformed pixels. I just changed the `PreferredBackBufferWidth` to 1920 and the `PreferredBackBufferHeight` to 1080 but my pixels are deformed.I did some research and tested some resolutions and the only ones that don't work are 1920x1080 and higher.(1920x1080 works in fullscreen)

Draw method for sprites:

```
public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch, Color color)
{
    spriteBatch.Draw(textureImage, position, new Rectangle(
    (currentFrame.X * frameSize.X),
    (currentFrame.Y * frameSize.Y),
    frameSize.X, frameSize.Y),
    color, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
}

```

spriteBatch.Begin:

```
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullCounterClockwise, null);

```

The first picture is the player head with the new resolution (without scaling the textures!) and the second picture is the player head with the default resolution (you can't see all the pixels at the bottom).

You can see that in the first picture a few pixels are deformed.

**Question**: Why doesn't 1920x1080 work in windowed mode (it works in fullscreen though) without deformation (I use a 1920x1080 monitor)? All I do is just enlarging the game window, I'm not scaling sprites...

-\> is this because I have a 1920x1080 monitor?

# Answer
> -\> is this because I have a 1920x1080 monitor?

Yes it is. On a 1920x1080 monitor you can't have a windowed game and also have a 1920x1080 canvas. The window title and edges also take up space. The graphics backbuffer is initialized at 1920x1080 but the internal windows logic scales the canvas to fit inside the window, causing the scaling artifacts. In windowed mode Windows also handles the graphics viewport so it knows where the window is on the desktop, this is a result of that.

You can see this by 'hiding' the windows border:

```
Using System.Windows.Forms; //also add reference to system.windows.forms in the project

Form MyGameForm = (Form)Form.FromHandle(Window.Handle);
MyGameForm.FormBorderStyle = FormBorderStyle.None;

```

It may *look* like fullscreen but it still is in windowed mode (just without showing the window border). But now the viewport can take up the entire screen and the artefacts are gone.

Note: This is default behaviour since XP/Vista. There may be code out there that overrides this but that is beyond this question.
> 2 votes

# Answer
The true cause of the artifacts you are seeing is going to be SamplerState.PointClamp. Due to the way this filtering works, you will see some texels taking up more or less space than neighboring ones as the texture is stretched over it's area.

What's more, is that the texels being deformed will likely change as the sprite or your camera moves about on screen.

There are various fixes for this that you can use, but one that I've recently implemented for a tiny pixel-art type game was to render to a smaller-resolution RenderTarget and then scale it to fit the window. The tricky bit becomes determining the size of your RenderTarget. If you want to keep your sharp edges, it needs to be the size of your screen divided by a round number.

So in your case of 1920x1080, to scale the pixels evenly by a factor of 2, you would create a RenderTarget at 960x540, render your sprites unscaled to that, then draw the RenderTarget to the screen, scaling it times 2.
> 1 votes

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