title: Time critical events based on framerate

text:
# Question
Title: Time critical events based on framerate
**Problem Description**

Basically, I've made a "programming game" in which I've made my own scripting language. It is a completely standard Lunar Lander game, though instead of directly controlling the lander using keyboard input, it instead fires a sequence of commands you have provided through the scripting language I made. This all works, and I've hit a critical problem.

So essentially, using the scripting language, you specify something like *After 5 seconds, activate thrust for 10 seconds, and then after 2 seconds, rotate the lander for 4 seconds*. The goal is then to chain together a sequence of commands which will get you to land the lander safely.

Of course, this comes with one problem. If you repeat the sequence of commands, each command will have to be fired at exactly the same spot in the level, that is, after x amount of seconds, but also with the lander being in the *exact* same spot. If you did not use timer-based movement, sure you could indicate that a command should activate after 5 seconds, but the lander moving at 60 FPS would have moved way further than a lander moving at 30 FPS.

Why of course, I thought I would simple just make the lander use timer-based movement so it is independent of FPS (I am using the very standard approach of taking the amount of time passed last frame, and multiplying it to a constant move speed). Then I would count seconds using the system clock. So the after x amount of seconds, the lander would be in the same spot in the level when the command activates.

Unfortunately, this approach do not work. Every time I run a sequence of commands, they will be activated with, sometimes very slight, variations, making it impossible to actually get a consistent and reliable path for the lander.

**My Question**

So my question is, am I tackling this problem a completely wrong way? What exactly do you do when it is absolutely critical that timed events defined by the user will activate at exactly the same time and spot in a level? I seem to be quite stuck with this question.

# Answer
> 6 votes
The general solution to this problem is to have an update function with a completely fixed timestep. Unity calls this FixedUpdate, in physics engines you can run the simulation several times before updating the world, etc. but it's all the same concept.

While this fixed update function will always be slightly out of sync with everything else in your world, if you select a small enough timestep (1/60 or 1/30 or so), this will be unnoticable. Another thing to remember is that you only need to use this update function for things that need to be absolutely deterministic, so it doesn't hog your cpu even if you need to run it several times before updating the world. And if it's not completely obvious, this function should have absolutely nothing to do with your system clock - this runs on a "simulated" clock that you keep track of, and that never actually steps over the real system clock, but is otherwise independent.

Having said all this, in your case there may be simpler solutions. You can pre-calculate the path for your unit and interpolate on that path. The idea behind this solution is that you think of your unit's movement as a continous function instead of a physical simulation.

Alternatively you can try to "snap" your ship to the correct position after every movement, so the arithmetic error doesn't add up. However this may cause visual glitches if your fps is low or not constant.

---
Tags: software-engineering, movement, events, frame-rate, timer
---


# Question
Title: create terrain with some vertical cliffs, natural arcades, caves using octree
I am about to start creating the first terrain. I would like to create a terrain with vertical cliffs, natural arcades and caves.

For instance in one point the terrain might look like this.

I want to discuss about how to store this information about the terrain.

I think quadtree will not do the trick. From my understainding with quadtree perfectly vertical terrain is bound to be low quality in the vertical part, as you cannot subdivide it.

So I thounght that octree should be the right tool. But I have a conceptual problem with octree. I cannot understand how to store the triangle data in a octree structure.

Understanding how to store data in a quadtree is easy: you subdivide the region in a lot of squares and you give a coordinate value to each vertex of the squares, then you just connect all the verticies with triangles.

But what can you do when it comes to octtree? Which information should you store conceptually in the octree tree?

I cannot guess the logic and the algorithm that lays behind a octtree terrain.

Thank you

# Answer
> 3 votes
*Note: This topic is way too large to be answered appropriately in a StackExchange answer. You will have to do your own further research / googling.*

**Voxel Grids**

Fundamentally, you're trying to figure out a representation of a voxel grid. The *simplest* possible way to represent a 3D grid is a simple array, like `map = new Voxel[width, height, depth]`, where Voxel is some kind of small structure that represents the material at a particular point, e.g. air, ground, water, etc. However, this wastes a lot of space on possibly empty or uniformly solid areas. The storage required is roughly O(N3). Finding a way to cut that down leads us to.....

**Space Partitioning Structures**

To overcome the storage shortcomings of a dense voxel array, you would look into a space-partitioning structure (such as a quadtree, octree, spatial hash, etc.) The primary advantages that all these structures satisfy are:

* Sub-linear retrieval time of the volume data at a particular coordinate. (The trees will have O(log N) and the hashmap should have O(1)). There will be some differences between the structures, such as the trees are scale-invariant and so are suitable for large-scale LOD operations.
* No space wasted on large empty (or possibly uniform) areas.

Typically for performance reasons, the leaf nodes of this structure will be **chunks** of voxels that represent, for example, an 16x16x16 volume.

One misconception in the question is that a quadtree would not be able to handle overhangs. This is not necessarily true. Even in a hash-table, a hash collision does not actually lose data. There are multiple ways of handling overlap. For example, *Minecraft uses a quadtree*, since its vertical-axis is limited to 256 units, which is small enough that its chunks are simply 16x16x256 columns.

**Isosurface Extraction**

We now have a data structure where, generally speaking, we can query for data like

```
Voxel v = myGridStructure.GetVoxelAt(100,100,0);

```

How do we translate this into a triangular mesh that the graphics card can render? The simplest way, (i.e. the Minecraft method), is to generate a square at every boundary between "air" and "not-air". This yields a blocky look that a lot of current "voxel games" use. There are many other algorithms out there that attempt to generate a smoother surface. The classic algorithm is called **Marching Cubes**, but there are also other algorithms such as surface nets(almost a smoothed naive algorithm) or dual contouring (requires a gradient vector, but gives nice sharp edges). This page is one of the first Google matches for isosurface extraction and links to some papers on the topic.

# Answer
> 2 votes
There are techniques based around traditional heightmaps, but instead of using a purely vertical height value, the textures contain a full 3D vector, indicating the displacement to apply to the vertex.

This allows you to stretch around and reallocate areas of the terrain, creating overhangs and jutting parts of the terrain. Complemented with carefully placed meshes, you can create pretty much anything.

A prime example of this is in Halo Wars, which had a video/slide presentation at GDC now available in the GDC Vault for free, which covers this in great detail.

# Answer
> 0 votes
Store the existence of terrain in your data structure. That would be a boolean value where true means solid and false means air. You could also extend this and store a material as integer, where 0 means air, 1 means dirt, 2 means stone, 3 means wood, and so on.

To generate a mesh from that data, use marching cubes or a similar algorithm. It calculates a polygon mesh out of voxel data.

By the way, I suggest octree if you want a tree data structure. It is the 3d equivalent of quadtree and therefore it fits your world better. Although I would go with a simple 3d array for now. Later on, for larger worlds, you can decide whether to use octrees or divide the world in chunks.

To save space, you can use run-length encoding.

There is a very good article on the blog *0 FPS* discussing different data structure for such terrains, including array, array chunks, octree and a combination of interval tree and hash table which shows up to be the fastest structure.

# Answer
> 0 votes
http://vterrain.org/Elevation/Caves/ has a collection of papers on modelling caves/terrain with caves.

Generally speaking, there are three methods used:

* The caves are modelled as a snake/chain of vectors, with a property which defines the thickness of the cave around the vector.
* Voxels
* The terrain is handled like a triangle mesh, with caves being modelled as part of the mesh (this can also be combined with heightfields if a portion of the heightfield is cut out near the tunnel/cave entrance)

Aside from that, there's also vector heightfields, which have already been mentionedin another answer.

---
Tags: terrain, terrain-rendering, octree
---


# Question
Title: Simplest way to render image over top of another with another image used as mask in OpenGL?
The effect I'm looking for is to have a single large background image that is always visible (at full alpha) and then show a second image (what I call a light map or specular map) that is partially shown over the top based on a third image (which is effectively a mask).

The effect is similar to this effect except instead of simply darkening or lightening the background image using the third image it needs to mask the second without effecting the first at all.

The third image is the only one that moves therefore hard baking the third images alpha into the second image isn't an option.

If my explanation isn't clear I'll provide visual examples when I have more time.

~~I'd prefer not to go down a shader route as I haven't taught myself this area yet so unless I have too I'd rather try to achieve this with simple alpha blending.~~ Happy to use a shader approach.

Cheers.

**Additional**

These third images are obviously light sources being cast onto the first image showing the specular information from the second image to simulate the light 'shining' off the objects in the first image. The solution I implement will need to allow two light sources to potentially overlap so my current thoughts are that the alpha values of the two images will need to be combined (Added?) to produce a final image which masks the second image?

Don't worry about things like coloured lights. For this technique the lights are all considered white.

# Answer
> 5 votes
For fixed-function, this *might* be what you want:

https://stackoverflow.com/questions/5097145/opengl-mask-with-multiple-textures

Essentially, use the *blend modes* (and proper use of the color channels vs alpha channel) to write a *mask* into your backbuffer and then render a foreground image masked.

With shaders, you can simply provide the mask/light texture as an input to the fragment shader, query the "real" input textures (for sprites or whatnot) and the mask texture and then discard fragments or blend them appropriately.

It's been long enough since I've used GLSL that the following code is probably syntactically invalid and certainly idiomatically off, but the gist of it is:

```
// mask.fragment.glsl
layout(location=0) uniform sampler2D sMask;
layout(location=1) uniform sampler2D sSprite;

in vec2 aTexCoord;
in vec4 aColor;

layout(location=0) out vec4 rtColor;

void main() {
  vec4 mask = texture2D(sMask, gl_FragCoord.xy);
  vec4 sprite = texture2D(sSprite, aTexCoord);
  rtColor = mask * sprite * aColor;
}

```

