# Question
Title: Better way to handle ordering and visibility of renderable objects?
I'm just wondering whether there is a more effective way to handle the ordering and visibility of renderable components that fits into the design of my already existing engine.

How I do it now:

1. In each update in my SceneHandler, do this:
2. Retrieve all renderable components that currently are in the current scene
3. Send these components to the RenderManager
4. Call RenderManager.Update
5. In each update in RenderManager, do this:
6. Iterate over the given list and perform an occlusion test
7. If the object is visible, put it in a new list of visible items
8. Sort the list of visible items in the order of their layer depth
9. When RenderManager.Draw() is called the RenderManager iterates over the list of visible items and draws them

Is there any way that is obviously better than this or is this how you usually do? Maybe I could keep a sorted list of all the current scene objects and then just perform occlusion testing and thus not having the need to sort each update?

Pros and cons of the suggested method are greatly appreciated.

# Answer
Might want to consider a priority queue instead of that list, if you want to keep the build sequence like you have, because it will automatically sort on insert.

I'm unsure how you're doing an occlusion test in step 7 *before* you've even sorted them into depth order in step 8...

Since it sounds like you normally keep these renderables in a big bag of chaos maybe consider keeping them instead in a spatial partitioning structure like an octree which maintains relative positioning (which would replace the caching you're considering in your discussion).
> 1 votes

---
Tags: xna, c#, 2d, rendering, monogame
---


title: Simulating (Human) Needs?

text:
# Question
Title: Simulating (Human) Needs?
How can I simulate the vegetation (of a human being)?

To simulate **Hunger** for example, I use some kind of saturation based system now. Means that every food-object saturates differently and the saturation influences how much gets substracted from the current hunger level.

But I'm not very satisfied with the result and I don't really have an idea how to realize the same with the needs **Fun** and **Energy**.

So, is there a special way to do this? Or is there an algorithm that is used in stuff like **The Sims** or even **Minecraft** (which has hunger only, but it has.)?

# Answer
First, any need can be viewed as a progress bar. Hunger, Fun, Energy, everything. Even non-need related things, like Fear. How the value of the progress bar increases or decreases, is up to the function manipulating the *need* behind it. The Sims clearly shows this:

```
abstract Need
{
    numeric CurrentValue;
    external function IncreasingRule;

    function Update()
    {
        IncreasingRule.Apply(this, Params);
    }
    ...
}

```

Increasing rules are functions that change the state of the needs attached to them. `Params` in my pseudocode above contains info that the increasing rule needs to use to apply changes to the need.

I do not believe such things as "standard" increasing rules exist. You pretty much have to come up with your own solutions or just copy other people's. Basic examples, to give you an idea:

```
IncreasingRule HungerRule.Apply(HungerNeed, Subject)
{
     if (Subject.Eating)
     {
            HungerNeed.CurrentValue -= Subject.FoodBeingEaten.HungerValue;
     }
     else
     {
            //Linear development as time passes.
            HungerNeed.CurrentValue = Subject.TimeSinceLastMeal;
     }
}

IncreasingRule FunRule.Apply(FunNeed, Subject)
{
     if (Subject.DoingSomethingThatCanBeFun)
     {
        //If the thing the subject is doing is among his favorites, the fun
        //need goes down based on their favorite rank. If, instead, they're
        //doing something boring, or if they absolutely hate what they're doing,
        //the fun need goes up (return value of CalculateFun is negative).
        FunNeed.CurrentValue -=
        CalculateFunBasedOnListOfFavoriteThings(Subject.FunObjectInUse);
     }
     else
     {
        FunNeed.CurrentValue = Subject.TimeSinceLastDidSomething;
     }
}

//Similar to the one in The Sims.
IncreasingRule RoomRule.Apply(RoomNeed, Subject)
{
     if (Subject.JustEnteredRoom)
     {
         if (Subject.CurrentEnvironment.ContainsNewDecorations)
         {
             RoomNeed.CurrentValue -=
             CalculateBeautyBasedOnSubjectPreferences(Subject,
             Subject.CurrentEnvironment.NewDecorations);
         }
     }
     else
     {
         RoomNeed.CurrentValue = Subject.TimeSinceSeenSomethingNew;
     }
}

```

Needs' current values should be kept under control, obviously, with a min/max boundary.
> 2 votes

# Answer
I'd model hunger against *calories*.

A hamburger that has 500 calories will last you for 2 hours assuming 250 calories per hour expenditure.

I don't think you can model *fun* like this. I'd model energy similarly to hunger, but factor in a reduction in energy for lack of sleep as well.
> 1 votes

# Answer
There are many ways to model each type.

Hunger can be calorie based like bobobobo stated.

Energy could be based on hunger: The less hungry you are, the faster your energy regenerates.

Fun could be measured like an hourglass: An activity would recharge your "fun" meter by a certain amount, with some activities providing more "fun" than others. Fun would slowly run out over time, and "unfun" activity may drain it faster.
> 1 votes

---
Tags: algorithm, ai, simulations
---


# Question
Title: Ground contact point for animated character sprites in an isometric game?
I'm working on an isometric game. I have the 3D pre-rendered sprites for directions per state (walking/running, etc.) per frame. Now I need to know where a particular character stands on the ground to have it synchronized. But this "ground contact point" (GCP) changes from frame to frame, and is basically (slightly) different for every combination. At this moment I have some rough average, but sprite wiggles a bit during animation. It's rendered correctly (1024x768), but cropping of the frames even though it correctly removes empty borders, it also removes the "offset" information, which is no longer there. So I basically need to remove empty borders while taking into account all the frames in all the animations. So the character in the sprite animation is still stabilized, but unneeded space is removed.

Example:

Is there any software that does it, or is there some technique to do it?

# Answer
Thanks to Byte56, I was able to realize what causes the loss of information (cropping), and was able to find a solution. I used ImageMagick command:

```
convert.exe "MyFrame.png" -crop WidthxHeight+HorizontalPadding+VerticalPadding
            +repage "MyResultFrame.png"

```

This command cropped the square of particular size for all the frames/states/directions. And frames are now correctly aligned, and animation is smooth and natural looking.
> 0 votes

---
Tags: graphics, animation, isometric, terrain
---


# Question
Title: How can I disable the green frames after a cinematic in UDK?
These green frames appear in my scene after the display of a cinematic (which I just added recently):

How can I remove them, ideally without resorting to transitioning the game mode?

# Answer
> 2 votes
As posted in your comment, the green frames are UnrealKismet references. Uncheck them from the Show menu to hide them.

---
Tags: udk
---


# Question
Title: How to make box2d bodies block each other but not push each other?
I want to use box2D to create a movement system for an RTS game. How can I make bodies block the movement of other bodies while preventing these bodies from pushing each other?

# Answer
> 1 votes
It sounds like you want standard collision detection, but a custom collision response. Sensors (Fixtures subsection 6.3) provide that functionality.

1. Disable the default collision (use static bodies, filtering, etc.)
2. Attach a sensor and implement a custom collision response

---
Tags: box2d, movement
---


# Question
Title: Do I need multiple perlin noise generators for different features in terrain generation?
I have a simple perlin noise algorithm in my 2d game, I feed it x and y location of a tile and get some value between 0 and 1. I then use a bunch of if-else statements to break these numbers into terrain types:

* 0 is water
* 0.5 and less is plain
* 0.6 and less is hill

Then there's features like forests, but in the current system a hill cannot have forest on it. I'm using only 1 perlin generator here, and my question is **whether I need to have multiple perlin generators with random seeds to control elevation, vegetation and other terrain features?**

# Answer
I think that it might be important for you to differentiate between the raw terrain and the stuff on the terrain. Many algorithms work with multiple passes.

First pass would be to use noise like you're doing to create raw terrain. Second pass would be to figure out what biome is appropriate in broad areas of your new terrain, you are *almost* doing this by assigning types like "hill" but this is deeper and more varied. Third pass then randomly drops down biome-stuff like trees.

How you represent this final version in your program is entirely up to you.

See Byte56's answer for good links to making more elaborate noise, you'll get some use out of that I warrant.

There's really only one perlin generator at work, everything else is built on top of its output. The biome-stuff doesn't need the properties of noise, it can be pseudo-random.

You can, of course, get more and more elaborate and start working with multiple levels of detail via parameter changes and multiple calls to the perlin function(s) but for simple uses it's not often necessary.
> 3 votes

# Answer
You don't need them no. You can easily design your perlin noise generator to accept various inputs to produce the desired outputs.

See my answer here for details about mixing noise. And here for controlling noise with noise.
> 3 votes

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


# Question
Title: Help with concrete examples of Perlin Noise variables for terrain generation
I believe this question can help beginner game developers. I've looked through a dozen or so answers on perlin noise here and on Stackoverflow, and found only 1 concrete implementation of perlin noise that I have listed below. There's a lot of advice, but it's hard to translate into what I have to do with X and Y values, and if I have to do this at all times, or only when I want specific features to appear.

Here's what I got from Stackoverflow: I believe this was advised as mixing various noise octaves. It seems to generate a fairly interesting terrain, although it rarely generates mountains for me.

```
  float perlinNoiseValue =
    +1/15.0* fabsf([generator perlinNoiseX: perlinX y: localYIndex z: 0 t: 0])
    +2/15.0* fabsf([generator perlinNoiseX: 2*perlinX y: 2*localYIndex z: 0 t: 0])
    +4/15.0* fabsf([generator perlinNoiseX: 4*perlinX y: 4*localYIndex z: 0 t: 0])
    +8/15.0* fabsf([generator perlinNoiseX: 8*perlinX y: 8*localYIndex z: 0 t: 0]);

```

I'm looking at this answer on Perlin Noise by Byte56, and it's hard for me to translate verbal descriptions into what I have to do with X/Y inputs. Can someone provide concrete examples, along with descriptions of what terrain features such noise generates?

For example, does mixing noise by picking the max value equates to something along the lines of

```
float perlinNoiseValue1 =  fabsf([generator perlinNoiseX: perlinX y: localYIndex + 300 z: 0 t: 0]);
float perlinNoiseValue2 =  fabsf([generator perlinNoiseX: perlinX y: localYIndex z: 0 t: 0]);

float finalValue = fmax(perlinNoiseValue1,perlinNoiseValue2);

```

Do I always pick the max value in the case above, or only in some cases when I want a certain feature to manifest?

Does flatter terrain look like ?

```
float flatterTerrain =  fabsf([generator perlinNoiseX: perlinX y: 0.2*localYIndex z: 0 t: 0]);

```

Does wider valleys and hills look like?

float widerValleys = fabsf(\[generator perlinNoiseX: perlinX\*3.0 y: localYIndex z: 0 t: 0\]);

# Answer
> 2 votes
As mentioned in the answer you reference, this is sort of the artistic side of procedural generation.

These are the kind of functions you just have to keep tweaking until you get something that works for you. Everyone is going to have different ways of generating terrain and even a number of different ways to generate noise. It's unlikely there's going to be a standard template for generating noise for specific terrain types.

I suggest you make an in-game interface for your noise values and set it up so you can tweak the values and have the terrain generate in real time. This will allow you to figure out exactly how different values affect your terrain, and the range of values that give you the types of terrain you want.

---
Tags: procedural-generation, objective-c, terrain, perlin-noise
---


title: Framerate and game loop on mobile

text:
# Question
Title: Framerate and game loop on mobile
I'm searching how to manage game framerate on mobiles devices, here is my problem:

**On a computer with got something like that:**

```
void main()
{
    while(game.isRunning())
    {
        event.handle(eventInfos);
        game.update(dt);
        graphic.render();
    }
}

```

**On a mobile device with got something like that:**

```
void update()
{
    game.update(dt);
}

void render()
{
    game.render(dt);
}

void event()
{
    game.handle(eventInfos);
}

```

When I search on internet, I found something like that everytime:

-\> GameLoop

-\> Fix your time step

I'm using IOS (With GLKViewController) and Android (with the NDK), and I've that rendering method is call from another thread

Thanks for your help!

# Answer
To get the right amount of movement when using a update(dt) function you must multiply the movement speed against delta time (dt = the amount of time since last frame update). So your position update could look like: newPosition = oldPosition + (moveSpeed * dt)

I hope this helps, I dont really understand what you mean by 'manage framerate'.
> 1 votes

---
Tags: android, ios, game-loop, frame-rate, timestep
---


# Question
Title: How to enable geometry shader in OpenGL 4.2?
I'm porting my Direct3D-based engine to OpenGL and I'm using geometry shaders for rendering text characters (basically, textured billboards).

D3D version works fine, but in OpenGL mode it gives only a flickering point right in the center of the screen.

It seems that somehow the geometry shader stage is not enabled (in AMD GPUPerfStudio the box, representing GS stage, is grayed-out).

I tripple-checked the OpenGL back-end and the shader code but couldn't find any mistakes. Maybe, I'm missing something.

Below is the source code of the relevant shaders:

Vertex shader:

```
in vec4 in_xy_wh;
in vec4 in_tl_br;   // UVs for top left and bottom right corners
out vec4 v_xy_wh;
out vec4 v_tl_br;
void main()
{
    v_xy_wh = in_xy_wh;
    v_tl_br = in_tl_br;
}

```

Geometry shader:

```
layout(points) in;
layout(triangle_strip, max_vertices=4) out;

in vec4 v_xy_wh[];
in vec4 v_tl_br[];  // UVs for top left and bottom right corners

out vec2 v_uv;

void main()
{
    vec2    pos = v_xy_wh[0].xy;
    float   width = v_xy_wh[0].z;
    float   height = v_xy_wh[0].w;

    vec2    tl = v_tl_br[0].xy;
    vec2    br = v_tl_br[0].zw;

    gl_Position = vec4( pos.x, pos.y, 0.0f, 1.0f );
    v_uv = vec2( tl.x, tl.y );
    EmitVertex();

    gl_Position = vec4( pos.x + width, pos.y, 0.0f, 1.0f );
    v_uv = vec2( br.x, tl.y );
    EmitVertex();

    gl_Position = vec4( pos.x, pos.y - height, 0.0f, 1.0f );
    v_uv = vec2( tl.x, br.y );
    EmitVertex();

    gl_Position = vec4( pos.x + width, pos.y - height, 0.0f, 1.0f );
    v_uv = vec2( br.x, br.y );
    EmitVertex();

    EndPrimitive();
}

```

Fragment shader:

```
in vec2 v_uv;
out vec4 v_color;

uniform sampler2D   s_font;

void main()
{
    vec4 color = texture( s_font, v_uv ).rgba;
    if( color.w < 1.0/255.0 ) {
        discard;
    }
    v_color = color;
}

```

I've added the "#version 420 core" preamble to each shader. I know I shouldn't use the glProgramParameteriEXT function to define GL\_GEOMETRY\_INPUT\_TYPE\_EXT, GL\_GEOMETRY\_OUTPUT\_TYPE\_EXT, GL\_GEOMETRY\_VERTICES\_OUT\_EXT, because these parameters are specified in the geometry shader (which is core in OpenGL 4.2).

EDIT: My mistake was incorrect usage of glVertexAttribPointer (wrong value of the the last parameter). Thanks for all the answers and sorry for your wasted time!

# Answer
Geometry shader is only available in GLSL version 1.5 and later, and you need to specify that explicitly in the geometry shader source. I guess it's `#version 400` in your case. Here is the list of GLSL verseions.
> 2 votes

---
Tags: opengl, shaders, graphics, pc, glew
---


title: Spritefont in OpenGL

text:
# Question
Title: Spritefont in OpenGL
I develop in OpenGL using C# as programming language.
I want to draw some text on the screen. For this i created a texture that contains all the characters.

Now i am not sure how to continue. I can draw now every character like this:

```
Gl.glBegin(Gl.GL_QUADS);
{
    Gl.glTexCoord2f(posX, posY);
    Gl.glVertex2f(-1, -1);

    Gl.glTexCoord2f(posX + size, posY);
    Gl.glVertex3f(1, -1);

    Gl.glTexCoord2f(posX + size, posY + size);
    Gl.glVertex3f(1, 1);

    Gl.glTexCoord2f(posX, posY + size);
    Gl.glVertex3f(-1, 1);
}
Gl.glEnd();

```

`posX` and `posY` contain the start position of the character in the character-texture. `size` is the size of the character in the texture.

This method needs a lot of draw calls. I mean i draw lots of quads but i only need one where i can put all the text on it. How can i improve my code?

# Answer
In my engine, I use a dynamic vertex buffer for batching up text data (each character == 1 vertex) and do point-to-quad expansion in geometry shader.

As far as I know, `glVertex*`, `glNormal*`, `glTexCoord*` are considered obsolete (like display lists) and are not recommended to use.

This gives a comprehensive overview of various OpenGL-based text rendering techniques:

The details of the technique I'm using:

Offline: 0) prepare a font texture atlas (with tightly packed glyphs, block-compressed) and remember glyph data (position, size, unicode =\> glyph index mapping); for these purposes I use MakeSpriteFont from DirectX Tool Kit.

