title: What exactly IS a model?

text:
# Question
Title: What exactly IS a model?
I'm trying to actually learn OpenGL after having experimented with it for a while, and so I'm trying to build a rudimentary rendering engine (not a game engine) to lead me through it. I've come to a conceptual obstacle however: I don't know exactly what a model really is. I mean obviously, it is composed of one of more meshes and textures, and other important data. But how much data? Should shaders be associated with models directly, with each one holding some sort of reference to the shader they require? Or should that be handled in another layer?

I think it makes sense to incorporate the shader program and the necessary parameters along with the meshes and textures as part of a model, but I wanted a more experienced opinion.

# Answer
> 3 votes
A model often refers to it's geometric data such as vertices (aka mesh data) and it's rendering properties commonly refered to as materials to give you the actual rendered object.

A single model can reference multiple materials where a material describes the blending algorithm, texture data, and shader references that combined together yield what finally gets rendered for a particular subsection of a model and other various rendering artifacts.

It's important that your shaders are kept separated like this because you likely will reuse a shader on multiple models or objects in your scene. For example, I have a shader that fades an object in and out of a scene based on opacity. Such a shader is useful for transitions as objects come into view or leave view for various reasons.

# Answer
> 2 votes
There is no absolute answer. Generally a "model" is some representation of something interesting in your computer program.

In CG it often means the geometry, and a typical model format might be something like:

* List of vertices (maybe with graphical attributes like color)
* List of polygons which reference vertex list with attributes like Material ref or Texture ref (and maybe overriding vertex attributes)
* A list of material definitions and texture content
* Maybe higher level groupings, like List of objects, each pointing to a list of polys
* Lists of instances of these objects, like a fleet of cars, with overrides for their particular position, rotation, maybe even color...

Or it could be very flat, like a raw OpenGL vertex triangle list.

Or it could be very high level, with parameterized instantiations of procedurally generated geometry invocations, like

* Gear(position,diameter, thickiness, number of teeth)
* CityBuilding(location, style, number of stories, footprint polygon)

The "model" is expressed at some level of abstraction, and that level depends on how it needs to be used.

That all said, if you take a look at the Collada format, you'll see a pretty common, useful, and relatively straightforward interchange format for rendering and geometry.

http://en.wikipedia.org/wiki/COLLADA

https://collada.org/

# Answer
> 0 votes
A model is a logical container that contains - among other things - mesh data. Depending on the format it can also reference external assets such textures and shaders. With FBX, for instance, you can even export cameras and lights from whatever DCC was used to create it, so your model can contain that data. At that point, you can even think of the model as a complex scene. OBJ on the other hand is pretty much vertices/indices/texture cords/materials only, so your model would have to be simplified down to that.

You could technically create your own "model" format/definition in your own engine and it could reference the things you mentioned (necessary/custom parameters).

---
Tags: rendering, models
---


# Question
Title: Adding gravity to arrival steering behavior
I trying to write an autopilot for the classic Lunar Lander or its clones.

According to this paper, the arrival behavior is exactly what I need for a soft landing. In this example, it accelerates at `max_speed` until it's near the target and decreases near the target to zero. Adding gravity and a engine to decelerate makes this a lot more complicated, at least for me since I couldn't wrap my head around the concept for the past few hours.

Currently my spaceship moves in the right direction but doesn't counter gravity and just throttles the engine, crashing near the target. I know my current position, velocity and the gravity is constant. I need to output thrust-levels (0-4) with a -90° to 90° angle.

Can you give me some pointers as to how I could incorporate gravity into this steering behavior?

# Answer
You don't need sophisticated methods to accomplish this if you explained the issue correctly. All you need is the following,

* `d` \- distance from the ground.
* `s` \- Current speed, going downwards.
* `g` \- Acceleration downwards resulting from gravity.
* `a` \- Acceleration upwards from the engine.

When the ship is heading down to the desired landing spot, you can check every frame for the following equality:

```
var t = 2 * d/s;
if (s ~= (a - g) * t) then slowDown()

```

Which you can translate to:

```
s ~= (a - g) * 2 * (d/s)

```

Which in turn translates to

```
s + epsilon > (a - g) * 2 (d/s)

```

This should do it.

What we are doing here is computing how much time will it take the ship to reach the ground if it could slow down and stop the moment it touches the ground?

If the ship linearly decreases its descent speed and stops completely when it reaches the ground then by average it would travel at half it's current speed, hence `t = 2 * d/s` which is basically saying -\> `t * 1/2 s = d`.

We use this to check if indeed with the current engine power, it would take the ship this much time to slow down and stop on the ground:

`a - g` =\> (how quickly could the ship slow decelerate). `s` needs to be zero when we touch ground. so we get that this needs to occur `(a - g) * t ~= s + epsilon`

Please notice that I assume all values are positive scalars.
> 2 votes

# Answer
I think you may want to do some research on PID regulators. Auto pilot is a regulation response. Some regulators even go as far as being able to compensate non linear input to get the desired response. (see \[off topic\] section for little story\*)

PID stands for "Proportional Integral Derivative". In electronics they are implemented with RLC circuits. They are "degree 2" which means they tend to target fast, and if the amortizement is not enough they can oscilate.

Numerically, you could try to make a learning machine, that tries varying ratios of modulated input. Do you know PWM ? Pulse-width modulation of power. It uses "hashing" of a DC source to create an average that can be modulated. Your engine, in a lunar lander, is a On/Off controller, therefore, unodulated it is a DC source. The position of your module is the integral (the `I` in `PID`) of your engine thrust. You can decide of a pusle frequency (10Hz, 30Hz?). Like a human would do actually, only faster so you have finer modulation grain. Then your regulator's (black box) input is a float number \[0,1\] signal that is used to change the width of the pulse. (look it up on wikipedia its going to be immediately clear what I am talking about). Then use a target, your target is a speed curve, the speed is a function of distance to land. Your regulator wants to match this curve. So at the beginning, the speed target is high because you are still far from land. your regulator will not apply thrust until the lander has accelerated near the speed target. then it will approach that target, and the derivative (speed at which the target is being approached), will play a role in the regulator to trigger the decision to apply thrust now, not after the target is overpassed.
Then this is when the actual width of the pulse should be learnt, by some memory (machine learning?) able algorithm. Not much experience with that though. Your regulation is not linear because of gravity, so it makes it slightly unconventional. But it should work more or less even without the learning system. (with some manual tweaking of the magical constants, by empirical testing. physicists could calculate the "charge constant" and be able to determine those factors mathematically, but I am no physicist.)
and this is only unidimensional for now. (vertical)
A simpler goal as a first implementation would be to try to oscilate around the speed target by using ON/OFF regulation (not smooth like PWM-PID) but enough to proof the concept quickly, and familiarize yourself with the reactions of the regulator. Just apply full thrust when over the speed target, to slow down, and release thrust when under speed target, to let it accelerate down naturally. The speed target still is "distance(lander,ground) * magical constant".
Of course mathematically, if this curve was respected perfectly, it would create the snail curve problem. If a snail divides his speed by two everytime he makes half the distance to its target, it will never reach the target. this is a contra-exponential assymptot. but we are in physics, not math, so some inertia and luck will solve this problem. Unfortunately, the same "luck" and "lag" will also result in crashes at times. But going to smooth PD or PID with PWM with some tweaking will get the landing routine perfectly safe at all times, eventually.

good luck, report progress ! :)

* \[off topic\]
This is actually something that happened as a problem in some industry. Consider this story: One day constructing an helicopter, somebody mounted the throttle mebrane in reverse. Nobody thought it would be possible to do such a thing so no defense existed against that. The membrane is a flexible piece of rubber/textile or fibers, that exists in the gasoline pipes, and is pushed by a piston to regulate gas flow to the engines. The control of the throttle does not go directly from manual lever input, to the piston drivers. It gets through a regulation device that modulates the piston force to get to the exact desired membrane position. The expected lifetime of the normally mounted membrane was 50k hours, but in reverse much less, because the piston had to apply much more force, however it went unnoticed, and the membrane broke quickly, helicopter crashed, people died. (true story)
\[/off topic\]
intelligent regulators are powerful but could be a risk if this kind of things is not considered :)

in your case, it is just a game, so you're OK though :P hehe
> -1 votes

---
Tags: physics, ai, trajectory
---


# Question
Title: Should I have multiple small textures or a single big one?
I'm using SDL 2 to create a small 2D game. Based on the docs, this is what I would do:

```
 SDL_Surface *surface = SDL_LoadBMP("image.bmp");
 SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface);
 SDL_FreeSurface(surface);
 ...
 SDL_RenderCopy(renderer, texture, NULL, &dest);

```

Since I have every single sprite in a different bmp, this would cause hundreds of texture objects to be created.

Another solution would be to create a single SDL\_Surface based on all the bmp files, create a single texture object from it and then blit it with something like this:

```
SDL_RenderCopy(renderer, texture, &src, &dest);

```

I use `src` to select the sprite I'm interested into blitting.

I know SDL 2 takes advantage of 3D acceleration and I'm not an expert of 3D graphics programming, but I do know that selecting the current texture is an operation that is very expensive. However, I'm not sure that a SDL texture is translated into a real Texture.

So my question is: are these 2 approaches the same in terms of performance, when using SDL 2?

# Answer
> 21 votes
The short answer: **Using one big texture atlas will probably be faster and should definitely not be slower than multiple small textures** and here is why:

After taking a look at the SDL source code i can see that SDL supports a bunch of renderers (OpenGL, Gles2, Psp, D3D ...) and (except the software one) all of them are implemented in the same fashion:

1:BindTexture, 2:SetShader, 3:DrawQuadWithGPU

The performance difference will be given by the renderer you choose(or SDL chose), so first one, **for software renderer there should be no performance difference!**

With the other renderers the problem is more complex and there are too many factors to be taken into account (drivers, platform, API implementation, batching, and so on)