You can change up how you use mask to make it color-based, alpha-based, whatever. Using that snippet you would use the alpha channel of the mask texture to make hide details and the color to have the light change the output color, supporting colored lighting.

---
Tags: c++, opengl, alpha-blending
---


# Question
Title: Chances of landing a job as a (AAA or medium sized studio) game programmer?
How competitive are these jobs? If I am a fresh college graduate with a degree in CS and I have a portfolio that consists of one self-published and self-developed game with a little over 1k units sold, would that put me way ahead of the curve or no (let's assume for the sake of completeness that the game in question is quality enough to showcase and be proud of on an interview)?

# Answer
> 4 votes
Having a game to show is always good, ofcourse. But as far as I know, you WILL be tested on your coding and knowledge during an interview. If you made a small game in a month, then great, but if you spent 2-3 years on a game a normal developer could finish in 1-2 months, you might be in some trouble ^^

It all comes down to what YOU know and how good of a programmer you are. getting a degree is a good way to learn, but its not going to code for you, and your employer wont be stupid, he will know if you can do what he needs or not after the interview.

This is all the info I can share, probably someone out here that can give a better and more detailed one :)

# Answer
> 0 votes
I can't tell you if it will help you very much, because I believe it depends on company and people working there (and doing interviews). But I can tell you this:

I was in similar situation 2 years ago. I was also looking for a job in bigger AAA game company (few month before my graduation, because after graduation a lot of people is looking for a job). And I was on an interview (and passed and was working there for a while).

I created 2 small games (in team) and had some other demos - like cloth simulation computed on GPU, some graphics demo using shaders etc.

First part of interview was with HR person. Some normal question as you can expect on every other interview. I didn't answered all of them, but maybe half.

Second part was interview with my future superior. He was asking me typical programming questions, like what is Singleton, some data structures questions, some puzzles, ... And he also asked me like 3 question about my demos (but it looked like he sees a lot of demos like this every day).

And then third part: I sat in front of a computer and had two hours to complete a small game - there was about 20 parts of game and I should complete as many as I could. I didn't completed all of them, but they wanted to test me - how I work under (time) pressure, how I deal with some hard tasks, how optimized code can I write (because this is pretty important in game programming). And I believe that this was the most important part for them.

---
Tags: jobs
---


# Question
Title: What is the difference between a modelview-projection matrix and world-view-projection matrix?
So basically I wrote a shader a long time ago that uses all World and WVP matrices. Now I am working in an engine that will only give me access to ModelView, MVP, and model to world space matrices. First I tried just using the model to world space matrix for my previous World matrix and the MVP matrix instead of my WVP matrix, but now my object isnt there and the vertices are sort of just flying at the camera; which makes me think these are probably the problem. Here are the shaders just incase Original:

```
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
float    g_fTime;                   // App's time in seconds
float4x4 g_mWorld;                  // World matrix for object
float4x4 g_mWorldViewProjection;    // World View Projection matrix

//--------------------------------------------------------------------------------------
// Vertex shader output structure
//--------------------------------------------------------------------------------------
struct VS_OUTPUT
{
    float4 vPosition   : POSITION;   // vertex position
    float4 Diffuse    : COLOR0;
    float3 Normal :TEXCOORD0; //extra variable for toon shading
};

VS_OUTPUT RenderSceneVSOutline( float4 vPos : POSITION,
                         float3 vNormal : NORMAL,
                         float2 vTexCoord0 : TEXCOORD0,
                         float2 vTexCoord1 : TEXCOORD1
                          )
{
    VS_OUTPUT Output=(VS_OUTPUT)0;
    float3 vNormalWorldSpace;

    //This is where you want to put your simple vertex animation code.
    //you should convert a vNormal to a float of 4 and multiply (sin(g_fTime)+1.0f)*0.5f
    //add the result of those operations to the incoming position
    float4 normal=float4(vNormal,0.0f);
  float4 result= mul(normal,  (sin(0.3f)+1.0f)*0.1f   );
    vPos += result;

    // Transform the position from object space to homogeneous projection space by:
    // Multiplying together the world and the world view projection. Then, apply that to the position
  float4x4 temp4x4= mul(g_mWorld,g_mWorldViewProjection);
  float4 pos=mul(vPos,temp4x4);
   Output.vPosition = pos;

    // Transform the normal from object space to world space
    // Convert the world to a float3x3.  Multiply the normal with converted world.  Normalize the entire result
   float3x3 anewworld=(float3x3)g_mWorld;

    vNormalWorldSpace = mul(vNormal,anewworld);
    normalize(vNormalWorldSpace);
    float3 lightDir ={ 0.0f, 0.0f, 1.0f };
    Output.Normal=vNormalWorldSpace;
   float4 dotresult=dot(vNormalWorldSpace,lightDir);
    //Take the max of 0, and the result of the dot product of vNormalWorldSpace and the lightDir.  This is
    //a simple lambert diffuse lighting

    Output.Diffuse =  max(0,dotresult);

    return Output;
}

//--------------------------------------------------------------------------------------
// Pixel shader output structure
//--------------------------------------------------------------------------------------
struct PS_OUTPUT
{
    float4 RGBColor : COLOR0;  // Pixel color
};

PS_OUTPUT RenderScenePSOutline( VS_OUTPUT In )
{
    PS_OUTPUT Output=(PS_OUTPUT)0;

    // Lookup mesh texture and modulate it with diffuse
    float4  fBlue = { 0.0f, 0.0f, 0.0f, 0.0f };

    //Multiply In.Diffuse by 0.8 and combine (by adding)
    //the result with the vector for blue.

    Output.RGBColor =   fBlue;

    return Output;
}

```

New Engine /ModelView edition:

```
  float4x4 matMVP  : register(c8);
  float4x4 World : register(c20); //the model to worldspace matrix

struct VS_IN
{
  float4 ObjPos  : POSITION;
  float3 Normal :NORMAL;
  float2 UV0     : TEXCOORD0;
  float2 UV1    :TEXCOORD1;
};

struct VS_OUT
{
  float4 ProjPos : SV_Position;
  float4 Diffuse: COLOR0;
  float2 Normal     : TEXCOORD0;
};

VS_OUT vs_main( VS_IN In )
{
  //VS_OUT Out;
   VS_OUT Output=(VS_OUT)0;
    float3 vNormalWorldSpace;

    //This is where you want to put your simple vertex animation code.
    //you should convert a vNormal to a float of 4 and multiply (sin(g_fTime)+1.0f)*0.5f
    //add the result of those operations to the incoming position
    float4 normal=float4(In.Normal,0.0f);
   float4 result= mul(normal,  (sin(0.3f)+1.0f)*0.1f   );
    In.ObjPos += result;

    // Transform the position from object space to homogeneous projection space by:
    // Multiplying together the world and the world view projection. Then, apply that to the position
  float4x4 temp4x4= mul(World,matMVP);
  float4 pos=mul(In.ObjPos,temp4x4);
   Output.ProjPos = pos;

    // Transform the normal from object space to world space
    // Convert the world to a float3x3.  Multiply the normal with converted world.  Normalize the entire result
   float3x3 anewworld=(float3x3)World;

    vNormalWorldSpace = mul(In.Normal,anewworld);
    normalize(vNormalWorldSpace);
    float3 lightDir ={ 0.0f, 0.0f, 1.0f };
    Output.Normal=vNormalWorldSpace;
   float4 dotresult=dot(vNormalWorldSpace,lightDir);
    //Take the max of 0, and the result of the dot product of vNormalWorldSpace and the lightDir.  This is
    //a simple lambert diffuse lighting

    Output.Diffuse =  max(0,dotresult);

    return Output;
}

struct PS_IN
{
   float4 ProjPos : POSITION;
  float4 Diffuse: COLOR0;
  float2 Normal     : TEXCOORD0;
};
struct PS_OUTPUT
{
    float4 RGBColor : COLOR0;
};

PS_OUTPUT ps_main( PS_IN In ) : SV_Target
{
 PS_OUTPUT Output=(PS_OUTPUT)0;

    // Lookup mesh texture and modulate it with diffuse
    float4  fBlue = { 0.0f, 0.0f, 0.0f, 0.0f };

    //Multiply In.Diffuse by 0.8 and combine (by adding)
    //the result with the vector for blue.

    Output.RGBColor =   fBlue;

    return Output;
}

```