At launch time:

1. load the font texture and glyph data (submit data of each mipmap level to `glCompressedTexSubImage2D`);
2. create a dynamic vertex buffer (`GL_DYNAMIC_DRAW`) for holding `MAX_TEXT_LENGTH` vertices;

At draw time: 4) parse the submitted text string and update the VBO using the glyph data; 5) draw the points from VBO

```
glBindBuffer( GL_ARRAY_BUFFER, dynamicVBO_id );
glDrawArrays( GL_POINTS, 0/*first vertex*/, vertexCount/*==character count*/ );

```

My vertex shader code:

```
#version 420 core

in vec4 a_texCoord0;    // .xy - center position, .zw - width and height
in vec4 a_texCoord1;    // st coords for top left and bottom right corners

out VSO {
    vec4 xy_wh;
    vec4 tl_br;
} outputs;

void main()
{
    // gl_Position will be written by geometry shader
    outputs.xy_wh = a_texCoord0;
    outputs.tl_br = a_texCoord1;
}

```

Geometry shader code:

```
#version 420 core

layout(points) in;
layout(triangle_strip, max_vertices=4) out;

in VSO {
    vec4 xy_wh;
    vec4 tl_br; // UVs for top left and bottom right corners
} inputs[];

out GSO {
    vec2 texCoord;
} outputs;

void main()
{
    vec2    pos = inputs[0].xy_wh.xy;
    float   width = inputs[0].xy_wh.z;
    float   height = inputs[0].xy_wh.w;

    vec2    tl = inputs[0].tl_br.xy;
    vec2    br = inputs[0].tl_br.zw;

    gl_Position = vec4( pos.x, pos.y, 0.0f, 1.0f );
    outputs.texCoord = vec2( tl.x, tl.y );
    EmitVertex();

    gl_Position = vec4( pos.x + width, pos.y, 0.0f, 1.0f );
    outputs.texCoord = vec2( br.x, tl.y );
    EmitVertex();

    gl_Position = vec4( pos.x, pos.y - height, 0.0f, 1.0f );
    outputs.texCoord = vec2( tl.x, br.y );
    EmitVertex();

    gl_Position = vec4( pos.x + width, pos.y - height, 0.0f, 1.0f );
    outputs.texCoord = vec2( br.x, br.y );
    EmitVertex();

    EndPrimitive();
}

```

Fragment shader code:

```
#version 420 core

in GSO {
    vec2 texCoord;
} inputs;

out vec4 o_pixelColor;

uniform sampler2D s_font;

void main()
{
    vec4 textureColor = texture( s_font, inputs.texCoord ).rgba;
    if( textureColor.w < 1.0/255.0 ) {
        discard;
    }
    o_pixelColor = textureColor;
}

```

I'm not in any way proficient in OpenGL.
> 5 votes

---
Tags: opengl, text
---


title: XNA Render Targets Depth Testing

text:
# Question
Title: XNA Render Targets Depth Testing
I imagine this is a problem that gets asked quite often, but reading up on it I can't seem to get a definitive answer on how to solve it.

I've got two HLSL shaders (I've simplified them in the example to just output a colour) that require RenderTargets. For example Blur shaders.

There are two balls spinning around a central point. As they spin, one passes between the other and the camera occluding the other ball and vice versa.

If I render them both to the same rendertarget (using the same technique) they obviously share a depth buffer, and the depth testing happens correctly.

However, when I need to use different techniques to render each ball seperately (one ball to one rendertarget and the other ball to a different) and then try to composite them depth testing fails and they are just rendered on top of each other.

Attach is the code I'm using. I've simplified it down a lot, but it indicates the problem I'm having.

How do I go about rendering two different objects, using two different techniques to two different rendertargets and then composite them?

DepthTesting.cs

effect.fx

# Answer
> 1 votes
I ended up solving this problem by ordering the SpriteBatch draw calls by the distance from the camera to the object being drawn. This, combined with depth testing on the SpriteBatch seems to work.

---
Tags: xna, hlsl, rendertargets
---


# Question
Title: Keyframing or programmatically changing attachment transparency in Spine
I've just recently been getting to grips with Spine and Unity 2D, porting some of my assets from different sources (SWFs, SVGs, GIFs, Canvas animations). Whilst I'm able to reproduce a lot of what I can do in these other systems — very nicely I might add — one thing that seems to be alluding me is how to animate an attachment.

Obviously Spine is still developing, so I don't expect to be able to run full bitmap/vector animations as attachments; but one thing the software does seem to have already is the ability to set transparency, and to set multiple attachments to one slot. I was hoping someone out there would know if these abilities can be combined to at least achieve a faded switch between attachments — either using the GUI or via coding.