**In general it is faster to use one big texture** because in certain cases, switching the textures often (BindTexture step described above) can break the performance so it is a general practice to put all the data in as few textures as you can so you cam minimize the texture changes in the GPU. It is important however to take advantage of this and if you have textures `A` and `B` to be rendered to the screen render as much content as you can with A and then B, otherwise if you constantly switch between drawing stuff from A then B (then A then B then A and so on) it might decrease the performance. If the OpenGL implementation on the platform you are using is smart and the BindTexture step can notice that you are using one texture you will defensively see a performance increase. Also as a side note, i see no evidence of any batching done internally by SDL so you have to do this yourself.

And why is switching the textures slow?

It depends on the platform and driver implementation but in general the GPU's can process massive amounts of data without interruption and when you tell the GPU to use a new texture on each draw that causes the GPU to stop and wait for all the previous tasks to end.

# Answer
> 3 votes
Because this game is 2D and I doubt you'd hit the limit of VRAM and unless you are swapping through thousands of textures, I don't think it makes much difference.

There are benefits and drawbacks to both:

* Packed textures are easier to manage and can be smaller on disk (potentially in VRAM) however require math to extract the correct sub texture.
* Individual textures can be easier to deal with as you can simply assign a texture to an object and not worry about it requiring cropping. However, there is a small performance degradation (again most likely negligible) due to the amount of parsing required for many images, and like you said, switching (again, negligible).
* Also, for things like animations, its usually easy to create strips as you can simply scroll through the image

Ultimately, it's up to you on whichever you think is easiest. Performance is not likely an issue.

# Answer
> 1 votes
Just like Raxvan said, generally a single large texture is the optimal way, but that does not mean you have to choose between either, at least as far as your assets go - it's not extremely difficult to write a texture packer that takes a number of images, and packs them into one or more larger textures, with a by-name or by-index lookup.

Depending on how much and how you have coded so far, it might be relatively simple to write a function set to pack your images into one texture atlas, and then just draw portions of the bigger image.

# Answer
> 1 votes
Short answer: probably not. Look here https://hg.libsdl.org/SDL/file/704a0bfecf75/src/render to see that there are implementations of generating real textures.

It depends on devices you are targetting. When current texture is being changed you call it a change of context on graphics card. It may work worse on mobile phones to often change texture, especially the older ones.

So generally it's best to have one big texture if possible. If you have more big textures then there starts the optimization part - sprites on texture should be grouped by usage.

---
Tags: 2d, sdl2
---


# Question
Title: How do I set a background image in OpenGL/GLFW?
I'm writing a simple 2D game with C++ and OpenGL/GLFW, and my current step is to create a menu. I finished with buttons, but I think it looks a little bit boring (with only 4 buttons and a black background).

I want to load an image (.jpg, .tga, .png, etc) to make a more beautiful menu, but I can't find out how. How can I do it?

# Answer
> 2 votes
After your glClear call you can render a full-screen quad with your texture (loaded like you would any other). You may want to disable writing to the depth buffer to avoid odd rendering issues.

---
Tags: opengl, c++, menu, glfw
---


title: MeshParts - Why do they exist?

text:
# Question
Title: MeshParts - Why do they exist?
For my current game I'm working on I've decided to implement a custom model class to store my models in. Reasons being is that I want to make adding new models as painless as possible for the rest of the team without needing to go through the XNA/Monogame content pipeline (Them having VS + Dev framework installed just to compile a few models, or passing them onto me to compile every time a change is made would just get tedious further on, not to mention different timezones when testing slowing things down)

To this end I've been looking at the model structure of different frameworks, XNA/Monogame, SharpDX and AssImp.NET being the main ones. The structure for XNA/MG and SharpDX is Model-\>MeshCollection-\>MeshPartCollection, whereas Assimp only has Scene-\>MeshCollection.

From previous experience in XNA, MeshParts seem kinda redundant. None of my meshes ever had more than one, and a lot of the XNA examples I've seen only ever had one mesh part per mesh.

From everything I've experienced and seen, MeshParts seem redundant, surplus to requirements and just makes for an extra level of complexity (Should I use a loop, or just hardcode it to use the first element in the collection?). Is there some useful aspect of them that I am not aware of, or a particular use case or scenario where they are actually useful?

# Answer
> 3 votes
Answer to your question can be found on Shawn Hargreaves Blog who was one of the XNA creators:

> Within a ModelMesh, each ModelMeshPart represents a single graphics card draw call. It contains a set of triangles that share the same material (stored in the ModelMeshPart.Effect property) and vertex declaration. For instance the ModelMesh for the body of our car might contain one ModelMeshPart for the painted car surface, one using an environment mapping effect for the reflective windscreen, and another using a normalmap texture for the snakeskin leather seats (I hasten to assure concerned readers that no snakes were harmed during the production of this blog post…)

the article about this hierarchy: http://blogs.msdn.com/b/shawnhar/archive/2006/11/20/models-meshes-parts-and-bones.aspx

# Answer
> 1 votes
MeshParts in XNA, SubMesh in Ogre or other similar entities usually serve the main purpose of applying multiple materials to the same 3D model, yet still dealing with it as a single higher level entity (Mesh). You can't assign different materials to different parts of the same mesh, without having multiple draw calls, hence separating the model to different parts.

---
Tags: 3d-meshes, data-structure
---


# Question
Title: Is it possible to calculate the TBN matrix in the fragment shader?
Just from model position, model normal and texture uv?

# Answer
Yes. There an article about this by Christian Schüler:
http://www.thetenthplanet.de/archives/1180
It's a followup to a book article (ShaderX 5) which did exactly what you need. I've used it myself.

Here is the part that you need: (p : world-space position, N : world-space normal)

```
mat3 cotangent_frame( vec3 N, vec3 p, vec2 uv )
{
    // get edge vectors of the pixel triangle
    vec3 dp1 = dFdx( p );
    vec3 dp2 = dFdy( p );
    vec2 duv1 = dFdx( uv );
    vec2 duv2 = dFdy( uv );

    // solve the linear system
    vec3 dp2perp = cross( dp2, N );
    vec3 dp1perp = cross( N, dp1 );
    vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;
    vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;

    // construct a scale-invariant frame
    float invmax = inversesqrt( max( dot(T,T), dot(B,B) ) );
    return mat3( T * invmax, B * invmax, N );
}

```
> 7 votes

---
Tags: textures, shaders, glsl, bump-map
---


# Question
Title: Android Canvas 2D Game: Supporting multiple screen sizes/resolutions
I'm planning to develop a 2D game for android devices by using simple Canvas Surfaces (I know that OpenGL might be more efficient - but Canvas should definitely be enough for my type of game).

I'm currently researching on how I should handle different **screen sizes/resolutions/ratios** of the different android devices. I don't think it's a big deal to *scale* a bitmap if the screen size is just 920x512 instead of 1920x1024 (for example) - but what about completely different ratios? Like 1200x800px screens? I would have to stretch these bitmaps, or just make more objects visible from my game, which would normally be hidden in shorter screens.

I didn't really find anything useful on my research (mainly some discussions about Canvas VS OpenGL...) - so I'm giving it a try here.
What's the best/most common used technique to adjust a game to different screen sizes? Other than just putting black borders along my game, if the width/height is too large.

# Answer
> 0 votes
If the aspect ratio remains constant, just scale the bitmaps. GUI elements might need some different handling though. For a more robust approach:

* Do your research into what resolutions are available for your target platforms and pick the most often used ones
* Create GUI configurations (ideally, purely visual rather than making more objects visible, etc) for the most common resolutions
* For a resolution that you do not support, find the resolution/aspect that's closest and programmatically generate a GUI configuration which resembles that.

---
Tags: 2d, android, html-canvas, screen
---


title: Dynamic Music Composition in FMOD