The only difference between the two is variable name changes (and values if MVP and WVP aren't the same). So does anybody know how I could convert from WVP to MVP?

# Answer
> 6 votes
Probably, the terms "model-view-projection" matrix and "world-view-project" matrix refer to the same conceptual transform. The two terms can be used interchangeably, and the difference in terminology could stem from one source being more familiar with OpenGL (which uses the term "modelview") or D3D (which splits the concept into "world" and "view" transforms).

The "modelview" transform bring an object from model space to view space (*conceptually* passing through world space on the way). The "world" transform would bring an object from model space to world space, and the "view" transform" from world to view space. Thus, the combined "world-view" transform is equivalent to the GL-style "modelview." Obviously, then, when you tack on the projection transformation at the end, you get the same logical origin (model space) and destination (clip space) spaces.

All of which is a roundabout way of saying that the *problem* you're seeing in your code is likely due to the values you're assigning to these matrices before you present the scene. Unless you're using some seriously non-standard terminology, there's no way to convert between a "modelview-projection" matrix and a "world-view-projection" matrix because they are the same thing; there isn't even a need.

I'll point out that your shaders aren't exactly identical except for variable renames. There's also some input layout differences, it seems. But the actual problem appears to be in the C++ code that causes these shaders to run, not the shaders themselves.

---
Tags: matrix, hlsl
---


title: Getting a 3d mouse position

text:
# Question
Title: Getting a 3d mouse position
I've looked at a few tutorials about picking and the method Unproject, so I have an idea of how getting the mouse in 3d space is done. The code I have does display a mouse position, but it is way off of the actual position the mouse is at.

```
    public Vector3 FindWhereClicked(MouseState ms)
    {
        Vector3 nearScreen = new Vector3(ms.X, ms.Y, 0);
        Vector3 farScreen = new Vector3(ms.X, ms.Y, 1);
        Vector3 nearWorld = device.Viewport.Unproject(nearScreen, cam.proj, cam.view, Matrix.Identity);
        Vector3 farWorld = device.Viewport.Unproject(farScreen, cam.proj, cam.view, Matrix.Identity);

        Vector3 direction = farWorld - nearWorld;

        float zFactor = -nearWorld.Y / direction.Y;

        Vector3 zeroWorldPoint = nearWorld + direction * zFactor;

        return zeroWorldPoint;
    }

```

This code is from another thread I found on here. I'm guessing the problem is the near and far world variables.

```
    public ThirdPersonCam()
    {
        proj = Matrix.CreatePerspectiveFieldOfView(0.78f, 1.7777f, 1f, 10000f);
    }

    public void CameraUpdate(Matrix objectToFollow)
    {
        Vector3 camPosition = objectToFollow.Translation + (objectToFollow.Backward * 10) + (objectToFollow.Up * 2);
        Vector3 camTarget = objectToFollow.Translation;

        view = Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up);
    }

```

The variables are grabbed from my camera class, but I don't know why it isn't working. A point that's supposed to be at 0, 0, 0 ends up being at something like 36, -1, 57

# Answer
Basically I got all my information from Picking sample from microsoft.

This method creates a ray in world space that i can use to pick something:

```
private void RenewRay(){
    var camera = _cameraService.Current;
    //get mouse position in screen coordinates
    var mousePosition = _mouseInputProvider.Position;
    //calculate cursor points in screen space
    var cursorOnNearPlane = new Vector3(mousePosition, 0);
    var cursorOnFarPlane = new Vector3(mousePosition, 1);

    //calculate cursor points in world space.
    var nearPoint = _device.Viewport.Unproject(cursorOnNearPlane, camera.Projection, camera.View, Matrix.Identity);
    var farPoint = _device.Viewport.Unproject(cursorOnFarPlane, camera.Projection, camera.View, Matrix.Identity);

    var rayDirection = farPoint - nearPoint;
    rayDirection.Normalize();

    Ray = new Ray(nearPoint, rayDirection);
}

```

This ray in world space can be used to intersect with bounding spheres in world space. So my picking looks like:

```
public float? PerformPicking(Ray rayInWorldSpace){
    if (WorldBoundingSphere.Intersects(rayInWorldSpace) == null) return null;

    var rayInObjectSpace = rayInWorldSpace.TransformToObjectSpace(ref _world);
    return PickableGeometry.PerformPicking(rayInObjectSpace);
}

```

As you can see, I first perform picking on the WorldBoundingSphere. This is extremly fast and so I don't have to perform TrainglePicking on every object I draw. If I picked the BoundingSphere, I should test weather I really the geometry so I have to transform the ray to the object space of my geometry. This is implemented in a extension method that looks like :

```
public static Ray TransformToObjectSpace(this Ray ray, ref Matrix worldMatrix){
    Matrix inverseWorld;
    Matrix.Invert(ref worldMatrix, out inverseWorld);
    Vector3 newRayStart, newRayDirection;
    Vector3.Transform(ref ray.Position, ref inverseWorld, out newRayStart);
    Vector3.TransformNormal(ref ray.Direction, ref inverseWorld, out newRayDirection);

    return new Ray(newRayStart, newRayDirection);
}

```

PickableGeometry.PerformPicking(rayInObjectSpace) simply uses a TrainglePicker class I wrote that adapts the algorithm written by microsoft that you can read in the triangle picking example from mircosft.

By the way, PickableGeometry.PerformPicking(rayInObjectSpace) gives you the distance from camera to object in object space. So if you use a world matrix with a scale!=1, you have to scale to distance value, too. Or you calculate the position of the intersection in object space and apply the world matrix to calculate the intersection point in world space. Its up to you!
> 0 votes

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


title: Valid gameloops

text:
# Question
Title: Valid gameloops
I've got a thread (gameloop) in my game that is super complicated, and is built with the help of tutorials when I was still a beginner. But now that I understand a bit more, I find myself wondering why I use over 300 lines of code in my thread when this is enough:

```
    While(true){
        paint();
        update();
        thread.sleep(17)
}

```

Obviously this isnt the exact code one would use, but you probably get my point. I just dont like having something in my game that I dont understand 100%, and I hate cluttered classes that could be done with much simpler code.

So my question is, are there any downsides to using a simple loop like this? Because to me it looks like it does the job, but why would then tutorials have much more in theirs?

# Answer
You shouldn't ever sleep manually like that - you're assuming that your game loop always takes the same amount of time to complete.. so you're always sleeping by the same amount. This might be true for games that are simple and run the same logic mostly all the time - but this is not true for more complicated games or games with varying levels, objects, and scenes. To avoid this problem, there's a lot of different game loops but I think reading up on them might be serve you better.

A more popular one that gets around this issues is using delta timing and basing your game off that. You can read more about these types of loops at this pretty good resource.
> 5 votes

# Answer
```
While(true){
    paint();
    update();
    thread.sleep(17)
}

```

This isn't going to run at 60 fps.

* What if your paint method takes 2ms to run? What if it's time is not totally consistent across different frames?
* What if your update method takes 2ms to run? What if it's time is not totally consistent across different frames?
* What if the timer your sleep call is based on has poor resolution? What if it's resolution is something like 15ms?
* What if the implementation of sleep on your platform can only guarantee a *minimum* time to sleep for but may actually sleep for any arbitrary longer time?
* What if the player is vsyncing at 60fps? What if the player is actually vsyncing at 72fps?

As I said in my comment: **if it uses a sleep call for controlling framerate it's not a valid game loop**.

Sleep calls are perfectly fine for reducing CPU usage if you really need to (but if your API or framework has better options available you should investigate them first); sleep calls are *not appropriate under any circumstances whatsoever* for controlling framerate. Framerate should be controlled based on a high resolution timer
> 1 votes

# Answer
typically using sleep() at all in a game loop is a bad idea. the OS will sleep for *at least* the time requested. so even doing sleep(0); means that the OS could sleep for as long as it wants to even though you're asking it to sleep for no time.

these days, we dont bother with sleeping at all within game loops, and typically rely on the OS to timeslice us. there is usually a yeild call of some sort (im not sure what the equivalent in java is?) to instruct the OS that "hey this would be a swell point to do something else for a bit".

see something akin to http://www.javamex.com/tutorials/threads/yield.shtml and note the difference between java 5 and java 6 ;)

moving on from the sleep thing. game "loops" tend to be as complex as they need to be. as you end up adding more and more complexity, the loop will tend to grow. If you're really keen on understanding how to deal with production level software, have a read of the CSP guidebook (communicating serial processes). the general gist is to have a number of "steps" within your loop, and tick each system in order.
> 0 votes

---
Tags: java, game-design
---


# Question
Title: Algorithm to shoot at a target in a 3d game
For those of you remembering Descent Freespace it had a nice feature to help you aim at the enemy when shooting non-homing missiles or lasers: it showed a crosshair in front of the ship you chased telling you where to shoot in order to hit the moving target.

I tried using the answer from https://stackoverflow.com/questions/4107403/ai-algorithm-to-shoot-at-a-target-in-a-2d-game?lq=1 but it's for 2D so I tried adapting it.

I first decomposed the calculation to solve the intersection point for XoZ plane and saved the x and z coordinates and then solving the intersection point for XoY plane and adding the y coordinate to a final xyz that I then transformed to clipspace and put a texture at those coordinates. But of course it doesn't work as it should or else I wouldn't have posted the question.

From what I notice the after finding x in XoZ plane and the in XoY the x is not the same so something must be wrong.

```
    float a = ENG_Math.sqr(targetVelocity.x) + ENG_Math.sqr(targetVelocity.y) -
            ENG_Math.sqr(projectileSpeed);
    float b = 2.0f * (targetVelocity.x * targetPos.x +
            targetVelocity.y * targetPos.y);
    float c = ENG_Math.sqr(targetPos.x) + ENG_Math.sqr(targetPos.y);
    ENG_Math.solveQuadraticEquation(a, b, c, collisionTime);

```

First time targetVelocity.y is actually targetVelocity.z (the same for targetPos) and the second time it's actually targetVelocity.y.

The final position after XoZ is

```
    crossPosition.set(minTime * finalEntityVelocity.x + finalTargetPos4D.x, 0.0f,
                minTime * finalEntityVelocity.z + finalTargetPos4D.z);

```

and after XoY

```
    crossPosition.y = minTime * finalEntityVelocity.y + finalTargetPos4D.y;

```

Is my approach of separating into 2 planes and calculating any good? Or for 3D there is a whole different approach?

* sqr() is square not sqrt - avoiding a confusion.

# Answer
> 13 votes
There is no need to break it down into 2 2d functions. That quadratic equation you are working with works fine in 3d as well. Here is pseudo code for either 2d or 3d. It implies a tower (tower defense) is shooting the projectile:

```
Vector totarget =  target.position - tower.position;

float a = Vector.Dot(target.velocity, target.velocity) - (bullet.velocity * bullet.velocity);
float b = 2 * Vector.Dot(target.velocity, totarget);
float c = Vector.Dot(totarget, totarget);

float p = -b / (2 * a);
float q = (float)Math.Sqrt((b * b) - 4 * a * c) / (2 * a);

float t1 = p - q;
float t2 = p + q;
float t;

if (t1 > t2 && t2 > 0)
{
    t = t2;
}
else
{
    t = t1;
}

Vector aimSpot = target.position + target.velocity * t;
Vector bulletPath = aimSpot - tower.position;
float timeToImpact = bulletPath.Length() / bullet.speed;//speed must be in units per second

```

'aimSpot' may be the vector you are asking about.

# Answer
> 1 votes
There is also a good blog post about same subject: http://playtechs.blogspot.kr/2007/04/aiming-at-moving-target.html. It also contains more complex samples that include gravity.

The author has done more simplification, which results in more compact code:

```
double time_of_impact(double px, double py, double vx, double vy, double s)
{
    double a = s * s - (vx * vx + vy * vy);
    double b = px * vx + py * vy;
    double c = px * px + py * py;

    double d = b*b + a*c;

    double t = 0;
    if (d >= 0)
    {
        t = (b - sqrt(d)) / a;
        if (t < 0)
        {
            t = (b + sqrt(d)) / a;
            if (t < 0)
                t = 0;
        }
    }

    return t;
}

```

**Update:** Original author took into account only bigger root. But in case of smaller root being non-negative, it results in better solution, since time of impact is smaller. I have updated the code correspondingly.

---
Tags: mathematics, ai, aiming
---


title: Optimize DOM game performance

text:
# Question
Title: Optimize DOM game performance
I am working on a game developed on DOM using Crafty JS framework, and Greensock GSAP JS (http://www.greensock.com/gsap-js/) for animations. It is my first time working with these technologies.

I have a problem with FPS going down to 15 and less while animations are performed on bigger DOM elements. After investigating the issue with Chrome Developer Tools Timeline I discovered that 80% of bottleneck events time are:

```
Image Resize(non-cached)

```

I assume it is caused by the fact that I am using

```
CSS Transform scale()

```

for the game to adjust to browser size. Performance is acceptable once the scaling is disabled.

Is there any way to cache the resized images in browser to improve performance? The game will only be used on a local computer.

Any help and advice will be greatly appreciated.

# Answer
Since many browsers have now support from the graphics card when doing 3d stuff, a common technique to improve performance is to not use the 2d method but it's 3d counterpart instead. So instead of

```
scale(x,y)

```

you should use

```
scale3d(x,y,0)

```

Perhaps there is also a method to cache those scaled images, but I am not aware of how to do that. Nonetheless, using the 3d method might already solve your problem.
> 0 votes

# Answer
FPS going down to 15 and less when animations are performed on bigger DOM elements. After investigating issue with Chrome Developer Tools Timeline I discovered that 80% of bottleneck events time are:

Image Resize(non-cached) I assume it is caused by the fact that I am using

CSS Transform scale() for game to adjust to browser size. After disabling scaling performance is acceptable.
> -1 votes

---
Tags: javascript, performance, crafty, chrome
---


# Question
Title: Betatesting an android game. Best practices?
Our game is in our final stage prior to be released. I would like at this stage to add some beta testers to let them hunt bugs, etc... Is there any good platform/site to achieve this? I have noticed there's a site called betalizer but they still are in beta.

Could anyone suggest how to find beta testers for a little-medium size android game without spending a lot of bucks or any platform that could help on it?

Thanks in advance.

# Answer
Google Play allows you to upload an alpha or beta version of your app and lets you choose a group of testers. The group can be a Google Group or Google+ Community. I highly recommend using social media to spread the word and involving (or hiring) interested people in beta testing. You can also hire people for few bucks on websites like Fiverr.com.

Disclaimer: I am not affiliated with Fiverr, but I use it.
> 3 votes

---
Tags: android, testing, playtesting
---


title: Matrix transforms in XNA

text:
# Question
Title: Matrix transforms in XNA
So in my most recent 2D game I draw objects like so.

> \_spriteBatch.Draw(\_sprite, Center(), null, Color.White, \_rotation, new Vector2(\_sprite.Width / 2, \_sprite.Height / 2), \_scale, SpriteEffects.None, 0);

My bounding boxes are generated using a two step algorithm where I make the transform matrix, then apply it to a Rectangle of the sprite's height and width.

```
    public Rectangle BoundingBoxTransformed
    {
        get
        {
            //Center and rotate our Rectangle

            Matrix m = Matrix.CreateScale(_scale) *
                Matrix.CreateTranslation(new Vector3(new Vector2((float)-BoundingBox.Width / 2, (float)-BoundingBox.Height / 2), 0.0f)) *
                Matrix.CreateRotationZ(_rotation) *
            //Move our rectangle toward the player, then recenter it by undoing the original translation (now that it's already rotated)

                Matrix.CreateTranslation(new Vector3(_location, 0.0f)) * Matrix.CreateTranslation(new Vector3((float)BoundingBox.Width / 2, (float)BoundingBox.Height / 2, 0.0f));
            return CalculateBoundingRectangle(new Rectangle(0, 0, _sprite.Width, _sprite.Height), m);
        }
    }

```

This is how I've been finding the new sizes for the scaled bounding boxes.

> ```
>    public static Rectangle CalculateBoundingRectangle(Rectangle rectangle,
>                                                        Matrix transform)
>     {
>         // Get all four corners in local space
>         Vector2 leftTop = new Vector2(rectangle.Left, rectangle.Top);
>         Vector2 rightTop = new Vector2(rectangle.Right, rectangle.Top);
>         Vector2 leftBottom = new Vector2(rectangle.Left, rectangle.Bottom);
>         Vector2 rightBottom = new Vector2(rectangle.Right, rectangle.Bottom);
>         // Transform all four corners into work space
>         Vector2.Transform(ref leftTop, ref transform, out leftTop);
>         Vector2.Transform(ref rightTop, ref transform, out rightTop);
>         Vector2.Transform(ref leftBottom, ref transform, out leftBottom);
>         Vector2.Transform(ref rightBottom, ref transform, out rightBottom);
>         // Find the minimum and maximum extents of the rectangle in world space
>         Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop),
>                                   Vector2.Min(leftBottom, rightBottom));
>         Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop),
>                                   Vector2.Max(leftBottom, rightBottom));
>         // Return that as a rectangle
>         return new Rectangle((int)min.X, (int)min.Y,
>                              (int)(max.X - min.X), (int)(max.Y - min.Y));
>     }
>
> ```

I thought that I had the transformations all figured out, but when I run the game, I can see that my bounding boxes do not match up with my sprites.

So what is it that's going on here? Are my transformations out of order? Quick edit: The purple boxes are the original bounding boxes, which are used to determine the height and width of the red (transformed, i.e. scaled and rotated) bounding boxes.

# Answer
> 2 votes
I think this may be your problem:

```
Matrix.CreateTranslation(new Vector3(new Vector2((float)-BoundingBox.Width / 2, (float)-BoundingBox.Height / 2), 0.0f))

```

It appears you are trying to create a translation to the point of origin, which is what you should do when creating a rotation matrix, however, you are creating it based on your BoundingBox width and height. This should be your sprites original width and height.

Instead try:

```
Vector2 origin = new Vector2(_location.X + _sprite.Width / 2, _location.Y + _sprite.Height / 2);

Matrix m = Matrix.CreateTranslation(new Vector3(-origin), 0.0f)) *
    Matrix.CreateScale(_scale) *
    Matrix.CreateRotationZ(_rotation) *
    Matrix.CreateTranslation(new Vector3(_location, 0.0f)) *
    Matrix.CreateTranslation(new Vector3(origin, 0.0f));

```

And then in your draw code:

```
_spriteBatch.Draw(_sprite, _location, null, Color.White, _rotation, origin, _scale, SpriteEffects.None, 0);

```

---
Tags: xna, matrix, bounding-boxes
---


title: Efficient foliage rendering with OpenGL

text:
# Question
Title: Efficient foliage rendering with OpenGL
Rendering foliage usually involves "hanging" triangles and textures that have completely transparent areas. I'm interested in knowing how are these usually handled by a 3D engine.

The first thing that comes into mind is blending, but the issue with blending is that it requires depth sorting and while on a per-object basis this isn't an issue, proper foliage drawing would require that all triangles on the object are depth sorted otherwise parts of the foliage object behind the transparent parts of branches or leaves could potentially not get rendered at all. Even with per-triangle depth sorting, the issue wouldn't go away completely.

Another approach would be to use `discard` in the fragment shader, however that could prevent the GPU from performing the early depth test. Is this an issue though? Maybe foliage is usually rendered with basic fragment shaders, so the performance impact is negligible?

As you can see, i have a few ideas on how this could be done, what i'm looking for though is how it **is** actually done. I'm sure that lots of people have hands-on experience with this, so please share practical solutions.

# Answer
Another way of doing it is with alpha test; in GL terms is looks like this:

```
glEnable (GL_ALPHA_TEST);
glAlphaFunc (GL_GREATER, 0.5);

```

With this setup, any fragment with an alpha \<= 0.5 will be discarded. Don't forget to glDisable (GL\_ALPHA\_TEST) when done.

Is this compatible with early Z? Maybe, maybe not. Historically it wasn't but more modern hardware may be able to do e.g. a coarser depth test based on the triangle being drawn; this would be very hardware-dependent of course (but then again so is traditional early Z) and I don't have a reference for it.

Does it actually matter though? Again, maybe and maybe not. Alpha test (or discard) offers a tradeoff in another direction, where you can save on color buffer writes (and you commonly see glDepthMask (GL\_FALSE) with alpha testing too, so you also save on depth buffer writes) if used, so maybe you'll come out on the right side of that tradeoff.

The nice thing about using alpha test is that you don't need to write another shader variation for it.

It's worth noting at this stage that under D3D10 and 11 alpha test no longer exists and you are expected to emulate it by using the D3D equivalent of the discard instruction; that obviously comes at the expense of needing another shader combination, but it does indicate that sometimes you can expect alpha test to be emulated in drivers by patching the fragment shader with discard instrcutions.
> 1 votes

---
Tags: 3d, graphics-programming
---


# Question
Title: Is implementing your own scripting language viable?
I am coding a beat 'em up game in C++ and the time has come to implement scripting for events, triggers, cutscenes etc. I have read around on the internet and gotten a fair bit of information. My first choice solution would be to implement my own scripting language like the one in Cave Story. I have seen this suggested but most poeple suggest lua but that does not seem to fit my type of programming.

Have you made your own scripting language? Why did you chose to roll your own instead of using an existing one? What resources did you consult during the development?

# Answer
> 41 votes
**No.** At least, probably not.

This is a very frequent case of reinventing the wheel is game development, a mistake that is still quite popular.

If you're asking this question, you're very likely to be influenced by what others do, so just look at what Epic Games just did with the Unreal Engine:

* UE3 had a custom, weird, non-optimized, hard-to-debug UnrealScript thing,
* If the rumor is true, its support is being removed in UE4, in favor of hot-reloadeable C++ DLLs.

Do you think you can do better than Epic?

*Creating progamming languages belongs to programming language creators*, not game engineers.

It takes years and years for a language to become fully mature, and its accompanying toolset (compiler, linker, interpreter, debugger..) usable. Nowadays you have a lot of available solutions at hand so there's absolutely no real reason to start a new thing from scratch, at least not if the goal is simply to make a game. Period.

To answer your side questions, no, for these very reasons I've never implemented my own scripting language. But I've suffered a lot with some half-baked ones. Because they were created with a very narrow feature set in mind, they always had this little insane quirks that make you crazy. Often, you'll find yourself spending an awful lot of time just trying to work around the language's limitation instead of just making your game.

If the reason you want to create a language is because it is intended for use by people that don't know programming very well, or if you believe you need it because you want something very domain-specific, let me tell you these are *also* bad reasons. You can write a very high-level API with functions that `do_what_they_say_and_say_what_they_do()`, and some very simple boilerplate code that exposes its basic usage. Your not-so-technical users will be glad to learn a bit of programming, and you will be glad not to be limited by some badly implemented language.

So, as this will sound a bit abrupt or even harsh, I'll say that there is *one* case where it *could* make sense: if you want to learn how a scripting language is made. But please, please, if you do so: don't force others to use it.

**Edit**

I just had a look at the Cave Story command list you've linked. Ouch:

```
<ECJx:y      [EC?] Jump           @ Jump to event Y if any npc with ID X is present

```

I don't want to show disrespect to the developer behind Cave Story, but this is a perfect example of a simple command list that mutated in a uncontrollable custom scripting language. This might be still usable for a single developer or a very small team, but at this stage I advice to switch to a proper Turing-complete and well-tried language (e.g. Lua), where you could do:

```
if (npc.id == x) then
    jump_to_event(y)
end

```

This will make things so much easier when, for instance, you'll need a more complex condition:

```
if (npc.id == x) or (npc.type == "enemy") then
    jump_to_event(y)
end

```

# Answer
> 9 votes
> Have you made your own scripting language and why did you chose to roll your own instead of using an existing one?

I have, although I borrowed the syntax from other languages. All in all it was a great learning experience and in my case not that hard because the language was simple.

I did it mainly because I wanted to use a regular C-style syntax for my scripts, as everyone on the team was familiar with it.

I was also interested in learning a bit about implementing programming languages, and since I only needed a very simple subset of features (variables, arithmetic, conditionals, loops, and calling in-game functions or coroutines) I decided to give it a try.

> What resources did you consult during the development?

My main resource was this book:

I managed to learn enough from this book to implement:

* A lexer: which was almost trivial using regular expressions, just using Regex.Match to identify and split tokens.
* A recursive descent parser: basically one function for each rule in the grammar and some helper methods to lookahead and consume tokens. I looked at the C# grammar specification for inspiration. Hardest part was dealing with arithmetic and relations operator precedences without going into infinite recursion.
* An AST interpreter: using the visitor design pattern, I traversed the tree generated from the parser,and executed each instruction node recursively.

I would have stopped there since almost everything I needed was already working, except for one thing - calling and yielding on Unity3D coroutines deep from within the recursive interpreter. In order to solve that problem, I had to get rid of the recursion, and turned once again to the book. This time I ended up adding:

* A compiler: another visitor, but instead of executing code, it generates a list of small, atomic instructions from each node of the AST (i.e. a simple stack-based custom assembly language). Operations like a while loop or an if condition, are converted into labels and goto-type instructions. At this point I also write the compiled script to disk as a binary file.
* A bytecode interpreter: simply iterates over a flat list of instructions. Without the recursion it was now easy to integrate with Unity3D coroutines.

The whole process took about 2 weeks from zero knowledge, and was a lot of fun :)

PS: At the end I also wanted to add syntax highlighting and intellisense for my custom language on our tools. Scintilla was a life saver in this regard. I used the following wrapper:

http://scintillanet.codeplex.com/

# Answer
> 5 votes
> I have seen this suggested but most poeple suggest lua but that does not seem to fit my type of programming.

OK, let's try this from a different angle: what is it about Lua that you don't like? Is it something that is easily fixable, or is it something fundamental?

For example, take the use of keywords such as `then/do/end` to denote code block rather than good C/C++-style curly braces. If that's your problem... that's something you can *fix.* All you need to do is define your own little dialect of Lua, and write a simple transformation tool that will convert your curly-brace syntax into actual Lua.

Do you want += in some form? That's also easily something you can do in a pre-processing system. Just turn statements of the form `expr1 += expr2` into `expr1 = expr1 + expr2`.

Granted, you're going to have to find a way to detect whether a pair of curly-braces represent a table or a `do/end` pair. And you'd have to hook your pre-processing system into Lua by overriding `dofile`, `loadstring`, and other standard Lua library functions. But it's all ultimately doable.

If small issues like that are your concern, and you're too wedded to one programming style to just change how you code (note: this is generally a *terrible* quality to have as a programmer), this is a *far* more viable alternative than simply writing your own language. This would take maybe a couple of week *at most*. Compare that to the *years* that would be spent on a proper language, with rich debugging support and the like.

If your issues are larger than this (globals being the default, thus requiring you to use `local` everywhere), some of these can be managed (simply make declaring new global an error, through the use of altered environments and metatables). If you hate functions as first class objects, coroutines, garbage collection, or other basic elements of Lua... well then, you're in a hell of your own making ;)

And if you really, *really* want to be hardcore about it, you can write your own language that you compile *into Lua.* So you will at least be able to leverage the very well-tested Lua runtime, the exceptional Lua API, and other basic Lua facilities, all from your !Lua language. This will take time, but it still won't be the *years* that you'd spend on something else.

# Answer
> 3 votes
To complement the other answers, this is not a strictly binary option. Within an existing scripting language, you can also create your own Domain-specific\_language. The advantages of this approach are:

* You don't actually have to mess with formal grammars, parsers, implementing custom editors etc.
* You're getting most of the benefit of implementing a specialized scripting language, i.e. an additional abstraction, specific to your game.
* vs. homebrew: users that are acquainted with the scripting language of your choice will immediately be able to use your DSL.
* vs. plain existing language: users unacquainted with the scripting language will just only need knowledge of the DSL for modyfying your game.

The primary disadvantage is that you would be designing the DSL with the constraints of your "base" language.

# Answer
> 2 votes
It *might* make sense depending on the mechanics of your game. Some games with simple enough mechanics could use an interpreted language to save themselves from some over-complicated Lua/Python coding, but the complexity savings might not be worth too much. For instance, one of those Interactive Novel games could easily use a custom-written scripting engine.

If your game involves a physics engine, various game components, and varying complexity of characters and abilities, you should definitely consider looking at other existing scripting languages, so you're not scrambling to add necessary features to your custom one, or fixing bugs with it. While Lua is most likely the fastest, there are many others that you may like more for their syntax, and many of them brag about how easily they integrate with C. Python, Ruby, and Angelscript are a few. (Feel free to mention others in the comments)

If you ensure such languages are only used for "logic control" (ie handling a specific collision case for certain object types, like the flame blaster touching an ice block) then performance will hardly ever be an issue. Of course, on the other hand, if you use them for more routine code (making a custom collision check algorithm that runs each frame) it's more likely to bog your down.

# Answer
> 1 votes
I say, go for it. On a resume it would be an extra show of ability. Though, keep in mind, you need that ability first. It's not going to be easy, it's going to be pretty hard. There are book's on the subject, and online tutorials too, but ultimatly it's going to come down to you and your understanding of how a compiler work's, and how code is parsed and translated.

Make shure you start out simple, test frequently, and hold onto your ideal. But always remember, LUA is there for you.

---
Tags: scripting
---


# Question
Title: How to know when your game concept is simply not fun and to stop
I'm a new hobbyist game developer but have yet to come up with something original that I found to be really fun. The hardest part I find about game development is this:

* You have an idea that in your head looks like it would be really fun.
* You build a quick prototype and you realise that in reality its not so much fun for the user.
* You realise that your brain was tricking you by giving you the impression that you had a complete idea but in reality it was skimming over lots of missing details that prevent you from reaching the fun that you envisaged.
* You come up with lots ideas to fill in the missing gaps and hopefully make it fun.
* You try these ideas one by one but it seems none of them really get you to where you wanted.

When do you know to stop trying these ideas and admit the overall game concept sucks? Do you just keep on iterating on them and hope you find the magic formula?

Do people have any rules they follow in this process?

# Answer
> 12 votes
You said that the game you're imagining "looks like it would be really fun."

When you close your eyes and imagine yourself playing the game, imagine every detail of how you're playing it. Is it still fun? Where's the fun? Then how is that not matching up with what you're prototyping?

If it's not really fun, move on. If it is, just make your real-life implementation more like what you're imagining.

And be willing to shoot your sacred cows. If you have this click-heavy procedure for shifting the weeble-blatz left so that the snork-cannon gets an aim-bonus and getting that aim bonus is awesome(!) but doing the five hundred mouse clicks to get there sucks eggs, you need to either make the aiming-the-snork-cannon minigame fun on it's own or ditch the entire subsystem. And sometimes the idea for your entire game started out with the snork-cannon aiming and you really, really, really don't want to cut it because it's your baby. Shoot it in the head.

Also, it depends on your situation. Do you have to ship something? Do you have to buy groceries? Are you doing this in your spare time as a matter of passion?

# Answer
> 8 votes
I like to analyze any ideas of mine that don't seem fun and break them down into a few components. The reason behind this is that there's probably SOMETHING you can salvage from any given failed game project for a future one. Maybe the arena combat gameplay doesn't match with your theme of atmospheric horror. Maybe most of the game is generic crap but there's on really COOL idea that kept tricking you into thinking the project was going somewhere. Figure out the bit of your concept that's the most interesting to you and see if you can jumble it up with a few ideas from other projects you've worked on our outside sources.

And by trying to mash up these ideas you may stumble on something that makes your original basic concept work. I'd say the best advice is to not think of games as really having a SINGLE concept, but instead being a collection of ideas that may be better off in a slightly different form.

# Answer
> 2 votes
In my opinion fun should be the core mechanic. It shouldn't need bells and whistles to make it fun - the fun should be there without the bells and whistles, you add those to make it deeper. If the core mechanic ain't fun, no bell or whistle will make it fun (unless one of those bells or whistles *is* the core mechanic. Having said that, I once worked on a game where while coding it I realized it was missing that one thing that made it fun and something did pop in my head and was what made it tick. The core mechanic we defined simply wasn't fun. But in the end you should be able to point at one defining element that defines the fun factor in your game - what is it that turns it from interacting with a simulation to actually feeling challenged.

# Answer
> 2 votes
I think the key point here is that you can trick yourself that what you're working on is actually fun, but only when other people come into contact with it will you really be able to see whether it is. Which means that you want to do that as early in the process as possible.

The moment you have your first prototype, you should be having players test it, and watch how they experience it. Maybe even before your first prototype (if you can figure out how to prototype the game in words and on paper).

# Answer
> 1 votes
Move on to another idea for a bit. If your brain drags you back to the first idea, revisit it. But don't let yourself get stuck.

# Answer
> 1 votes
There's no perfect method for knowing a mechanic is "fun" but by intuition and experience. Prototyping it and finding out whether it works or not is really the time-tested procedure.

Remember a bad mechanic in one context may work in another, or with different tuning. Platforming, for example, can feel like a chore or smooth and agile depending on how you adjust speeds and accelerations.

# Answer
> 1 votes
Really, you don't really know what is fun until you have shared the idea with two or more ardent game players.

# Answer
> 1 votes
If the game is a RPG or MMORPG, you can always try playtesting these ideas on Pen & Paper, before doing so actually prototyping.

While it may sound weird, restricting PnP gameplay to what would be allowed in a video game can actually help you find out what is fun and what is not. Why is it fun? Why isn't it? Your players can help tell you, when you test your gameplay and game mechanics.

When in doubt, replace unknown mechanics with a PnP game ruleset that closely mimics what would be the mechanics.

# Answer
> 0 votes
If you have to ask that question, you've already answered it!

Additionally, try to sum up your game in one sentence. If you can't make this sentence exciting, its because the core game foundations aren't fun and no amount of polish will change that.

# Answer
> -1 votes
Unfortunately, I think a lot of it comes down to experience. If you feel like you're beating your head against a wall and you have no other ideas, it's time to get rid of the idea.

On the bright side: you can continue to come up with other ideas. The real limiting step here is not usually ideas, but time to work on them. If you kill one game idea, it gives you the time to work on your others. If you have no other ideas... well, then I guess you keep working on your current one until a new idea occurs to you that you want to try.

---
Tags: game-design, methodology, prototyping
---


# Question
Title: How to determine depth of a pixel perfect collision
I am trying to figure out how to determine the depth of a pixel perfect collision in XNA. I want to know the depth in order to be able to use it in my collision response.

At the moment I have the following code, that provides me with a working pixel perfect collision detection:

```
public static bool IntersectPixels(Matrix transformA, int widthA, int heightA, Color[] dataA, Matrix transformB, int widthB, int heightB, Color[] dataB)
{
    Matrix transformAToB = transformA * Matrix.Invert(transformB);

    Vector2 stepX = Vector2.TransformNormal(Vector2.UnitX, transformAToB);
    Vector2 stepY = Vector2.TransformNormal(Vector2.UnitY, transformAToB);

    // Calculate the top left corner of A in B's local space
    // This variable will be reused to keep track of the start of each row
    Vector2 yPosInB = Vector2.Transform(Vector2.Zero, transformAToB);

    // For each row of pixels in A
    for (int yA = 0; yA < heightA; yA++)
    {
        // Start at the beginning of the row
        Vector2 posInB = yPosInB;

        // For each pixel in this row
        for (int xA = 0; xA < widthA; xA++)
        {
            // Round to the nearest pixel
            int xB = (int)Math.Round(posInB.X);
            int yB = (int)Math.Round(posInB.Y);

            // If the pixel lies within the bounds of B
            if (0 <= xB && xB < widthB && 0 <= yB && yB < heightB)
            {
                // Get the colors of the overlapping pixels
                Color colorA = dataA[xA + yA * widthA];
                Color colorB = dataB[xB + yB * widthB];

                // If both pixels are not completely transparent,
                if (colorA.A != 0 && colorB.A != 0)
                {
                    // then an intersection has been found
                    return true;
                }
            }

            // Move to the next pixel in the row
            posInB += stepX;
        }

        // Move to the next row
        yPosInB += stepY;
    }

    // No intersection found
    return false;
}

```

How would I determine how deep the collision is into the dataB texture data?

# Answer
> 1 votes
I managed to pull this off, by grabbing all (x,y) coordinates of the sprites that intersect, then calculating as follows:

```
VerticalDepth = Bottom.Y  - Top.Y
HorizontalDepth = Right.X - Left.X

```

Based on the direction of the collision, I would then adjust accordingly.

```
if (depth > 0)
    AdjustPosition();

```

That is the simplified explanation. I would suggest you do not attempt to do this, as it is very slow, and a solution using Rectangle or Circles would most likely be better.

---
Tags: xna, c#, collision-detection, response, per-pixel
---


# Question
Title: Desire advice on implementing this animation timeline system
I have read a lot of questions on here, as well as books regarding game architecture. I have a general question about the implementation of a game's animation timeline, on which many isolated animations sit. I implemented one recently that proved rather inefficient and bug-prone, so I'm doing it again but this time seeking some advice. According to one book I've looked at, the implementation of a timeline does not have a well-known standardized technique and everyone seems to roll their own. Perhaps some of you can offer advice.

Here is the general situation, where "Time" is the game's passing time, starting at 0 when game launches:

**The task:** Finding the best data structures to be used such that I can throw any arbitrary value of `t` at the timeline entity and retrieve the active animation objects at that point in time, and finding these *quickly*. (Note: this is not a question about finding keyframes, but rather about finding valid animation objects on a timeline of many scheduled animations.)

I am using STL for simplicity. One idea I thought of was to have a general `map` of `animation`s as my timeline, where the map's `key` was the start time, since maps automatically sort based on keys. Then, for any value of `t` I can stop iterating as soon as the `key` is a value higher than `t` since I know the animation has not started yet.

But this seems inefficient:

I would always iterate from the beginning, even for animations that have already completed. I don't want a technique that stores flags or pointers for completed animations, because I want to always be able to jump to any `t` and get active animations for that point in time.

Another problem, the map can only have one key, in this case the start time. To know if an animation is active, the algorithm must also peer inside the `value` of the `map` to see if its duration has been completed yet. This seems wasteful, surely there is a better way.

I think you get the path I'm going down, and I know this is an issue that everyone tackles. Any advice?

# Answer
> 3 votes
Limiting my answer to your actual question:

> The task: Finding the best data structures to be used such that I can throw any arbitrary value of t at the timeline entity and retrieve the active animation objects at that point in time, and finding these quickly. (Note: this is not a question about finding keyframes, but rather about finding valid animation objects on a timeline of many scheduled animations.)

Firstly, I'd recommend doing the simplest thing that could possibly work first. The following assumes that your timeline isn't changing frequently (or at all).

Keep your animations in a vector (avoid lists or maps unless you have a good reason to use them).

To find all the animations at time T, just iterate through the list returning all the animations whose start time is less than T and whose end time is greater than T.

If you have a very large list of animations in your timeline, and the above approach is too slow, notice that your problem is similar to the geometric one of finding intersections between a line and some axis-aligned boxes. Generally, if we have too much geometry to test at once, we use spacial partitioning to avoid too many intersection tests. You could do the same here, except the problem is much easier (it's one dimensional). Adapt a quadtree solution (or just use a fixed vector of buckets) to do "temporal partitioning".

# Answer
> 4 votes
A *seeking* is your primary concern, a skip list might be your best bet. These can be implemented as a literal linked list or a more compact and cache-friendly data structure using indices into a vector instead of list nodes.

To *scrub* or *advance* the timelines, keep a list of *events* (points in time at which any animation starts or ends). Keep these in a sorted sequence of some kind, e.g., a vector of something like:

```
struct AnimationEvent {
   float time;
   enum { START, END } type;
   int animationID;
};

```

Keep a point to the "last time event" you encountered and the last time you looked for. When adding time, you can simply grab the leading time events that fall within the new period, no need for extended searching.

For example, in the graphic above, you'd have a list like

```
|   0 | START | 12 |
|   0 | START | 13 |
|   0 | START | 16 |
|   1 | START |  1 |
|   1 | START | 14 |
|   2 | START |  2 |

```

You check what happens in the first second. You see that animation nodes 12, 13, and 16 all start. You record that the last node you consumed was at index 2 and at time 1. You advanced another 0.5 seconds. The next event starts at 1s so nothing happens. You now record that the last node you consumed was still index 2 but at time 0.5s, and you advanced the active nodes (12, 13, 16) by 0.5s. You advance another 0.5s. Now your time is 1s so you consume the records indicating nodes 1 and 14 have started. You advanced your previously active nodes (still 12, 13, 16) by the additional 0.5s. You record that the last node you consumed was at index 4 at time 1.0s. Repeat. When you consume a node for animation, start it or end it as appropriate, and update nodes by the delta in time as appropriate (if an animation was due to start in 0.3s but you advanced 0.5s, then you must both start that animation and advance it by 0.2s).

I will note that this latter technique is super useful. It's used in animation, clipping, spatial partitioning, etc. Internalize it.

# Answer
> 0 votes
ok, im still not quite clear on what problem you're trying to solve. but im going to describe it as "you have some odd game mechanic that means you want to jump around randomly within a set timeline". and that the timeline itself has no logic (which you usually see with cutscene animation tools).

the difficult part here is that usually for cutscene animation tools, you'll trigger an animation at particular frames, and that animation will have been authored in a different tool, and you'd just tell your animation to play. and fix any problems with the seperate authoring tool. thats basically how cutscene playback works ;) just keyframes to start animations (or end looping ones).

the problem we appear to be solving here is one of random access. and im going to assume that this is the desired access pattern over linear playback. which would have a different solution completely. (which i'd be happy to ramble on about if you want).

right. to optimise for random access, im going to go with doing this on a per frame basis, rather than on a node-timeline basis. the general idea is that you're optimising being able to go directly to frame N, over memory footprint, or overall linear playback. to keep things to a sane memory footprint. i'd recommend having a buffer of some arbitrary number of frames that you've pre-processed in the per frame approach. while keeping the actual datastructure the more traditional node-timeline based paradigm.

so lets say that we're going to have a buffer of 1024 frames that we can jump to at any point. each "frame" would contain an array of two 32bit values per node. one an ID for the animation that's playing, and the other would contain the frame (or duration as a float) of the playback position within that animation. the thinking behind having a contiguous sized array is that it may lead to slightly more predictable memory usage and cache usage, but i'd recommend profiling that and working out whether you can get away with only storing the information for the nodes that *have* animations on that frame, rather than storing all nodes per frame regardless of animation state.

its then up to your animation system to be able to "jump to" a particular animation / time slice when requested by this system, which is a slightly different concern. the system we're talking about here shouldn't really be handling the animations themselves, but slaving a separate system. a similar approach, but unpacking keyframe / node data may work except it'd require a hell of a lot more memory!. it really depends on exactly what you're trying to do, which isnt really clear.

when you have more than 1024 frames, you would need to use a sliding widow approach and "decompresss" from your original space optimised data structure to your memory unfriendly optimised structure. you'll need at least two buffers, one you're reading from, and one you're decompressing too. assuming you're playing back linearly. jumping back to a frame which is no longer "decompressed" would require decompression before you could jump to it. but you could easily keep as many buffers around as you need depending on overall memory requirements.

the major downsides to this is that, linear playback suddenly becomes a hell of a lot of work for absolutely no benefit. you're doing a hell of a lot of preprocessing that you simply dont need to do. if you've got a number of these systems running at the same time, you're going to thrash the hell out of cache. its really not an approach that i'd recommend other for solving the "random access" problem.

doing linear playback is far easier achieved by just storing animation start points, and kicking off animations at particular frames, and stopping them when required. leaving the delta time to keep the animation in sync with the overall timeline. a hell of a lot less effort ;)

*whew*. ok hopefully that was slightly more useful? and you're kinda getting what im talking about? does this actually solve the problem you're asking?

I you're actually just asking "how do i write a cutscene system". the answer is far far far easier than the above.

---
Tags: c++, architecture, animation
---


title: Game concept sketching

text:
# Question
Title: Game concept sketching
I am looking for 2D game concept sketching software(not engine). Something that will let me put sprites, backgrounds together and maybe do some minimal animations. The ultimate goal is to design game concept, to transfer something from your mind to visual representation with ease. So I can quickly look at those skethes and see if the concept worth something, show to others and then start development. I work with photoshop, but it is not as productive as special software could be.

# Answer
> 1 votes
I use Photoshop (GIMP is a free alternative) to do such that.

I use a combination of 2D images, background, pixel coordinate placement, and tile based movement using the "Align to Grid" function and have even done some animating in it.

I would definitely suggest using a 2D art program of some kind, even if not photoshop. You can do all kinds of things with online white boards, Maptools.net, Photoshop, MS Paint, or even printing out cutouts of 2D graphics and using paper IRL.

# Answer
> 0 votes
Paint.net! It's like photoshop, but it's free and much easier to use without tutorials

---
Tags: game-design
---


# Question
Title: sample project that mix unityscript and c#
I like the simplicity of unityscript, at same time I also like the plenty of c# library and open source projects. I prefer to put my model/controller/logic flow in unityscript using standard unity3d sdk and invoke c# extension library. Is there any sample project demonstrate how to mix the two scripts in one project?

Your comment welcome

# Answer
> 2 votes
If you want to use C# classes within UnityScript, you need to place the C# classes directly in the 'Standard Assets' folder.

Otherwise, due to the way that Unity compiles it's code, you cannot reference C# classes from UnityScript or vice versa. By placing them within the 'Standard Assets' folder, you ensure that those files are compiled first, and then the classes they generate will be available to the other script files at compile time.

# Answer
> 1 votes
You can mix Javascript and C# scripts in one project with Unity. They cannot be compiled into the same file, but the same project is fine. I believe the base project that you start with in Unity3D contains both Javascript and C# if you want an example.

# Answer
> 1 votes
I agree with Byte56 and, just as an improvement at his answer, I recommend to check the official Car Tutorial: it's a project containing both Unityscript and C# scripts.

# Answer
> 0 votes
You can do it, it is done most of the time when it comes to projects that need to use servers. Your game client can run on C# and UnityScript, while the server runs on Java. As Byte said, you need to compile it in different project files. **"No JavascriptContents.cs"**

You can go to http://www.3dbuzz.com/ they have a ton of tutorials. You need to pay for it, but I haven't seen a place with more hours of tutorials in one place. You don't need to bother watching tutorials how to do this in particular. But the best shot would be not to mix it up too much. You might have problems while trying to access c# variable data with JavaScript(unity script). So don't do health with C#, movement and mana with Java, because this will generate problems, big ones.

http://answers.unity3d.com/questions/186244/how-do-i-access-a-variable-in-one-script-from-anot.html

---
Tags: unity, unityscript
---


# Question
Title: How to combine multiple sprite sheets from multiple sources (Actionscript/Starling)
In starling, it's faster if you use BitmapText instead of traditional text. Which is well great except for one issue. Right now the sprite sheet I was making was with a single Fla. I just created the sheet from Flash IDE.

The bitmap text however is generated using a tool like BMFont . Which generates it's own sprite sheet. Now, imagine I have three or four types of texts . Also for some reason I have multiple Sprite sheets of assets.

So the question is, how do I stick multiple sprite sheets together. Is there any available tool for it?

Does using multiple sprite cause performance issues?

# Answer
I'm not aware of any existing tool for that purpose. What I would do is write a custom script (I'd use Python, but using some other scripting language would work just as well) that first invokes ImageMagick to combine the separate images, then reads in the accompanying XMLs to get data for each of the spritesheets, modifies the data as needed, and then writes the modified data into a new combined XML.
> 2 votes

# Answer
To combine multiple sprite-sheets you'll have to revert to a method like jhocking describes in his post (eg. combine the images and make sure coordinates in the XML files are being updated accordingly).

That's a suboptimal way to go about it though. Instead of exporting several sprite sheets, why not export just one? Texture-Packer is a really great tool for this. You can simply create a folder, export all your sprites there (eg. animations as image-sequence) and drag the folder into texture-packer. The tool will combine all the images from that folder into a sprite-sheet and even auto-detect new images when you add them.

When it comes to special sprite-sheets such as fonts, you usually have to resort to other methods. In case of the starling framework, this is a non-issue though. You can pack your font-bitmap (the whole sheet) into a sprite-sheet like any other sprite. Then in starling you do something like this:

```
var font:BitmapFont = new BitmapFont(atlas.getTexture("fontName"), xmlData);

```

Where `atlas` is the loaded texture atlas. "fontName" references the font-sheet inside the atlas. The `xmlData` parameter is the loaded font data (file sometimes has `.fnt` extension).
> 2 votes

# Answer
Not sure if i understand you right but it seems you are looking for something like http://www.codeandweb.com/texturepacker for creating a textureatlas
> 0 votes

# Answer
This forum post also explains how it's done. http://forum.starling-framework.org/topic/bitmapfonts-sharing-a-textureatlas
> 0 votes

---
Tags: sprites, spritesheet, text-based
---


# Question
Title: 2D Terra(ria)in generation - Accidental noise
I'm currently trying to implement terrain generation as described on the following page: http://accidentalnoise.sourceforge.net/minecraftworlds.html.

But I have issues understanding how to interpret the noise function values.

1) What does the gradient function in the ANL library exactly do? I see its purpose is to create the gradient, but I don't understand what the output/input for it exactly is. You input the line segments (0,0,0,1) but what does it return?