For example, this video shows my character animated with the two states I wish to switch between.

I'm aware that you can key frame a switch between attachments, but this leads to a sudden jump in what graphic is shown. I could theoretically create 8 extra attachments on each slot and set their opacity graduating from 0.1 to 0.8 — but this seems like a rather hack way of doing things, and would also be awkward to shift along the timeline.

My fallback would be to animate the two full states of the character, export them, and leave Unity to handle switching from one to the other.

Any ideas?

# Answer
> 4 votes
**If you want your character's look to change uniformly** (i.e. at any time, all sprites are at the same point of transition between states), the simplest way I can think of is to create them as separate *skins* in Spine. The Unity runtime tfor Spine then lets you render the skeleton with either skin, so you can control the transparency by rendering each skin once, the second time with variable transparency.

The issue with this is of course that the transparency is applied to the whole skin.

---

**If you want your character's images to change independently** (so, for example, the lower arms have a "powered up" skin, while the rest stays normal), you can create multiple slots for your character's bones each with a different image.

If you drag an image onto a bone that already has a slot, you'll get this handy dialog:

That bone will then have two slots, each of which has an associated image:

You can then keyframe your slots' transparencies in an animation. In *Animation mode*, you can select a slot in the tree and change its colour tint from the properties box just below the tree:

This brings up a colour selector that includes a transparency slider.

As usual, hit the key icon to keyframe the change.

This way, you can control the relative visibilities of two images attached to one bone with just the usual animation keyframes. Spine runtimes also let you manipulate these transparencies at runtime.

---
Tags: transparency, skeletal-animation, spine
---


# Question
Title: Telling my shader when to use which Texture
So I've just managed to get Texturing via GLSL shaders to work and i can pass a sampler2d textureHandler + my uv coordinates into my shader to specify the texture to be displayed on my Tiles.

Now im Wondering how I could define which tile should get which Texture cause right now I can only put 1 single texture on ALL tiles I have...

My vertex shader:

```
in vec3 position;
in vec2 vertexUV;

uniform mat4 orthoMatrix;

out vec2 UV;

void main()
{
    gl_Position = orthoMatrix * vec4(position, 1.0);
    UV = vertexUV;
}

```

my fragment shader:

```
in vec2 UV;

out vec4 outColor;

uniform sampler2D myTextureSampler1;

void main()
{
    outColor = texture2D(myTextureSampler1, UV);
}

```

My Texture Loading right now looks like this: http://puu.sh/62MhS.png

# Answer
"myTextureSampler1" should be a big texture containing all your tiles (Texture Atlas). This way, all you need to do is pass the right UV for each tile.
> 1 votes

---
Tags: opengl, textures, sprites, glsl, lwjgl
---


title: Purpose of Displaying Loading Screen

text:
# Question
Title: Purpose of Displaying Loading Screen
Is it necessary for a game developer (on Android, game consoles, online, or desktop) to display the loading screen to cover unfinished rendered game environments and prevent users from thinking that this game is either lagging or freezing ?

I'm thinking if the game runs seamlessly, then, I don't need to add loading screens since it appears to be too showy or takes long for making animated presentations before the game.

Or, if displaying loading screen is a general standard required for each published game, was it okay to "cheat" by displaying a fake loading screen with any certain length of time even though the game renders smoothly? I would like to know why game developers added the loading screen during when the gameplay is started.

# Answer
> Was it necessary for a game developer (in Android, game consoles, online, or in desktop) to display the loading screen to cover unfinished rendered game environment and to prevent from other users thinking that this game is either lagging or freeze.

Yes, loading screens are used to hide resource loading and it's somehow a more entertaining way to tell the player to wait. Otherwise the player will have terrible impression on the game, if I showed him an unfinished scene. I can recall that many reviews always mention when levels aren't completely loaded; be it textures or 3D objects, not only it will have bad impact on the gamers impression it will usually affect the critic reviews (which may or may not be important).

> I'm thinking if the game runs smoothly, then, I don't need necessarily to add the loading screen since it appears to be too showy or took long for making animated presentations before the game.

If you let the player continue traversing the game while the level is not really loaded then I don't really call this is a game "that runs smoothly".

On the technical side, introducing a seamless world isn't always technically possible (and even if possible isn't particularity easy to do) due to the size of the current gen game worlds and somehow limited memory (at least on PS3 and XBOX360, also on mobile devices). This often requires building an asynchronous loading mechanism, and do alot of swapping between the hard disk and the memory, this is particularly tricky to manage without affecting the game performance.

Even if you have a huge memory it's not always practical to load the whole level into memory. This has a lot to do with caching and computer architecture, being in memory doesn't mean it won't affect performance, if your game has a lot of chache misses then it won't particularity perform *well*. That's is why games are moving towards cache friendly architecture (component driven design).

I can recall Borderlands, Mass Effect and Skyrim, even though they almost managed to get seamless open world right, I usually noticed a lot of pop-ups and unfinished objects (PS3 version). Uncharted 2 on the other hand was an almost seamless experience but keep in mind that the game was linear and is not as the same scale as the others I mentioned.

At last a lot of games innovated in that area. Skyrims shows nice 3D Models, Heavy Rain and Beyond Two souls show some characters detailed faces.

Some games like Beyond Two Souls innovate in their loading screens, so loading screens might add artistic value to the game and might even let you connect with the characters . Others give you tips and tricks.

And my favorite Fallout 3 loading screens, gives you more info about the world and the environment in usually a funny way and lets you connect with it.

To be honest I don't see them going anytime soon, I always see loading screens more than a polite way to tell the player to wait, sometimes it adds to the artistic value of the game, but I am sure things will get *better* and you will see less of them, especially if SSD dominated the market.
> 8 votes

# Answer
A few things to consider :

* What happens after your fake loading screen is over in the case some user has a machine slower than yours? (Which will happen)
* Making a loading screen has never been a rule (i do not know if there is "rules" in video game making) but a good practice to prevent users with slower machines to see objects pop on the screen.
* If after all your tests loading is still very fast, then you could avoid doing a loading screen and just create a simple Black or White fading (Excellent for very fast loading and still good in case of slow machines)
* Finally, i've never seen a loading screen after gameplay is started except in games with huge environnement and usually it's placed in stategic moments : opening a door, crossing a corridor, passing a canyon etc.. moments when the camera has to be ideally placed for users not to notice objects popping in or out of the scene
> 3 votes

---
Tags: multithreading, loading, screen, synchronization, standards
---


# Question
Title: How can I control how quickly a character levels up in an RPG?
I am working on an RPG and I've mostly followed formulas from the *Dragon Quest* series and they've all been fairly simple. (For example, `dmg = (Attack/2 - Defense/4)`, where `Attack` is `Weapon Power+STR`.)

**Experience points** are more complicated though. I want one of the characters to level more slowly compared to the others. I'm not comfortable with the maths, but how would I go about creating a suitable exponential growth formula that is slow from let's say levels 1 through 40 and then speeds up to 99?

# Answer
You can always set fixed values of XP for killing monsters/doing quests/interactions/crafting, so that e.g. after reaching 40 level or so player is capable of handling packs of monsters that give him much XP, so that he will level up quickly, or maybe set quests that give you much XP. Also, test your setup, and if you feel like player will be leveling up too slowly, you can always change these.
> 0 votes

---
Tags: game-design, rpg, mathematics
---


# Question
Title: Is multipass rendering possible with SpriteBatch?
I'm trying to implement a bloom effect. This requires three shader passes: a brightness threshold, a horizontal blur, and a vertical blur. It also requires resizes, but these are irrelevant to the question. I've also omitted the threshold, as the problem lies in the blurs.

Now, I've read that HLSL passes are just syntactic sugar for different shaders, and that switching between them is about as expensive as setting a new effect to the `GraphicsDevice`. Still, I prefer to keep them in one .fx file.

The passes:

```
    pass Pass0
    {
        PixelShader = compile ps_2_0 PS_Threshold();
    }
    pass Pass1
    {
        PixelShader = compile ps_2_0 PS_BlurHorizontal();
    }
    pass Pass2
    {
        PixelShader = compile ps_2_0 PS_BlurVertical();
    }

```

The blurring code:

```
        private void Blur(SpriteBatch SpriteBatch, RenderTarget2D Source, RenderTarget2D Rendertarget1, RenderTarget2D Destination)
        {
            // Blur pass 1
            Contents.BloomEffect.CurrentTechnique.Passes["Pass1"].Apply();
            SpriteBatch.GraphicsDevice.SetRenderTarget(Rendertarget1);
            SpriteBatch.GraphicsDevice.Clear(Color.Black);
            SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, Contents.BloomEffect);
            SpriteBatch.Draw(Source, Rendertarget1.Bounds, Color.White);
            SpriteBatch.End();

            // Blur pass 2
            Contents.BloomEffect.CurrentTechnique.Passes["Pass2"].Apply();
            SpriteBatch.GraphicsDevice.SetRenderTarget(Destination);
            SpriteBatch.GraphicsDevice.Clear(Color.Black);
            SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, Contents.BloomEffect);
            SpriteBatch.Draw(Rendertarget1, Destination.Bounds, Color.White);
            SpriteBatch.End();
        }

```

Finally, the Draw loop:

```
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.SetRenderTarget(RT1);
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, bloom);
            spriteBatch.Draw(android,
                             new Rectangle(0, 0, 258, 294),
                             Color.White);
            spriteBatch.End();

            Blur(spriteBatch, RT1, RT11, RT1);

            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, null, null, null, null);
            spriteBatch.Draw(RT1,
                RT1.Bounds,
                Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }

```

The output, however, is as follows:

It's obvious what happens: the last pass is applied twice. I've tested the passes individually by snipping them out of the shader, and they work fine. Is `EffectPass.Apply()` simply not meant to be used with SpriteBatch, or is there another way to change what passes are applied (without putting the passes in different .fx files)?

This has all been in XNA. To make this even weirder, when I do the same thing in Monogame the opposite occurs: the shader will only use Pass0. However, I'm converting the shader to OpenGL there, so that might be a conversion quirk.

EDIT: I fixed this by putting the different passes in different techniques, and switching techniques instead of passes. That doesn't answer the original question though, so I'll leave it open.

# Answer
> 1 votes
Yes, multipass rendering is possible with `SpriteBatch`. If you set the current technique of some effect to the desired one, and then pass a reference to that effect to the `Begin` method, then all passes of that technique will be applied.

Internally, a sprite batch will do its actual rendering from the `RenderBatch` method, which is private and called from the public `Draw` or `End` methods, depending on whether or you not you have requested immediate or deferred rendering.

`RenderBatch` looks like this (the relevant code is in the positive branch):

