# Question
Title: How can I perform 2D side-scroller collision checks in a tile-based map?
I am trying to create a game where you have a player that can move horizontally and jump. It's kind of like Mario but it isn't a side scroller. I'm using a 2D array to implement a tile map.

My problem is that I don't understand how to check for collisions using this implementation. After spending about two weeks thinking about it, I've got two possible solutions, but both of them have some problems.

Let's say that my map is defined by the following tiles:

```
0 = sky
1 = player
2 = ground

```

The data for the map itself might look like:

```
00000
10002
22022

```

For *solution 1*, I'd move the player (the `1`) a complete tile and update the map directly. This make the collision easy because you can check if the player is touching the ground simply by looking at the tile directly below the player:

```
// x and y are the tile coordinates of the player. The tile origin is the upper-left.
if (grid[x][y+1] == 2){
   // The player is standing on top of a ground tile.
}

```

The problem with this approach is that the player moves in discrete tile steps, so the animation isn't smooth.

For *solution 2*, I thought about moving the player via pixel coordinates and not updating the tile map. This will make the animation much smoother because I have a smaller movement unit per frame. However, this means I can't really accurately store the player in the tile map because sometimes he would logically be between two tiles. But the bigger problem here is that I think the only way to check for collision is to use Java's intersection method, which means the player would need to be at least a single pixel "into" the ground to register collision, and that won't look good.

How can I solve this problem?

# Answer
I have recently implemented in my own game engine a system that handles side-scroller physics and rendering.

Addressing Solution 1 is pretty straightforward, but far less interesting. Just grab the player's intent to move, compare it to the collisionmask (essentially the grid you described above, but adjusted to just indicate whether the tile is collideable or not) for the tile he would move into, and either execute, adjust, or reject his intended movement.

Solution 2 is more challenging, but generally a better gameplay experience. Let me start by saying you are correct in identifying there is a problem with using pixels. You should separate the game logic from the render logic, and use generalized coordinates (doubles or something to that effect), and convert that to pixel-space when it's time for rendering (if necessary, I don't know what your rendering pipeline looks like).

In my implementation, I registered a simple struct describing the location and size of each tile with a physics manager, adding it to a list. I used the Axis-Aligned Bounding Box (AABB), which for tiles is the whole tile. I also registered a physics struct associated with all of the objects I wanted to collide with walls to a separate list. This struct contains the position, velocity, and size of each object.

Then, each update frame, you compare each registered physics object with each registered physics wall, and generate a list of colliding pairs. You can also compare the physics objects with eachother to generate physics object collisions. Then you pass the lists of collisions off to a collision resolution system.

You have several options with the collision resolution system. If everything is axis-aligned, then you don't need a finer collision comparison. If, however, you have slanted and curved surfaces, you'll want to do a finer test for exclusion. This should be fairly straightforward, but of course ask if you need further clarification.

When objects collide with walls, the tangential component of their velocity (often determined by wall penetration depth and AABB side overlap) are zero'd out, and they are offset so they're no longer inside the wall. When physics objects collide with eachother, it's up to you.

Improvements that can be made: Rather than using a list of walls and physics objects, you could use a QuadTree. This will allow you to skip comparing a large number of objects that have no potential to collide with eachother.
> 2 votes

# Answer
Just a short answer : i think you are confusing yourself by using x,y to define both the world coordinates and the tile coordinates.
Let us say that (x,y) are your world coordinates, then you have to build a function that returns you the tile coordinates for this point. It will look like :

```
tileX = IntegerPartOf ( ( x - offsetX) / tileSizeX ) ;
tileY = IntegerPartOf ( ( y - offsetY) / tileSizeY ) ;

```

So when checking if the player if standing, you check wether grid\[tileX\]\[tileY+1\] == 2.

To check for collision, compute the next position, (nextX, nextY), and then compute the tile coordinates (nextTileX, nextTileY) of this next position. if grid\[nextTileX\]\[nextTileY\] != 0 you have a collision you have to handle (stop or bounce or...)
> 1 votes

# Answer
This is one of my favourites.

This is one of the best tutorials IMHO for learning to implement tilebased games;regardless of the tutorial being done for flash actionscript. The fundament principles remain the same. This shows how to handle collision while jumping up and hitting floor when coming down, even collision with an overhead brick or blocked element while jumping and then suddenly falling down. Clouds, slopes, one-sided-entry platforms. You can find a lot of information for tile based games here 1.) TonyPa's Tile based game tutorials for flash

Also you might find this a good read Amit's Game Programming Information
> 0 votes

---
Tags: collision-detection
---


# Question
Title: How can I support PlayStation 3 controllers in my Java game?
Is there a way to interpret the input from a PlayStation 3 controller, and use it in a Windows and MacOS program that I am writing in Java? I have been looking at SDL and OIS, but they aren't coded in Java, so I would have to write a Java wrapper.

# Answer
After doing a little research I found a good library I could use called JInput.

> HowTo: Set up JInput API and Library for Java Development on Mac OS X or Linux Platform (archived)

This tutorial helps you install it and start up a basic programming. I used this tutorial to install JInput but ended up not using the library that the author offers.

For using Netbeans if you get stuck at the step where you have to add the `.jnilib` put the file path in the virtual machine options under right click your project \> project \> run. Then add something like this `-Djava.library.path="/path-to-folder-of-the-jnilib"` Put the path to the folder where it is located not the actual file.
> 1 votes

---
Tags: java, input, playstation3
---


# Question
Title: How can I set my application to run on the High performance GPU by default?
Nowadays a good deal of laptops come with 2 GPUs - a high-performance one and a power-saving one (less powerful). Most of the application, which I use on my laptop run with my integrated(power-saving) GPU, but still some of them are set to open with the high-performance card. I am trying to config the app which I am building to run on the high performance GPU by default, but I can't find any information about the topic anywhere. I hope that someone can shed a bit of light onto this. I will distribute my application with an NSIS installer and I guess that I'll have to add the path of my application to a list of applications for NVidia/ATI cards. The application is programmed in C#. Also, does anyone know how things stand with desktop PCs? What happens if a PC has 2 GPUs and I have to choose the more powerful one?

Milcho

# Answer
> 7 votes
NVIDIA have a document here outlining some strategies that may be helpful for you: http://developer.download.nvidia.com/devzone/devcenter/gamegraphics/files/OptimusRenderingPolicies.pdf \- unfortunately, the one I would otherwise suggest - the NvOptimusEnablement export - is only documented for C++; it may be possible to also do this with C# but someone who actually knows would have to chime in with the info.

I'm not aware of anything similar for AMD.

So unfortunately it looks as though there is no vendor-agnostic way of doing this (even enumerating display devices would leave you at the mercy of users forcing settings through their driver control panels, which users have an unfortunate tendency to do in order to max out games that don't come with fully configurable graphics settings). In the absense of such you may have to rely on a readme and hope that people actually read it!

# Answer
> 5 votes
In general, you can't.

The dual-GPU driver hides the two GPUs behind a single interface, so solutions like Nathan Reed's typically don't work in most common high-speed/low-power dual-GPU setups.

The GPU selection must be handled by the driver in some way. With NVIDIA Optimus, you usually update the Optimus profiles to add the application to the list of applications that use the discrete GPU, generally by right-clicking the EXE and clicking on Properties. You can also use some very-specific-to-Optimus calls. as per mh01's answer. With AMD setups, this is totally different.

On yet other systems, there is a hardware switch or an OS flag to decide which GPU is active. Again, the application has no control over which GPU is used.

This is something I'm really hoping is "fixed" in a future DirectX update. Ideally both GPUs would be enumerated like Nathan suggested and then there would be hints to indicate which of them is meant for high-speed or low-power, so an application can intelligently choose the right one or even switch which device it uses based on whatever factors (say, letting a web browser choose depending on WebGL load).

# Answer
> 4 votes
You should be able to enumerate the GPUs on the system and pick which one to use when your application starts up. You didn't mention which API you're using, but for instance in D3D11 you'd use IDXGIFactory::EnumAdapters to get the list of GPUs and pass the one you want to D3D11CreateDevice.

DXGI can give you some limited information about the GPU, such as a description string, vendor ID, and device ID. I suppose you can use this information to tell which GPU is the high-performance one, but you'd have to build some kind of database of GPUs, or try to use some heuristics to guess. Or you could let the user pick which GPU to use on startup.

---
Tags: c#, gpu
---


title: Kickstarter "last minute cold feet"

text:
# Question
Title: Kickstarter "last minute cold feet"
today I scheduled the publication of a video on Kickstarter requesting approximately $5,000 in order to complete the iPhone shooter game I started 1 year ago after quitting my job.

I invested more than $20,000 in the game so far (for artwork, music, legal and accountant expenses) and I am now getting **cold feet** about my decision of publishing the video.

The game is "nearly finished", in other words: the game mechanics are working but I still have some bugs to fix. Once I will have finished this (I hope will take me 1 or 2 weeks) I plan to start working on the actual **level balancing** (e.g. deciding the order of appearance of enemies for each level and balancing the number of **hitpoints** and strength of bullets that the enemies have).

Reasons for **not publishing** the video are:

* **fear that the concept can be copied easily**: the game is a shooter game set in a different environment (its a pretty cool one, believe me :)) and I am worried that someone might copy\* the idea (I know, its the usual "I am worried story.."). A shooter game is one of the easiest game to implement and hence there will be hundreds game developer able to copy it by just adapting their existing code and changing graphics (not as straightforward).

*It took me one year to develop this because I was inexperienced plus there are approximately 6/7 months of work from the illustrator and there are 8 unique music tracks composed.*
* The soundtrack of the video is the soundtrack of the game which is not yet published and has not been deposited to a music society. I did create legally valid time-stamps for the tracks and I am considering uploading the album on iTunes before publishing the video so I can have a certain publication date. But overall I am a bit scared and worried because I have never done this before and even the simple act of publishing an album requires me to read a long contract from the "aggregator company") which, even if I do have contracts with the musicians do worry me as I am not a U.S. resident and I am not familiar with the U.S. law system

Reasons for **publishing the video** are:

* I almost run out of money (but this is not a real reason as I should have enough for one more month of development time)
* ...I kind of need extra money as, even if I do have money for 1 month of development I do not have money for marketing and for other expenses (e.g. accountant)
* It will create a fan base
* I could get some useful feedback from a wider range of beta testers
* It might create some pre-release buzz in case some blogger or game magazine likes the concept

Anyone has had similar experiences? Is there a real risk that someone will copy the concept and implement it in a couple of months? Will the Kickstarter campaign be a good pre-release exposure for the game? Any references of similar projects/situations? Is it realistic that someone like ROVIO will copy the idea straight away?

# Answer
> 19 votes
**If you want to self-publish and sell your first game successfully, you will have little other choice than to create lots of attention, and a gameplay video seems unavoidable to do that. As for fears of plagiarism, having the largest possible upfront attention should actually be positive for you.**

Ideas are cheap and plentiful, it's the execution that matters and that people are willing to pay for.

Showing off your game seems to be a necessity, since as a new game developer you don't have the exposure or the fan base to create attention without showing actual game footage. A company like Blizzard could put out the most cryptic and nondescript announcement about a possible future announcement, maybe, when it's done, and still get everyone into a feeding frenzy. You don't have that choice yet.

As for copying a game: It is already illegal to commercially copy and use your actual assets, or make assets that are extremely similar. As for your ability to sue in that case, I don't know, but if you have a case, you can easily generate a lot of negative press for the offender for free by turning to various gaming web sites, kind of David-vs-Goliath style. For that, however, you first need a public record that you are indeed the original author, and a successful Kickstarter is about as public as it gets for newcomers nowadays.

So in a way, being the first to the attention market can actually provide more protection from outright plagiarism than if you released it quietly and it turns into a sleeper hit.

As for copying game concepts, or ideas: You already mentioned that the shooting genre is highly derivative, like many others. Copying mechanics is really part of the industry; without it, 99% of all games simply wouldn't exist. A "setting" is a pretty broad term, if we are talking about the same thing: something like Steampunk, or SciFi, or Medieval, that's a setting, right? In that case, I'm not even sure there is much left to truly innovate, but even if you do, there isn't much to stop others from exploring the setting further, **and there shouldn't be**!

If you have found a truly innovative and cool setting, awesome! Be the first to exploit it for what it's worth and accept the fact of life that others will follow your success to try and repeat it.

# Answer
> 1 votes
I would suggest filing for an LLC if possible in your case, if you do not already have one. An LLC grants you protection among other things and is really ideal for someone in your position. Don't waste any more time and get it public to help bring in a fanbase; especially with it being close to being published, now is an ideal time.

Keep the video short, concise, and engaging; break the gameplay up with headlines about the game-- include *part* of *one* of the tracks in the background of the video. All of this at the very least will likely land you an interview at a cool place to work; while failure would be a loss financially and emotionally, putting off project completion is worse as you may miss your moment.

---
Tags: game-design, game-industry, release
---


title: Physique and exports from 3ds Max

text:
# Question
Title: Physique and exports from 3ds Max
Are there any file formats that support Physique and are compatible with Unity? I really don't want to start over from scratch and have to use the Skin modifier...

# Answer
Yes there are - FBX supports that. You need to get a Physique to skin conversion 3ds Max plugin. Not sure if it is still supported by the newest Max.
> 0 votes

---
Tags: animation, 3dsmax, file-format, skeletal-animation, export
---


# Question
Title: How do I flatten terrain under a game object?
I've got a script that makes a terrain object and paints it with textures, but I'm having an issue. When I attempt to place game objects (such as the simple water object that unity provides), I use a Raycast to determine the correct height to place the game object, but that just ensures that it is correctly placed at that particular point.

How would I go about flattening the terrain under the game object so that it doesn't go into the terrain or hang out into thin air in the case of hills?

# Answer
> 6 votes
As I said in my comment, you'll want to find all the vertices that make up the triangles under your game object and set their y value to the same value.

I'll expand my comment with more detailed steps. I'm not too familiar with Unity, so I don't know the best tools to use for the job, but I believe I can get you started down the right path.

**Brute force method:**

1. Cast a grid of rays straight down from your game object. The grid should be tight enough to ensure it won't miss any triangles on the terrain surface.
2. For each ray that hits something, you can get the triangle in the terrain mesh with the following:

```
RaycastHit hit;
if (!Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition), out hit))
    return;

MeshCollider meshCollider = hit.collider as MeshCollider;
if (meshCollider == null || meshCollider.sharedMesh == null)
    return;

Mesh mesh = meshCollider.sharedMesh;
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
Vector3 p0 = vertices[triangles[hit.triangleIndex * 3 + 0]];
Vector3 p1 = vertices[triangles[hit.triangleIndex * 3 + 1]];
Vector3 p2 = vertices[triangles[hit.triangleIndex * 3 + 2]];

```
3. p0, p1 and p2 are all the positions of the three vertices that make up the triangle that's been hit. You want to adjust each of those vertices positions to have the same `y` value. You can either collect all the vertices, then set them all to an average `y` value, or you can use the initial picked `y` value you found when placing your game object.

**Optimizations:**

* Instead of just casting a grid of rays, you can sweep a collider down from the game object and collect the contact points of the collisions between the game object collider and the terrain collision mesh. Then for each of those contact points, perform the steps above for getting the vertices you want to move.
* Create your terrain in such a way that each vertex's `x` and `z` values are aligned to a grid, and only varies in its `y` value. Now you can easily get the bounds of your game object and change all the y values of the vertices within those bounds.

That last optimization is really an alternative method that would likely be easy to implement and fairly effective.

# Answer
> 1 votes
Its typically want the ground under the object to be flat and the ground immediately around it to be smoothed.

If the land is made from a grid and the building is axis-aligned, this is much easier.

In the general case, you subdivide triangles the building sits on, and then set the y of all the vertices on the triangles the building sits on to the same *y*, and then do a midpoint displacement smoothing for all vertices within a certain distance which are not themselves under a building.

I have used this approach to put roads onto a 3D terrain.

You typically want to enforce a minimum separation between buildings in order to have enough land to smooth. Or you might run the algorithm provisionally before placement and see if some threshold of steepness is exceeded and so policing where the user can place buildings.

---
Tags: unity
---


title: Knowing when an ad was clicked

text:
# Question
Title: Knowing when an ad was clicked
Is there a way in Unity to know when an ad was clicked? Some plugins for different advertising networks have events that fire when the ad was clicked, but if there is no such event - how do I know when an ad was clicked?

# Answer
> 3 votes
There is. I hope you know that through the advanced analytic options inside of the google adsense you can get a lot data.

You could add a blank field across the onGUI funcion. For every touch, in the spot where the ad shows up send packet to your server. Just with location. Your server will know that someone clicked, while you will not have to worry about trolls that love changing their phone time.

---
Tags: unity, marketing
---


# Question
Title: How do you determine where the user wants to place a block in a 3d scene?
I am still in the think-ahead-and-plan stage of a project where I'll want the player to be able to drag-out blocks - tiles but a minecraft-like 3D block-world.

So my question is: how can you determine where the user wants to place a block?

Here's a random minecraft screenshot I found on the internet:

My game will not be first-person camera; the user will be able to click anywhere to place a block.

If the user clicks on the centre of that green cross I've marked, which just misses the stonework to its right, where should the block be placed?

Technically determining the ray under the mouse cursor is trivial.

Given a ray and computing its distance / intersection with all existing block faces, and knowing the blocks that have previously been placed e.g. the last placed block, how can you 'do the right thing' with regards ambiguous movement? What rule set can you use?

# Answer
The process is the same as with a reticle that's fixed to the center of the screen as with a reticle that moves with the mouse. I'm familiar with the idea of 3rd person placement of cubes, I've implemented exactly that in my game Age of Goblins.

New cubes are place adjacent to the selected face. The selected face is found by casting a ray from the camera, and detecting the cube and cube face the ray first passes through. For example:

The grey outline shows the selected face. When a cube is added it's placed adjacent to the selected cube, in the direction of the selected face.

This is fairly intuitive for users, since they're likely not expecting to be placing cubes floating in the air. So they expect them to be attached to something, and that something is the selected face of the cube they currently have selected.

You can kind of see a short example of it in action in this video at the 1:24 mark.
> 5 votes

---
Tags: user-experience
---


# Question
Title: How can I make an enemy to step around solid objects and follow the player at a given distance?
```
var target_distance = 40;
var distance_to_object = 0;

target_distance = distance_to_object(objPlayerParent);

if ( target_distance >= follow_distance )
{
    mp_potential_step_object(objPlayerParent.x, objPlayerParent.y, 1, objEnemyParent);
}

```

With this code, the enemy ships are chasing the player, but are still colliding with each other, they also rather fly around the player than following his trail.

```
mp_potential_step(objPlayerParent.x, objPlayerParent.y, 1, true)

```

This did not lead to the desired effect either.

**How can I make an enemy to step around all solid objects in my level and follow the player at the given distance?**

*More context: The whole game plays in space and at the moment there are not many objects, but each type of object has it's own parent ( objPlayerParent, objEnemyParent, objPowerUpParent etc) and they are supposed to avoid all objects marked as solid. I also apologize for the quite noobish question but I am really new to advanced AI programming.*

# Answer
> 2 votes
There are two popular solutions to your current problems.

## \- Steering:

## \- Pathfinding:

They can be implemented independently or in conjunction. Likely the easiest of the two to implement is steering. Steering also has the benefit of providing additional behaviors that can handle groups more easily, to avoid enemies colliding with each other when they're moving towards the player. The behaviors combined are called flocking.

There are lots of questions on this site that relate to implementing both pathfinding and steering. Additionally, the article linked above for steering has some excellent resources for implementing these behaviors.

---
Tags: game-maker
---


# Question
Title: How to deal with lot of textures in one draw call?
I'am currently developing text rendering & some kind of tile based texturing for simple landscape with textures blending. e.g. something like this but in 3D.

In first realization I have been used 2D texture arrays to achieve problem of texture switching to be able to draw whole landscape mesh at one opengl draw call and it works great, but this should run on opengl es 2.0 devices and they are don't have 2 texture array support. So my question is - what can I do to deal with that kind of problem?

---

Of course i can just draw every landscape quad separately, but I'm pretty much sure, that this solution will really, really heart the performance. (mb i wrong?)