2) How should / can perlin noise values be interpreted? In my project I have ported the 2d noise function defined by stefan gustavson to python but I don't know what to do with the values itself? People keep posting images of "perlin" noise, but I assume that are the values mapped to a RGB code?

3) For the Fractional brownian motion, is this algorithm the result of combining several noise functions with each other? (I.e the output of a perlin noise function gets combined with another perlin noise function but with different parameters?

4) In essence, I'd love (if possible!) an explanation on how the image below gets generated from the fbm fractal. (In the hopes it makes the *click* that I'm missing\*)

# Answer
1) The gradient function returns a field of values, when those values are mapped

`0->1 == White->Black`

you get something like the following:

Further explanation is given in the article you linked:

> So here we are mapping the line segment (0,1)-\>(0,0) to the gradient. This sets the gradient to lie between the Y=1 and Y=0 areas of the function.

Basically, what this gives us are some values we can use to manipulate the noise we get, to better fit what we expect from land. Since black is "nothing" and white is "solid", adding and/or multiplying the above gradient to any noise we get will ensure the world is (mostly) "solid" at the bottom and "nothing" at the top.

2) Yes, those values are mapped as the gradient image above. How should you interpret them? Ideally the noise values would return values from `0` to `1`. Then, you'll pick some cut off point, like `.5`, and everything larger than that value is empty space and everything smaller than it is solid (or vise versa, it doesn't really matter as long as you are consistent). Now when you're building your world, if it's Terraria style, you'd sample the noise at discrete intervals. Each sample would tell you the value of the noise at that position. That value will be determined as solid or not, so you decide if you want to put a tile there based on the noise value.