```
private void RenderBatch(Texture2D texture, SpriteInfo[] sprites, int offset, int count)
{
    if (this.customEffect != null)
    {
        int num2 = this.customEffect.CurrentTechnique.Passes.Count;
        for (int i = 0; i < num2; i++)
        {
            this.customEffect.CurrentTechnique.Passes[i].Apply();
            base._parent.Textures[0] = texture;
            this.PlatformRenderBatch(texture, sprites, offset, count);
        }
    }
    else
    {
        base._parent.Textures[0] = texture;
        this.PlatformRenderBatch(texture, sprites, offset, count);
    }
}

```

Since you are passing your custom bloom effect to `Begin` within your `Blur` function, you are executing that positive branch, so all passes of your technique are applied both times you call `Draw` within `Blur`, yielding incorrect results because those passes are not all meant to be applied to each texture.

By switching to multiple *techniques* (as you have), you work around that behavior since each technique only has a single pass. You could also solve the problem by passing `null` for the effect within your `Blur` method.

---
Tags: xna, shaders, hlsl, monogame, spritebatch
---


# Question
Title: Can I load a SpriteFont without a content project?
I'm developing a game in XNA, however, I do not want to use a content project. I'm loading all my textures through different means, and I'd also like to load my fonts without a content project.

Is there any quick way to maybe include the `SpriteFont` in the main game project?

# Answer
XNA is designed around the content processor pipeline and `SpriteFont` resources are designed to make use of that. There are really no *good* ways to circumvent that.

You *could* create a separate project that used a content project to generate and load the sprite font, and then use reflection to access the `SpriteFont` object's private members, including `textureValue` (which is a `Texture2D`) and spit them out to some format you can parse yourself. But that is really a bit heavy-handed, and at that point not much different than using a third-party, API-agnostic bitmap font generation tool (like BMFont).

Plus it still uses a content project somewhere in your pipeline. Your best option if you really don't want to make use of XNA's content pipeline is to find third-party tools.
> 1 votes

---
Tags: xna
---


# Question
Title: Why am I running out of memory in D3DPOOL_DEFAULT?
When trying to using my company's D3D9 renderer and allocating everything in `D3DPOOL_MANAGED` I would run out of memory in the 32-bit process space.

I tried using our D3D9Ex renderer and allocating in `D3DPOOL_DEFAULT`, but that's giving me an error of `0x8876017C` (`D3DERR_OUTOFVIDEOMEMORY`).

I'm unclear on what this means. Is this implying that the driver will not manage anything in `D3DPOOL_DEFAULT`?

I have 2.5GB of AGP space and 4GB of device memory, and all of my application meshes and textures are only 2.4GB on disk. I'm only using about half of those at any given time. Is there some hidden limit I'm bumping into here?

# Answer
To solve this problem, I'd recommend you build a paging or streaming system. This will allow you to dynamically load and unload resources as they are needed, keeping only what is necessary for the current area of your game on the GPU (instead of trying to keep *everything* there all the time).

If you have single resources (such as textures) that are overly large, you'll have to consider ways to break them up or reorganize them so you don't have single, monolithic, gigabyte textures floating around.

As to the background, or *why* you get this error:

`D3DERR_OUTOFVIDEOMEMORY` means that the graphics device is being asked to utilize more resources in a single frame than will fit in video memory.

Using `D3DPOOL_DEFAULT` for a resource means that that resource will be placed, based on the set of usage criteria you specify when creating the resource, in the most-appropriate memory pool. This is usually video RAM. The API will *not* manage anything in the default pool like it would with the `D3D_MANAGED` pool (if the device is lost, you must release and re-create default-pool resources), if that is what you are wondering about.

The error you are getting means that your resources can't all fit. Keep in mind that

* the size of a texture or any other buffer data on *disk* (and even in system RAM) does not necessarily equal the size of the resource once it gets to the graphics card. The data may be reorganized and resized to improve performance. It is unfortunately very difficult to get D3D to give you good statistics about on-GPU memory consumption and breakdown.
* the driver may subdivide GPU memory into buckets for various uses ("this much" for texture memory, "that much" for vertex buffers). You don't necessarily get the full range of physical GPU RAM to do whatever you want with, so you shouldn't write against that assumption.
* Direct3D may logically subdivide its memory; consider that even if a default-pool resource is not placed on the GPU, D3D keeps the CPU-side `D3DPOOL_MANAGED` and `D3DPOOL_DEFAULT` memory pools distinct.
* the previous two points will result in memory fragmentation, meaning that even if there is physically enough free RAM floating around to satisfy a request, it might not all be contiguous within the same logic pool and thus the request must be denied. This can, in fact, happen even within a single pool of memory (just like it can on the CPU side of things), resulting in a failed allocation.
* there are other resources besides the textures or buffers you create from your own data on disk that D3D has to maintain on the GPU; they take up some space as well.

Because it's difficult to get D3D to tell you useful things about GPU memory usage breakdowns, you're likely going to need to assume the worst and take a broader approach to solving the problem (as outlined in the beginning).
> 4 votes

# Answer
Your process address space is actually going to be considerably smaller than you think; for a 32-bit program (and this is true even on 64-bit Windows) it's 2GB, so your 2.4GB of resources are going to considerably overflow that.

One way of working around this is to use special startup switches in your boot.ini (XP or lower) or bcdedit options (Vista or higher), which increases you to 3GB for user mode allocations but at the expense of reducing kernel mode allocations to 1GB. Even if it did work for you, all users of your program would also need to do the same, which is a requirement you shouldn't force on them.

You need to look at that 2.4GB of resources and ask yourself a few questions about it.

First of all, do you really need all 2.4GB loaded at the same time? Most games don't load all resources at once; aside from onerous memory requirements it just takes too much time. That's why games are often divided into "maps", and for each map you only load the resources needed by that map. When the player transitions to a different map you unload resources from the previous one and load resources for the new one.

Secondly, it's likely that a lot of your textures are quite high resolution. Do you really need them to be so high? Reducing texture resolution is a great way of reducing memory requirements, and your program will load faster and run faster too.

Using these approaches you should be able to get your memory usage down to something more manageable.
> 1 votes

---
Tags: directx9, resource-management
---


# Question
Title: How can I draw a perspective-correct quad?
I'm trying to draw a quad in 2D (in SharpDX, but that is basically XNA). But texture correction is not working, and I'm getting only an affine textured quad.

I'm using `BasicEffect` to render it.

```
BasicTextureEffect = new BasicEffect(Device)
{
    Alpha = 1.0f,

    TextureEnabled = true,
    LightingEnabled = false,
    VertexColorEnabled = true,

    Projection = Matrix.OrthoOffCenterLH(0.0f, ScreenWidth, ScreenHeight, 0.0f, 0.0f, 1.0f),
};

```

It is an 2D isometric game. I have pseudo-3D coordinates in isometric world (it's a shadow on the ground) converted to screen space, and then rendered using `DrawQuad`.

Do I need to set-up view (or projection?) somehow, to real 3D (emulate the isometric camera), and then draw this quad in 3D coordinates instead? How eventually? Or is there a way to correct this in 2D?

**Update:**

I've uploaded the actual partial screen-shot (Figure A), for you to see it's almost the same. (I cut it a bit, but it goes all to the corner)

Figure A Figure B

**Update 2:**

I can confirm now, that plain SharpDX (XNA) `BasicEffect` does this with just plain UW mapping (4 corners of a square), and plain `DrawQuad`. I've temporarily changed it to include center point, and I do draw 4 triangles instead of 2 (Figure B), this reduces effect to minimum, but it's still there. It still needs to be solved, because I won't be using it only on shadow.

# Answer
I've changed the shader according to the article suggested by Seth Battin. Now it performs perspectively correct quad texturing. Phew, bacon delivered:

For the future generations that may never happen. The input is in a form of the line vertexes A1/A2, B1/B2 that creates diagonals (rather then sequential vertexes):

```
public static Vector3 DrawPerspectiveCorrectQuad(VertexWithPerspective v1, VertexWithPerspective v2, VertexWithPerspective v3, VertexWithPerspective v4)
{
    // detects intersection of two diagonal lines
    Single divisor = (v4.Position.Y - v3.Position.Y) * (v2.Position.X - v1.Position.X) - (v4.Position.X - v3.Position.X) * (v2.Position.Y - v1.Position.Y);
    Single ua = ((v4.Position.X - v3.Position.X) * (v1.Position.Y - v3.Position.Y) - (v4.Position.Y - v3.Position.Y) * (v1.Position.X - v3.Position.X)) / divisor;
    Single ub = ((v2.Position.X - v1.Position.X) * (v1.Position.Y - v3.Position.Y) - (v2.Position.Y - v1.Position.Y) * (v1.Position.X - v3.Position.X)) / divisor;

    // calculates the intersection point
    Single centerX = v1.Position.X + ua * (v2.Position.X - v1.Position.X);
    Single centerY = v1.Position.Y + ub * (v2.Position.Y - v1.Position.Y);
    Vector3 center = new Vector3(centerX, centerY, 0.5f);

    // determines distances to center for all vertexes
    Single d1 = (v1.Position - center).Length();
    Single d2 = (v2.Position - center).Length();
    Single d3 = (v3.Position - center).Length();
    Single d4 = (v4.Position - center).Length();

    // calculates quotients used as w component in uvw texture mapping
    v1.TextureCoordinate *= Single.IsNaN(d2) || d2 == 0.0f ? 1.0f : (d1 + d2)/d2;
    v2.TextureCoordinate *= Single.IsNaN(d1) || d1 == 0.0f ? 1.0f : (d2 + d1)/d1;
    v3.TextureCoordinate *= Single.IsNaN(d4) || d4 == 0.0f ? 1.0f : (d3 + d4)/d4;
    v4.TextureCoordinate *= Single.IsNaN(d3) || d3 == 0.0f ? 1.0f : (d4 + d3)/d3;

    // this is just PrimitiveBatch<VertexWithPerspective>
    // where VertexWithPerspective is basically VertexPositionTextureColor
    // with Vector3 (uvw) instead of Vector2 (uv) for texture coordinates
    // note: you need to create VertexWithPerspective yourself (decompilation ftw)
    PerspectivePrimitives.DrawQuad(v1, v3, v2, v4);
}

```
> 8 votes

---
Tags: textures, directx, xna-4.0, perspective
---


# Question
Title: How can I import a .3ds file into JMonkeyEngine 3?
I am trying to import an animated character body (with skeleton) from 3D Studio Max to JMonkeyEngine 3, but while we succeeded at importing some animations, we cannot seem to export the skeleton to `.skeleton.xml` using OgreXML format. Since OgreXML seems to be the favored way to import models into JME, we dropped `.obj` files and such.

How can I get a `.3ds` file into my JMonkeyEngine project?

# Answer
> 1 votes
JMonkeyEngine does not natively support `.3ds` as of this writing. Your best bet is going to be to wrangle your `.3ds` models into a format it *does* support, such as `.blend` or `.obj`.

If you don't need the animations, I'd go with `.obj`. Even though it may not be "favored," it sounds like it will work, and that's more important.

You could also import the Max file into Blender and then save it, since the engine's asset pipeline supports `.blend`.

It appears that as of the beginning of January, support for importing `.3ds` was added, but it's unclear whether this was only a community-build set of scripts or if it will eventually make it into the real product.

---
Tags: 3d, jmonkeyengine
---


title: What are registers in HLSL for?

text:
# Question
Title: What are registers in HLSL for?
I've read this document about HLSL registers, but it's more of a syntax description and not a purpose explanation.

What are registers in HLSL, actually? How and when do I use them? What happens if I don't (what's the default)?