Also i know about texture atlases, but can I guarantee that I can put all possible textures into fragment shader for every possible tiles combination?(terrain tiles for landscape & every possible text chars with different sizes, I think you get the point) I almost sure that i can't, that's basically why I'm asking this question here.

Sorry for my horrible english, I'm working on that.

# Answer
The first thing you should do is to just get something on the screen and have it render a landscape. If that means rendering every landscape quad in a separate draw call then so be it.

Next, determine how slow it is exactly. Scale your landscape to the size you will most likely want in your game, for example 1000 x 1000 quads.

Now you can start looking for optimizations. Do you need to render the entire landscape or only the portion visible to the player? If not, try using frustum culling to only render the tiles that are actually visible.

If it's still too slow after frustum culling, then and only then can you start thinking about using a texture atlas. Determine the maximum texture size your target devices support, for example 4096 x 4096 pixels. You can use a tool like Texture Packer to create your texture atlas.

Group the terrain textures and try to make them fit in that space. Maybe the grass texture needs lots of detail, while the snow texture doesn't need much at all. In that case, you could make the grass texture 1024 x 1024 and the snow texture 128 x 128.

Play with different sizes until you have a good trade-off between the size of the atlas and the rendering speed.
> 1 votes

---
Tags: opengl, tiles, opengl-es2, texture-atlas
---


title: Box2D: Asteroids-Like Spaceship Physics

text:
# Question
Title: Box2D: Asteroids-Like Spaceship Physics
I'm new to Box2D (JavaScript) (and the world of physics/mathematics) so I'm having a hard time working out the methods I need to use to make a spaceship act like it does in the classic arcade game Asteroids. I've tried varying methods and nothing works quite right (as I obviously don't understand what I'm doing).

For example, in Asteroids you can rotate the ship but it turns at a constant rate and won't continue to spin after you let go of the key, unlike the rest of the ship's physics. So I tried SetPositionAndAngle(position, angle-0.1) as an example to make the ship turn without having it rotate after key up, however when I then press the up key to make the ship go forward, it turns left as well as going forwards (via ApplyForce).

Can anybody give some tips on how I should be dealing with Asteroids-type spaceship physics?

# Answer
Box2D is massive overkill for Asteroids.

Without Box2D, assuming you're forcing yourself to use that for some reason, you just need some basic Newtonian physics.

*Velocity* is your speed in a particular direction. *Acceleration* is your change in velocity in some particular direction.

You can take your heading (rotation), generate from that a unit vector `(cos(theta), sin(theta))` and then set your acceleration to that vector +/- a particular amount depending on whether up or down is pressed.

You can then integrate your new position and velocity each frame with simple Euler integration:

```
velocity += dt * acceleration
position += dt * velocity

```

For rotating, just modify your heading angle when you press left or right directly.

You now have the same 'physics' Asteroids has. Now you just need to add in collision detection so asteroids kill your ship and your bullets kill asteroids. Simple circle-circle collision can work just fine here.

```
check_collision(center1, radius1, center2, radius2):
  distance = square_root(center1.x * center2.x + center1.y * center2.y)
  if distance < radius1 + radius2:
    collide
  else
    no collide

```

And there you have it. Add random Asteroids spawning, lives, and bullets, and you have reimplemented Astroids exactly.

Even if you want to keep using Box2D, to use it *well* you need to understand Newtonian dynamics, impulses and forces, what constraints are in theory, linear and rotational dynamics, etc. It's not hard to learn it all, but you will need to take some time reading up on it (it's not really feasible to fit it all in a single SE answer). Having had introductory high school or college physics will come in *extremely* handy.
> 4 votes

---
Tags: physics, javascript, box2d, html5
---


# Question
Title: Per-fragment lighting system behaves like ambient lighting system
This is the relevant section of my fragment shader

```
  varying vec3 normal;
  varying vec3 halfv;
  ...
    vec4 color = ambient * gl_LightSource[0].ambient;
    vec3 n = normalize(normal);

    float nl = max(dot(n, gl_LightSource[0].position.xyz), 0.0);

    if (nl > 0.0)
      color += (diffuse * gl_LightSource[0].diffuse * nl)
            +  (specular * gl_LightSource[0].specular * pow(max(dot(n, normalize(halfVector)), 0.0), shininess));

    gl_FragColor = color;

```

Where ambient, diffuse, specular, and shininess are all already defined. `normal` and `halfv` are defined in my vertex shader as

```
normal         = normalize(gl_NormalMatrix * gl_Normal);
halfv          = gl_LightSource[0].halfVector.xyz;

```

My light is directional, position is set to `100, 100, 100, 0`. Ambient, diffuse, and specular values are `1, 1, 1, 1`, `.01, .01, .01, 1`, and `0, 0, 0, 1`, respectively. When might light vector is `100, 100, 100, 0`, the entire mesh appears ambient lit. Any other position or magnitude causes the mesh to go dark, only showing the ambient component.

**EDIT**

This is the updated fragment shader:

```
  vec4 color = ambient * gl_LightSource[0].ambient;
  vec3 n = normalize(normal);
  vec3 ldir = normalize(gl_LightSource[0].position.xyz);
  vec3 halfv = normalize(normalize(cam) + ldir);

  float nl = max(dot(n, ldir), 0.0);

  if (nl > 0.0)
    color += (diffuse * gl_LightSource[0].diffuse * nl)
          +  (specular * gl_LightSource[0].specular * pow(max(dot(n, normalize(halfv)), 0.0), shininess));

  gl_FragColor = color;

```

and vertex shader:

```
normal         = normalize(gl_NormalMatrix * gl_Normal);
cam            = camera_pos.xyz - gl_Vertex.xyz;

```

I'm still seeing a dark, ambient tone only. I've also normalized my vector CPU side, now as `1, 1, 1, 1`

# Answer
The problem is here:

```
dot(n, gl_LightSource[0].position.xyz)

```