3) ANL describes fBm with:

> Fractals are a special type of combiner that combine up to 20 noise sources using fractal methods pioneered by Perlin, Musgrave, and friends.

So yes, your interpretation is correct enough to get you what you need from the library.

4) It's really a process of combining that gradient (with turbulence) with some noise. The description in the site you linked does a decent job at it:

> Anywhere that the above image is black represents -0.25, anywhere that is white represents 0.25. So whereever the fractal is the darkest black, the corresponding point in the ground function is distorted "downward" by 0.25. (0.25 represents 1/4 of the screen.) Since one point might be distorted a little bit, and another point above it in space might be distorted more, this results in the possibility of overhangs and floating islands.
> 3 votes

---
Tags: 2d, procedural-generation, python, perlin-noise, fractal
---


# Question
Title: How to determine the demographics of a game after release?
I am interested in demographics of people who actually play my game. Here are few assumptions I made:

* Players, especially the younger ones, are often not the buyers (or downloaders in case of freemium) and I don't think I can get data about buyers anyway
* Games targeted to a certain audience can be played by completely different group in the end (Pokemon vs. Call of Duty)

The closest I can get is to probably get a similar game that already has demographics data. But how did they get the data?

---

I have read the following questions:

These questions give me some data, but not the way how were the data obtained. Also some of the links are already invalid.