# Answer
A given shader model exposes a particular set of registers to HLSL; these registers are underlying hardware registers on the GPU, like CPU registers, but have more refined scopes (for example, there are registers dedicated to holding samplers).

Registers are where all your data is stored during the execution of your shader (with the exception of data, like texture or vertex buffer data, that is held in the GPU's RAM). On a GPU, you don't have the same flexibility in reading and manipulating memory as you do on a CPU. There's no "store this value to RAM for a moment," so everything has to be in registers. This is particular obvious in old shader assembly (from the shader model 1 era).

Data transfer can occur via these registers as well, which is why the keywords still exist in more modern shader models. If you're not using the effects framework, for example, you can manage the allocation of your sampler or constant registers yourself (for example via methods like SetVertexShaderConstant). Similarly, data from buffers can be mapped to registers; the vertex input registers typically get your vertex buffer data mapped to them prior to execution of your shader.

You can find a list of registers and their purpose on the MSDN. Here, for example, is the set for VS 5.0.

Often, you don't need to use them directly, much like CPU registers. They will be used automatically by the higher-level language constructs that you use in your shader code or in the API (such as the aforementioned effects framework).
> 9 votes

# Answer
The specific registers you deal with syntactically will be some form of I/O register. Josh explained excellently what registers are and why they're used on the GPU. The syntax you use to declare variables in specific registers is for transferring data. On the CPU you create an Input Layout (Vertex Array Object in GL) or set uniforms or samplers/textures. This maps values in your vertex buffers to specific registers (via semantics for vertex data). The C++ code and HLSL code must agree on which data will be in which register for input as well output for MRT and the like.

If you don't specify registers explicitly, the HLSL picks them for you. You should not rely on how it picks them; even if it seems stable it may change in a future version. You can use the shader introspection APIs to determine which registers the compiler picked so you can setup your input layouts appropriately. This is less efficient and more difficult than just declaring the registers in your shader code.

Essentially, the C++ says something like "the camera data is in constant buffer register 3." The shader then must read that buffer from register 3 or it won't work correctly. You can do it by name like old GL forced you to, but you shouldn't.

This is all the same for recent GL/GLSL too, though obviously with differing syntax and APIs.
> 4 votes

# Answer
Registers are a type of storage that is located on a processor, and accessible very rapidly. They are typically substantially smaller, and are used as input and output locations for processor instructions. HLSL provides a method for mapping up data to these registers from the CPU side, to be used within your shader on the GPU. They should be used whenever you have data that needs to be referenced within a GPU, but is only available at run time on the CPU(such as world view projection matrices), and thus must be copied to a GPU register. Here is an article describing registers in a non-hlsl context http://en.wikipedia.org/wiki/Processor\_register
> 0 votes

---
Tags: hlsl, directx11
---


# Question
Title: Do glColorMask and glDrawBuffer accomplish the same thing?
I'm doing a shadowmap pass (only storing depth values) so I set `glDrawBuffer(GL_NONE)` to disable color writing for the moment.

Yet, I see some tutorials also do `glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE)`. Is this really necessary, given `glDrawBuffer(GL_NONE)`? Don't they accomplish the same thing?

# Answer
The behavior of both of those functions, in general, is different:

`glDrawBuffer` controls writes to an *entire color buffer*. You can use it to enable or disable *all* writes to the front left, front right, back left, or back right buffers (or to some combination thereof).

`glColorMask`, however, controls writes of *entire color channels* to *all* color buffers (the related function, `glColorMaski` can be used to control entire color channels for a specific buffer).

In the case where you using the functions as specified, the effective result is the same for both calls: `glDrawBuffer(GL_NONE)` specifies that *no buffers* are to be drawn to, whereas `glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE)` specifies that no colors are to be written to all buffers.

In general, of course, the behavior is different. You'd use `glColorMask` if you wanted to only disable writes of the red color channel; `glDrawBuffer` does not give you that kind of granularity. However, `glColorMask` only makes sense in RGBA mode, but it has a nice parity with other masking functions like `glDepthMask`. Et cetera.

In the case where the effective result would be the same, you can choose whichever function you like best... and it doesn't make sense to do *both*, as you are implying some tutorials suggest.
> 3 votes

---
Tags: opengl
---


# Question
Title: Is it acceptable to buffer no data OpenGL?
Correct me if I am wrong, but if you call "glBufferData(...)" upon an existing buffer, it will resize the buffer to whatever data you upload.

Does that mean if I call something like

```
glBufferData(GL_ARRAY_BUFFER, 0, NULL, GL_DYNAMIC_DRAW);

```

it will keep the buffer in existence, but it will have size and no data?

In the description of `glBufferData`, it says it is acceptable to pass `NULL` as a `data` parameter, but it mentions nothing of the `size` parameter.

# Answer
I have only seen this done with buffer orphaning. The idea is to manually map your buffer for use, this way as a user you know which portions of your buffer have been written and commit to the OpenGL driver. Once you run out of memory on your buffer you call `glBufferData` with a NULL parameter.

This tells OpenGL to find a new contiguous memory chunk to use. You need to pass in your desired size of this new buffer, so your example with zero is (I think) not what you want.

The reason to do this is to allow for asynchronous writing. With this method you can just send data to the GPU over and over without caring about if the previously mapped buffer sections are still locked or not (still being read by the driver).
> 1 votes

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


# Question
Title: Strategy for detecting hits from a "cylinder ray"?
I was planning on using ray casting for collision detection in my game. However, when I use an attack similar to this:

(which would project something like a cylinder), how would I go about detecting if it hits the other player?

# Answer
I think this is what you want:

Physics.SphereCast

From the docs:

> Casts a sphere against all colliders in the scene and returns detailed information on what was hit.
>
> This is useful when a Raycast does not give enough precision, because you want to find out if an object of a specific size, such as a character, will be able to move somewhere without colliding with anything on the way. Think of the sphere cast like a thick raycast.

It basically tests for collisions against a capsule (cylinder with rounded ends) with a specified start point, direction, radius, and length.

Note that this will not detect collisions with triggers. It will only give you information about the first collision encountered - so if you want the beam to pass through the first target and hit a second/third/etc, you'll want to use Physics.SphereCastAll instead.
> 4 votes

# Answer
This is typically done with multiple raycasts. The game design dictates the exact pattern needed but a simple one is to just do 4 or so casts at equal distances along the surface of the cylinder. Do all the tests, collect all their results, then take the hit with the shortest distance. Avoid overly small or narrow objects in your design and you don't need to worry about "gaps" in the cylinder's rays.

If the cylinder is particularly wide, add one or more rays, both to the surface and inside.

A similar technique is used for comes and certain scatter weapons, like shotguns.
> 0 votes

# Answer
Transform key points (see below) of the other player's body into the object space of the cylinder.

Then check whether any of them fall within the axis-aligned bounding box of the cylinder.

If so, then check whether they fall within the cylinder, by checking radial distance from cylinder's axial centre.

Key points to check would be on the other player's extremities, e.g. head, hands, feet, maybe elbows and knees, aside from obviously torso centre.

This will likely be faster than `Physics.SphereCast`.
> 0 votes

---
Tags: collision-detection, unity, raycasting
---


# Question
Title: Developing a browser-based RPG: Loading user data
I'm writing a browser-based RPG in JavaScript, HTML5 with Canvas, EaselJS, etc... I'd like to develop the back end data saving/user profile aspect now.

This is a single player RPG where the player will interact with NPCs to solve quests. It is not online.

I've developed a website in PHP before where I saved my own data in a database, and loaded the images to the page via MySQL and PHP.

For a RPG, how would this process be? In my mind... I will try:

* At the RPG menu, have a user login screen. Handle this with a traditional PHP session.
* Once the user logs in, load their stats from the database.

What I'm confused about is:

* Loading text data is okay I suppose... but how can I load objects that were on the screen in the correct locations at the time of the save? Can this be handled through the database?
* I have generated the Players, Objects, and NPCs as Javascript objects using EaselJS. To save the state of these objects, do I have to load the character as a PHP object?

Kind of like:

```
/**
 * Load a character and all related items and skills.
 * Do this when the user logs in. You can save the data in a session or
 * reload it every time the user makes a new request
 */
$Character = Character::model()->with('items, skills')->find(
    'username:=username',
    array('username' => 'demo')
);

```

Any tips for loading appropriate data per user profile?

Thanks!

# Answer
You could save the objects data structure serialized into a JSON structure and then save that blob of data as a database entry. Then on level load, deserialize the JSON and populate your game objects with the data pulled from the JSON.
> 1 votes

---
Tags: rpg, loading
---


# Question
Title: NavMeshAgent in Unity giving jerky performance
I am using NavMeshAgent in my Unity project to calculate and move my object to a particular location.

When I do:

`navMeshAgent.destination = destinationPt`

the object starts moving, but the motion of the object is very jerky.

Is there a way to override the function which is responsible for the jerkiness of the object motion? Or is there a way I can remove the jerkiness of the motion some other way?

I also tried setting

`navMeshAgent.updatePosition = false`

after which I use

`navMeshAgent.CalculatePath(destinationPt, path)`

to get the path, but then after this I am not able to figure out how to write my own logic to make the object move. I want a smooth motion with a given acceleration and a max velocity.

# Answer
Your camera movement is jerky, not the movement of your object.

When updating the camera position it's best to use `LateUpdate`, this ensures that the update takes place after all of the other `Update` calls. This means the position of the camera will be accurately positioned for the same frame you're updating. As stated in the documentation:

> For example a follow camera should always be implemented in LateUpdate because it tracks objects that might have moved inside Update.
> 3 votes

---
Tags: unity, path-finding, navmesh
---


# Question
Title: How to create texture using raw RGBA texture data without having to use LockRect
I was previously uploading textures to DirectX by creating texture in `D3DPOOL_MANAGED` and then calling `LockRect` to upload the texture data to DirectX. However, I have switched to using DirectX9 Ex, and can no longer use `D3DPOOL_MANAGED`, so in order to call `LockRect` I have to make the texture use `D3DUSAGE_DYNAMIC`. However, I would prefer not to have to use `D3DUSAGE_DYNAMIC`. Is my only other option to create a texture in system memory, and then call `IDirect3DDevice9::UpdateTexture` to get the texture data into video memory? I also see there is a `D3DXFillTexture` function. But what i really want is something equivalent to `glTexImage2D` where i can create a texture and pass it raw data.

Note that I have stripped down RGBA texture data, otherwise I would try using `DXCreateTextureFromFileInMemory`.

# Answer
> 1 votes
Other alternatives include using UpdateTexture or UpdateSurface from a D3DPOOL\_SYSTEMMEM source.

Under Vista+ (which I assume you're targetting since you're using 9Ex) you can supply the texture data via the pSharedHandle arg to CreateTexture; per the documentation:

> In Windows Vista CreateTexture can create a texture from a system memory pointer allowing the application more flexibility over the use, allocation and deletion of the system memory.

Caveat: I haven't done this and can't vouch for it.

---
Tags: directx, directx9
---


# Question
Title: Could I make my own pokemon game without running into a copyright issue?
I've always wanted to make a video game that criticises pokemon. I want to know if I could use pokemon as the characters in the game without running into copy right laws. The game itself will have nothing to do with the normal purpose of pokemon but at one point also mimics pokemon mystery dungeon a little. that point in the game would be similar to the rescuing of other pokemon and will also have some of the same characters in pokemon mystery dungeon. so, could I possably make this game? or not. If I couldn't, what would it take to have permission. If your wondering how the game criticises pokemon, it does so cause it's supposed to be a gory hard core M game. What if I was to not include any of the titles from pokemon like pikachu for example and just simply give the characters real life names as well as give minor changes in designs and abilities? Could that help avoid copyright problems?

# Answer
> 8 votes
When I see these types of questions, I like to give the same answer:

Unless you have deep pockets (which I'm assuming you don't; otherwise you'd be asking a lawyer), you shouldn't really ask whether something is legal (etc.) but whether you're likely to get sued. If you can't defend yourself, it doesn't really matter whether you *could* win in court, it only matters that you couldn't adequately represent yourself legally. And often times companies that *do* have deep pockets are well aware of this. (*cough cough, Zynga*)

Of course, you should always keep your conscience in mind - is this moral? Unfortunately this seems to be less relevant as capitalism grows.

**Edit:** To answer your question more directly, you would be very likely to encounter legal recourse if you used original game characters in your game, particularly if you use original artwork. I'm no lawyer, though, so you should seek professional legal advice before moving forward with your game idea.

# Answer
> 6 votes
To parody Pokemon, you are not required to *copy* Pokemon. You simply need to reference it. Traditionally, this is done with obvious knock-off characters.

So instead of Pikachu, you might have Zapachu or something like that. Just look at common parodies in fiction; that's generally how they work.

Parody, legally speaking, is protected. You're allowed fairly wide latitude to parody things. But be warned: if your parody strays too close to the source material, you could be in for a lawsuit, even if it is a parody. Where that line is depends on who's the copyright holder.

Lawsuits are expensive even if you ultimately prevail. So I suggest *discretion*: try to make it clear that you're parodying it without taking too much directly from it.

# Answer
> 3 votes
I suspect you would run into copyright troubles.

On the one hand, copyright law does allow fair use exceptions for parodies and documentaries that criticize the original work. On the other hand, this description does not sounds like a criticism:

"it's supposed to be a gory hard core M game"

That's not criticizing Pokemon, that's making Pokemon:XTREME

# Answer
> 3 votes
I think this is a question that you can answer on your own, if you're honest with yourself.

Imagine for a moment that you've spent more than ten years of your life creating a suite of hundreds of characters and a huge game world. You've made a series of child-friendly games that people around the world love, and done pretty well by yourself through them. These games are one of the core franchises that keeps your company afloat, and allows you to continue to pay your employees.

Now imagine that a no-name developer contacts you out of the blue, and wants permission to remake one of your existing games, but including gore and other adult content. Under what circumstances would you *ever* agree to that?

# Answer
> 0 votes
I know this post is old as shit but, I'm getting into this kind of area right now, thinking of making a game about an existing franchise.

Through what I've researched so far, it all comes down to money. If you're not turning a profit, then game companies shouldn't care so much, unless what you're doing dramatically alters the lore, context, genre, story, ethos, context, presentation, chronology etc of the series of games. And ultimately, put a giant disclaimer in your game somewhere that denies all rights, and say that it is a non-profit product.

If you ARE turning a profit, then chances are the company is gonna be interested, they'd probably like a large slice of cake. What I'd do, is contact the developers on their policy and ask them how they'd feel about what you're doing, and if it comes to it, discuss what % of money they would have out of it. Better yet, if what you're doing is successful, sell them the idea or ask to work for them based on that, like catch me if you can.

Don't try to avoid the company, work *with* the company!

---
Tags: game-design, legal
---


# Question
Title: Should the game update loop compensate for slowness
I am building a game engine and considering the design for the core game loop that will drive the game.

In the most basic form, the implementation looks similar to this (in pseudo-code):

```
while (game.running)
{
    // Calc time delta from last update
    var timeDelta = Time.now - lastUpdate

    engine.components.update(timeDelta)

    engine.drawAll()
}

```

This loop updates and draws in a 1:1 ratio (for every update there's a draw).

Should there be any compensation for the engine when it runs slower than its target update rate?

I've seen frameworks such as XNA for example, with the IsRunningSlowly property: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.gametime.isrunningslowly.aspx

Is it preferred to keep a 1:1 update/draw ratio? or should i compensate for slower updates?

# Answer
First, Fix Your Timestep. The component update should always have a fixed time interval. This is critical for stable physics and can avoid bugs in other systems as well.

You may have cases where the time interval becomes huge, too. This can happen if you set a breakpoint while debugging. You'll want to cap the update time used for the time accumulator (or the raw update value if you don't follow the linked article's advice) to avoid really broken behavior when debugging.

Additionally, you can interpolate between the current frame's data and the last frame so the motion stays smooth and buttery. Simply keep two copies of game object animation data (position, skeletal animation state, etc.) and then interpolate between them. Thus your game will mostly look like it's running at a full 60+ FPS even if updates are running less often.
> 6 votes

# Answer
I've +1'd @Sean Midleditch 's answer, but as some considerations:

(I'm not really happy with how this is kind of a disorderly rant, but...)

* Video hardware varies wildly between hosts, unless you're on a Gaming Console (3DS, Wii U, PS4, Xbox1). Even "the same device" will have different GPU capabilities between generations (e.g. "iPad"), or may have different screen resolutions connected (e.g. SDTV, HDTV)
* All major platforms (the Big Four consoles, iOS, Android, and PC/Lin/Mac/Win) commonly have *at least* dual-core CPU's, and often more (many home PC's have 4, 6, or 8 cores). Having a single driver function push physics and graphics means you're binding most of your game's functionality to one core.
* The rate at which your *simulation* occurs shouldn't be limited to – nor impose a limit upon – your graphics systems.

EG: the sudden spike in scene complexity when walking out a doorway into an open space might drive the graphics framerate from 65fps to 50fps suddenly. If your physics continues to run smoothly, though, the human eye will compensate for it.

Now, unless you're using a hardcore ECS model with immutable entities, you're *probably* going to encounter the situation of mutating (i.e. writing/setting) state onto a shared "object" of some kind that is read/written by the simulation and read by the graphics subsystem.

The difficulty is maintaining sync points between them.

One simple way is to maintain a mutex which the simulation system must acquire before writing to the shared state. When the simulation wants to mutate an object that the graphics engine might want to access, it has to acquire the mutex in read-write mode; when the graphics system is in its "critical path" and needs to grab data on a great many objects very quickly, it acquires a "read-only, but locked for writing" condition on the entire affected area.

If you're simply running two threads in parallel on different cores, now you have a time during which your simulation might "stall," but you can hopefully still show improvement over using a single core and doing `(loop (simulate) (draw))`

(You might have one mutex per "room" or other subdivision of the game world, for example.)

* **Warning:** I am a fierce proponent of "Pure" ECS systems and immutable objects. Other people will tell you that the below is over-the-top or silly, and they might be right.

The "hardcore" way I referred-to above is something that OOP generally is poorly-equipped to handle, so it's not often used in C++/Java/C#, but is used sometimes in Haskell/ML/Erlang/Lisp type systems. The essential idea is that an object is immutable; in Java terms, it has "only `final` fields". When the simulation wants to "mutate" the object, it instead must create a new object with the mutated value(s), and then cause it to replace the "old one."

Think of it in terms of read-only files in a read-write directory:

```
 echo "(:SIZE 92 :X 100 :Y 100 :Z 100)" > ~/world/thing1

 echo "(:SIZE 92 :X 102.2 :Y 100 :Z 100)" > ~/tmp/.#thing1.new

 echo "(:SIZE 92 :X 102.2 :Y 104.3 :Z 100)" > ~/tmp/.#thing1.new

 mv -f ~/tmp/.#thing1.new ~/world/thing1

```

The new instance replaces the old instance, requiring memory policing or garbage collection on every mutation.

If you were instead sharing a mutable object without mutex protection of some kind, then it's possible that you might make multiple mutations and the graphics system could display an inconsistent state. EG: imagine the "Draw" of thing1 occurring after the second `echo` mutation above, when X had been updated, but not yet Y.

(Furthermore, you can make the memory objects recycleable, by allowing them to be re-written and re-used, just never doing so while they're linked to the world database, to avoid constructing new objects inside your simulation loop, since memory allocation and garbage collection are relatively slow operations. That's an optimization that you might wish to keep in mind – e.g. having a common place to construct and replace the objects, so you can more easily implement some kind of recycling pool later if you need it – but probably not the kind of thing you need to worry about until/unless you profile your simulation system and discover that you're spending too much time in construction or garbage collection.)

Why go to such oddball lengths? In theory, you don't need to have only one simulation system! On a multicore system, you can break out various systems to run in their own threads or processes, each potentially running at a different rate.

With the use of the seemingly-complex immutable-object model, each of them can "not really mutate, but effectively mutate" the game state at approximately the same time.

Using other models, you might need to have mutexes protecting access to some parts of your world at any given time, and handle the interaction between systems with a little more care.

For example: Consider having

* one thread for reading player controls (keyboard, gamepad, mouse, touchscreen, whatever);
* another for playing sounds;
* another for graphics;
* another for network I/O to share the game state;
* another for performing local physics simulations;
* another for processing "special triggers" in the UI, e.g. detecting when the player's health is beneath 10% to start flashing their health gauge;
* another for managing "scripted events" in the game world;
* another for running AI character logic

Each of these might have a different "best rate," and you might wish for some of them to run at a higher or lower priority than others. If your AI pathfinding solution takes 230ms instead of 200ms, it's less likely to be noticed than if your physics simulation drops from 24fps to 20fps. As long as sound, graphics, physics, and player input are consistently smooth, you can get away with less frequent updates occurring in some areas.

Yes, thread context switches have a cost – and there are ways to do the same kind of thing without threads, e.g. having a "time-shared" slot in your update loop that calls different subsystems on different "frame numbers" (do AI on every frame 1, 3, 5, and 7, modulo 8, input polling on frame 0, scripted events on frame 2, sound changes on frame 4, and triggers on frame 6, while running physics on every frame)
> 1 votes

---
Tags: architecture, game-loop
---


# Question
Title: Blurry Background Images When Player is moving
So I've been developing a platformer and the when the player moves around the world the background images and tiles become really blurry. I've tried a number of fixes. I've made sure that the position given out by the camera and player are both whole numbers as you can see in the video below.

http://www.youtube.com/watch?v=1AFuP1yXhY4&feature=youtu.be

On top of that I've also made it a point to use PointWrap in every SpriteBatch call made in the game

```
spriteBatch.Begin(SpriteSortMode.Texture,
                   BlendState.AlphaBlend,
                   SamplerState.PointWrap, null, null, null,
                   camera.TransformMatrix);

```

None of these works are really working, could someone please give me some other suggestions to try ?

# Answer
> 1 votes
I had the same issue. Try the following:

Set PreferMultiSampling to false to prevent multi sampling this.graphics.PreferMultiSampling = false;

cast the camera positions to int if you can it

set the sampler state to PointWrap, (SamplerState.PointWrap)

if nothing helps, try to use a power of two texture for the tiles, background etc. 256, 512, 1024 ....

---
Tags: xna
---


# Question
Title: Alpha Value at 0 Shows Black for Android Canvas Bitmap
There have been a few questions similar to this but none seem to give a straight answer. If I am creating a Bitmap from a .png image and want to set a color (i.e. true pink) to transparent, the color turns black instead. I am using get and set pixel methods, iterating through an array of pixel colors.

The method I wish to accomplish this in is as follows:

```
public Bitmap getFormattedBitmap(Bitmap bm, int newHeight, int newWidth, int r, int g, int b, int a) {
int width = bm.getWidth();
int height = bm.getHeight();
int pixNum = width * height;
int[] pixels = new int[pixNum];
int scaleWidth =  newWidth * width;
int scaleHeight = newHeight * height;

bm.getPixels(pixels, 0, width, 0, 0, width, height);

for(int k = 0; k < height; k++) {
   for(int j = 0; j < width; j++ ) {
        int red   = Color.red(bm.getPixel(j, k));
        int green = Color.green(bm.getPixel(j, k));
        int blue  = Color.blue(bm.getPixel(j, k));
        int alpha = Color.alpha(bm.getPixel(j, k));
        int index = k * width + j;

        if(red == 0 && green == 0 && blue == 0 && alpha == 255) {
            pixels[index] = Color.argb(a, r, g, b);
        }
        else {
            pixels[index] = Color.argb(0, 255, 255, 255);
        }
    }
}

bm.setPixels(pixels, 0, width, 0, 0, width, height);

Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm, scaleWidth, scaleHeight, true);
return resizedBitmap;

```

}

As you can see, I am using the Color.argb() method to set the alpha to 0, but in reality, it just shows those parts as black on the screen. I recognize bitmaps don't take kindly to alpha channels (unless you configure it to ARGB\_8888), but this has me stumped. It is also interesting to note that I do have SOME control of alpha via the Color.argb() method, it is just if it is too close to 0 it turns black anyway. Something in that method or whatever I am doing does not like full transparency apparently.

# Answer
> 2 votes
I just love these simple methods that throw a wrench in your gears.

I perused the internet a little harder and found that I needed to add `bm.setHasAlpha()` before the image is reformatted, so it realizes it has alpha. I know, it seems redundant, especially since it appears to be in `ARGB_8888` the entire time.

Hopefully others can learn from this, I am implementing in a game actually to change a color on my spritesheet to transparent (blitting is the term I believe). While not many phones have pre-Honeycomb anymore, it would be interesting if anyone can find a work around for \< API 8.

Thanks for reading, here's the method:

```
public Bitmap[] loadText(String msg, int size, int red, int green, int blue, int alpha) {
    //Jumping to next line algorithm
    //Would use toUpperCase, but location problem w/upper case in other languages...
    Bitmap[] phrase = new Bitmap[msg.length()];
    for(int i = 0; i < msg.length(); i++) {
        for(int j = 0; j < characters.length(); j++) {
            if(msg.charAt(i) == characters.charAt(j)) {
                if(j <= 38) {
                    letter = Bitmap.createBitmap(Assets.textFont, j * 8, 216, 8, 8); //Subset method
                    letter.setHasAlpha(true);
                    letter = getFormattedBitmap(letter, size, size, red, green, blue, alpha);
                    phrase[i] = letter;
                }
                else {
                    letter = Bitmap.createBitmap(Assets.textFont, (j - 39) * 8, 232, 8, 8); //Subset method
                    letter.setHasAlpha(true);
                    letter = getFormattedBitmap(letter, size, size, red, green, blue, alpha);
                    phrase[i] = letter;
                }
            }
        }
    }
    return phrase;
}

```

---
Tags: java, android, html-canvas, alpha
---


title: Rendering a minimap from large bitmap

text:
# Question
Title: Rendering a minimap from large bitmap
I'm trying to create a minimap for my game but am having an issue.

I'm using Direct2D as the graphics API and have a ID2D1Bitmap\* which contains the pixel data for the loaded area of the world.

I'd like the minimap to be around 100 x 100 pixels but the ID2D1Bitmap\* contains about 3500 x 3500 of pixel data. When I try to render 3500 x 3500 pixels in a 100 x 100 pixel area, the image becomes very distorted and unpleasant.

In most cases, I thought this was solved by generating a mipmap chain but I don't see any options like this offered by Direct2D.

How can I create a clear minimap using DirectX?

# Answer
> 1 votes
Usually minimaps are done by rendering the scene using a special, top-down camera. In your case though, the amount of scaling is extreme, so you'll lose a lot of detail one way or another. However, I suspect that your biggest issue is that the *important* fine detail is lost, like contours and edges.

I suggest you try using an image processing technique to preserve those edges. You can either find a library to do these, or if you know your way around bitmaps and multiplying pixels, they're fairly simple to implement too.

To demonstrate, I'll use this giant picture of the world map with political boundaries. Here's a close-up of the British Isles and an extremely scaled-down version (using basic bilinear, similar to what DirectX would be doing) to compare the loss of fine detail:

## Resize and sharpen

One easy method is to perform gradual resizes, but also sharpen at each iteration to preserve the edge detail. In this example, I'll resize to 50% and sharpen the image repeatedly until the image is tiny. Here's the result of a few iterations of resize and sharpen:

And here's the final result, at about 258x128:

## Edge detection

Another method is to use an edge detection image filter, thicken the edges, and combine the results with the normally-scaled image. Here's the result of one such filter:

Combined with the result of a normal scale, I get this:

---
Tags: c++, directx
---


# Question
Title: 2D jerky motion with AddForce and physics
I have a problem smoothly motion - I see jerking when I am using physics and AddForce.

It's not a question related to Update or Time.deltaTime - I created simple scene with few lines and sphere. When player clicked "\>" button, I apply force to sphere, but motion is jerky and is not smoothly (please see web version below).

Project: fixed ortho camera, sphere with disable gravity, few cubs and bouncy as default material.

To fixed this problem, I tried to use some solutions from posts, related with jerking motion in Unity:

* http:// answers.unity3d.com/questions/10907/smoothing-rigidbody-movement-over-a-bumpy-track.html
* answers.unity3d.com/questions/228095/why-is-the-motion-jerky-in-a-simple-2d-game.html
* answers.unity3d.com/questions/275016/updatefixedupdate-motion-stutter-not-another-novic.html

Things, that I tried:

1. Interpolate for sphere rigibody - slightly better, but jerky is still here.
2. Change Vsync(Dont Sync, Every Blank, Every Second Blacnk) and Quality (Fastest-Fantastic) - nothing
3. Use different object for collission (just rigibody and collision object) and display object(mesh renderer). This InterpolateToTarget.cs script in source folder - nothing.
4. In previous other game (with gravity, other default material, etc.) I used motion forward without AddForce, but I faced with jerky motion, too. I tried all solutions, that I find (FixedUpdate/Update with deltaTime, Coroutine, Transform.Translate, Interpolation, Lerp, LateUpdate...) and I saw that only one combination (small AddForce/Interpolation and Simply Quality setttings (VSync is turn off)) give me acceptable smoothly motion. But in this game I need AddForce with larger value and this solution is not work in this case.

Web version: https://dl.dropbox.com/u/15321992/2DjerkyMotion.rar

Sources: https://dl.dropbox.com/u/15321992/2DjerkyMotion.rar

Android apk: dl.dropbox.com/u/15321992/2dJerkyMotion.apk

Code that I am using for motion: public class TestMovingScript : MonoBehaviour {

```
private Rect restartBtnRect = new Rect(20, 20, 120, 60);
private Rect rightMoveBtnRect = new Rect(Screen.width - 100, Screen.height - 100, 100, 100);
private GameObject _player;
private Vector3 _movingVector = new Vector3(1, 0, 0);

// Use this for initialization
void Start () {
    _player = GameObject.FindGameObjectWithTag("Player");
    _player.rigidbody.AddForce(_movingVector * 20);
}

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

}

private void OnGUI()
{
    if (GUI.RepeatButton(restartBtnRect, "Restart"))
    {
        Application.LoadLevel(0);
    }
    if (GUI.RepeatButton(rightMoveBtnRect, ">"))
    {
        {
            _player.rigidbody.AddForce(_movingVector * 20);
        }
    }
}

```

}

I suppose in web version this jerking is not as noticeable, but on Android it is a horrible. Also, try to play in web version few minutes and you will see it. I don't believe, that Unity3d does not allow to build smoothly Android game, so maybe I missing something in physics/player setting.

I will be grateful for any suggestions and ideas.

Thanks, Dmitry.

# Answer
As stated in docs :

> If you add or subtract to a value every frame chances are you should multiply with Time.deltaTime. When you multiply with Time.deltaTime you essentially express: I want to move this object 10 meters per second instead of 10 meters per frame.

Try doing this :

```
public class TestMovingScript : MonoBehaviour {

private Rect restartBtnRect = new Rect(20, 20, 120, 60);
private Rect rightMoveBtnRect = new Rect(Screen.width - 100, Screen.height - 100, 100, 100);
private GameObject _player;
private Vector3 _movingVector = new Vector3(1, 0, 0);
private Vector3 _appliedForce = Vector3.zero;

// Use this for initialization
void Start () {
    _player = GameObject.FindGameObjectWithTag("Player");
    _appliedForce = _movingVector * 2000 //Notice that here i multiply your value by
                                         // 100 (approximately what you need to
                                         // compensate deltaTime (around 0.01xxxx)
    _player.rigidbody.AddForce(_appliedForce *Time.DeltaTime);
}

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

}

private void OnGUI()
{
    if (GUI.RepeatButton(restartBtnRect, "Restart"))
    {
        Application.LoadLevel(0);
    }
    if (GUI.RepeatButton(rightMoveBtnRect, ">"))
    {
        {
            _player.rigidbody.AddForce(_appliedForce *Time.DeltaTime);
        }
    }
}
}

```

Why multiplying by DeltaTime might fix the issue?? : Because AddForce() ADD a force to the sum of forces applied to your rigidbody, and then each force applied will diminish with time (except if you have no gravity and even ther i'm not sure) and if used in Update() it will add every frame the amount of force you want but frames are NEVER evenly timespaced so sum of forces will have different value each time you apply a new force so even if you add every time the same force, because you do not add it at the same interval of time it will stutter.

What delta time does is that it will multiply your force by the timespan between the previous frame and this one so the final value will compensate this timegap between the two frames

It is worth noticing that in this particular case you might try :

```
_appliedForce *Time.fixedDeltaTime

```

As Fixed Delta Time is the timespan between two physics calculated states

Docs here :
> 1 votes

---
Tags: unity
---


# Question
Title: How is a splash screen that is disposed upon user input meant to be implemented?
I'm going through Gustavo Steigert's tutorials on libgdx, but I have a feeling that this is more of a design question, rather than specifically regarding libgdx. My question is regarding the splash screen. I can implement what he has in that tutorial without any errors, but I want to add a little extra. In every game I've ever played, the splash screen goes away when the user left-clicks or presses esc, so I'm trying to add that (strangely, I can't find any tutorials with splashes like that). So, I have this method in my `SplashScreen` class:

```
public boolean handleInput() {
    if (Gdx.input.justTouched()) {
        game.setScreen(new MenuScreen(game));
        return true;
    } else {
        return false;
    }
}

```

At first, I tried to make that method return `void` and simply call `splash.handleInput()` in the `render()` method of the main Game class, `Tyrian`. However, that doesn't work, because once the splash screen has been moved on from, `handleInput()` will still be called on every `render()`, and the game crashes if the user clicks a menu button. So, I made `handleInput()` return a boolean and used this code in `render()`:

```
if (onSplash) {
    if (splash.handleInput()) {
        onSplash = false;
    }
}

```

`onSplash` is a boolean inside the `Tyrian` class that is true by default.

Something else odd: when using the `void` version of `handleInput()`, the game will only crash if a button on the menu (the menu screen is the next screen) is pressed., and not if the screen is pressed. I am worried that the splash screen is never being disposed of (though my current solution does not seem to show that), because I can see from logging messages being printed to the console that the menu screen is being created upon every screen click, which is what `handleInput()` does. Also, if I put an `else` to that code above, with `splash.dispose();` as a result, the game will crash.

This is such a common action in games, I would be surprised if there was not a common and cleaner accepted way of implementing it that I have missed.

**EDIT**: I have changed the `handleInput()` back to `void` and have used the `instanceof` keyword in my main game file. It's a cleaner solution, but I'm not sure if it's the best (it's an extra check on every render!).

SplashScreen.java

```
public void handleInput() {
    if (Gdx.input.justTouched()  ||  Gdx.input.isKeyPressed(Input.Keys.ESCAPE)) {
        game.setScreen(new MenuScreen(game));
    }
}

```

Tyrian.java

```
if (this.getScreen() instanceof SplashScreen) {
    splash.handleInput();
}

```

# Answer
Take a look at this tutorial. It's one for AndEngine but I'd recommend it as I think it's design is pretty good.

I've been using this design and in my game you can also touch the screen to go to the menu quicker and it has never crashed before. The technique is actually, like you might've tried, to switch scenes and then unload everything from the previous scene.

I hope this helps! Let me know if it doesn't
> 1 votes

---
Tags: libgdx, screen, scene
---


# Question
Title: Car physics - velocity and latheral force
Im developing simple car racing game. To turn a car, I need to calculate slip angles for each tire and then use those angles to find lateral force (using Hans B. Pacejka magic formula). One thing I don't understand is relation between car\`s speed and lateral forces.

Everywhere is written, that lateral force depends only on slip angle. But it means that lateral force will be the same for slow and very fast velocity. Is that true? How to use lateral forces to move a car? In my opinion lateral force should be small if velocity is small.

# Answer
> 3 votes
Well, first of all I am by no means a physics expert.

Regarding your question, Your observation is correct, faster cars should have higher lateral forces, well but that's not the whole story.

I think your problem is that the question that needs to be asked, where does the lateral force come from in the first place?

In normal circumstances the car's engine generates force that makes the car moves forward. This force along with other forces that act on the car movement direction (or opposite) is called longitudinal forces.

On the other hand, in high speed cornering scenarios, the tires develop lateral forces also known as the cornering or side force. Which means this force is only generated when the tires have an angle between the tire's heading and its direction of travel.

Now the important point is, the angle between the tire's heading and its direction of travel is called `alpha`. When the movement direction is the same as the tires heading direction then Alpha is Zero. This results in a lateral force that equals zero.

When there is an angle between heading direction and the tire's traveling direction the velocity vector of the car is **now split into two components**:

* The longitudinal vector has magnitude cos(alpha) * velocity.
* The lateral vector has magnitude `sin(alpha) * velocity` and causes a resistance force in the opposite direction: the cornering force.

Which means that lateral force depends on the As the slip angle grows, so does the cornering force. Now the point is, at low slip angles, the relationship between slip angle and cornering force is linear.

> Flateral = Ca * alpha

Now, since this equation is only true for small angles, I believe this equation is using small angle approximation where:

Hence, dropping the sin and the velocity from the equation. Keep in mind that the linear relation is only true for small angles, otherwise the linear relation doesn't apply anymore. But I might be wrong someone with more knowledge might correct me.

---
Tags: physics, car
---


# Question
Title: Pipe connection game algorithm - Java/Andengine
I am creating a game based on Pipe Dream/Pipe Mania using java/andengine for android. I have a square grid of tiles each representing a type of pipe. The player needs to swap tiles to connect the pipes from point A to B.

How do I determine if the pipes are connected to starting point A? How do I then find how far a connected path goes? How do I determine if the path connects point A to point B? How do I handle the switching of tiles which may be in the middle of the path?

This functionality will be almost the same as the pipe mini game in the first Bioshock game.

I am looking for advice on how to go about tackling this problem.

# Answer
You are indeed working with a "graph" here and are looking at a connected component problem.

I would suggest keeping track of a source and continuing connection variable for each pipe point. Each piece has a variable noting if it is connected to point A, and which pieces depend on it for connection to A.

When you add a piece, check if its connecting neighbours are connected to A. If they are, mark this piece as connected to A, and mark each neighbour on which it may depend as having this piece depend on them and their neighbours too. Upon removal of a piece, you check the pieces dependant on it and procedurally mark them as disconnected from the source.

You can also keep track of the number of parent pieces all the way back to A. When you add a piece, you just take the smallest/largest parent, add 1 and store it.

When something connects to B, you can check if that connection goes all the way back to A and the largest/smallest path.
> 1 votes

---
Tags: java, android, algorithm, andengine
---


# Question
Title: JavaScript - 2D Top-down Collision Detection issue
I'm developing a 2D Top-down Game using HTML5 Canvas and a custom Game Engine. I'm implementing the Quad-intersection detection (Function below, if it helps) on different areas of the Sprites (As they're larger than Tiles in some cases), and have thought of an issue with this. I want to check these areas before moving, using the amount of pixels I will move if allowed to (Nothing blocking the character). Below if the code I use to move the Player:

```
move: function(delta) {
    var distance = Math.floor(this.getSpeed() * Math.floor(delta / 10));

    this.setMoving(false);

    if(Engine.input().isPressed(Engine.keys.LEFT_ARROW)) {
        this._config.x -= distance;

        this.setMoving(true);
        this.setDir(0);
    }
    if(Engine.input().isPressed(Engine.keys.RIGHT_ARROW)) {
        this._config.x += distance;

        this.setMoving(true);
        this.setDir(1);
    }
    if(Engine.input().isPressed(Engine.keys.UP_ARROW)) {
        this._config.y -= distance;

        this.setMoving(true);
        this.setDir(2);
    }
    if(Engine.input().isPressed(Engine.keys.DOWN_ARROW)) {
        this._config.y += distance;

        this.setMoving(true);
        this.setDir(3);
    }

    this.boundaries();
}

```

As the distance is not 1 pixel, it will be checking a few pixels ahead of the Player for solid tiles, and if there is one X many pixels in front of them, they can't move the distance and stop.

## Problem

So - let's say the distance is 3. If they're 2 pixels from a Solid Tile, they will not move those 2 pixels because of the collision detection, meaning there will be a 2 pixel gap between the Player and the tile, which will only increase the larger the Player, or Entities, speed.

Is there any way to get around this, other than having to check pixel-by-pixel for each anchor point I want to check collision on?

## Collision Detection

```
collided: function(box1, box2) { // Basic Quad-intersection Collision
    return (
        ( (box1.x >= box2.x && box1.x <= (box2.x + box2.width) ) ||
        ( (box1.x + box1.width) >= box2.x && (box1.x + box1.width) <= (box2.x + box2.width) ) ) &&
        ( (box1.y >= box2.y && box1.y <= (box2.y + box2.height) ) ||
        ( (box1.y + h1) >= box2.y && (box1.y + h1) <= (box2.y + box2.height) ) )
    ) ? true : false;
},

```

# Answer
> 2 votes
There's a couple of things you can do in this case:

1. **Move the player sprite then resolve collisions.** For simple 2D games you should probably use impulse resolution. The gist is that you move the player sprite, figure out what it is colliding with, then move the player sprite the shortest distance out of the colliding bounding box so that it isn't colliding anymore. This is a super common method of handling this that is used in many game engines. You can make this more complicated by taking the two objects' masses into account or just moving the player sprite if it is colliding with terrain.
2. **Only move the player sprite enough so that it isn't colliding in the first place.** If you know exactly what the player sprite is going to hit (as is common in the case of tile maps), then don't move the player sprite the full distance -- just enough so that the collision takes place, then set the player sprite velocity to 0. This is basically like #1, but might be simpler depending on what the rest of your physics code looks like.

Some useful terms that'll help with later Googling include: AABB (axially-aligned bounding box), collision resolution.

---
Tags: collision-detection, javascript
---