The light vector needs to be normalized. For a directional light, this can be precomputed as a unit vector pointing toward the light (note that directional lights don't have a position, only a direction). For point lights you would subtract the light's position and the vertex position in the vertex shader, then normalize that in the pixel shader.

Similarly, the half-angle vector for specular lighting needs to be normalized, and it needs to be computed per-pixel based on the camera vector and the light vector at that pixel. It can't be precomputed (except in the very special case of a parallel projection with a directional light).
> 1 votes

---
Tags: opengl, shaders, lighting, fragment-shader, per-pixel
---


# Question
Title: Handling actions in component based multiplayer game
Please stay with me as I explain my question.

I'm creating a multiplayer game. My design pattern follows broadly thoughts described in the post here.

The idea is that each actor whether be it a (local) player or a npc does what a `GameAction` attached to this actor tells it to do. These GameActions are obtained by reacting to a received `GameEvent`. This enables only sending GameEvents through network and each client logic will obtain own GameActions for e.g. moving local copies of remote players themselves and also getting sanity checks from time to time.

**How should these actions be composed then? Who takes responsibility stopping actions?**

My problem right now is that if a `LocalInputHandler` produces on `keyDown()` a `CHARACTER_INPUT` event it will be delivered to and consumed by a parent node the local player is living in. The parent node obtains a `CHARACTER_MOVE` GameAction and attaches it to the specific local player. On `update()` the player/character excecutes the GameAction. It moves, by itself. Like a small script interpreter. *Isn't that awesome?* No it isn't because if I didn't release the button (aka holding it) no new `CHARACTER_INPUT` will be emitted and the player excecuted it's action and nothing happens.

***To solve this problem I came up with 6 classifications or types of GameActions:***

* Unstoppable - *loops forever, can only be stopped by itself*
* OneTimeLooper - *loops until getting stopped, always finishes task before getting interrupted*
* Looper - *loops until getting stopped, can be interrupted any time*
* OneTimer - *performs action only once and can't be interrupted while doing it*
* WeakWorker - *Performs action once but can always be interrupted*
* Stopper - *AntiAction: interrupts all types except unstoppables. Is a OneTimer*

This would lead having a `CHARACTER_MOVE` action be a `OneTimeLooper`. It moves the attached actor until a `CHARACTER_MOVE_STOP` action tells it to do, being created because of an event originating from a `keyUp()` call.

But this solution smells bad to me, because then each Character/Actor/Player has to have more than one GameAction it can hold to. A *Stopper* must have access to it's counterpart to know if it is allowed to stop. Also shouldn't higher order classes like parent nodes have the power to stop an GameAction since they also created them? Why not give LocalInputHandler power? How to change input style if you have a menu opened on top of the screen representing everything that happens in your world?

---

*Clarifications and optional text:*

LocalInputHandler and localPlayer are coupled by handing over LocalInputHandler the ID (represented by UUIDs, which I'm still not sure using because they are so big for networking applications) of localPlayer in construction. Each InputHandler whether be it a remote or ai InputHandler will only now by ID which actor they are handling and will refer to this ID when creating a `CHARACTER_INPUT` event by writing `recepient = actorID` into the event. The message of this event is a `int[] keymap` which holds information about which key is held down. keymap is a member variable of a InputHandler It could be a boolean\[\] but for now it's an int\[\] array. Parentnode of an actor takes these informations (recepientID and keymap) and packs a `CHARACTER_MOVE` GameAction into the event passing it down to the actor for consumption. In this process the keymap is being copied by calling `.copy()`on keymap because this will prevent opening a channel of direct communication from the InputHandler to the GameAction by not letting it just copy a reference but the array as a whole.

# Answer
Your GameActions and GameEvents are a pretty classic Finite State Machine (FSM). But not quite yet. An FSM is neatly described by what each state (action) does and exactly what inputs (events) produce a new state as output. It helps when faced with structural problems like this to keep interaction in precise terms.

Note that a game character will typically have a **lot of states** that it can go into but always **only one current state** that it is in, which implies a lot of input types to the FSM to change states. An example would be "Idle" changing to "Walk" when the "Idle" state sees a movement\_key\_press event, at some point later this "Walk" state sees a movement\_key\_release and changes to "Idle."

Your engine is producing a lot of different inputs: time, key events, world events like collison, movement speed, getting hit for damage, etc... And your single active GameAction in your FSM should consume these and react only to the ones it's interested in to change to another GameAction (like the idle-\>walk-\>idle states above).

HSM (hierarchical state machine) is just an elaboration on FSM which you may find useful once your designs become more advanced.

**So in answer to what I think your question is**: it's OK for a character to have a large number of states it can get into, as long as there's a clean organization like FSM/HSM to handle what it's currently doing. This is why commercial component systems have a big "character controller component" instead of a bunch of little components flying around.

Current **actions are responsible for stopping themselves based on inputs**, the outside world only knows that it's feeding your FSM input and only the current action in the FSM knows what that input means. Most accurately it's not the action stopping itself, it's the action telling the FSM to change to another action in one, big and endless cycle.

Your list of action types is very good, you can use those as a pattern to build your individual states from.

While this may sound like a lot of responsibility to cram into a simple component, remember that this component is only handling one thing (character state) and trying to break it up further would most likely result in a big mess.
> 3 votes

---
Tags: multiplayer, component-based, input
---


# Question
Title: Manipulating Perlin noise output to create different ore veins in different depths
I am developing a simple project using Java, for Android. It is a side-scroller with a procedurally generated, infinite world. Most of the generation will be working on underground but I expect the same principles would apply to features that would be above the ground.

I have 2 coordinates. **X** goes Left-Right and **Y** goes Up-Down. I have managed to generate a density map using Perlin. What I do is looping through X and Y values, putting them in a noise function, and evaluating the resulting float to decide whether to place a specific tile or not. I have successfully created a uniform tile distribution. However I need something a bit more specialized.

You see, in order to make this interesting, I need to place various resources (Coal, Iron, Silver, Gold) as well as monster spawns in the map. I am thinking that it would be more realistic to place different resources in different **depth levels**. So for example, I need coal to appear between Y = -20 and Y = -50, Iron between -40 and -100, ogre spawners between -40 and -300 etc.

However, if I set these boundaries with a simple if statement like:

```
if (y<-20 && y>-50) {
    // Generate coal
    noise = perlin.getnoise(x,y,7);
    if (noise>=threshold) map.put(x,y,TILE_TYPE_COAL);
}
if (y<-40 && y>-100) {
    // Generate iron
    noise = perlin.getnoise(x,y,7);
    if (noise>=threshold) map.put(x,y,TILE_TYPE_IRON);
}

```

This generates sharp edges between those boundaries, like this: https://i.stack.imgur.com/XJGLk.jpg

I need the noise to somehow generate resources that, when digging down, would **gradually** appear more often, and then **gradually** less so. Ease in and ease out.

For example, if I set the boundaries for coal to be between -20 and -50, most of the coal should appear in the middle of this ribbon, -35, while it should appear less in -20 and -50 levels. Perhaps I need a Gaussian distribution? I don't know where to start.

To put the question in a more mathematical form:

*How do I manipulate the output of a Perlin noise function depending on one of the inputs (Y) in a non-abrupt, natural way, in order to gradually increase or decrease density for specific ranges of Y?*

Thanks in advance

# Answer
> 3 votes
A simple way to do this is to modify the threshold value based on the height.

```
if (noise>=threshold) map.put(x,y,TILE_TYPE_COAL);

```

This means that where `threshold` is small you'll be more likely to place coal, and where `threshold` is large, less likely to place it. So, you should be able to get a gradient in coal density by setting `threshold` as a function of `y`, in such a way that the threshold is high near the boundaries of the coal area, and low in the middle. Assuming your noise function outputs values from 0 to 1, you could try something like this:

```
ribbonDist = (y - ribbonCenter) / ribbonRadius;
threshold = 1.0 - coalOverallDensity * min(ribbonDist*ribbonDist, 1.0);

```

Here `coalOverallDensity` is a factor controlling how much coal there is overall, `ribbonCenter` is the y-value at the center of the ribbon (-35 in your example) and `ribbonRadius` is the distance from the center to the edge of the ribbon (15 in your example). You can see a graph of this function and adjust the parameters here.

I chose a quadratic function (`ribbonDist*ribbonDist`), but you could also use other options like a triangle function or a Gaussian to get a different look, if desired.

---
Tags: java, android, maps, procedural-generation, perlin-noise
---


# Question
Title: 108 kb - size of most in-game activation passes, skins, etc... Any idea Why?
I have been playing xbox 360 for a while now and whenever there is a pass, character/weapon skin or even multiplayer access code that needs downloading, the file size is usually 108 kb, no matter the game/application. I've tried googling around and have not come across anything useful. Could someone explain or even speculate why that happens? I ask out of curiosity :) Possibly, this question may belong in a different forum - if so, please advise which. :)

# Answer
> 1 votes
It's unlock key, that is disguised as downloadable content. You would think, that you download new content to your Xbox, but infact, you just unlock content that is already in disk.

---
Tags: xbox360
---


title: A quick question about culling

text:
# Question
Title: A quick question about culling
So I have some vertices that I'm drawing with XNA and the issue I had ages ago was that they weren't appearing when the camera was placed above them. By turning on backface culling this fixed it, but now I'm also using 3D models and whenever backface culling is turned on it goes through it. I could just turn it on and off based on when these objects get drawn, but that feels like such a sloppy fix and I remember the person who helped me mentioned something about the order that the vertices are drawn in is what determines the natural culling state for them. Could somebody please elaborate on this and explain how I could get the original vertices to be drawn properly with backface culling off?

Thanks!

# Answer
> 0 votes
It depends on the order of the vertices of each triangle. The vertices can be saved clockwise or counterclockwise. The default what most 3D programs should do is counterclockwise. In XNA 4.0 you can set the cullmode like this:

```
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
//GraphicsDevice.RasterizerState = RasterizerState.CullClockwise;
//GraphicsDevice.RasterizerState = RasterizerState.CullNone;

```

---
Tags: xna, culling, face
---


# Question
Title: Getting a uint color array from a portion of a Texture2D
I'm currently using the Farseer tools to create a body from a Texture2D. However, my texture is a spritesheet and I need to get the uint array containing the colors from a portion of the full Texture2D.

Let's say may texture is 200x200 big and I need to get the colors in the Rectangle(20, 20, 40, 40). I know that there is a GetData() overload and I'd imagine I have to call it like this:

```
        uint[] subData = new uint[40 * 40];
        polygonTexture.GetData(0, new Rectangle(20, 20, 40, 40), subData, 0, 40*40);

```

However, I always get a `System.NotImplementedException`, probably due to MonoGame. Is there another easy way to do this? Or do I have to create a Subtexture and then get the Colors from that subtexture?

# Answer
> 2 votes
I noticed this question has been around for a while unanswered so I thought I'd put some information here for future reference. It's not a complete answer, but it might help the next person.

Is seems there are a number of open issues with lots of discussion around this issue and why it's difficult to implement.

https://github.com/mono/MonoGame/issues/1405

https://github.com/mono/MonoGame/issues/644

https://github.com/mono/MonoGame/pull/1789

The primary issue is that OpenGL ES 2.0 does not support retrieving data from textures. However, it looks like there have been plenty of attempts to solve it and it may be solved now for some platforms. Not sure.

---
Tags: c#, xna, monogame, farseer-physics-engine
---


title: How to know if the player is signed in?

text:
# Question
Title: How to know if the player is signed in?
I was wondering if there's any way to know if the "player" is signed in or not?

Something like this:

```
if (GamePad.GetState(PlayerIndex.Two).IsConnected && !Gamer.PlayerTwo.IsSignedIn)

```

So that the controller is connected and it can be used, but the player is not signed in to an account. Something like a guess.

# Answer
> 11 votes
In XNA there is a `SignedInGamer` class with a `SignedInGamer.PlayerIndex` member that should tell you just that if you can get a hold of the `SignedInGamer` object.

To do that, there is the `Gamer.SignedInGamers` static property which contains a collection of `SignedInGamer` objects based on the current state of the system. This is from the `Microsoft.Xna.Framework.GamerServices` namespace.

With this information you could do something like the following:

```
//If player 2 is connected
if (GamePad.GetState(PlayerIndex.Two).IsConnected)
{
    //If we can't find a signed in gamer with a PlayerIndex of two
    if (!Gamer.SignedInGamers.Cast<SignedInGamer>().Any(x => x.PlayerIndex == PlayerIndex.Two))
    {
        //Your handling code here
    }
}

```

---
Tags: xna, xna-4.0, xbox360, xbox-controller
---


# Question
Title: Options for a functional-style enthusiast?
Senior programmer who has been coding in a functional style for years. I want to make an attempt on the indie games market, but I don't find any good, big platform that provides a good way to code using a functional style. And the fact Unity3D pretty much domains that market, I'm pretty much limited to C#. I wonder if there is another way?

# Answer
> 0 votes
F# works as well as C# with libraries like OpenTK and XNA.

I have not used Unity, but it seems that you can import external dlls into Unity, so you could write your core logic in F# dlls and use those classes from within Unity as well.

# Answer
> -1 votes
What about OpenGL for Haskell?

# Answer
> -2 votes
What about using JavaScript, there are quite a few JavaScript Game engines out there. And Javascript is functional.

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


title: Libgdx ShapeRenderer rectangles

text:
# Question
Title: Libgdx ShapeRenderer rectangles
I'm trying to draw a filled rectangle in Libgdx and according to the API this should work:

`shapeRenderer.begin(ShapeRenderer.ShapeType.FilledRectangle);`

But it gives me an error and tells me to change `FilledRectangle` to `Filled`, `Point`or `Line`.

imports: `import com.badlogic.gdx.graphics.glutils.ShapeRenderer;`

Any ideas on what is causing this?

# Answer
> 7 votes
If you read the documentation, you'll see that `ShapeRenderer.ShapeType` is an enum with the following values defined:

```
Filled
Line
Point

```

So the error message you're receiving is accurate.

If you want to draw a filled rectangle, choose the `Filled` enum type, then use shape rederer to draw a rectangle:

```
 shapeRenderer.begin(ShapeType.Filled);
 shapeRenderer.identity();
 shapeRenderer.translate(20, 12, 2);
 shapeRenderer.rotate(0, 0, 1, 90);
 shapeRenderer.rect(-width / 2, -height / 2, width, height);
 shapeRenderer.end();

```

# Answer
> 2 votes
With LibGdx 0.9.8 they removed `ShapeyType.Rectangle`, `ShapeType.FilledRectangle` and introduced `Filled, Line, Point` to optimize the shape rendering.

---
Tags: libgdx
---


# Question
Title: Implementing Scrolling Background in LibGDX game
I am making a game in LibGDX. After working for whole a day..I could not come out with a solution on Scrolling background.

My Screen width n height is 960 x 540. I have a png image of 1024 x 540. I want to scroll the background in such a way that it contuosly goes back with camera

x-- as per camera

I tried many alternatives... drawing the image twice ..did a lot of calculations and many others.... but finally end up with this dirty code

```
if(bg_x2 >= - Assets.bg.getRegionWidth())   {
//calculated it to position bg .. camera was initially at 15
                bg_x2 = (16 -4*camera.position.x);
                bg_x1=bg_x2+Assets.bg.getRegionWidth();
            }
            else{
                bg_x1 = (16 -4*camera.position.x)%224;  // this 16 is not proper
//I think there can be other ways
                bg_x2=bg_x1+Assets.bg.getRegionWidth();
            }

//drawing twice
       batch.draw(Assets.bg, bg_x2, bg_y);
        batch.draw(Assets.bg, bg_x1, bg_y);

```

The Simple idea is SCROLLING BACKGROUND WITH SIZE SOMEWHAT MORE THAN SCREEN SIZE SO THAT IT LOOK SMOOTH. Even after a lot of search, i didn't find an online solution. Please help.

# Answer
You can use parrallaxBackgroung and ParrallaxLayer classes

They will manage all u need in an optimized manner and also its very easy to implement

http://www.badlogicgames.com/forum/viewtopic.php?f=17&t=1795
> 3 votes

---
Tags: libgdx, side-scroller
---


title: Creating a map editor for cubes

text:
# Question
Title: Creating a map editor for cubes
I was told that I should create a map editor, instead of hard coding out all the grids of my map. It sounds like a fun project and would make things easier in the long run, but I wouldn't even know where to start with it. It would be pretty simple, 3 cube types, a 1000x1000 grid, and the ability to stack cubes on top of each other. Exporting the map into something I can use in my game would be an issue though. Also creating the UI for the editor would be something completely new to me. Are there any links out there that can help with this?

# Answer
> 1 votes
This is a pretty broad question, but I'll try to give you a few pointers. See if they're of any help to you.

# Exporting/importing map data

In order to be able to use the maps created with your map editor, you will need to define a **data format** for the map data. The exact format is irrelevant, but it can be as simple as a plain text file or a xml file. You should create a `MapSerializer` class, which should have the functions `serialize` and `deserialize`.

The `serialize` function should take the map structure as a parameter. If you've already hard coded some maps to your game, then you already have this representation defined. The output of the function should be the serialized, e.g. string formatted, representation of your data.

`deserialize` method should then do the exact opposite: take the serialized map data, e.g. a string, and produce the representation you use in your game internally.

# Actual editor

The interface should likely use your rendering engine to represent the current state of the map, with controls to move around the map freely. You can use **ray tracing** to find the spot in the 3D world where the user clicks.

Separating the cubes to chunks is not necessary in the map editing phase, you can do that when loading/drawing the map.

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


# Question
Title: DirectX 11, using Tessellation & Geometry shader in a single pass
Before all, sorry for my poor english !

With DirectX 11, i'm trying to create a random map full with GPU.

Using Hull shader stage, I'm managing LOD with tessellation.

Using Domain shader stage, I'm generating the map (based on perlin noise).

Now my goal, is to compute normals in the geometry shader (normal on vertex). For that, I must use vertex adjency, like geometry is capable of.

But here is the problem... For tessellation, my primitives must be D3D11\_PRIMITIVE\_TOPOLOGY\_3\_CONTROL\_POINT\_PATCHLIST.

But for geometry shader with 6 vertex (triangle primitive and adjency), I must use : D3D11\_PRIMITIVE\_TOPOLOGY\_TRIANGLELIST\_ADJ.

Think I'm missing something... It must be possible to tessellate and use the results in the geometry shader... However, it's working with 3 points, but I cannot use the 3 others (they are 0.0, 0.0, 0.0)....

Thank you in advance for any help ;)

# Answer
> 0 votes
You can use the geometry shader together with tessellation, but in DX11 I don't think you can get the tessellator to generate adjacency information. The topology generated by the tessellator is controlled by the outputtopology attribute of the hull shader, and there are no options for it that include adjacency.

It's understandable why this is the case: while the hardware tessellator could presumbly have been designed to generate adjacency information for triangles *internal* to a patch, it would have no way of knowing what the adjacency should be for triangles on the *edge* of a patch, as each patch is processed in isolation.

An alternate approach would be to generate normals in the domain shader, using the derivative of the noise function. Another possible approach would be to stream-out the tessellated vertices to a buffer and run a separate pass over them, perhaps using a compute shader, to generate the normals.

---
Tags: shaders, directx11, geometry, tessellation
---


title: XNA HLSL Exclude texture?

text:
# Question
Title: XNA HLSL Exclude texture?
I'm going through HLSL tutorials and I have lighting and texturing setup. Right now in my shader I take a texture, but if I leave that variable blank it gives me an error. Half of my models have textures and the other half don't, is there a way to "skip" the texturing part for the models that don't have them and set it for the models that do without having to make a completely seperate shader that only deals with lighting?

Also, whilst I'm asking this, is saturate and normalize the same thing?

Thanks

# Answer
> 2 votes
You will have to use two separate shaders to achieve this. Probably the best way to go about this is to add preprocessor directives to remove your texture code when a certain symbol is defined i.e.:

```
#if USE_TEXTURES
//texturing sctuff here
#endif

```

This makes it easier to maintain changes that would affect both shaders.

# Answer
> 1 votes
There is no way to "skip" texturing, but if you don't want to make two separate shaders, you could simply create a 1x1 white texture and use that for all the untextured models.

---
Tags: xna, hlsl
---


# Question
Title: Why is Minecraft's default resolution (seemingly) non-standard?
Background: I'm writing some articles on Minecraft in an attempt to introduce 10-year olds to development through modding. I know very little about the game itself, though :)

I'm trying to understand why Minecraft appears to run in an "odd" default resolution. Grabbing a screenshot, I think it's rendering at 550x310 but that doesn't seem to match any of the "common" aspect ratios (although it's close to 16:9), nor is it evenly divisible by 16, which appears to be what the texture packs use.