# Answer
> 3 votes
* Directly ask them on sign up, tell them to write down their date of birth. Seen this on many websites. AAA Projects do that. Such as Star Wars 1313:

> http://www.lucasarts.com/games/1313/index.html

* Give the players an additional bonus, for logging in with facebook or other social website. Take their email address and date of birth, along with other information you need. Try not to use the option "allow this application to write stuff on your timeline" - it makes people angry. Here you get complete intel on the person.
* Polls usually have a low "clickability" it depends on the community but they are clicked by those who love the game the most\*
* Use Google Analytics on your website, a small line of code that is free, can show exactly where people are from, when do they visit.
* Put some bonuses, for filling the entire bio. Keep in mind that people can always type in that they are Batman.
* Pokemon, etc. would be harder, for the sake that you don't really have an internet connection on a Gameboy (I didn't have). The only thing that comes to my mind, would be creating an external knowledge base. PokeDex with tricks and other useful trivia on the game.

This would be tricky, but... For every sold copy of the game, I'd create a serial key (done all the time for PC games). Tell the player that if they want to unlock some in-game content, they need to create an account on our website, give an option to log in with facebook, again no nagging with posting stuff on players timeline. Once they login, they enter the game code. You can give them the code.
* If you sell the game, through your website you can ask the buyer to answer a poll, after they bought the game. Personally, I don't mind answering five questions.
* For online games: After they played for a while encourage them to fill in their account data, make a joke that they are not NSA and that you would love to know what the audience is.
* For offline games in end, you could make a pop up in the main menu, which would say: "If you enjoyed watching this game, please fill in a poll for us, so that we know who plays our game - 2 minutes, we/I promise. click **HERE**"
* If you are using Steam to deliver the game, you have complete demographics, including the graphic card used to play the game.
* While you make people pay for the game with a credit card, put an optional field (done all the time by pretty much everyone). `"I am buying this for:" "Myself, My son, My daughter, My father, My husband"`