text:
# Question
Title: Dynamic Music Composition in FMOD
I would like to dynamically "build" a song in my game by adding/removing instrument layers. This is normally possible exporting each instrument layer as a separate track, but this method is not so efficient for memory (it's like having multiple songs). I've started to use FMOD recently, so I would like to know if there is a method to save a song with multiple instrument tracks, for example, in an internal format, so that I can manipulate which instrument is going to play by code.

EDIT: An example from my game: I have a character that can transform to different forms. Imagine that the player has an aggressive melee form: I want that the main theme changes accordingly with the current player form. In my example, when the player is in the melee form, I want to add an electric guitar. If I change to a "bird" form, it would be nice to have a marimba instead of the guitar. Note that the rest of the main theme remain exactly the same. I know that I can export different songs, each one tailored for each player form, but I was wondering if it is possible to do something "better". When you save a song as a project file, you have more information than the actual music. Take FMOD Designer, for example:

Here we have all the information about layers, instruments etc. so that is possible to mute an instrument, for example. What I want to achieve is to make one song, containing all the instruments(guitar,marimba in the example), so that I can mute/un-mute them by code. Is there a way to have such a format loaded by FMOD c++ API?

# Answer
Here is a video of how you can achieve multiple tracks using FMOD : https://www.youtube.com/watch?v=GZJrCF6DwF0, There is a long series of tutorials that should guide you further than that even. Hopefully you will find this useful.
> 1 votes

---
Tags: audio, fmod
---


title: How unity works on Web

text:
# Question
Title: How unity works on Web
How Unity can work on Web if the code is written in C#? I understand that you can compile the C# code to a shared library and use it in Java (for Android) in ObjectiveC (for iOS) to enable Unity on multiple platforms, but you cant use shared library on JS. Does Unity do language to language translation from C# to JS to enable Unity on Web?

As I understand now starting from Unity 5.0 it even doesn't use Unity Web Player.

# Answer
> 2 votes
Unity Web Player, as you probably know, is a browser plugin so it is allowed to run anyway it likes.

Unity 5 will export to WebGL, and the article you linked says they worked with Mozilla to bring that technology, so they are most likely using Emscripten which is a LLVM to Javascript compiler. Several languages can be compiled to LLVM (including C# and Unity Script) so the proccess would be something like C# to LLVM to Javascript.

Some of the things that not supported currently:

* Runtime generation of Substance textures
* MovieTextures
* Networking other then WWW class (a WebSockets plug-in is available)
* Support for WebCam and Microphone access
* Hardware cursor support
* Most of the non-basic audio features
* Script debugging
* Threads
* Any .NET features requiring dynamic code generation

You can read more about this technology on their blog.

# Answer
> 0 votes
From the link you pasted we can read:

> Helgason puts it this way: "We're coming into a world where some browsers will not support the \[Unity\] **plugin**, but some browsers will not support WebGL. Us having both means you can cover every browser."
>
> Unity has spent two years working closely with Mozilla to ready this technology, which is being demoed live at GDC in both Firefox and Google Chrome browsers.

So since there is just a plugin I see no reason to use JavaScript but I'm not sure how entirely Unity Web Player is done. Wikipedia says it's C# and C++.

The other fact is that translation of Java into JavaScript is rather popular in LibGdx and PlayN thanks to Google Web Toolkit so it's possible.

---
Tags: unity, web
---


# Question
Title: Is there a better way than to use render targets for a "glowing" effect?
I am making glyphs on a wall "glow", by changing how much of the overlay textures light intensity is blended into the diffuse map. The basic approach is to capture the diffuse map into a render target, and then `spritebatch.draw(additive)` the light intensity texture on top of it.

This worked great for smaller textures. Now I want to do the same for a larger scene that has massive texture maps. It doesn't make sense to capture all of that just to make some portions "glow".

Is there a better way than to use render targets for a "glowing" effect?

# Answer
> 1 votes
As Namek says, one way is to bind the overlay texture and do the adding yourself in the pixel shader.
Alternatively, re-render the geometry that contains the glyphs using additive blending and bind the overlay textures instead of the regular ones. Depth test should be enabled, depth writes should be off, and you would need to add a small depth bias to avoid z-fighting.

# Answer
> 1 votes
You could look at projecting your texture (decal) onto a surface.

Wolfire have a good blog post to get started on decal projection here.

---
Tags: textures, glow
---


title: Shader - Transmittance or Absorption

text:
# Question
Title: Shader - Transmittance or Absorption
I am trying to create a **transmittance** or **absorption shader** (glsl, hlsl, cg, etc...) in **realtime** but I don't find any good tutorial or white paper about this subject. I only find offline rendering references.

Is it possible to achieve this kind of effect in realtime using standard rasterisation of a 3D mesh ? How ?

# Answer
> 1 votes
You don't specify what rendering method you want to use. Standard rasterisation of a 3D mesh? Or do you have a volume representation of the model and your renderer uses that directly?

If you render a volume, check this:
http://http.developer.nvidia.com/GPUGems/gpugems\_ch39.html

especially 39.2.

The effect in the picture you provide is mainly **subsurface scattering**. Here's a shader for real-time rendering:
http://www.iryoku.com/screen-space-subsurface-scattering

---
Tags: opengl, shaders, directx, glsl, hlsl
---


# Question
Title: How to implement mouse based movement in an RPG? (Java)
I'm making a 2D rpg and I want the character to move with the mouse, ie the user clicks and then the character moves to that location. How do I accomplish this?

# Answer
> 0 votes
In my game I currently have this system in place. Unfortunately it is in c# and you might not be able to get what you are looking for. What I do is store the location of the player, and the location of the mouse click. When the first click to move happens, I have a boolean that is false until the character reaches the clicked location, or he happens to get stuck.

Keep in mind if you have other game objects, you will need to have a path finding method to check if you are attempting to walk into a collidable object, and have logic in place for your character to navigate around said collidable objects.

For an example of this, feel free to reference my 2D RPG thats a work in progress : https://github.com/shroeder/GameRPG/tree/LukesBranch/Game/Game. Look at the GlobalVariables class, and search for the PathFind method. It returns a boolean that tells the game class if the character has reached his destination or not, and also sets what direction he needs to move in order to navigate around a collidable object. From the game class(game1.cs) you search //character movement to see that it evaluates a GlobalVariables.Dir, which is an enum, to see if the method called in GlobalVariables has set the direction in which to move.

---
Tags: java, movement, rpg
---


# Question
Title: Finding next AI move using MinMax algorithm for Checkers
I am currently working on a Checkers game using Unity ( human vs computer ) I am done with the base architecture of the game ie defining the rules, moves, jumps etc.

I am currently stuck in implementation of MinMax for computer AI. I know how it works but I am confused on two things. Firstly, the heuristics ( I am using simple red checker count - black checker count ) but I am not sure if its correct. Secondly, outputting the final path of nodes for my AI to make its next turn.

Below is my MinMax implementation so far.

```
int MiniMax(TreeNode node)
    {
        int depth = 2;
        List<TreeNode> pathNodes = new List<TreeNode>();
        int final = MaxMove(node, depth, pathNodes);
        return final;
    }

int MaxMove(TreeNode currNode, int depth, List<TreeNode> pathNodes)
{
    if (depth == 0)
    {
        return currNode.getPriority();
    }
    else
    {
        depth--;
        int v = -10000;
        List<TreeNode> allPossRedMoveNodes = gameBoardScript.createNewRedBoardsFromCurrent(currNode.getCurrentBoard());
        foreach (TreeNode RedNode in allPossRedMoveNodes)
        {
            int v1 = MinMove(RedNode, depth,pathNodes);
            if(v1 > v)
            {
                v = v1;
            }
        }
        return v;
    }
}

int MinMove(TreeNode currNode, int depth, List<TreeNode> pathNodes)
{
    if (depth == 0)
    {
        return currNode.getPriority();
    }
    else
    {
        depth--;
        int v = 10000;
        List<TreeNode> allPossBlackMoveNodes = gameBoardScript.createNewBlackBoardsFromCurrent(currNode.getCurrentBoard());

        foreach (TreeNode BlackNode in allPossBlackMoveNodes)
        {
            int v1 = MaxMove(BlackNode, depth,pathNodes);
            if (v1 < v)
            {
                v = v1;
            }
        }
        return v;
    }
}

```

Max in this case would be Black Checkers ( Computer AI ) and Min is Red Checker, the human player

Let me briefly explain what I am trying to do with my code above. I have a TreeNode structure that stores the GameBoard, next possible move and also the Heuristic value

In My Max Move, I get all the possible Red Move Nodes from the current board. Logic for finding all possible moves is working absolutely fine. And for my Min Move which would be the human player, I get all its possible black nodes.

I am currently testing the code with depths 2 to 3 for my game tree. Please correct me if my current implementation is wrong. And finally how or where do I trace the final path of all my final Tree Nodes based on Min and Max values generated and get the next move for the Black Checker?

# Answer
> 1 votes
The usual implementation for this is to have only a MaxMove function, and negate the value returned.

You only need to remember the top level move, although remembering the path to the move that constitutes the principal variation can be helpful to understand the result, you only need to make the best move and re-run the search from the new position after the opponent responds.

---
Tags: unity, algorithm, ai, board-game
---


# Question
Title: How to manipulate browser pixels on different mobile devices
I'm creating a board game using HTML5, CSS3 and JavaScript. It's working fine on Desktop browsers properly. But when i load it on Windows phone it's not behaving properly. The resolutions and the game board are not matching. I'm targeting **Windows and Android platform**.

Game Board is **1050x650 px** which is implemented using **HTML and css3**. now what i want to know is most browsers don't support certain CSS3 features like **rotations and key-frames animations** so will it be better if i use photoshop to make the board for different resolutions or is it possible to do the same as i did using HTML5 and CSS3.

And in the above image, let's say distance between B and a red dot is 200px and i use JS to manipulate the movement of B from one point(red dot) to another point(red dot), now will the distance 200px be the same in all the devices? If not how to write a proper code to manipulate the movement in all mobile devices?

# Answer
If you'd like your game board to appear sharp, with lines of 1px width, at different resolutions, then you may be better off drawing your game board in the SVG vector format, using a tool like Inkscape or Illustrator.

SVG files do have a nominal pixel resolution, as defined by the viewBox attribute of the SVG tag. This makes calculation of the positions of the dots and lines easier when creating the SVG. However, the SVG file can then be scaled using CSS e.g. to 100% of the body width, with no loss of sharpness.

Additionally, because SVG is an XML format, the elements within an SVG definition can be animated using CSS if required. Better still, the animations can be specified using the nominal pixel dimensions of the SVG file. So, your "B" element could be defined in SVG, and if the horizontal distance between the red dots is a nominal 200px, then your animations can be defined in terms of this distance. The CSS scaling will then also apply to the animation automatically.

Have a look at http://css-tricks.com/animating-svg-css/, particularly at the translateY animation of the dinosaur(!) which is defined in nominal SVG pixels. I can confirm that, if I use CSS to scale the SVG e.g. to 50% of its original width, then not only is the dinosaur 50% smaller, but it also moves 50% as far.
> 1 votes

---
Tags: game-design, javascript, html5, mobile, css
---


# Question
Title: In OpenGL, what is "zero state" rendering?
Recently at a job interview, I mentioned that I taught myself modern OpenGL and rendering with vertex buffer objects because my university only taught the fixed function pipeline with immediate mode rendering at the time. The interviewer briefly interrupted me to say that VBOs have effectively been replaced by something called "zero state rendering" and then let me continue.

I forgot to ask later on about what that meant, because we quickly moved onto different subjects and the interviewer had run out of time at the end due to a busy schedule.

Later, I searched online for "OpenGL zero state" and "zero state rendering" with no results that seemed relevant, mostly just things about the OpenGL state.

The organization in question is very heavily research based, so is there a chance that it is an extension with currently little support, or that the terminology used varies due to it's cutting edge nature?

# Answer
> 9 votes
Your interviewer was talking, with his own words, about *bindless* API. nVidia made nice presentations recently about all that, which they call *direct state access* (, ). This does not replace VBOs.

---

*EDIT*: Actually, let's consider Trevor Powell's suggestion:

This seems like some people could definitely decide to drop VBOs, in favor of attribute-less rendering, using geometry shaders fetching uniform data or textures, as mentioned in this article.

I can see how somebody could decide to switch one's engine to full attirubte-less, but I would not condone such a move if I was in the team: The reason—if you read this overview of the pipeline carefully—is that with attribute-less, the vertex FIFO cache becomes unusable as it's skipped altogether. Attribute-less hence removes a nice optimization opportunity.

This needs benchmarking of course, but purely a-priori, it sounds like a bad idea for a generic, all purpose solution.

---
Tags: opengl, rendering, graphics-programming, terminology
---


title: Dealing with multiple scenes /levels

text:
# Question
Title: Dealing with multiple scenes /levels
**Overview**

I have a scene manager in my game and in each 'Scene' I have a render() and a update() method for drawing and updating my game's logic.

Basically, when I want to switch to another scene, let's say, when the player progresses to the next level or going from game-over back to the main menu, I just do something like this:

```
SceneManager.getInstance().setCurrentScene(level2); //Where level 2 is a 'Scene' class.

```

I have a 'MainGame' scene who's sole purpose is to house all the methods I call from my individual levels. So I might then do something like this:

**Current method**

```
public class Level1 extends MainGame implements Scene {

    private Resources res;
    private MyGLRenderer r;

    Level1(MyGLRenderer r, Resources res){
        super(r, res);
        this.res = res;
        this.r = r;
    }

    @Override
    public void render() {
        draw(background);
        draw(playerSprite);
        draw(blue-enemies);
    }

    @Override
    public void update(){
        super.movePlayer();
        super.moveEnemies();
        super.checkCollision();
    }

}

```

However, in my game, when the player survives for a certain amount of time, I want to introduce more elements into the game, so I might then have a 'level2' Scene (although strictly, from the player's perspective, the game is perceived to be one big rolling level).....

```
    public class Level2 extends MainGame implements Scene {

        private Resources res;
        private MyGLRenderer r;

    Level2(MyGLRenderer r, Resources res){

        super(r, res);
        this.res = res;
        this.r = r;
    }

    @Override
    public void render() {
        draw(background);
        draw(playerSprite);
        draw(blue-enemies);
        draw(pink-enemies);  //New!!!! *********************************
    }

    @Override
    public void update(){

        super.movePlayer();
        super.moveEnemies();
        super.checkCollision();
    }

}

```

So, as you can see, Level2 is exactly the same as Leve1 but now I'm also drawing my 'pink-enemies', I can keep doing this for 'levels' 3 through 10 but I'll end up *duplicating* and simply adding to each level each time. Seems like a lot of effort just to introduce 1 or 2 new things every 'level'.

**Using conditions within my render / logic?**

Is there a cleaner / tidier way of achieving that which I'm trying to achieve? I could do away with all my individual 'Level' classes altogether and just work straight out my MainGame class's Render() and Update() methods, but then I would have to have something like:

```
Render(){

    //Render elements common to all levels
    draw(background);
    draw(playerSprite);
    draw(blue-enemies);

    //Render specific level objects

    Switch (Level){

        case 4:{draw(giantAlienSpaceship);}
        case 3:{draw(orange-enemies);}
        case 2:{draw(pinkEnemies);break;}
    }
}

```

And then a similar **switch** in my logic. I'm not sure about this however, as it adds additional switch/conditional statements in my rendering and seems somewhat 'amateur' however, I could be completely wrong and this may be an acceptable method that people do use.

Am I missing any other obvious cleaner / cleverer way to do this (similar to my first method but without the duplicated super method calls)

# Answer
Before addressing the specifics of your question, I do want to point out that I disagree with your approach to your inheritance model.

A `Game` generally does not implement a `Scene` but instead a `Game` consists of one or more active `Scene`s that are being rendered and updated in a main loop. It's important to think about whether a class relationship can be described as *has-a* versus *is-a*. In the former, it implies composition and therefore a property/variable of the class. In the latter, it implies inheritance.

Therefore as I said, a game has a list of active scenes so the code might look like:

```
 public class Game {
   List<Scene> activeScenes;
   public void mainLoop() {
     while(!shutdown) {
       for(Scene scene : activeScenes) {
         scene.update(deltaTime);
       }
       for(Scene scene : activeScenes) {
         scene.draw(renderer);
       }
     }
   }
 }

```

What's important here is that you have a solid basis for core game logic that is independent of what your scene logic may be. This class could hold a list of active rendered game objects, it might hold a reference to your camera, graphics context, etc.

Now your `Scene` class looks somewhat like what you've described.

```
 public interface Scene {
   void load(Game game);
   void unload(Game game);
   void update(float deltaTime);
   void draw(MyGLRenderer renderer);
 }

```

If you build off what ratchet said, your `Scene` essentially has a list of `GameObject` instances that represent your various enemies and get instantiated when the scene is loaded. As a scene gets updated, any enemy logic can be updated and during draw you actually render each one. During the unload, you free any resources for each `GameObject` associated with the level.

Not only does this give you good separation of concerns and responsibility, but it also opens the door for having multiple active scenes that are contributing to the same rendered view; such as when you pause the game and render the main menu or as you want to introduce a complex scenario into a level randomly :p.

If you now use the term `State` rather than the term `Scene`; you'll notice this is precisely the State design pattern and is often implemented in most game engines in some variant providing precisely this kinda functionality.
> 4 votes

# Answer
why not create a list of enemies in the level so the draw becomes:

```
List<GenericEnemy> enemies;//filled during construction
Render(){
    //Render elements common to all levels
    draw(background);
    draw(playerSprite);
    for(GenericEnemy enemy : enemies) {
        draw(enemy);
    }
}

```

where `GenericEnemy` is a superclass of all enemy types, then you only need one Scene class
> 3 votes

---
Tags: java, android, scene-graph
---


title: How to make a scrollbar?

text:
# Question
Title: How to make a scrollbar?
I am making my own UI for my game, no libraries used, basic UI with simple controls and I am almost done. Now, let's say I need to display lots of information, controls or items which obviously won't fit in the screen space. I must use a scroll bar to achieve this task. But how does one make a scroll bar?

I just don't understand how to do it. The concept for vertical and horizontal scrollbars is the same. Virtually there is a huge plain with data, but we can only display cut of it all in a such by such screen space. We use scrollbars to move that viewable rectangle across our giant plain. The scrollbar itself is a displayed line/texture/sprite on the side of the screen which has a button inside that we can interact with by moving it across the scrollbar. The button is dynamic, its size is relative to total item count and possible item count that can be shown in given space. Our button shrinks when there are more items added, expands when items are getting removed and the whole scrollbar disappears when all the items can be successfully displayed at once.

I can't seem to find online tutorials on this matter. Perhaps it's so basic for everyone except me? Still can't wrap my head around it...

# Answer
> 7 votes
Let's call the content you want to scroll `content` and the viewable area of that content `viewPort`. Your `scrollbar`s will be at the sides of the `viewport`.

The first step is to create a mask such that only parts within `content` which intersect with `viewPort` are visible. I can't answer exactly how to do this because it depends on your language and technologies. Search for something like 'graphics masking in your language'.

The next part is to link the scrollbar's position with the position of `content`. For a vertical scrollbar, as `scrollbar.grip.y` increases, `content.y` should decrease, and vice versa. The following code should set the correct position of `content`:

```
content.x = -(horizontalScrollbar.grip.y / horizontalScrollbar.width) * content.width;
content.y = -(verticalScrollbar.grip.y / verticalScrollbar.height) * content.height;

```

You would run this code whenever the scrollbar positions change. Also, you would need to set the sizes of each scrollbar's 'grip' (the button the user can drag to scroll):

```
horizontalScrollbar.grip.width = viewPort.width / content.width * horizontalScrollbar.width;
verticalScrollbar.grip.height = viewPort.height / content.height * verticalScrollbar.height;

```

As well as limit their positions to the scrollbar 'track':

```
if (horizontalScrollbar.x > horizontalScrollbar.width - horizontalScrollbar) {
    horizontalScrollbar.x = horizontalScrollbar.width - horizontalScrollbar;
}
if (verticalScrollbar.y > verticalScrollbar.height - verticalScrollbar) {
    verticalScrollbar.y = verticalScrollbar.height - verticalScrollbar;
}

```

# Answer
> 3 votes
A scroll bar is like a 2D camera control that controls the scroll area's viewport's contents. I will assume you know how to render your gui in its entirety. I also strongly advice against making a gui that is complex unless it truly contributes to ux. This could lead to a mediocre gaming experience. I also strongly urge you to use a UI library.

In abstract high level pseudo code:

1. Initialization:
    1. Define the scrollable area's width and height.
    2. Define the viewport's width and height.
    3. The "handle" is the same % of the scrollbar as the viewport is of the scrollable plain.
        * The "handle" is the rectangle that travels up and down a vertical scrollbar.

Example: The scrollable area's height is `1000 pixels` and the viewport's height is `200 pixels` so the "handle" will be 20% of the scrollbar's height, if the scrollbar has the same height as the viewport than the handle will be `40 pixels` high.

2. Main loop:

1. Render the entire scrollable area (if it's not gigantic).
        * Otherwise you need to smartly render only elements close the current position of the viewable area.
    2. The "handle" has an upper and lower bounds in % of the scrollbar.
    3. Blit the relevant rectangle with the same upper and lower % of the scrollable area.
    4. Place the result inside the viewport.
3. Accepting input:

1. When a user clicks in the scrollable area's viewport, consider the "handle's" upper bound.
    2. Adjust the click to a position % of the scrollable's area pixels lower based on upper bound.
4. Dragging the scrollbar's "handle":

1. Detect a mouseDown event that occurs on the scrollbar.
        * If the event occured on the handle:
            1. Remember the position.
            2. Adjust the handle and viewport with the correct offset from that position until the mouseUp event occurs.
        * If the event occurs on the scrollbar but not on the "handle":
            1. Adjust the "handle" so it's centered on that position.

The explanation is based on a vertical scrollbar but the same applies to a horizontal bar.

---
Tags: gui, ui-design, scrolling
---


title: Draw Primitives with Unity 2D

text:
# Question
Title: Draw Primitives with Unity 2D
I would like to be able to draw primitives in unity 2d to define my game objects. I have tried the following example:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Material mat;
    private Vector3 startVertex;
    private Vector3 mousePos;
    void Update() {
        mousePos = Input.mousePosition;
        if (Input.GetKeyDown(KeyCode.Space))
            startVertex = new Vector3(mousePos.x / Screen.width, mousePos.y / Screen.height, 0);

    }
    void OnPostRender() {
        if (!mat) {
            Debug.LogError("Please Assign a material on the inspector");
            return;
        }
        GL.PushMatrix();
        mat.SetPass(0);
        GL.LoadOrtho();
        GL.Begin(GL.LINES);
        GL.Color(Color.red);
        GL.Vertex(startVertex);
        GL.Vertex(new Vector3(mousePos.x / Screen.width, mousePos.y / Screen.height, 0));
        GL.End();
        GL.PopMatrix();
    }
    void Example() {
        startVertex = new Vector3(0, 0, 0);
    }
}

```

However I cannot find information on setting the Materical element of a game object anywhere. I am trying to create a simple 2d game using GL to draw the sprites instead of textures. My questions are:

* What is the material object reference used for and is this required for unity 2d games?
* Is using GL the easiest way to draw primitives in unity?

# Answer
Aras Pranckevičius explained this issue, more clearly than I am able to, in a post on the Unity Forums:

> GL immediate drawing functions use whatever is the "current material" set up right now. The material controls how the rendering is done (blending, textures, etc.) So unless you explicitly set it to something before using GL draw functions, the material can happen to be anything. Also, if you call any other drawing commands from inside GL drawing code, they can set material to something else, so it's not good to mix them.

Your `mat` variable is just a public field so you could:

1. Assign a value using the inspector.
2. Load one of the standard materials e.g.

`mat = new Material(Shader.Find("Diffuse"));`
3. Define a custom Shader in code (Aras' example).

```
using UnityEngine;
using System.Collections;

public class LineSample : MonoBehaviour {

    static Material lineMaterial;

    private static void CreateLineMaterial() {
        if( !lineMaterial ) {
            lineMaterial = new Material( "Shader \"Lines/Colored Blended\" {" +
                "SubShader { Pass { " +
                "    Blend SrcAlpha OneMinusSrcAlpha " +
                "    ZWrite Off Cull Off Fog { Mode Off } " +
                "    BindChannels {" +
                "      Bind \"vertex\", vertex Bind \"color\", color }" +
                "} } }" );
            lineMaterial.hideFlags = HideFlags.HideAndDontSave;
            lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave;
        }
    }

    public void OnPostRender() {
        CreateLineMaterial();
        lineMaterial.SetPass( 0 );
        GL.Begin( GL.LINES );
        GL.Color( new Color(1f, 1f ,1f ,0.5f) );
        GL.Vertex3( 0, 0, 0 );
        GL.Vertex3( 1, 0, 0 );
        GL.Vertex3( 0, 1, 0 );
        GL.Vertex3( 1, 1, 0 );
        GL.Color( new Color(0f, 0f, 0f, 0.5f) );
        GL.Vertex3( 0, 0, 0 );
        GL.Vertex3( 0, 1, 0 );
        GL.Vertex3( 1, 0, 0 );
        GL.Vertex3( 1, 1, 0 );
        GL.End();
    }
}

```

Once you have a material defined calling `SetPass()` assigns it as current.

---

If familiar with OpenGL Immediate Mode this approach is pretty straight forward, but if you later decide that you would like to texture your primitives I would recommend using a MeshRenderer with a custom mesh. Morten Nobel has published a tutorial on using this approach with 3D meshes his blog. The same approach can be used create a plane of arbitrary shape.
> 1 votes

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


title: Maximum sensible audio sample rate

text:
# Question
Title: Maximum sensible audio sample rate
I work as a multi-purpose engineer/developer at a very small startup game company. Recently, I've been asked to help out with audio development and editing, and I've been mostly able to hold my own.

I'm unfamiliar with sample rates though: I understand what they are, and I know 44100 Hz is considered a safe default because it's CD Quality.

However: **Is there a practical max sample rate above which the human ear can no longer hear an improvement?** In graphics, we have a guideline that humans cannot tell the difference above 60 frames of animation per second (although some people are starting to say 75-90 Hz, I think). Is there a similar upper limit in audio development?

# Answer
> 5 votes
The ear is analog. So there's no defined sampling rate (a digital restriction) that would match best with what humans hear. The typical approach here is empirical testing. Luckily, most of that work has been done already, and you can just pick one of the higher standard sampling rates. (It's best to pick one of the standard rates, since most hardware is configured for those rates).

Wikipedia lists some of those standards:

> * **88,200 Hz**
>
> Sampling rate used by some professional recording equipment when the destination is CD (multiples of 44,100 Hz). Some pro audio gear uses (or is able to select) 88.2 kHz sampling, including mixers, EQs, compressors, reverb, crossovers and recording devices.
> * **96,000 Hz**
>
> DVD-Audio, some LPCM DVD tracks, BD-ROM (Blu-ray Disc) audio tracks, HD DVD (High-Definition DVD) audio tracks. Some professional recording and production gear is able to select 96 kHz sampling. This sampling frequency is twice the 48 kHz standard commonly used with audio on professional equipment.
> * **176,400 Hz**
>
> Sampling rate used by HDCD recorders and other professional applications for CD production.
> * **192,000 Hz**
>
> DVD-Audio, some LPCM DVD tracks, BD-ROM (Blu-ray Disc) audio tracks, and HD DVD (High-Definition DVD) audio tracks, High-Definition audio recording devices and audio editing software. This sampling frequency is four times the 48 kHz standard commonly used with audio on professional video equipment.

Clearly you could just pick the highest frequency you can get. But there are other considerations. Primarily, the hardware being used to playback the audio. Typical configurations for PCs are usually around 96 kHz. The most common sound card out there is the Realtek HD Audio and its manual lists its typical rates:

> 44.1KHz: This is recommend while playing CD
>
> 48KHz: This is recommended while playing DVD or Dolby.
>
> 96KHz: This is recommended while playing DVD-Audio.

As with many things in software (and "IRL"), it's a balancing act. If your game has audio as a primary features, you'll want to include high quality sound but you may want to keep the storage requirements low too. The production of higher quality sound is also typically more expensive, with higher equipment cost and more processing times.

In my opinion, 96,000 Hz is enough.

# Answer
> 13 votes
The audible frequency range (pitch) for humans is usually considered to be 20 to 20,000 Hz https://en.wikipedia.org/wiki/Hearing\_range

Because of a phenomenon known as the Nyquist limit, you must sample at a rate at least double the frequency of the signal you want to reproduce. Note 44100 is double 22050 or slightly above the top of the human hearing range. If you don't care about high frequencies you can sample at a lower rate. You primarily see this in audio codecs not targeting music, like Speex. https://en.wikipedia.org/wiki/Nyquist\_frequency

It isn't like graphics frame rates it is more like compressing images, fewer samples means there is less data available to reconstruct the image\sound wave. With lower sample rates you get what amounts to dithering in overly compressed images. Sampling below the Nyquist limit of a particular sound more or less means that sound is lost. Sampling above the Nyquist limit means the sound is reproduced more accurately. Lowering the sample rate impacts treble before bass, so if your high notes aren't crisp and clean sounding raising the sample rate may help.

# Answer
> 3 votes
As with graphics, it really depends on the content. You can use a 8kHz sample rate for certain sounds (for example a voice over a 2-way radio) and the quality will be indistinguishable from the same so d using a 48kHz sample rate.

Another important question is what your target audience and platform is. If you are targeting an iPhone, you won't want to use a super high quality sample rate, because the hardware will not necessarily profit from it. Additionally if you are playing a Facebook game, you'll want a smaller footprint and a lower sample rate would help reduce the audio footprint.

Modern AAA video games don't use anything higher than 48kHz, because of application size and hardware constraints. The native sample rate for most Android devices is 44.1 kHz, and I believe iOS devices are the same. For Windows it is 44.1 kHz (or 48kHz depending sound card).

It is important to note, on Windows, that while the sound card may support 96 kHz, you can only use the sample rate the system has configured.

# Answer
> 3 votes
The answer you've selected is the least accurate of the bunch, but there's a lot of information missing in the other 3 as well. The question has 4 contexts:

1. Playback perception. As has been mentioned, 44.1khz is more than enough for human hearing. However, there is some evidence that higher samplerates may not be consciously perceived but nevertheless affect subconscious perception of listening as is demonstrated in this study. It is generally acknowledged that the conscious difference between 16bit and 24-bit audio is more noticeable than between 44.1khz and 96khz audio.
2. Recording. In this field many (mainly lower-quality) ADC's (analog-digital convertors) do a better job when recording at higher samplerates than 44.1khz due to poor filtering. However in most professional-grade (ie. non-prosumer) solutions high-end ADC's the difference is minimalised. Despite this many professionals choose to record at 48khz or 96khz due to the final two scenarios below.
3. Processing. In the field of DSP's and audio plugins, aliasing means that a lower samplerate is likely to contain more artifacts. However in a well-designed plugin, a developer can shift the audible aliasing above the human hearing threshold ie. above 22khz, if the samplerate is 60khz or above.
4. Output device/format. As noted, CDs use 44.1khz, games use 44.1 or 48khz, DVDs generally use 48khz but can use 96khz (but almost never do), DVDa and high-audio formats use 96khz or 192khz respectively. But there is no reason to record/process at 44.1khz just because your end-format is 44.1khz, and in fact you almost always should not do so due to the reasons above. Resampling algorithms have come a long, long way from the 1990's and a downsample from 96khz to 44.1khz creates zero audible artifacting, certainly a lot less than recording and processing at 44.1khz will create. However if aiming for a higher-samplerate end-format, it's ideal to record and process at the end-format samplerate, where possible. Again, upsampling is not so problematic nowadays either.

This is stuff I understand both intellectually and perceive subjectively from having run a music studio, doing sound for various formats and platforms, including games, for the past 10 years. Cheers-

# Answer
> 2 votes
I used to work for a games company in audio and produced tools/engines for audio work. Basically the sound engineer would choose a sample rate for each sample (or more likely, group of samples). Generally:

* High Quality (44100, 48000) for music
* Medium Quality (22050) for sound effects
* Low Quality (11025) for speech

As with everything, *it all depends*.

If you've got 80GBytes of audio data and only 2 or 3 GBytes to fit it into, you're going to do a number of things:

1. reduce sampling rate until you feel it sounds ok at that point, but worse any lower.
2. reduce the number of channels to mono unless it's music.
3. use some compression technique - this depends on the platform.

Each platforms has its own compression tools - so I wrote a tool that did sample rate conversion and the appropriate compression, so you could have one set of master assets with several output targets. Some platforms have a hardware decompressor, so you can take advantage of those avoiding a hit on the game processor.

When I first joined, the sound engineers complained it took weeks to get sound into a game before they could hear the results of their changes; with the tool I wrote (which could preview the sound after processing), it got down to hours instead.

Another thing I got working was in game level mixing. The game had a means to show audio channel settings that could be overridden while the game is running and let a sound design tweak the levels in situ. I seem to remember there are YouTube videos of others doing this. Sadly I don't have the ones I had for my implementation.

# Answer
> 1 votes
A few other things to consider as well.

* Samples can often be mono, but they will often be played back from a "world position" relative to the listener. This will give the sample its position (or pan) in the stero/surround sound stage.
* Realistically, human hearing is about 20hz (ish) to about 20khz (ish). Below ~50hz we start to feel more than we can hear. The top end decreases with age.
* This is why CD audio is sampled at 44khz, as the Nyquist Frequency will be 22khz for CD's. You can use that rule to work out the sample rate you have to use depending on the upper frequencies of your samples. You can often get away with lower sample rates if the content does not contain any high frequency content (or content you don't mind losing)

To answer your actual question, it's more about the device you use to play the audio back (and the room you're in!), than the format or quality you record it at. Amplifiers and DA/AD converters have got a lot better, and cheaper, but you're still going to struggle to find consumer headphones or speakers that will accurately reproduce content below 50hz, even with a subwoofer. Consumer audio hardware is often "hyped" towards the upper midrange as well, at the expense of actual midrange reproduction accuracy and even with expensive monitors, lack of room treatment will also considerably colour the reproduced audio.

Most people are going to be hard pressed to hear the difference between 96 and 44khz, much like most people cant tell the difference between 128 and 192kbps mp3's purely due to their playback hardware ;)

---
Tags: audio
---


# Question
Title: How can I use CCClippingNode to trim the top and bottom from a CCTableView?
I'm fairly new to Cocos2d and struggling with sizing a `CCTableView`. How can its height be controlled so that I have space at the top and the bottom?

I'm trying to visually wrap the top and bottom of my table view with a sprite, to provide the look and feel of a frame. But when I touch the table view, to scroll it up or down, it occupies most of the screen vertically. I thought the `contentSize` would alter where each cell appears and disappears from the top and bottom, but changing it had no effect.

Having had a Google about, I'm reading that I have to use a Clipping Node with a Stencil? Coming from UIkit, this seems like a bit of a faff. Would anyone like to hazard at a tutorial, bit of code with a simple `CCTableView` representation, sat in the middle of the scene where each cell appears and disappears under a content frame?

# Answer
> 1 votes
I ended up altering the contentSize of the CCTableView.

So,

```
someTableView.contentSize = CGSizeMake(200, 300);

```

...and then I placed a CCSprite over it with a hole in the middle that had transparency. This way, the table view was clipped how I wanted it clipped. I added the tableView to my scene with a lower z-order than that of the sprite. Did not need the complexity of what I was describing above.

---
Tags: ios, cocos2d, viewport, clipping
---


# Question
Title: Can someone provide a practical example of decoupling game world updates from frame redraws in iOS?
Please bear with me as I've been spending some time lately trying to get a better grasp of some game dev fundamentals. My specific issue is a direct result of trying to apply what I've read about here: When should I use a fixed or variable time step?

I understand that a common option is to write your game framerate-dependent and be done with it. However, once you mix in `SKAction`'s or physics bodies, this seems like a good way for things to get out of sync. For example, one scenario I can think of is something like an endless runner where the earth is moving beneath you at a steady rate (`.position.x -= someDistance`) mixed with other objects whose positions are updated with a `[SKAction moveTo: duration:]`, or physics bodies whose positions are updated by applying a force/impulse.

So it makes sense to me that the solution to this problem is to decouple game world updates from frame redraws. This means *not* using `[SKScene update:]` for world updates and instead coming up with your own game loop.

So I guess my question is twofold. Am I on the right track or am I off-base with any of my assumptions? Does Sprite Kit have a game loop set up outside of `[SKScene update:]` that is redraw independent, and whose resolution I can specify, that I can leverage? `NSTimer` has turned out to be way too inaccurate in my tests. Specifically a practical example would be great.

# Answer
I spend a bit more time on this and I do think I was making a few wrong assumptions. First of all, I think one big mistake was in thinking that I should avoid `[SKScene update:]` for framerate-independence. But since iOS devices are vsync'ed, and the update method is coupled to screen redraws, I can reliably expect that that method will fire every 1/60th of a second (60fps) at best, and when performance degrades, it'll step down in discrete increments. That is: 30fps (60/2), then 20fps (60/3), then 15fps (60/4), etc. This is because if load is too much that an updated frame 1/60th of a second later is not ready - whatever was drawn last is repeated - the next opportunity to draw an update only comes 1/60th of a second after that and so on.

So what this tells me is that I should always be able to figure out the number of frames I need to catch up to. My understanding now is that this is what an accumulator does. Anyhow, here's the code more or less:

```
var lastTime: CFTimeInterval = 0.0
override func update(currentTime: CFTimeInterval) {

    if (lastTime == 0.0) { lastTime = currentTime }

    var accumulatedFrames = round((currentTime - lastTime) * 60.0) // assume updates at 60hz and catch up if we drop below that

    lastTime = currentTime // for the next update

    // update the world as many times needed to "catch up"
    while (accumulatedFrames > 0) {
        updateMyWorld()
        accumulatedFrames--
    }
}

```

It appears to be working well but I would love if someone could confirm my approach.
> 0 votes

---
Tags: ios, game-loop, spritekit
---


# Question
Title: How should I collect user behavior data in an MMO?
In an MMO, and I'm trying to collect data about user behaviors for the purpose of tweaking the game rules to achieve maximum user satisfaction.

Clearly one way to do it is to hand-roll specific things into an application, much like one might use `Console.WriteLine()` to view the contents of a variable, or the `StopWatch()` class to see how long something takes to execute. But you can use a profiler in lieu of StopWatch, and you can use a debugger in lieu of WriteLine.

How should I collect my data? Are there generalized techniques for instrumenting an application to observe user behavior, or some form of code instrumentation technique?

Also, I'm only interested in collection techniques; you can assume that I already know how to transmit, store and analyze said data.

# Answer
We are using *Command Oriented Interface/Architecture* to audit user activity.

It means that requests to the server, cause the server side to instantiate instances of classes that represent commands (atomic actions the user can preform).

For instance, lets say the user makes a purchase in an item store:

```
//We could have done something like
someShop.sell(item, player); // This function deducts money from the player
                             // and stores the new item in their inventory

//Instead we do this:
$buyItemCmd = new BuyItemCommand(item); // The player is already known from the sessionId
$cmdExecuter.run($buyItemCmd);

```

Now we add logging / auditing features in the `cmdExecuter` that apply to all commands. This way there is little to no code duplication and we can turn off auditing, either by re-configuring a specific command class constants and / or modifying the cmdExecuter.

It helps to keep things organize. We currently create a database record for each "important" command. This helps track behavior that is interesting to us.

**Further Reading**
Command-Oriented Inteface by Martin Fowler
> 14 votes

# Answer
The "technique" is here is so simple that it almost doesn't deserve to be called as such: you just record the data from game systems you think are relevant.

*How* you record that data (to a database, to files, whatever) is too broad to discuss here (and the techniques and patterns are not particularly game-development specific in any case, making them better suited for discussion on SO), as is the question of *which* systems are relevant. There are no clever automatic techniques to answer those questions; that would be quite the feat of artificial intelligence.

The thing you want to make sure of with a game where there is a server component is that the *server* should do all the logging it can. Nothing you get from the client can be trusted, and especially if you're going to be using this data to tailor changes to the game you don't want players to be able to tamper with it.

The client should only record and transmit statistics that the server wouldn't normally have access too. For example of you want to record UI click heat maps, that's probably only feasible on the client.
> 7 votes

# Answer
In an MMO you already have data about where the user is going, which quests he takes and what equipment he uses sent to the server.

Other data you may be interested in is how they use the various guis, how long they keep stat and inventory screens open. You can for example record the number of times a feature has been activated with the mouse vs. the keyboard.

One important factor is to allow the user to opt-out (or make the collection opt-in) of the (non-critical) data collection to comply with privacy regulations. And to allow the server to decide what data should be recorded during the game session/next hour to spare your players some bandwidth.
> 2 votes

---
Tags: mmo
---


title: How to make text hyperlink in AndEngine

text:
# Question
Title: How to make text hyperlink in AndEngine
Currently to open the link i am using button sprite. But now i want to link a text to website. Is there any way to do this in AndEngine?

# Answer
Make the link clickable and then go to url using intent.

```
      Text link = new Text(100, 100, this.mFont, "Link", this.getVertexBufferObjectManager()){

            @Override
    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
          switch(pSceneTouchEvent.getAction()) {
          case TouchEvent.ACTION_DOWN:
               Intent i = new Intent(Intent.ACTION_VIEW);
               i.setData(Uri.parse("http://www.google.com"));
               startActivity(i);
                  break;
          }
                        return true;
        }
            };

```
> 1 votes

---
Tags: andengine
---


title: Prototype experience: Unity3D vs UDK

text:
# Question
Title: Prototype experience: Unity3D vs UDK
Has anyone yet prototyped a game in **both** Unity3D and UDK?

If so, which features made prototyping the game easier or more difficult in each toolkit?

Was one prototype demonstrably better than the other (given the same starting assets)?

I'm looking for specific answers with regard to using the toolkit features, not a comparison of available features. E.g. Destructable terrain is easier in toolkit X for reasons Y and Z.

I can code, so the limitations of the inbuilt scripting languages are not a problem.

# Answer
I set up a simple platformer prototype for iOS with both UDK and Unity from having zero experience with either.

The tools for Unity are a lot more intuitive all around, and because of this I was a lot more productive.

The existing classes for use in Unity and the overall component-based structure is a lot more consistent than UDKs, where it's very difficult to know the exact responsibilities each object has and which objects it communicates with, without doing research or digging through the code.

The fact that I could make changes even while the Unity game was running was nice.

UDK did have a iOS controller, where you could send inputs to your Windows PC from your iPhone or iPad - Unity did have this but it was mac only.

I didn't use the same assets for both prototypes (I used assets that came with the development kits), but neither prototype was demonstrably better than the other, they were virtually identical.
> 8 votes

# Answer
Udk is based on a shooter for that engine to prototype that type of game is better.

But Unity is very intuitive and easy to work with and also has a store with a lot of tools at low price for various tasks. A very useful tools within Unity for prototyping are Action Box and Prototype. It is also essential to use the snap (sortcut: Ctrl) and snap polygon (sortcut: v) to place the blocks precisely

Good luck!
> 0 votes

---
Tags: unity, udk
---


title: How to measure skill in a pinball game?

text:
# Question
Title: How to measure skill in a pinball game?
I am trying to come up with a system to measure or estimate the skill of a player at a single player game (so no head-to-head rating system help here). Specifically, it is a pinball game, but I do believe it is similar to most point-based single player games.

I have thought of 3 approaches:

* total points scored with a threshold for each skill level
* average points scored over all time
* average points scored over last X games

All of them use points, which I think is probably the right metric: anything a player does in pinball grant points, with the most difficult objectives worth more points. Points also take into account all of the rare combination of objectives (like score multiplier + multiball) that would be hard to track manually.

However, I am not sure which approach to use and I bet other games have implemented similar skill-measuring system that I can use as a guide, so I'd appreciate any and all help on this.

# Answer
> 2 votes
When you say you're going to measure skill by points, it's circular reasoning / logic. How are you going to decide how many points the player deserves for each goal accomplished? You can't rate the player's skill by points cause in order to do that, you require the base assumption that the sum of points accurately reflects the challenge surpassed, which may be false.

In order to properly judge a player's ability, you need to have some base data to compare with. You can collect this data by letting testers attempt different challenges; you can also let non-testers attempt these challenges and encourage them with badges.

Once you collect statistics from dozens of players or more (if possible), you could compute (an approximation of) the probability that a certain player will accomplish a certain feat. You could compare a new player to the statistics. You can even take the *time played* into account to tell if a person is relatively good for a beginner or relatively poor for an experienced player.

# Answer
> 1 votes
You would want to evaluate the player's skill using a set of recent data( three play-throughs) or something like that.

As a user continues to play, their skill increases along with their familiarity of the game mechanics.

Having a point threshold seems to be the best way to control a users skill. Naturally a person will have a couple good runs here and there that are outliers of thier base skill level. The trade off is that as you go back further, you are looking at the players previous skill level, so it is up to you to find the right amount of games to go back to balance the players skill level over a period of time, while accounting for their increase in skill over time.

Have you thought about classifying shots as "Skill shots" to see how many times a player hits a very limited or narrow shot per ball? This way you can eliminate some of the assumptions that evaluating a set of points would conclude.

# Answer
> 1 votes
I would think you could get an assessment of a player's skill by tracking a few things, and various skill levels could be defined based on these items. As stated already, overall score could be one of them. I think examining how well a player does on a per ball level, will also give you a good gauge to go by. For instance, how long a single ball is in play, how many times multipliers are achieved, how long the play maintains a multi-ball state, how many times hard-to-hit items are hit.

Again, a high score is an indicator of all these thing, however you might be able to factor out some dumb luck high scores by monitoring these items.

---
Tags: game-design
---


# Question
Title: How to make an object that has no rigidbody2d component smoothly fall on the ground in Unty2d?
I have two character in my game: enemy and main character. Enemy can throw different objects into the main character. For this moment i am doing this action in such way:

```
void FixedUpdate(){
    if (CanMove){
        transform.position = Vector2.MoveTowards(transform.position, TargetPlayer.transform.position,  15 * Time.deltaTime);
    }
}

public void StartMove(bool canMove){
    CanMove = canMove;
    TargetPlayer = GameObject.FindGameObjectWithTag(Tag).transform;
    rigidbody2D.gravityScale = 0;
}

```

This script is attached to the prefab of the object that will be thrown into main character by the enemy. This script is working, but in this case the object that was thrown will follow by main character all the time, because of this line of code: **transform.position = Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 * Time.deltaTime);**

To my mind this is not good, because i want to give my player the opportunity to escape from the object that was thrown at him. For example run away. When the object reaches the player position (and the player is on the new position) - he will simply fall onto the ground. I did this, but this wasn't looking nice, because when the object was reaching his position, he was hanging in the air. Can anyone give me an advice how to make this process more good-looking?

Edit: I need to make good-looking movement of the object, that was thrown by the enemy into main character. Every frame i am moving the instantiated object to the **current player position**. So the player can't escape from that object, because he always knows current player position. I think that this is not good idea, and i want to give to player an opportunity to run away from that object. In this case i am saving the position of the player into variable, and then every frame i am moving the instantiated object to that position. So when the player run away, the object, that was thrown doesn't know anything about new position of my player. But this is looking not good, because when the object is reaches its destination position he hangs in the air((

Edit # 2: I was thinking about destroying that object anyway, but to my mind this will not look good: the object is moving and suddenly disappears from screen(. May there is some ways how to make him smoothly fall onto the ground? The problem is in that this instantiated object has no Rigidbody2d component attached to it, so it will never fall down by itself.

# Answer
> 3 votes
Instead, get the direction from the origin to the target. Instead of moving the projective towards a destination, move it in a direction. Something like:

```
// Determine the direction
Vector2 direction = (origin - direction).normalized;

```

Then something like:

```
void FixedUpdate()
{
    if (CanMove)
    {
        transform.position = transform.position + (direction * speed * Time.deltaTime);
    }
}

```

Move it until it hits something (goes off camera, or hits the ground or a building, platform, tree, whatever) and THEN destroy it.

You can also transition the end collision in some way rather than a simple `Destroy(gameObject)` by playing a sound effect, swapping the sprite, etc. in order to avoid the jarring disappearance of the object.

---
Tags: unity, physics
---


# Question
Title: How can I make sprites from multiple images using SDL2?
Using SDL2 in C++ I can load textures with out problem however, I have sprites that are from about 15 different png's that I was hoping I could load them all up and for loop through them. However, when I try this it looks like the image is still .

I am hoping that I wouldn’t have to photo shop them into one image and shift/pan through that considering I have about 3K of images to go through.

can some one provide an example of how this could be done cleanly?

I have been working on this for a while for a bit and yes, this is probably a coding mistake as I am learning C++ still and know that for me to learn is to take up a project.

```
int main ( int argc, char *argv[] )
{

    SDL_Init(SDL_INIT_EVERYTHING);
    Window = SDL_CreateWindow("NEW WINDOW",100,100,300,300,SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
    renderer = SDL_CreateRenderer(Window,-1,SDL_RENDERER_ACCELERATED);

    if (Window == NULL)
    {
        std::cout << "Window Couldn't be Created!\n";
    }

    struct imagebatch
    {
        const char *image;
    };

    imagebatch foto;

    //  A for loop is needed here to loop through Healer0.png Healer1.png to Healer15.png
    foto.image = "DData/towners/healer/healer/Healer0.png";
    HealerTexture = IMG_LoadTexture(renderer,foto.image);

    //loads an image;
    //HealerTexture = IMG_LoadTexture(renderer,"DData/towners/healer/healer/Healer0.png");

    //defines the rect of this image;
    SDL_Rect HealerRect;
    HealerRect.x = 0;
    HealerRect.y = 0;
    HealerRect.w = 90;
    HealerRect.h = 90;

    while (!quit)
    {
        while( SDL_PollEvent( &event ) != 0 )
        {
            //User requests quit
            if( event.type == SDL_QUIT )
            {
                quit = true;
            }
        }
        SDL_RenderClear(renderer);

        //Blit everything here.
        SDL_RenderCopy(renderer,HealerTexture,NULL,&HealerRect);

        SDL_RenderPresent(renderer);
    }
    close();

    return 0;
}

```

Full code is here: http://pastebin.com/H5fD6cfX

# Answer
> 1 votes
For loading the images, you could do:

```
std::vector<imagebatch> fotos;
std::vector<SDL_Texture*> healerTexture;

// Parts of filename string that occur multiple times.
char* filenameBase = "DData/towners/healer/healer/Healer";
char* fileExt = ".png";

// This is 15 because of the number of images there are.
for (int i = 0; i < 15; ++i)
{
    char filename[64];
    strcpy(filename, filenameBase); // Copy the first part of the filename into the variable filename.

    char fileIndex[4]; // Create a string of length 4 for storing converted numbers.

    sprintf(fileIndex, "%d", i); // Convert i to a number (that's what %d specifies) and store in fileIndex
    strcat(filename, strcat(fileIndex, fileExt)); // Append the number to filename, and then append the file extension to that.

    // Create a new imagebatch to push onto the imagebatch vector.
    imagebatch foto;
    foto.image = filename;
    fotos[i].push_back(foto);

    // Finally, load the filename that we generated.
    healerTexture.push_back(IMG_LoadTexture(foto.image));
}

```

You may want to double check the string manipulation code, although I highly recommend `std::string` where possible with `boost::lexical_cast` since you won't be using it in a very performance sensitive area.

I've also used `std::vector` which is better because you don't have to pick their max length before compiling the code (amongst other things).

Don't forget to include `vector` and `string` at the top of each file if you use them as follows:

```
#include <vector>
#include <string>

```

And finally, when you want to render a particular sprite, you can do the following:

```
int spriteToRender = 5; // Edit this to the sprite you need to render.
SDL_RenderCopy(renderer,healerTexture[spriteToRender],NULL,&healerRect);

```

# Answer
> 0 votes
I highly recommend you look into spritesheets, for memory efficiency/performance. There are a couple of tools out there to help you convert your collection of images into a spritesheet, such as SpriteSheetPacker (open source) or my Gimp plugin for it. A quick google found me this sdl2 tutorial on spritesheets.

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


# Question
Title: How can I pass a std::vector<Vector3f> to my shader?
I have a `Vector3f` type which has `x`, `y`, and `z` properties. I have a `std::vector` of these vertices which describe my terrain.

I would like to pass these values to a vertex shader through a uniform variable, but all the OpenGL functions expect `GLfloat *`. Which is the best way to this? I would like to avoid conversions if possible.

# Answer
Assuming that `location` is the uniform location you've already retrieved from the shader, and `vec` is your vector, then in C++11 you can do:

```
glUniform3fv(location, vec.size(), reinterpret_cast<GLfloat *>(vec.data()));

```

Prior to C++11:

```
glUniform3fv(location, vec.size(), reinterpret_cast<GLfloat *>(&vec[0]));

```

The "old" method will work in C++11 as well, but the `data` method codifies the intent better.

This *only* works if you've ensured your vertex structure is tightly packed: there cannot be any padding between elements, at the front of the structure, or the end of the structure. This will *usually* be the case by default for current compilers and platforms, but if you want to guarantee it you should look into the pack pragma (for Microsoft's compiler) or the packed attribute for GCC/LLVM compilers.
> 2 votes

# Answer
Assuming your Vector3f class is laid out linear in memory.

```
std::vector<Vector3f> m_verts;

float* address = &m_verts[0].x;

```

This will get the address of the x value of the first element, so long as your data is laid out linearly, and your sizeof(Vector3f) == size(float) * 3 you should be fine.
> 0 votes

---
Tags: opengl, glsl, vector, projection-matrix
---


title: OpenGL Question about scaling 3D Object

text:
# Question
Title: OpenGL Question about scaling 3D Object
I got some scaled cubes `(1, 2.5, 1)` in a 3D Space with a grounded floor with position `(0, 0, 0)` and scale `(100, 0, 100)` like in the picture. But why are the cubes scaled out from the center. I want to level them on top of the ground.

This is my matrix manipulation code:

```
Matrix4f.scale(scale, mMatrix, mMatrix);
Matrix4f.translate(position, mMatrix, mMatrix);

```

So how is OpenGL scaling my cube, How can I level it?

# Answer
> 7 votes
You need to translate them before scaling them. Otherwise, the entire coordinate space is scaled. For example:

```
// Scale the coordinate space by two.
Matrix4f.scale( 2, 2, 2 );

// Now because of the scale this is the same as translating by 2 in every axis.
Matrix4f.translate( 1, 1, 1 ); // Actually means Matrix4f.translate( 2, 2, 2 ) here.

```

When you transform you are transforming the coordinate space, not the object. If you translate, scale then rotate, the transformations should have no effect on each other.

That's one of your problems, potentially. Your cubes are scaling from the center because that is where the origin is in model space. Each vertex of your cube is placed relative to the center( 0, 0, 0 ) of the cube. To change this either make your model origin the bottom center( I don't recommend this ) or translate up by half the cubes height after scaling.

EDIT:

To go more in depth about why your cubes are scaled from ( 0, 0, 0 ), you should understand how vectors work. All vectors have an origin and a distance from that origin( unlike a point, which just has a location ), this origin is zero. To scale a matrix, we can simply multiply it by a scalar:

```
Vector3( 1, 1, 1 ) * 2 = Vector3( 2, 2, 2 )

```

This doubles each component of the vector. Similarly, if we scale the up vector by, say, 5, we get:

```
Vector3( 0, 1, 0 ) * 5 = Vector3( 0, 5, 0 )

```

This is just simple arithmetic. This vector is scaled up to 5 units. It is now 5 times higher than it was before, however the x and z components remain unchanged, because they are 0.

So, each of the vertices that make up your cubes have a vector to describe where they are. They are all relative to some origin( ( 0, 0, 0 ) in this case ). So, if we have a cube made up of the following vectors:

```
Top
( -0.5, 0.5, -0.5  ), ( 0.5, 0.5, -0.5 ), ( -0.5, 0.5, 0.5 ), ( 0.5, 0.5, 0.5 )

Bottom
( -0.5, -0.5, -0.5 ), ( 0.5, -0.5, -0.5 ), ( -0.5, -0.5, 0.5 ), ( 0.5, -0.5, 0.5 )

```

We can see how these are scaled. Let's take one of the top vectors and scale it by the up vector * 5:

```
New Vector = ( -0.5, 0.5, -0.5 ) * ( 0, 5, 0 )
New Vector = ( -0.5, 2.5, -0.5 )

```

So, this vector has been scaled upwards. Great, just like you were expecting( although only half as much ). Now let's try one of the bottom vectors:

```
New Vector = ( -0.5, -0.5, -0.5 ) * ( 0, 5, 0 )
New Vector = ( -0.5, -2.5, -0.5 )

```

This vector scaled downwards instead because it was negative to begin with. So, if we scale by a positive number, it's just going to get further away from the origin, the same with the top vectors. They just have different directions.

You might wonder why the cube is constructed like this. The cube's origin is 0, 0, 0( this is chosen to simplify things like placing the object, and scaling. Like I said, the origin doesn't have to be 0, 0, 0, but it's a good idea ) so, to get a cube of area 1, we want the total length between vectors in each component to be 1.

So, you can see how it works mathematically. Technically the origin is as arbitrary as the bottom center of the cube. Having weird origins can be a pain when scaling though.

---
Tags: opengl
---


# Question
Title: Box2D recommended step, velocity and position iterations
Here in this article there is a nice explanation that velocity iterations and position iterations settings affect the way bodies will react when they collide, and step affects on speed and how gravity acts. So the precision is hidden behind position and velocity iterations, whereas you need to have the world step to advance the time in physics world. I also know that step should be constant to be able to have consistent and debug-able game physics. Hence I do this (where `dt` is FPS delta time):

```
if (m_world.GetBodyCount() > 0)
{
    static const double step = 1.0 / 70.0;
    static double accumulator = 0.0;

    // max frame time to avoid spiral of death
    if ( dt > 0.25 )
        dt = 0.25;

    accumulator += dt;

    while (accumulator >= step)
    {
        m_world.Step(step, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
        accumulator -= step;
    }
}

```

So I guess the step should not be less then FPS minimum value to avoid discrete simulation (cutting effects). Usually FPS is 1/60.0 hence I have chosen 1/70 as a step to have the best performance. And as Velocity and Position iterations I use 6 and 2 respectively which turned to be enough for collisions till today. Is my logic correct or I miss something? Is there a way to optimize more? What are the recommended values for this parameters for mobile games (considering that the game should work on week devices too). Should I use non-constant velocity iterations and position iterations reducing them when FPS drops?

# Answer
> 7 votes
First of all, if you want to avoid aliasing problems, you need to respect the Shannon rule. So you need to take 120FPS or more.

Secondly, you don't really need to care, you can simulate at 40 if you want, just be sure to linearly interpolate all of your matrices, the frame presentation time is the `t`, and your physics simulation always have to run some amount of frame ahead of the graphics frame, to be able to interpolate.

Thirdly, stability also depends on the integrator, apparently Box2d uses some modified Euler:
http://www.box2d.org/forum/viewtopic.php?f=8&t=1609 (symplectic Euler)
for which I would recommend not to go under 50.

Fourth, non constant integration is just a pathway to horrible explosions and weirdish problems that only your user will experiment, because of Muphy's law.

In Fifth, as you most certainly have seen in the doc your 6/2 numbers are recommended for simple simulations so they surely will do. They just indicate how many sub-iterations the constraint solver will take to clean the impulses of each body when they are in contact with multiple others.

---
Tags: box2d, physics
---


# Question
Title: How to find the points of intersection of two OBBs
In my game I need to be able to find the points of intersection between two OBBs.

I'm using Separate Axis Theorem to check if there's an intersection and get the penetration vector if there is one.

Can I use SAT to also solve this problem? If not, how can I solve this?

# Answer
I assume that we're in 2D, and by intersection points you mean the points where an edge of one OBB touches an edge of the other. SAT won't give you those points, but you can easily find them with a simple line segment intersection test (such as the one in this SO answer), applied to each pair of edges. There are 16 such pairs, so it's not a huge amount of work to simply check all of them.
> 1 votes

# Answer
An alternate (but potentially more difficult) method to solving OBB vs OBB collision is to transform one OBB into the space of the other, such that one of the OBBs becomes axis aligned.

Basically you translate the two OBBs so that the center point of one is at (0,0) then rotate the two around (0,0) until the OBB at (0,0) becomes axis aligned. You can then use SAT to resolve the collision, but all resulting values will be relative to the current transformation (and thus you'll have to un-rotate around (0,0) and un-transoform)

tldr; Linear Algebra + SAT
> 0 votes

---
Tags: mathematics, geometry
---


# Question
Title: Corona SDK, display.contentWidth and height does not get the expected values
I'm drawing a simple rectangle to fill the entire screen.

```
local bg=display.newRect(0,0,display.contentWidth,display.contentHeight)

```

Instead of drawing a full screen rectangle, all i get is this:

How do i rectify this?

# Answer
Its anchor points is in the middle of the object. do this:

```
bg.anchorX = 0; bg.anchorY = 0;

```

from here
> 3 votes

# Answer
the x and y value 0 start from the middle of the screen so

this should start far upper left

```
local bg=display.newRect(0,0,display.contentWidth,display.contentHeight)

```

while this should start from the content center and then sets the image width and height according to screen dimensions

```
local bg=display.newRect(display.contentCenterX,display.contentCenterY,display.contentWidth,display.contentHeight)

```
> 1 votes

---
Tags: corona-sdk
---


# Question
Title: Why does Corona SDK not build a .apk file?
I'm trying to put a game I created in Corona SDK on my Galaxy S5. I go to the Corona Simulator, click Build for Android.. Then I fill out the information, and then I hit build. The problem is, it's not an apk file, it's a GameSpy Arcade Online file. Why does it do that? How could I fix it?

Thank you, -Bryce

# Answer
Have you tried renaming it? Maybe theres a installed program that detects APK files as what you have said. And just to make sure, check show known extension in you folder options in windows
> 1 votes

# Answer
It *is* an apk, but your computer associates that filetype with Gamespy Arcade Online. When I search on "gamespy arcade online filetype" I see that it is also APK:

> What is .apk file?
>
> The APK file extension is used by GameSpy Arcade service, a shareware multiplayer game server browsing utility

To change this, search for "windows associate filetype". For example, one of the results is: http://www.7tutorials.com/how-associate-file-type-or-protocol-program
> 1 votes

---
Tags: android, corona-sdk
---