1. Is it actually running at 550x310 in its default windowed mode? If not, what is the resolution?
2. Depending on the answer to the first question, why isn't it using one of the standard aspect ratios? I'm not familiar with OpenGL programming either so perhaps there is a common resolution close to what I'm guessing at that would make perfect sense.

# Answer
Actually, Minecraft will run at whatever resolution you size your window to (348x866):

So it's likely that whomever took the screenshot you grabbed, just happened to have their window sized that way.

The default screen size when I start the game appears to be 856x482, which is pretty close to 16:9. It doesn't need to use a standard aspect ratio or resolution. The display size doesn't have anything to do with the texture packs. It's not required to be divisible by 16. A game might have these restrictions if it was 2D and you wanted to fit a whole number of tiles on the screen at one time. However, with a 3D game the display size (in windowed mode) can be whatever the developer decides they like.

When the game is run full screen, it's best to match the game resolution and aspect ration with the resolution and aspect ratio of the screen.
> 15 votes

---
Tags: opengl, minecraft-modding
---


title: Drawing text in SlimDX with Directx 11?

text:
# Question
Title: Drawing text in SlimDX with Directx 11?
How can I draw text to the screen in directx 11 with slimdx? In SlimDX.Direct3D10 there's a font class which can be used but there's no font class in SlimDX.Direct3D11.

# Answer
The easiest way is to use a bitmap font. You create a table that maps each ASCII (or UTF) character code to a region of a texture that contains all the characters you want to use. To draw a string, you create a vertex buffer with positions and textures, adding on a quad for each character, where the quad's size and UV coordinates are taken from the table.

This page is a bit of a read, but it's quite an in-depth tutorial on bitmap fonts.
> 1 votes

---
Tags: fonts, slimdx, text
---


# Question
Title: How do I implement 2D shadows cast between layers?
**How could I implement 2d shadows that are cast by objects in a different layer?**

NOT like the dynamic lighting in the well known tutorial from Catalin Zima:

But like the shadows of the pipes in this video:

And like the shadow of the platform and the character in this video:

I would like to use the same kind of lighting in a scene with many layers and a lot of lights with different colors.

I could imagine doing this by drawing a black copy of the layer over the layers behind that layer, and adjusting it according to holes in the layers on which the shadow is cast. But I hope there is a less expensive, pixel-shader based approach for this.

# Answer
This can be done with masking. There are multiple ways to do it.

One way would be to have a way to render a shadow version of foreground elements. Draw the background. Then draw the foreground elements, offset slightly depending on how you want lighting to move, in such a way that you only output black colors. Then draw the foreground normally.

Another way would be to render the foreground into a buffer, a little bit more than you'd actually see. Then do some "to black" pass and maybe a blur pass. Now render the output of this set of passes and then the visible section of the foreground buffer.

To support multiple lights at different angles, you can just do the previous step multiple times, or accumulate them all in a single buffer. The math will vary based on what you're trying to achieve, but a first guess at what's going on in that first video is that they just take the position of the light against the position of the camera (center of the visible area) and then use that vector (scaled) to determine how to offset the shadows. Something like:

```
draw background
for each light intersecting viewing bounds:
  offset = light.position - camera.position
  offset *= SCALE FACTOR (0.25 maybe)
  draw shadow foreground at offset
draw foreground

```

Lights that are "closer" to the scene will have a smaller scale factor. If you want multiple depths, there's some math to work out there, simple geometric stuff.
> 1 votes

---
Tags: xna, 2d, fragment-shader, shadows
---


# Question
Title: How do I handle game objects with two depths?
I want to be able to do what you see in the image, but with a single wall. **The player should be able to walk on either side of the same object**. That is, the same wall is below the hero when I go down from it, and it's above the hero if I come from above it.

It's like two depths in the same wall, so its not just a matter of drawing it before or after. I could cut the object in two, but that would be the easy (and maybe computationally expensive) solution. How should I do this?