# Answer
> 5 votes
My approach would be to openly and directly ask the players:

* Include the information as *optional* fields in the signup process if a game account is required.
* Mail a questionaire or web-vote to each user if you have their e-mail. Preferably with some kind of (ingame) reward for participating.

Personally, I would avoid the psychological approach since it could be perceived as manipulative if the players got wind of it.

# Answer
> 2 votes
This will maybe not give you exact results, but at least some. I also presume, that you are interested in countries of the whole world:

You are talking about people, that really play your game. So probably you need to figure out something about their computer. If I look for example at Windows and .Net, you may use CultureInfo to get some information about user's PC. For example language (country and region) of his Windows. I know that this is OS / technology specific, but I believe that you can get such an information with other technologies too. It's very likely that user in some country has localized operating system.

This information can be then send to you (if you have for example updates or some high score tables). Question is - do you want to try to send it secretly?

---
Tags: game-design, demographics
---


title: Images not found in textureregion

text:
# Question
Title: Images not found in textureregion
Previously I was using simple `Texture` for sprite based animations, but that did not provide support for images which were not in the power of 2. TexturePacker provides with the ability to load all the images at once, and then fetch the required image from an `imageatlas`.

That said, I followed a couple of tutorials from the Libgdx wiki and it works well till the loading part. But I suppose during rendering, it is causing some problem. This is how I am loading the images into the `texturepacker` in my desktop project:

```
private static final String INPUT_DIR = "../Drop-Android/assets/images";
    private static final String OUTPUT_DIR = "../Drop-Android/assets/image-atlases";
    private static final String PACK_FILE = "pages-info";
    public static void main(String[] args){
        LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
        cfg.title = "Drop";
        cfg.width = 800;
        cfg.height = 480;

        Settings settings = new Settings();
        settings.maxWidth = 512;
        settings.maxHeight = 512;
        TexturePacker2.process(settings, INPUT_DIR, OUTPUT_DIR, PACK_FILE);
        new LwjglApplication(new Drop(), cfg);
    }

```

**Question**: Do I have to create `pages-info` i.e. the `PACK_FILE` manually in the images-atlases folder? If I do not, it throws `File not found exception`.

I happen to create `pages-info` file in the `image-atlases` folder and the following files are generated: `pages-info.png` and 'pages-info.atlas'. While, `pages-info` files is empty, the `.png` and `.atlas` files have the images and JSON image data, respectively.

This is what I am using to extract the `textureregions` out of the `pages-info` file (which is empty):

```
TextureAtlas ta = new TextureAtlas(Gdx.files.internal("image-atlases/pages-info"));
        imageOneRegion = ta.findRegion("image1.png");
        imageTwoRegion = ta.findRegion("image2.png");

```

As expected, it returns a `nullpointerexception` when drawing the `textureregion`. I am running out of ideas here, any help and ideas?

# Answer
The textures are named as in the `.pack` file, without extensions. Try using `"image1"` instead of `"image1.png"`.

If you watch your `ta` variable using the debug tool you should be able to see the names of textures actually loaded.
> 3 votes

---
Tags: android, textures, libgdx, texture-atlas
---


title: Jump without bouncing in physics engine

text:
# Question
Title: Jump without bouncing in physics engine
I am using Ogre3D as my rendering API, and OgreBullet as my physics engine.

I have an test entity that when the y part of the velocity is 0 and spacebar is pressed, the velocity changes to, lets say: (10, 10, 0) that is a forward jump.

The thing is that when it arrives to the ground, instead of staying still (like any normal human jump) it bounces like a box and changes orientation.

What would be the correct way of implementing a human-like jump in 3D? I fixed it using a `if()` in the update loop that sets the y-velocity to 0 if it touches the ground, but this doesn't seem the correct way of doing it.

# Answer
> 1 votes
No, setting the y-velocity isn't the correct way of doing things. You need to set the restitution of the object by passing the correct value (0 = no bounce) into the btRigidBodyConstructionInfo which is passed into the rigid body.

# Answer
> 0 votes
I read somewhere on the Bullet forums that a certain amount of bounce velocity is nearly always added to deal with overlapping (I'll find the source if I can but for now you might have to take my word for it). I think the only way to avoid this is indeed to set the y velocity to 0, or set it to the same as the whatever your object lands on (if you are jumping on moving objects). This might also mean you need to resolve overlapping yourself, however, by moving the object upwards a certain amount.

---
Tags: 3d, physics, ogre, bullet-physics, rigid-body-dynamics
---


# Question
Title: What to do after detecting OBB-OBB intersection
I'm using this code to detect intersections between two OBBs. The problem is that i don't know what to do after detecting it. I tried using a simple algorithm:

```
    if (collision detected) {
        move character back to its position on previous frame
    }

```

But this is not what i need, because the character is rotating and moving to certain points (usually to mouse click position). When it's close to an object with OBB and it rotates to a point, its OBB updates (the position of all OBBs corners is recalculated) and most of the time the updated OBB intersects with an object that is near, so the charecter gets stuck at its position.

**How can i deal with the rotation problem or what other methods can you offer for stoping character when its OBB itersects with another?**

# Answer
You need to find penetration distance and an axis of resolution. The axis of resolution will be the axis of least penetration between the two objects. Finding this information is non-trivial and makes for a much more in-depth implementation than the one you currently have.

See Box2D Lite for an example of an OBB to OBB test. For a working generalized polygon to polygon test, I suggest studying this: https://github.com/tutsplus/ImpulseEngine/blob/master/Collision.cpp
> 1 votes

---
Tags: physics, intersection
---