# Answer
> 9 votes
Here are three ways to do it. Which one will be suitable depends on what kind (graphically) of game you're making.

1. As user Fabinout already commented: “Splitting the object in two … The upper part is behind the character, and the lower part is between the player and the character.” If you are making a rigidly tile-based game (the shown paths are the only two possible paths near the wall), this is likely a fine way to do it. Note that for this to work, the distance between the upper and lower paths must be at least as much as the height of the character.

A disadvantage of this method is that it only helps with cases like this particular one; it's not a general strategy for stacking sprites.
2. Draw all sprites — both the player and the scenery — from top to bottom in order of their “ground level” positions (base of the wall, player's feet). This will automatically cause the wall to be shown on the correct side, and is a common strategy for “isometric” and “2D RPG” styled games.

Another advantage of this is that it generally looks good even if objects pass through each other — e.g. characters that don't block others' movement; walking through a field of tall grass. Disadvantages are that you need to efficiently determine the drawing order (e.g. either sort your sprites, or have an 2D array of tiles which know what sprites are in them) and that it gets complicated when you have objects which are not all visually rooted on the same ground level.
3. Have a “front layer” and “back layer” where your character occupies one or the other (and the wall is drawn after back but before front). Depending on how you approach the wall, the character gets switched to the front or back layer by trigger zones. This is how Sonic the Hedgehog games handle things like loop-the-loops.

The advantage is that you can have essentially two independent 2D planes to build your level elements on. However, this is more appropriate for a game where vertical motion is jumping up, whereas from the shape of your graphics, your game appears to be one where vertical on-screen motion is moving front/back on the ground, and there are far more than two different positions in that dimension.

# Answer
> 1 votes
Draw objects in order of the `Y` value, so objects "further away" (higher up on the screen) are drawn before/underneath "closer" objects. That simple.

More generally, just give objects a depth value (which might be implicitly based on `Y` or explicitly set, depending on game and needs) and render in that order.

This is the "painter's algorithm" at work.

---
Tags: 2d, draw-order, depth
---


# Question
Title: Should I use delta time (elapsed time between frames)?
Unfortunately I cannot recall where but I definitely read it somewhere, that the use of delta time should be avoided for some reason. Is there really a scenario where controlling animation or other in-game events using delta time is bad or it was just a wierd dream of mine?

# Answer
> 7 votes
Using delta time is usually the correct solution. However the issue I believe you're thinking of is using a varying delta time in conjunction with a physics engine. In this case the time step should be fixed for the best/most consistent results.

Fix your timestep is a good resource on the matter.

# Answer
> 2 votes
Adding to @elFarto's answer, you should use a fixed timestep for all game logic. You really want AI and such in sync with physics.

You use your frame's delta time to update an accumulator to know *when* to step your fixed timestep.

You also apply the delta time to interpolation when drawing. A frame must be drawn *just before* the next fixed timestep. If you just draw the current state, you'll end up with some jitter in movement. You need to store both the "last" state (relevant bits for graphics) and compute one step ahead. You can then look at your time accumulator to see at what point you are between those two steps and draw interpolated values (positions, rotations, animation data, etc.) that represents that time. So long as your fixed timesteps aren't too far apart, you shouldn't see any glitches from the interpolated values, but it will hide any jitter.

The jitter is less pronounced the smaller the timesteps are. For simpler 2D games, you can often set your timesteps to particularly small values (such that every frame typically is 'stepped' many times before rendering). Because the values are so small, interpolation won't be necessary.

---
Tags: game-mechanics
---


# Question
Title: Cocos2D: Box2D body that is movable by one type of object but not another
I'm in the process of creating a simple platform game using **Cocos2D 2.0** and **Box2D**. I'm trying to create a kind of crate object that cannot be moved by the player, but that *can* be moved by an elephant object. When the player runs up to the crate, it should stop him dead in his tracks (as if he is running into a static Box2D body). If the elephant runs into it it should get knocked out of the way (as if the elephant was running into a dynamic Box2D body of much smaller mass/density). I can't use collision bitmask because of course I want collision to occur in both cases, I just want that collision to result in different things depending on which type of object is hitting the crate.

Anyone have a hint as to how to make this work?

Thanks in advance!

# Answer
Depending on the rest of your logic, you could either use **collision filtering** to create a case where players ignore the box, but react to an invisible unmovable box, while elephants ignore the invisible box, but react to the visible box.

Or you could use **postSolvers**, using the contact object passed by postSolvers in this way:

```
if (contact.GetFixtureA().GetBody().itemType == 'player' && contact.GetFixtureB().GetBody().itemType == 'box' ) {
contact.GetFixtureB().GetBody().setMass(999);
}

```

That's an oversimplified javascript example, your implementation might be different, but the concept is that you can manipulate the bodies referenced by the contact object passed to the postSolver you set.
> 1 votes

---
Tags: box2d, cocos2d
---


# Question
Title: Why should I write a computer program if I don't know exactly how the program gets run in its entirety?
One can not simply just write some code and competently believe they know how their little MAIN.exe is getting executed underneath the exposed API functions.

I want to know deeper on how my games are running under the APIs; I want to know how the kernel gets everything going to get my game working, and I want full assurance that everything I code is working with my knowledge of bloat ware.

How can one simply just "write a game with SDL, compile, link, run, i.e., F9" without wondering the abstracted reality of your game's execution?

I know terms in regards to low-level programming, such as without an OS, but the OS makes it even more complicated than just with a bare machine, since there's so many endless modules, programs, and kernel work done that most people have no 100% idea or clue of.

# Answer
"How can one simply just "write a game with SDL, compile, link, run, i.e., F9" without wondering the abstracted reality of your game's execution?"

Simple I do it all the time...

"Why should I write a computer program if I don't know exactly how the program gets run in its entirety?"

You would need to write a computer program in order to learn how it gets run in its entirety. Maybe you could create an OS, then make a game using your OS, that would teach you an awful lot about how your program gets ran in it's entirety

Oh, wait but to understand everything you may want to make the computer from scratch too
> 1 votes

# Answer
You certainly can just write all your code in machine code and totally understand and control everything. However, it will only run on the one specific hardware setup you developed it for. This is why we abstract things. So we can do our thing, and have the hardware vendors control the details
> 0 votes

---
Tags: software-engineering
---


# Question
Title: Why are my sprite sheet's frames not visible in Cocos Builder?
I have created a sprite sheet with zwoptex. Then I just dragged the `.plist` and `.png` files to my Cocos Builder project. After this I wanted to take a sprite frame and set it to a sprite:

But the sprite image is empty! At first I thought it was just empty in Cocos Builder, and that it must have been working correctly when imported to a project. But if I try to run that scene with *CCBReader* I still see an empty sprite. Why?

# Answer
> 0 votes
The plist file was invalid because I renamed the image, so that the name contained in the plist file wasn't the true one. So I just made the spritesheet again with zwoptex and now everything works fine.

---
Tags: cocos2d, spritesheet
---


title: When to apply AA as post?

text:
# Question
Title: When to apply AA as post?
I'm working with a deferred shading technique. I have diffuse, normal and depth buffers, which I combine for the final scene composition. Where and when exactly do I apply an anti-aliasing pass (such as FXAA)? Just on the color buffer before lighting or any processing? Or as a separate pass on the final scene? Or something in-between?

# Answer
Techniques like FXAA, MLAA etc. are normally applied almost at the very end of the graphics frame - after all lighting, postprocessing, color correction etc. is complete, but before rendering UI and text (because those normally already have sufficient antialiasing built in to their textures and don't need any more).
> 2 votes

# Answer
Anti-aliasing in a deferred shader is a complex topic. WikiPedia lists a number of techniques for doing anti-aliasing in a deferred-compatible way.

Typically you'll need to do it after lighting, otherwise you can end up with lighting artifacts. Most approaches I know of do another pass on the scene after the entire deferred pipeline is complete.

If you are using more recent hardware and APIs, you can "simply" use multisampled render targets for your color and light buffers (the newer APIs allow you to sample those as needed) at the usual cost of increased memory usage. The other techniques can work with nothing more than a small number of extra buffers/passes and have only compute time costs.
> 5 votes

---
Tags: hlsl, deferred-rendering, post-processing
---


# Question
Title: Accessing and changing texture data in SlimDX
How can I access and change texture data in SlimDX? I have a Texture2D and a Texture3D and I need to be able to go in and change either a single or group of pixels.

# Answer
If you need to update textures once in awhile (e.g. while loading a new level), you can do it with UpdateSubresource. However, **beware** that this can cause a CPU-GPU sync point, which will trash your performance if you're doing it every frame.

If you need to update textures in real-time, a better way is to bind it as a render target and draw on it with a shader that performs the required alterations.
> 1 votes

---
Tags: textures, directx11, slimdx
---


# Question
Title: Xna Particle Explosion like Geometry Wars
I am making a game, in similar graphics display as Geometry Wars. In Geometry Wars (noticeable in the title, as well as when you blow up an enemy), there are these colorful explosions that emit, then fade away at the end. An example is this video. I know very little about particles. I already have an effect that will make objects glow (Bloom, if you didn't know). I would like to know if there is an Xna library that can do this effect. If not, is there code that I can use? Or some documentation that I could implement?

And also, could the code for the explosions be modified slightly to simulate the stream effect that the ship emits when it is moving around?

# Answer
There's few particle engines, that are designed for XNA.

Mercury comes with built in particle editor, where you can define and see the effects of a particle right away, realtime and after you are satisfied with results, you can import it to game.

> And also, could the code for the explosions be modified slightly to simulate the stream effect that the ship emits when it is moving around?

You don't have to modify any code. You just have to create particles that do what you want. This kind of effect would consist some single small particle, that does not move and fades away in short time. Where as explosion would start as small and start emitting fire and smoke effects and shoot smaller particles around it in sphere. It's all up to you, how the particles behave.
> 3 votes

---
Tags: xna, particles, effects
---


# Question
Title: How to create a main menu using java swing
I have been trying to figure out for quite some time on how to create a basic main menu for a game that just has a couple clickable labels, but I don't know how to write them. I have created a class that `extends JFrame`, made a `JLabel` and that is it. I don't know much to do after that.

# Answer
> 1 votes
Firstly, You may want to check google for basic tutorials. To make your class appear and work as expected, we first need to set it's size. You would do so with YourClass.setSize(x-dimension, y-dimension). Then, if you want it to close properly, you need to use YourClass.setDefaultCloseOperation(JFrame.EXIT\_ON\_CLOSE). This allows the frame to close and terminate the application that's running. finally, you set its visibilty to true, so you can see it with YourClass.setVisible(true), all the while replacing YourClass with an instance of your class. If you wish to add buttons, then **before setting your frame's visibility**, create a new JButton. Then, add it too your JFrame by using YourClass.add().

# Answer
> 1 votes
You should be able to do this by adding a mouse listener to the labels. E.g.

`label.addMouseListener(someMouseListener)`.

Then you'll just have to handle the click events in the listener. If you need to do different things based on which label was clicked, then do something like this in the mouse listener's click method:

```
public void mouseClicked(MouseEvent e) {
    if (e.getSource() == label1) {
      ...
    } else if (e.getSource() == label2) {
      ...
    }
}

```

If you don't (want to) have a mouse listener that handles many sources like this, you can just add an anonymous listener to each of the labels:

```
label.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        ...
    }
}

```

---
Tags: java, swing
---


# Question
Title: Random 2D point in rectangle, but not in a polygon
I have a static rectangle and dynamic polygon. I need to generate a random 2D point in that rectangle, but not in a polygon. This is what I mean:

Green is where random point can be generated and red is where it can't be generated. I'm not really familiar in this thing, so I ask for an algorithm. It also must be fast and efficient, because it's going to be on mobile platform and might be generated few times a second. I could check if point is in polygon, but how do I move it away from polygon to make it still "feel random"? Thanks.

P.S. polygon will always have 4 vertices.

# Answer
The simplest solution is to generate a random point within the rectangle and reject it if it lies in the polygon. You would repeat the process until you got a valid point. This same algorithm is used to uniformly distribute points over an area or volume, except points that are considered outliers are rejected. This type of sampling is known as rejection sampling, if you want to research it further.

The way I would do the polygon test is to test the point against the 4 edges individually. Imagine that all the lines extend out to infinity in both directions. Any point on the 2d plane belongs to one of the two partitions created by a single infinite line. For example:

```
           A

   (0, 2)     (4, 2)
<--.----------.------>

           B

```

The two points `(0, 2)` and `(4, 2)` form the line at y = 2. Point A is considered "above" the line, while point B is considered "below" the line.

Now extend the idea to 4 of these lines. If a point tests in a specific way for all 4 lines, the point has to be in the polygon. This is the same logic used when testing for point containment in an AABB, just simplified where all the lines are parallel to the X or Y axes, making the comparison much simpler.

The way this is calculated on a computer is actually very straightforward, this StackOverflow answer provides a function that takes 3 points - 2 that form a line and one to test.

If you use the same function as on the SO answer, you'll want the left edge of the polygon to return false, the right edge to return true, the top edge to return false, and the bottom edge to return true for the point to be considered contained.

The test requires, in the worst case, 20 subtractions, 8 multiplications, and 4 comparisons. Even on a low-end smartphone, that's nothing. Even having to test several points per frame, it won't make a dent in performance.

The benefit of this kind of sampling over your suggested moving of the point is that any simple algorithm for moving the point will skew your distribution to be more dense around the polygon. Rejection sampling keeps the same distribution, it just cuts out anything that doesn't belong.
> 11 votes

# Answer
I think what you said about checking if its in the polygon then moving it could be fine, the user wont notice anything if say you move the point up or down till its not in the polygon. You could move it by random amounts so it wont always end up on the boundary of your polygon.

You could also try dividing the space around the polygon up and picking one segment randomly, then make your point in that space.

Iv done that before in a simple game but the area I was avoiding was a static square.
> 1 votes

---
Tags: algorithm, geometry, random
---


title: GUI layouts in games?

text:
# Question
Title: GUI layouts in games?
What is a general process of making a GUI in a game without resorting to a full blown GUI library? What I mean by this is how would I go about constructing a GUI layout like those in Java that are not reliant on pixels at a certain app state and are not only dependent on common presets like centering, right, or left aligning of an image via the window size?

# Answer
Usually, elements in graphical user interfaces are laid out in a **hierachical** fashion, e.g. all the elements are children of the window or another element.

In most ui systems I've worked with so far, the **parent element is responsible for layouting the children**.

But let us digress to event handling first: When a user clicks somewhere on the gui, the window (respective the root element) receives the event and hands it down to its children, which either process the event (e.g. a button could fire its 'I HaveBeenClickedOn'-event) or hand it further down. When no child processes the event, the root element processes the event or discards it.

Most guis are modular. They're also mostly made from **heavily decorated rectangles**.

The most simple **ui element** is a **label**, which is just a line of text displayed at the specified position (depending on the renderer used, this could be actually rendered text or just a prepared texture with the text).

Next up is the **button** \- this is basically a label with a (rounded) rectangle drawn around and the abillity to fire an event when a user clicks inside the buttons area. Many ui libraries allow the user to add an image to buttons, or to use an image instead of the text and outline.

(As I will mostly deal with Layout in the rest of the answer, I won't go into other ui elements. An overview over commonly used elements can be found in http://qt-project.org/doc/qt-4.8/gallery.html and/or http://algo.math.ntua.gr/~symvonis/other-material/java\_material/JavaTutorial/ui/features/components.html)

So, how does a gui layout the components? Let's say we've got, for example, a **simple dialog**, which might be made from a window, which itself contains a vboxlayout, which contains a label and a button.

The simplest **layout** is the **hboxlayout** (respective vboxlayout): it **divides the available space horizontally** (respective vertically) **by the number of child elements**, providing each child with an equal amount of space.

Going back to the dialog example: Assuming our window sits at (100px, 150px) and has a width of 300 pixels and a height of 42 pixels. The Vboxlayout takes this space, halves it vertically (because there are two children, label and button) and sets the labels position to (100px, 150px) and its size to (100px, 21px) and sets the buttons position to (100px, 150px + 21px = 171px) and its size to (100px, 21px).

A thing to note here is that many Interfaces work with invisible panels. Say we wanted to expand the dialog to have not one button, but two (e.g. ok and cancel). We could add a panel and a hboxlayout, so our dialog would look like this:

* window with vboxlayout
* vboxlayout with label and panel
* panel with hboxlayout
* hboxlayout with ok button and cancel button

The label would get the same position and size as before, but the lower space would be divided further by the hboxlayout.

Of course, this is a **gross oversimplification**. Most ui systems provide the abillity to add space between elements (e.g. padding and spacing) and/or allow the user to set the minimum and maximum size of objects. For **an overview over more advanced layouts**, you might want to look at http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html and/or http://qt-project.org/doc/qt-4.8/layout.html for examples.

While more difficult to implement, they all have one thing in common: **Layouts divide the available space according to some rule, then assign their direct children each to one of the resulting spaces**. (Unless it's a grindlayout/gridbaglayout and you're allowing elements to span multiple rows/columns)
> 7 votes

---
Tags: gui
---


title: GLSL Atmospheric Scattering Issue

text:
# Question
Title: GLSL Atmospheric Scattering Issue
I am attempting to use Sean O'Neil's shaders to accomplish atmospheric scattering. For now I am just using SkyFromSpace and GroundFromSpace. The atmosphere works fine but the planet itself is just a giant dark sphere with a white blotch that follows the camera. I think the problem might rest in the "v3Attenuation" variable as when this is removed the sphere is show (albeit without scattering). Here is the vertex shader. Thanks for the time!

```
uniform mat4 g_WorldViewProjectionMatrix;
uniform mat4 g_WorldMatrix;
uniform vec3 m_v3CameraPos;     // The camera's current position
uniform vec3 m_v3LightPos;      // The direction vector to the light source
uniform vec3 m_v3InvWavelength; // 1 / pow(wavelength, 4) for the red, green, and blue channels
uniform float m_fCameraHeight;  // The camera's current height
uniform float m_fCameraHeight2; // fCameraHeight^2
uniform float m_fOuterRadius;       // The outer (atmosphere) radius
uniform float m_fOuterRadius2;  // fOuterRadius^2
uniform float m_fInnerRadius;       // The inner (planetary) radius
uniform float m_fInnerRadius2;  // fInnerRadius^2
uniform float m_fKrESun;            // Kr * ESun
uniform float m_fKmESun;            // Km * ESun
uniform float m_fKr4PI;         // Kr * 4 * PI
uniform float m_fKm4PI;         // Km * 4 * PI
uniform float m_fScale;         // 1 / (fOuterRadius - fInnerRadius)
uniform float m_fScaleDepth;        // The scale depth (i.e. the altitude at which the atmosphere's average density is found)
uniform float m_fScaleOverScaleDepth;   // fScale / fScaleDepth

attribute vec4 inPosition;

vec3 v3ELightPos = vec3(g_WorldMatrix * vec4(m_v3LightPos, 1.0));
vec3 v3ECameraPos= vec3(g_WorldMatrix * vec4(m_v3CameraPos, 1.0));

const int nSamples = 2;
const float fSamples = 2.0;

varying vec4 color;

float scale(float fCos)
{
float x = 1.0 - fCos;
return m_fScaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25))));
}

void main(void)
{

gl_Position = g_WorldViewProjectionMatrix * inPosition;
// Get the ray from the camera to the vertex and its length (which is the far    point of the ray passing through the atmosphere)
vec3 v3Pos = vec3(g_WorldMatrix * inPosition);
vec3 v3Ray = v3Pos - v3ECameraPos;
float fFar = length(v3Ray);
v3Ray /= fFar;

// Calculate the closest intersection of the ray with the outer atmosphere (which is the near point of the ray passing through the atmosphere)
float B = 2.0 * dot(m_v3CameraPos, v3Ray);
float C = m_fCameraHeight2 - m_fOuterRadius2;
float fDet = max(0.0, B*B - 4.0 * C);
float fNear = 0.5 * (-B - sqrt(fDet));

// Calculate the ray's starting position, then calculate its scattering offset
vec3 v3Start = m_v3CameraPos + v3Ray * fNear;
fFar -= fNear;
float fDepth = exp((m_fInnerRadius - m_fOuterRadius) / m_fScaleDepth);
float fCameraAngle = dot(-v3Ray, v3Pos) / fFar;
float fLightAngle = dot(v3ELightPos, v3Pos) / fFar;
float fCameraScale = scale(fCameraAngle);
float fLightScale = scale(fLightAngle);
float fCameraOffset = fDepth*fCameraScale;
float fTemp = (fLightScale + fCameraScale);

// Initialize the scattering loop variables
float fSampleLength = fFar / fSamples;
float fScaledLength = fSampleLength * m_fScale;
vec3 v3SampleRay = v3Ray * fSampleLength;
vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5;

// Now loop through the sample rays
vec3 v3FrontColor = vec3(0.0, 0.0, 0.0);
vec3 v3Attenuate;
for(int i=0; i<nSamples; i++)
{
    float fHeight = length(v3SamplePoint);
    float fDepth = exp(m_fScaleOverScaleDepth * (m_fInnerRadius - fHeight));
    float fScatter = fDepth*fTemp - fCameraOffset;
    v3Attenuate = exp(-fScatter * (m_v3InvWavelength * m_fKr4PI + m_fKm4PI));
    v3FrontColor += v3Attenuate * (fDepth * fScaledLength);
    v3SamplePoint += v3SampleRay;
}
vec3 first = v3FrontColor * (m_v3InvWavelength * m_fKrESun + m_fKmESun);
vec3 secondary = v3Attenuate;
 color = vec4((first +  vec3(0.25,0.25,0.25) * secondary), 1.0);
// ^^ that color is passed to the frag shader and is used as the gl_FragColor

}

```

Here is also an image of the problem:

Something strange of note: there is a different effect present when I use gl\_Color and a varying variable. This is what I get when I use gl\_FragColor = vec4( c0 + vec3(0.25,0.25,0.30), 1.0); where c0 is the varying version of "first" below:

and here is the product when gl\_Color.rgb is used in place of c0 and c0 is replaced with gl\_FrontColor on the vertex side:

And finally when gl\_Color and gl\_Secondary color are used together the sphere is entirely black with a white blotch as seen above...

EDIT: Here is the section where I create the spheres and apply their corresponding materials:

```
    Mesh plan = makePlanet();
    pla = new Geometry("Mesh" , plan);
    mat_P = new Material(assetManager, "GroundFromSpace.j3md");
    setupGroundMaterial(mat_P);
    pla.setMaterial(mat_P);
    Mesh atmosphere = makeAtmosphere();
    atm = new Geometry("Mesh", atmosphere);
    mat_A = new Material(assetManager, "SkyFromSpace.j3md");
    mat_A.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Front);
    setupSkyMaterial(mat_A);
    atm.setMaterial(mat_A);

```

setUpMaterial(); just enters the scattering parameters into the shaders.

```
public Mesh makePlanet(){
planet = new Planet(4, new Vector3f(0,0,0));
Mesh pl = new Sphere(128,128,planet.getRadius());
return pl;

```

}

```
public Mesh makeAtmosphere(){
Mesh atmosphere = new Sphere(128, 128, planet.getOuterRadius());
return atmosphere;

```

}

Something interesting. I changed the number of samples taken in ground from space scattering from 4 to 400 and the following result was observed: The color still isn't right (it's supposed to be (0.25,0.25,0.25)) and this obviously isn't a fix since the number of samples should be much less...But why could this be happening?

# Answer
It is not entirely clear how you are applying your shaders or how you are rendering the spheres.

In O'Neil's examples the planet consists of two spheres with radiuses m\_fInnerRadius (ground) and m\_fOuterRadius (atmosphere). The spheres are rendered individually where GroundFromSpaceShader is blended with the terrain texture to form surface and the back-facing triangles of the outer sphere are rendered to act as atmosphere.

I've found that common mistakes with Sean O'Neil's shaders are related to distance between camera to the center of the sphere and forgetting that the original SkyFromSpace shader is expected to be rendered only on triangles that are backwards facing.

First problem is easy to solve. You need to ensure that your camera is outside of the sphere's radius. This means that length of the vector from the camera position to the center of the sphere must be bigger than m\_fOuterRadius. Bear in mind, that this is only the case with these two specific shaders.

The second problem is just as easy: you need to change the winding order of your triangles or use clock-wise with glFrontFace (or similar API call) instead of counter clock-wise.

The shaders are based on a model that is not exactly trivial to implement and relies on a function that O'Neil found using curve approximation software. The consensus online seems to be that the function is extremely picky in terms of parameters, which can also be part of your problem.

Best advice I can give to you is to take O'Neil's working sandbox and see the sources for yourself. In your own code, it is good idea to make each parameter adjustable real-time so that you can see how the parameters affect. Some parameters seem to have very little effect, while others are few tenths away from showing nothing instead of everything.
> 2 votes

# Answer
I was being careless and simply wasn't passing the square of the outter radius correctly. Fixing this fixed all issues. Thanks for the input!
> 0 votes

---
Tags: glsl
---


title: Loading is not working after saving

text:
# Question
Title: Loading is not working after saving
I have difficulties to implement loading a savegame file in my Windows Phone project. I use EasyStorage to load and save files. I get the following exception when I try to load after saving a file.

An exception of type 'System.IO.IsolatedStorage.IsolatedStorageException' occurred in mscorlib.ni.dll but was not handled in user code

I'm sure that I get this exception because saving is not finished when I try to load the file. But how can I solve the problem? I want to load the file after it was created. The file needs to be created when you start the game the first time.

What is the best way to solve the problem?

```
public void LoadingData()
    {
        if (saveDevice.IsReady == true)
        {
            if ((saveDevice.FileExists("TestContainer", "Data" + ".txt")) == false)
            {
                // save a file asynchronously. this will trigger IsBusy to return true
                // for the duration of the save process.
                saveDevice.SaveAsync(
                  "TestContainer",
                  "Data" + ".txt",
                  stream =>
                  {
                      using (StreamWriter writer = new StreamWriter(stream))
                      {
                          writer.WriteLine(10 + ";" + 2 + ";" + 2);
                          int Start = -50;
                          int Offset = 150;
                          int Row = 150;
                          for (int i = 0; i <= 5 - 1; i++)
                          {
                              Start += Offset;
                              writer.WriteLine("Image" + (i + 1).ToString() + ";" + Start + ";" + Row + ";" + false);
                          }
                      }
                  });

                saveDevice.Load(
            "TestContainer",
             "Data" + ".txt",
            stream =>
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    strs = reader.ReadLine().Split(';');
                    game1.Levels = int.Parse(strs[0]);
                    game1.LevelProgress = int.Parse(strs[1]);
                    game1.CurrentLevel = int.Parse(strs[2]);
                    strs = reader.ReadLine().Split(';');
                    game1.levellisttexstring.Add(strs[0]);
                    game1.levellistvec.Add(new Vector2(int.Parse(strs[1]), int.Parse(strs[2])));
                    game1.levellist.Add(bool.Parse(strs[3]));
                    strs = reader.ReadLine().Split(';');
                    game1.levellisttexstring.Add(strs[0]);
                    game1.levellistvec.Add(new Vector2(int.Parse(strs[1]), int.Parse(strs[2])));
                    game1.levellist.Add(bool.Parse(strs[3]));
                    strs = reader.ReadLine().Split(';');
                    game1.levellisttexstring.Add(strs[0]);
                    game1.levellistvec.Add(new Vector2(int.Parse(strs[1]), int.Parse(strs[2])));
                    game1.levellist.Add(bool.Parse(strs[3]));
                    strs = reader.ReadLine().Split(';');
                    game1.levellisttexstring.Add(strs[0]);
                    game1.levellistvec.Add(new Vector2(int.Parse(strs[1]), int.Parse(strs[2])));
                    game1.levellist.Add(bool.Parse(strs[3]));
                    strs = reader.ReadLine().Split(';');
                    game1.levellisttexstring.Add(strs[0]);
                    game1.levellistvec.Add(new Vector2(int.Parse(strs[1]), int.Parse(strs[2])));
                    game1.levellist.Add(bool.Parse(strs[3]));
                }
            });
            }
            else
            {
                saveDevice.Load(
                "TestContainer",
                 "Data" + ".txt",
                stream =>
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        strs = reader.ReadLine().Split(';');
                        game1.Levels = int.Parse(strs[0]);
                        game1.LevelProgress = int.Parse(strs[1]);
                        game1.CurrentLevel = int.Parse(strs[2]);
                        strs = reader.ReadLine().Split(';');
                        game1.levellisttexstring.Add(strs[0]);
                        game1.levellistvec.Add(new Vector2(int.Parse(strs[1]), int.Parse(strs[2])));
                        game1.levellist.Add(bool.Parse(strs[3]));
                        strs = reader.ReadLine().Split(';');
                        game1.levellisttexstring.Add(strs[0]);
                        game1.levellistvec.Add(new Vector2(int.Parse(strs[1]), int.Parse(strs[2])));
                        game1.levellist.Add(bool.Parse(strs[3]));
                        strs = reader.ReadLine().Split(';');
                        game1.levellisttexstring.Add(strs[0]);
                        game1.levellistvec.Add(new Vector2(int.Parse(strs[1]), int.Parse(strs[2])));
                        game1.levellist.Add(bool.Parse(strs[3]));
                        strs = reader.ReadLine().Split(';');
                        game1.levellisttexstring.Add(strs[0]);
                        game1.levellistvec.Add(new Vector2(int.Parse(strs[1]), int.Parse(strs[2])));
                        game1.levellist.Add(bool.Parse(strs[3]));
                        strs = reader.ReadLine().Split(';');
                        game1.levellisttexstring.Add(strs[0]);
                        game1.levellistvec.Add(new Vector2(int.Parse(strs[1]), int.Parse(strs[2])));
                        game1.levellist.Add(bool.Parse(strs[3]));
                    }
                });
            }
        }
    }

```

# Answer
Notice how you used saveAsync. Either listen for an event from saveAsync to tell you it's done, or use sycronous saving, then load when the call finishes
> 1 votes

---
Tags: xna, c#, storage, windows-phone-8
---