# Question
Title: Android AndEngine creating a body behind the sprite exactly
I am using AndEngine for Android. I created a body, but it is not behind the sprite as I wanted.

```
                                Body.setTransform(Sprite.getX()/32, Sprite.getY()/32, 0);

```

This is what I am currently using and this is how it appears.

My body is the white circular borders, and my sprite is the red circle.

**and** When I remove `/32` from the code the body doesn't even appear.

Extra code;

```
                    FIXTURE_DEF = PhysicsFactory.createFixtureDef(
                            1,     // density
                            0.75f,  // elasticity
                            0.5f, // friction
                            false); // isSensor

```

the Body

```
                Body = PhysicsFactory.createCircleBody(this.physicsWorld, Sprite, BodyType.KinematicBody, this.FIXTURE_DEF);
                Body.setUserData("eSprite");
                this.physicsWorld.registerPhysicsConnector(new PhysicsConnector(Sprite, Body, true, true)

```

my sprite is 65px ..

# Answer
I'm not an 'andengine' user so I can't give you the correct code.

However it seems that your problem is that you are targeting the sprite x & y position which is wrong.

You must target the sprite x + **his center x**, and the sprite y + **his center y**.

```
Body.setTransform((Sprite.getX() + Sprite.getWidth()/2) /32, (Sprite.getY()+Sprite.getHeight()/2)/32, 0);

```

I guess 32 is the indice to convert values for your box2d world. if you don't know the correct way to do it you should use this code :

```
 indice_w = box2d_width / render_width;
 indice_h = box2d_height / render_height;

```

**render\_width** is camera viewport used to render the sprite;

**box2d\_width** is the viewport of your box2d world;

Thus you can do this code :

```
Body.setTransform((Sprite.getX() + Sprite.getWidth()/2) * indice_w, (Sprite.getY()+Sprite.getHeight()/2) * indice_h, 0);

```

I hope this will help you.
> 0 votes

---
Tags: android, sprites, andengine
---


# Question
Title: Can't Use Hammer Editor Grid or 3d Camera
I can't place anything (tried Shift + R) and it shows two white lines making a right angle when I open a map. I can't edit my maps currently. Can anyone help? An alternative to editing maps?

Only ray-traced works for 3D:

# Answer
Supposedly the Source SDK went bonkers when Steam implemented SteamPipe. I have tried it myself and I frequently get a pop-up error saying:

"Failed to load the default scheme file. The map view may be missing some visual elements."

All of the view ports in the ui are blank and I can't interact with them at all. I'll do some more research into it and comment on this if I find a fix anywhere.
> 0 votes

---
Tags: source-engine, hammer
---


# Question
Title: How can I use a Texture2D larger than 2048 x 2048?
I'm having issues working with a large image. I've read other threads on using images larger than a `Texture2D` supports, but found nothing that addresses my problem specifically with implementation hints.

My screen resolution is 1920 x 1080. I'm working in C# XNA. The game in question is pretty much a board game.

I have an 3840 x 3840 image I planned to use for the terrain map. The idea was to make each new game look a little different from the last by having the program randomly select a 1920 x 1080 segment of that large image to display. My code to randomly select and display a part of the image is working.

Unfortunately, I can't even get the initial 3840 x 3840 image to load. Just picking "*Add Existing Item*" and adding the image to the content window on the right causes my program to error that a `Texture2D` can only be 2048 x 2048 maximum.

How do I best handle this? I may later need to scale or rotate the map.

---

Suggestions I've seen around:

* Cut it up into sections.
* Use a smaller image that is made "seamless" or "tile-able", then choose a random starting `X,Y` point in it and fill the screen with that.

Are these good ways to go about it? How would I actually do this? Would I still be able to scale and rotate the map?

# Answer
> 2 votes
I would not use the content pipeline for this image. Instead I would load the image into a buffer using your choice of image loader (eg: `System.Drawing.Bitmap`). Then create a `Texture2D` of the desired final size and use `SetData` to fill it with the desired pixel data. Then unload the original image.

There are two major reasons for doing this. First of all, it gets around the maximum texture size issue - as per your question. Secondly, it allows you to store your very large image in a format like `jpeg` or `png`, which will have a much smaller file size than an `xnb`.

If you find yourself needing more than a small, fixed area of this image (for example, if you rotate, you might have to have a larger area of the map loaded in), then you can still use the above technique to slice up your image into small enough chunks at runtime and render it as multiple "tiles".

---

Scaling and rotating the map (at runtime) is as simple as doing the appropriate maths and passing the correct parameters to `SpriteBatch.Draw`. Alternately, you could pass an appropriate tranformation matrix to `SpriteBatch.Begin`. (The best choice is generally the one that requires the least code.)

(You could use render target if you wanted to "bake" this transformation into a texture. Remember to handle "device lost", or bounce it back to a regular texture with `SetData`. It doesn't really gain you anything when rotating, and very little when scaling. I wouldn't bother.)

---

**Alternately, you could change your game to use the `HiDef` profile, where the maximum texture size is 4096 x 4096.** (Set this in the properties for your project.) Obviously this only works if your map image is not going to get any bigger than that.

---
Tags: xna, c#, textures, graphics
---


# Question
Title: How can I copy/move a file from a folder to another with RGSS?
I've been trying to do this but I can only find Ruby answers. I'm trying to move or copy a file from, say, `Game Directory/Graphics/Pictures/file.png` to `Game Directory/file.png`. How can I do this in RGSS?

# Answer
> 1 votes
Well, I found two answers. The first one, way simpler and the one I'm going to use is just using `File.rename(from, to)`.

The second solution, a bit more complicated for the simple and one-use action I wanted to do, is to add the FileUtils module to your scripts, then use `FileUtils.mv(from, to)`.

---
Tags: ruby, rpg-maker-xp
---


# Question
Title: SpriteBatch being drawn outside of Stage?
Currently working on my first game, though running into some problems with libgx and screen aspect ratio.

What I have is a Stage which contains things like menu buttons etc, and the rest of the game is pretty much sprites being drawn with via SpriteBatch. To avoid having multiple SpriteBatches and cameras, I have re-used the ones that are created when Stage is created.

```
    stage = new Stage(WIDTH, HEIGHT, true); // keep aspect ratio
    batch = stage.getSpriteBatch();
    camera = (OrthographicCamera) stage.getCamera();
    // move camera so 'active' screen is centred
    stage.getCamera().translate(-stage.getGutterWidth(), -stage.getGutterHeight(), 0);

```

Anything that is Stage/Actor related is drawn fine - all goes within the aspect ratio adjusted boundaries.

The problem I'm having is anything that drawn via SpriteBatch, seems to ignore this viewport that is defined by Stage and can be visible outside of the Stage area.

```
batch.begin();
...
sirWuffles.draw(batch);
...
batch.end();

```

For example, in the above, if Sir Wuffles is generated outside of the defined WIDTH/HEIGHT it might still appear in the "gutters" of the screen.

Tried to explain it in the below screenshot. It's an exaggerated screen ratio to make the gutters large. I've also covered most of the gutter area in the blue/cyan rectangle so they are very obvious.

Does anyone know what is happening? and how to fix it?

Currently, my "fix" is to use ShapeRenderer to draw rectangles that correspond to the gutters on top of the sprites...

# Answer
You need to manually apply the stage's projection, defined by the camera, to the batch before rendering as such:

```
batch.setProjectionMatrix(stage.getCamera().combined);

```

Also remember to call `camera.update()` after you change the camera's position, which will update the projection matrix.

You gotta think about the `SpriteBatch` as its own separate entity for `Stage`, in that you shouldn't expect anything you do to the `Stage` to have an effect on the `SpriteBatch` when used in another context, such as manual batch rendering in your case.
> 0 votes

# Answer
```
public void resize(int width, int height) {

     Vector2 size = Scaling.fit.apply(FIXED_STAGE_WIDTH,FIXED_STAGE_HEIGHT, width, height);
        int viewportX = (int)(width - size.x) / 2;
        int viewportY = (int)(height - size.y) / 2;
        int viewportWidth = (int)size.x;
        int viewportHeight = (int)size.y;
        Gdx.gl.glViewport(viewportX, viewportY, viewportWidth, viewportHeight);
        stage.setViewport(FIXED_STAGE_WIDTH, FIXED_STAGE_HEIGHT, true, viewportX, viewportY, viewportWidth, viewportHeight);
}

```

This should do the trick for you. Here the drawing outside the stage is not possible.
> 0 votes

---
Tags: libgdx, spritebatch
---


# Question
Title: C# - XNA - Making a Modular Screen / State Manager
I'm not entirely sure how to ask this question since its somewhat broad, but also a bit specific to my code.

I'm making a game in C# XNA and attempting to have the parts of it be fairly modular so that they can be used in any other relevant programs I create down the road. For instance, I have an InputHandler accessible from any class in my program that simply checks the state of the keyboard and mouse and has various methods to find out specifically if a key / button is held down, pressed, or released, etc.

The groundwork of my program was made by following these tutorials: Part 1 Part 2 and Part 4

*(Its not a mistake that I don't have a link to part 3 as that dealt with adding in Xbox 360 gamepad functionality only, which isn't something I needed in my testing.)*

In those tutorials there is a GameScreen Game Component made which is what all the other screens / states inherit from.

The way the tutorial handles screen management is that a type of screen is created in the Game1 class and then only in the Game1 class can you Hide / Show a screen or change which screen is active.

For instance, when the program is first run in the LoadContent section of Game1 a StartScreen(which inherits from GameScreen) is created. The StartScreen is then set to be the ActiveScreen and is set to Show.

My problem is that in my StartScreen I'm handling the checks for what menu option a user selects, but I can't actually hide the current screen and change to the one that was selected because that can only be done from the Game1 class.

I could just handle all of my input checking for the different screens in the Game1 class by using an if statement based on not only what menu option is selected, but also what screen is active, but that would mean a lot of clutter in my Game1 class and it would kind of ruin my goal of making my game components modular by having all of the stuff relevant to a given screen being handled within that screens code.

My question is essentially what I should do to address this...

I tried several times to make a separate ScreenManager Game Component that is accessible from everywhere much like my InputHandler, but each time that ended in disaster with numerous errors that I simply don't have the experience or grasp on lingo to troubleshoot.

My most recent attempt at making a separate one ended with me being able to choose which screen was active, but not being able to use the ".Hide()" method that is part of the GameScreen base class. I also had numerous "accessibility" errors.

I also tried to simply make my screens themselves be public. For instance, in my Game1 class I have variables for GameScreen activeScreen and StartScreen startscreen. I've tried making those two variables be Public or even Public Static, but I still couldn't use them anywhere outside of Game1.

I've looked at numerous other posts and tutorials on making a Screen Manager or how to handle State Management, but that only served to confuse me more. They were either WAY over my head, like the Microsoft State Management sample, or they were understandable and working, but far too different from the one I have now for me to grasp how to apply it to my current code.

Is there something easy and obvious that I'm stupidly overlooking or is there some key concept at work that I'm unaware or failing to grasp?

Or am I going about it all in the wrong way entirely?

# Answer
> GameScreen Game Component made which is what all the other screens / states inherit from.

This is all you need to reference your `Game1` class.

Each `GameComponent` has a property called `Game`, which is of type `Game`. Your `Game1` is a subclass of `Game`, so it can be used to fill the property. And indeed it is used exactly that way when you call its constructor within your `Game1`:

```
GameComponent gameComponent = new GameComponent(this);  // "this" is your Game1 class

```

This property is accessible like so:

```
gameComponent.Game;

```

In order to retrieve the properties and methods of *your* subclass of `Game`, just cast it to your subclass:

```
Game1 game1Ref = (Game1)gameComponent.Game;

```

This is how each menu can cause the main class to update the active menu.

P.S.: I think if you study the GameStateManagement example a little more closely, you'll find those menu items are already able to update the active screen using C# event-type properties. Events, delegates, expressions, lambdas, yadayada are a complex part of the C# language, but you would do well to learn to use them. They are very handy.

Your tutorial seems to do something similar to the example content. But it also refers to XNA 3.0 and 3.1, neither of which is the latest (final) version. It might be better to study the more recent code example.
> 2 votes

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


# Question
Title: In Unity, can I load a local (/Resources folder) website to safari on an ipad
In Unity, can I load a local (/Resources folder) website to safari on an ipad?
This works fine on a Mac, opening up a wepage from my Resources folder.

```
string path = "file://"+(Application.dataPath)+"/Resources/testsite.html";
    void OnGUI(){
        if(GUI.Button(new Rect(20, 20, 100, 100), "site")){
           Application.OpenURL(path);
        }
    }

```

but when I try to load this on an iPhone or iPad, it doesn't seem to work.
Am I accessing the address incorrectly for iOS using "file://"?
If this is not possible, is there an alternative way I can load a locally stored website on an iOS device?

# Answer
Yes you can, but you're using wrong folder. The Resources folder is not copied with your build; rather, it is compressed into a single file cotaining all assets from the folder. To actually copy some files into your app, use StreamingAssets folder (http://docs.unity3d.com/Documentation/ScriptReference/Application-streamingAssetsPath.html). This folder is simply copied into resulting build, so you can use files in it like normal OS files, including, I suppose, opening them in Safari (I don't know, maybe some iOS quirks can still prevent you from doing that. It definitely works on desktop).
> 2 votes

# Answer
According TO Unity's Manual,

Any files placed in a folder called StreamingAssets in a Unity project will be copied verbatim to a particular folder on the target machine. You can retrieve the folder using the Application.streamingAssetsPath property. For reference, the location of this folder varies per platform:

On a desktop computer (Mac OS or Windows) the location of the files can be obtained with the following code:-

```
path = Application.dataPath + "/StreamingAssets";

```

On iOS, you should use:-

```
path = Application.dataPath + "/Raw";

```

...while on Android, you should use:-

```
path = "jar:file://" + Application.dataPath + "!/assets/";

```

It's always best to use http://docs.unity3d.com/Documentation/ScriptReference/Application-streamingAssetsPath.html to get the location of the StreamingAssets folder, it will always point to the correct location on the platform where the application is running.

For more information have a look into http://docs.unity3d.com/Documentation/Manual/StreamingAssets.html.
> 1 votes

# Answer
You \[probably\] aren't going to be able to do that.

But with some Objective-C work (and I'm sure there are some easy plugins on the asset store to do this, such as this one), it should be relatively straight forward to push a WebView from within the app itself with whatever html data you want.
> 0 votes

---
Tags: unity, ios, loading, assets, file
---


# Question
Title: Dual marching squares/cubes - divide or do not divide a node?
In the marching squares/cubes algorithm, how is it decided if a node in the quadtree/octree will be divided further (into `2^dimension` nodes)?

I read about this heuristic that uses a trilinear interpolation to decide if an octree needs to be divided further for not.

It is not clear what the line represents and against what it's tested.

# Answer
> 4 votes
Usually the metric used is node overhead. You can take it to the pathological case (if you can subdivide you do), but at some point the extra effort stops gaining you better results. For normal spatial partitioning octrees, that's processing overhead and memory overhead. Marching Cubes is an odd one, because the subdivision is gaining you more **accuracy**. The finer grained the nodes, the smaller the polygons generated, and the closer the surface generated is to the actual surface shape. But the same principles still apply - you're choosing to subdivide if the smaller nodes will get you substantially better results.

The heuristic is basically just a decision on how much better things will be if you subdivide. The threshold is just a number below which you consider the improvement in results to be trivial / insufficient to warrant the extra cost.

In marching cubes, the items (polygons) don't exist when the partitioning tree is being generated. Only the density and surface threshold is available. The triangles representing that surface are still to be generated, but the assumption is that lumpier parts of the surface will need more triangles to represent them. So the metric being used here is "how lumpy is the surface within this node". If it's flat/planar, it doesn't need subdivided, because the triangles in that node will be large and relatively flat.

I can't follow the maths exactly in your linked paper but I presume the logic is the same as any error metric. For each node you can calculate an error - if you stopped subdividing at that node and just generated the surface polygons at that resolution, how bad would the result be (in terms of error difference against the **real** surface). You'd be calculating 'error improvement' from subdividing, where the improvement in the error is: `'total error for all the subdivided nodes' - 'error for the parent node'`

Reading further into the heuristic, it seems like they are comparing the interpolated values between the 8 corners with the actual values at the subdivided node corners. Not sure why they're interpolating trilinearly. But this seems to me like a good way of estimating lumpiness. If the surface was relatively flat, the surface values at the midpoints used for the sub-divided nodes would be very close to the values you'd get if you just interpolated from the corners of the parent nodes. If the surface was very lumpy, the actual and interpolated mid-points would be way off. How far off can be calculated - and that looks like what that graph is. v represents the distance from the estimated surface to the actual surface at that point. Higher values of v mean that the actual surface has diverged a lot from the estimated surface that you'd get if you didn't subdivide. That gives you an error metric that you can use to threshold whether or not to subdivide.

If it were that naive though, it would fall down in the case where sinusoidal variations in the surface neatly aligned with node boundaries, and happened to result in the mid-point being accurate (imagine a case where in the left side of the node, the surface bulges outwards, but on the right side the surface bulges inwards by the same amount - at the midpoint, the surface is at the same position as it would be if it were flat). I presume that's why the tangent of the surface is also considered - it's much harder for the surface to be in the right place with the right tangent and not also be flat.

---
Tags: marching-cubes, heuristics
---


# Question
Title: Is Spine's XNA runtime missing an importer?
I'm writing an XNA 4.0 game and use Spine for animation. Until now, I've been making spritesheets with Spine and using them with a custom animation class. I recently discovered there is an official Spine runtime for XNA. I've been trying to use it but encounter an error.

The closest I've come (after adding the runtime's classes to my project) is this error:

> Cannot autodetect which importer to use for "data\goblins.atlas". There are no importers which handle this file type. Specify the importer that handles this file type in your project.

Is there such an importer in the runtime and I simply missed it? If so, how can I get XNA to recognize it? If not, is there an alternative?

# Answer
> 1 votes
Found it! For those solutions that have a content project included you just have to add the data inside the main project and NOT the content. You must also make a copy of the data in the bin folder of the release.

---
Tags: xna, c#, xna-content-pipeline, visual-studio, spine
---


# Question
Title: How do I get my polygons to be lighted by either side?
Okay, I am using Ogre3D and Gorilla(2D library for ogre3D) and I am making Gorilla::Screenrenderables in the open scene.

The problem that I am having is that when I make a light and have my SR(screenrenderable) near it, it does not light up unless the face of the SR is facing the light...

I am wondering if there is a way to maybe set the material or code(which would be harder) so the SR is lit up whether the vertices of the polygon are facing the light or not. I feel it is possible but the main obstacle is how I would go about doing this.

# Answer
> 1 votes
In a typical shaders, no mater if it's a vertex or fragment one, you have somewhere a dot product between light direction and surface normal. Then you have a check if the result is less than `0`, which means your surface has light at its 'back'.

Now, if you compute `abs( dotproduct )` instead of just `dotproduct` you should get lighting on both sides of your geometry.

---
Tags: c++, lighting, ogre
---


# Question
Title: Sweep collision between two moving spheres?
Say I have a scenario like this:

Here I got two spheres (sphere A and B) that moves from on spot to another during a frame. How can I predict where these two collide if they collide at all? In between these frames?

I tried to look it up and found this page, but I didn't understand much of it. Could someone try to explain this to me? I'm coding this in C# with XNA and I've been stuck with this issue for a very long time now

# Answer
> 1 votes
Explaining the provided link:

The linear segments

`A(u) = A0 + u * Va`

and

`B(u) = B0 + u * Vb`

are just parametric representations of the segments `Va = (A0, A1)` and `Vb = (B0, B1)`. You should recall that the vector can be represented by the difference of the end points. That's why `Va = A1 - A0` and `Vb = B1 - B0`.

`A(u)` and `B(u)` are said to be parametric because as you vary the parameter `u` from `0` to `1` you get points `A(u)` or `B(u)` that will build the segment `Va` or `Vb` (respectively) from the starting point `A0` or `B0` (respectively) to the the end point `A1` or `B1` (respectively). You can see that by thinking of the cases where `u = 0, where A(u) = A0 and B(u) = B0` (starting points) and where `u = 1, where A(u) = A1 and B(u) = B1` (end points). Any value of `u` between `0` and `1` will result in points between `A0` and `A1` or `B0` and `B1` (respectively).

The expression

`( B(u) - A(u) )* ( B(u) - A(u) )`

is just the dot product of the vector that represents the distance of the points `B(u)` and `A(u)` with itself. The formula of the squared distance between two points is

`d^2[ A(u), B(u) ] = ( xA(u) - xB(u) )^2 + ( yA(u) - yB(u) )^2`

Derivation come from the Pythagorian theorem and can be seen here. By the definition of the dot product, we see that

`( B(u) - A(u) ) * ( B(u) - A(u) ) = d^2[ A(u), B(u) ]`

, since the dot product sums the product of the components of the vector.

The last statement of the article is that when the collision occurs

`[ B(u) - A(u) ] * [ B(u) - A(u) ] = ( ra + rb ) ^ 2`

where ra and rb are the radii of the spheres. What this expression means is that the first time of collision occurs when the distance between `A(u)` and `B(u)` is equals to the distance between the centers of the spheres. This is true because `ra + rb` represents the distance of the centers when the spheres are side-by-side. It is squared just because the other side of the equation also is, so they are in the same measuring unit.

# Answer
> 1 votes
Change the frame of reference and *everything* will become wonderfully simple.

You currently have:

* sphere A (position `Pa`, velocity `Va`, radius `Ra`)
* sphere B (position `Pb`, velocity `Vb`, radius `Rb`)

In terms of collision detection, this is equivalent to:

* sphere A' (position at origin, velocity zero, radius `Ra + Rb`)
* point B' (position `Pb - Pa`, velocity `Vb - Va`)

Now you just need to check whether (and when) the **point** hits the **sphere**. This becomes a simple segment/sphere intersection test. If there is a collision, the change in the frame of reference doesn’t affect the collision time `t_coll`. You can then compute the new positions of the two original spheres: `Pa + Va * t_coll` and `Pb + Vb * t_coll`.

---
Tags: xna, c#, collision-detection, sphere
---


# Question
Title: What is the delta value passed to the Screen's render method?
The delta value given to the `render` method in the `Screen` class is a non-constant number. What is it? Where does it come from? Does it differ by screen size?

# Answer
The delta time is the time elapsed since rendering the last frame.

Since the optimal number of frames rendered by the GPU is roughly 60 frames per second (the optimal frame rate for games), then, in normal conditions, when the game does not have any performance issues, then the delta time will roughly be equal to 1/60.

Simply googling for "libgdx delta" produces various results, the first of which is a link to the Screen interface API, which has javadoc description for the `public void render(float delta)` method.

Here it is:

```
void render(float delta)
Called when the screen should render itself.
Parameters:
  delta - The time in seconds since the last render.

```

Hope this helps. Just also remember that Google is your first best friend in situations when you don't understand stuff ;).
> 3 votes

---
Tags: libgdx, rendering
---


# Question
Title: How do I implement pixel-exact collision server-side?
Recently I made a 2D offline game with HTML5 Canvas and JavaScript. I'm detecting collisions by first checking whether image bounding boxes overlap. If they do, I check against the bounding boxes, to see if there are any pixels that exist in the same location for both images.

I learned the technique from this tutorial (YouTube).

Now I'm making a multi-player version of the game, in a client-server configuration. I've decided to have the server handle all physics, including collision.

However, I'm not sure how to implement that. Since the images are drawn client-side, the server cannot access image's data to do the pixel collision tests. I can make bounding boxes on the server side, but how do I detect pixel collisions?

---

Tech details: I intend to write the server in node.js, using either CouchDB or MongoDB as my database.

# Answer
At the conceptual level, the way you do image-based collision tests in server code is by loading images into memory and operating on the grid of pixels they contain, either directly or by using helpful libraries.

Image loading and manipulation libraries like ImageMagick and GraphicsMagick tends to have bindings to pretty much any platform in existence, and node.js is not an exception with the `gm` and `imagemagick` modules.

As you'll be doing the tests in software, it's possible that they'll have some impact on CPU usage, but as you claim you're doing broad-phase rejection with bounding volumes already, it's likely to be Good Enough.

Evaluate the libraries and the `node-canvas` library mentioned in another answer and see what works out. `node-canvas` has the benefit of being API-similiar to HTML5 canvas, while `gm` has a richer set of image processing functions.

Edit: The technique demonstrated in the YouTube clip is an naive iteration over the pixel data with an early-out. Doing the same on the server side will at worst be as expensive as the same operation on the client, and if the libraries have some optimized queries or thresholding operations, it's possible that they may be faster.
> 1 votes

---
Tags: collision-detection, client-server, pixel, node.js
---


# Question
Title: InputAssembler and emtpy/incomplete buffers
I was wondering what the InputAssembler does if the size of the bound buffers does not match the vertex count of the Draw() call.

I've seen the example at http://msdn.microsoft.com/en-us/library/windows/desktop/bb232912%28v=vs.85%29.aspx where the InputAssembler is used without any buffers, however, the vertex shader input is simply defined as

```
struct VSIn
{
    uint vertexId : SV_VertexID;
};

```

and I understand that SV\_VertexID is filled in by the InputAssembler.

But what if I define the input as follows?

```
struct VSIn
{
    uint vertexId : SV_VertexID;
    float4 color : COLOR;
};

```

I tested this and it appears that input.color always returns the default value float4(0, 0, 0, 0). Is this expected behavior or might other drivers produce different results?

A more elaborate example: If I bind a buffer with ten positions to slot 0 and a buffer with five colors to slot 1 and render ten vertices, will the first five vertices have the color as defined in the color buffer and the other five have color zero? I tested this as well and this seems to be the case. Again, Is this expected behavior or might other drivers produce different results?

And even if i *can* to this, *should* I?

Background: I have "regular" vertex data which I bind to slot 0. In some (rare) cases I have additional data which I bind to slot 1. At the moment if I don't have additional data I will still generate a secondary buffer of equal size as the "regular" buffer filling it all with zeros. I was wondering if this is necessary or if I can simply set the secondary buffer to null and let the InputAssembler do the work.

Bonus question: Can I change the default value the InputAssembler uses if there is no buffer value?

# Answer
> 0 votes
I just tried this with the debug layer enabled and I got the info:

> D3D11 INFO: ID3D11DeviceContext::DrawIndexed: Element \[1\] in the current Input Layout's declaration references input slot 1, but there is no Buffer bound to this slot. **This is OK, as reads from an empty slot are defined to return 0.** It is also possible the developer knows the data will not be used anyway. This is only a problem if the developer actually intended to bind an input Buffer here. \[ EXECUTION INFO #348: DEVICE\_DRAW\_VERTEX\_BUFFER\_NOT\_SET\]

which answers the first part of the question, and

> D3D11 WARNING: ID3D11DeviceContext::Draw: Vertex Buffer at the input vertex slot 0 is not big enough for what the Draw\*() call expects to traverse. **This is OK, as reading off the end of the Buffer is defined to return 0.** However the developer probably did not intend to make use of this behavior. \[ EXECUTION WARNING #356: DEVICE\_DRAW\_VERTEX\_BUFFER\_TOO\_SMALL\]

which answers the second part of the question.

# Answer
> 1 votes
If your actual vertex buffer differs in layout compared to what is set to the input assembler that is most likely undefined behaviour. In my opinion you only *should* do this extreme way you described if you can actually test this on multiple different hardware. For the first vertexID example which you show, you can use that input without any vertex buffer because vertexID comes from the draw call itself from the parameter vertexCount or indexCount. This way you generate SV\_POSITION outputs from these values. This is usually used when rendering a full screen quad.

UPDATE: I just tried messing a bit with different vertex buffers and I was getting different results with an Nvidia and an Intel GPU, though not the exact case you suggested.

---
Tags: directx, hlsl, directx11
---


# Question
Title: Rasterizing parametric solids in Minecraft voxel space
I'm trying to render giant procedurally generated trees in Minecraft. I have code that generates a tree model and represents it parametrically as a collection of cones and spheres using vectors and scalar values. As a final step I'd like to rasterize the parametric model into Minecraft blocks.

So far I've only found resources for rendering 3d parametric solids onto the 2d viewport. Does anybody have any recommended resources or algorithms I can use to rasterize my tree model into Minecraft's 3d voxel space?

# Answer
I'm aware of three basic methods for rasterizing arbitrary solid volumes (from finite differencing approximation):

* midpoint occupancy: If the cell (cube) centre is inside the object, it's solid.
* Volume fraction: If the majority (or some other cutoff value) of the cell volume is filled by the object, it's a solid space. \[requires calculating the volume of an intersection cube-parametric surface\]
* Point occupancy fraction: Choose a representative (or random) set of points inside the cube, test if they are inside the parametric object, on cutoff percentage declare occupied or not.

The central point method has high aliasing, so is suitable only for small voxels (which Minecraft(c) does not have). The fractional occupancy varieties can have intermediate cases linked to other cutoff values as an anti-aliasing technique. For example, one could actually consider binary Marching Cubes to be a version of point occupancy that chooses the 8 corners as its test points and has anti-aliasing.

As I've personally not gotten to rasterizing trees (and will probably go with cellular automata inside the grid confines, as an aesthetic choice) for my own project, I have no specific guides or commentary to recommend.
> 1 votes

---
Tags: rendering, procedural-generation, voxels, minecraft-modding
---


title: Tiled/TMX C++ Library/Parser

text:
# Question
Title: Tiled/TMX C++ Library/Parser
Where can I find an easy to use and up to date **C++ parser/library** for the **.tmx map format** (used by the Tiled Map Editor) ?

**EDIT:** David's comment, *'Unless you want to build your game around the format of the parser..'*, got me thinking... So I have downloaded pugixml, which is an easy to use xml-parser with very straightforward documentation. Together with the spec for the TMX Map Format, I think I'll give it a try myself. I'll probably compare with Cocos2d-x's CCTMXTiledMap at some point.

# Answer
> 7 votes
Are you talking about this editor? If so, it states right away:

> General purpose tile map editor with **XML-based map format**

So you could just use a good, general purpose XML library such as rapidxml.

After that it's just a matter of following the TMX specification. In other words, you will simply need to ask the XML library to fetch you the nodes and attributes you need from that list, which is usually a trivial task.

PS: It also seems to be capable of exporting to JSON format, in which case you could use a JSON library instead (e.g. this).

But yes there seems to be a parser for this format available. A quick search returned this

I have never tested it, but give it a try.

If you don't want to install SVN just to download it, you can use DownloadSVN (I've tested it, and it works - no need to install anything)

And since you need an example of how to use it, here it is (based on this link):

1. Create a new instance of type `Tmx::Map`.
2. Call `Map::ParseFile()` passing it the path to your map file.
3. Check for errors using `Map::HasError()`.
4. Iterate through tilesets using `Map::GetTileset()` and `Map::GetNumTilesets()`. Get individual tile information inside the tileset using `Tileset::GetTile()`.
5. Iterate through layers using `Map::GetLayer()` and `Map::GetNumLayers()`. Use `Layer::GetTileGid(y,x)` to get the ID of a specific tile in the layer.
6. Iterate through object groups using `Map::GetObjectGroup()` and `Map::GetNumObjectGroups()`. Iterate through objects inside each group using `ObjectGroup::GetObject()` and `ObjectGroup::GetNumObjects()`.

For individual properties on each of these objects, check the link.

# Answer
> 3 votes
you can use a part of cocos2d-x library, it's a gameengine developed in c++ for 2d games, but you can just use the CCTMXTiledMap class from that engine to parse tmx file for you.

# Answer
> 0 votes
Here's a small one I wrote a while ago. It uses Boost property tree for parsing the XML. It's probably not feature complete - it will only parse the features I needed for my own game. Should be easy to extend though.

# Answer
> 0 votes
Here is one I quickly wrote: https://github.com/halsafar/libtmx-parser

C++ but at the moment requires C++11x. However it is very easy to add to a project. TinyXml2 is used which is also very easy to a project.

It simply parses the XML into simple structs you can manage. Nothing fancy here, coded in haste to do one job.

---
Tags: c++, map-editor
---


# Question
Title: Client-side dice rolls in turn-based game
I'd like to create a turn-based multiplayer game on Android. I'm thinking of using Google Play Game Services and get rid of any other webservice to create and host games.

The problem is the game involves dice rolls. I don't believe GPGS offers the possibility for third party dice roll, so my first thought was to integrate them in the app, however this gives great opportunity for cheating.

I've read the answers given in this question: Fair dice over network w/o trusted 3rd party , but they require all players to participate in the roll, which isn't possible if everyone isn't in the app at the same time.

Is there any alternative solution? Or do I have to use a third party for this?

# Answer
> 2 votes
I'm not familiar with Google Play Game Services, however it might be worth looking into how old console games did randomness. Often random number seeds were taken from hidden but not random states within the game and then the numbers come off a hidden list or calculator.

* What frame of the game's start menu 'start' was hit on.
* What enemies were killed in the prior room.
* What frame of animation the target of an attack was on.
* The X\*Y coordinates of the player or enemies.

While these tricks don't directly apply to your case you still can learn from the past here.

One option could be to generate a seed value that all players know from the start of the game. This seed value decides the starting point on a known list or represents the first value in a known method of generating pseudo-random numbers. Because all players know both what the initial value is, and how many random numbers have been selected for secure actions, they all know exactly what the next value should be.

Another could be to hash all the specific relevant information about the game state to create a key (plus a game key to ensure each game is unique) that can be used to generate a pseudo-random number at both ends that is ensured to be the same number given the same game state. The numbers will differ only if the games are not exactly the same on both sides.

# Answer
> 1 votes
There is a concept called "**synchronous networking**", that means that all actions in the game are deterministic and thus will return the same result on all devices. If that is a given then you simply execute all actions on all devices in the same order and will end at the same state.

```
onMovePlayerLeft(player):
  player.X += 1

```

Now instead of sending over the result of onMovePlayerLeft, you just send over the fact that the "onMovePlayerLeft" was executed. Upon receiving the message you can than execute exactly the same code and both games are in the same state again.

Almost all calculations are deterministic as long as they don't depend on the hardware or the OS. (Unfortunately you will have to avoid using floats as different CPUs implement floats differently.)

---

*But Beast, how does that help?! A dice roll isn't deterministic!*

No, that is wrong. Random numbers as we use them in games aren't actually random, they are pseudo random. If the state of the RNG is the same the result will also be the same.

So if your game is synchronous then you just need to make sure that both clients use exactly the same seed at the start of the session.

---

**Edit:** *But Beast, I don't want the player to know the result of the throw before hand!*

In that case you'll need to negotiate a secret every time you want to make a throw.

This could look like this.

**Peer A**: I want to roll a dice for Action and need a RNG Seed for that.
**Peer A**: The checksum of my part of the seed will be 459023.
*Peer B*: The checksum of my part of the seed will be 390564.
**Peer A**: My part of the seed is 38000.
*Peer B*: My part of the seed is 76000.

The checksum is needed to enforce that the seed is generated before the peer has received the other seed.

Now you can generate the actual value of the negotinated seed by doing some simple math, such as (38000 + 76000) / 2.

---
Tags: random, turn-based, client, google-play
---


# Question
Title: Midpoint Displacement 1D - How to properly reduce my random number range?
So I'm trying to implement this http://www.gameprogrammer.com/fractal.html#midpoint algorithm, to generate myself a terrain. In the tutorial is said:

`OK, before we go into 2D fractal surfaces, you need to know about the roughness constant. This is the value which will determine how much the random number range is reduced each time through the loop and, therefore, will determine the roughness of the resulting fractal. The sample code uses a floating-point number in the range 0.0 to 1.0 and calls it H. 2(-H) is therefore a number in the range 1.0 (for small H) to 0.5 (for large H). The random number range can be multiplied by this amount each time through the loop. With H set to 1.0, the random number range will be halved each time through the loop, resulting in a very smooth fractal. With H set to 0.0, the range will not be reduced at all, resulting in something quite jagged.`

Let's say `rand_start` and `rand_end` are the starting and ending values that a random number can be generated by using for example `random.uniform(rand_start, rand_end)` or `random.uniform(-1.0, 1.0)`

Then I must reduce the number range so I do:

`rand_start *= H * (pow(2, -H))`

`rand_end *= H * (pow(2, -H))`

With `H` set to 1.0 for example.Both `rand_start` and `rand_end` will be lowered by half and in the next iteration the random value will be between -0.5 and 0.5. All clear, just like the tutorial said it.

**Here is the problem:**

My `x` coordinate starts at 0 in the left side of the window, and `y` coordinate in the top of the window, in Pygame

I draw my line at this coordinates:

`line_start = (0, 300)`

`line_end` = (WINDOWWIDTH, 300)

How to reduce my random range if start and end values are initialized like that:

`rand_start = 400`

`rand_end = 200`

Again, my line starts at `y` coordinate 300 and the highest the midpoint can be displaced is 200, the lowest - 400.

Any code required will be provided asap.

# Answer
I'm not sure what your actual problem is (I first thought it was that you wanted to bias the initial midpoint range, but it looks like you actually don't), but here's a simple midpoint displacement implementation in Python:

```
# generic midpoint displacement routine
def displace ( points, max_disp ):
    last_point = points[0]
    new_points = [ last_point ]

    for next_point in points[1:]:
        midpoint_x = 0.5 * ( last_point[0] + next_point[0] )
        midpoint_y = 0.5 * ( last_point[1] + next_point[1] )
        midpoint_y += random.uniform( -max_disp, +max_disp )

        new_points.append( (midpoint_x, midpoint_y) )
        new_points.append( next_point )
        last_point = next_point

    return new_points

# initialize the endpoints
points = [ (0, 300), (window_width, 300) ]

# set the initial displacement range and scaling factor
max_disp = 100
scale = 0.5

# repeat the displacement process 10 times
for i in xrange(0, 10):
    points = displace( points, max_disp )
    max_disp *= scale

```

If you do want to bias the first midpoint selection, the easiest way to do that is to cheat — just start with a three-point list, and reduce the iteration count by one:

```
# initialize the endpoints and first midpoint
points = [ (0, 300), (0.5 * window_width, 200), (window_width, 300) ]

# set the initial displacement range and scaling factor
max_disp = 50
scale = 0.5

# repeat the displacement process 10 times
for i in xrange(0, 9):
    points = displace( points, max_disp )
    max_disp *= scale

```

This code, using the same `displace` routine as above, will ensure that the middle point of the line will always be at height 200, while the endpoints are at height 300. Adding some randomness to the middle point is left as an exercise.
> 3 votes

---
Tags: python, pygame
---


# Question
Title: Pro's/Con's of separating game logic and render threads
Originally, I have thought that it is good practice to separate my game logic (updating) from my rendering thread. In this threading model, the rendering thread has no limitation on frame rate and simply draws whatever information is currently made available by the updating thread. On the other hand, the updating thread is monitored, and has a capped frame rate.

I'm led to believe this is BAD and will lead to many coding struggles down the road...

So, I'm wondering what are the POTENTIAL benefits for separating updating from rendering? Likewise, what are the POTENTIAL benefits gained when keeping the updating and rendering in the same thread? What are the losses for each method?

# Answer
> 9 votes
In a word, synchronization. If you have some data (your world) which you're reading from one thread (the rendering thread), and writing to in another thread (the logic thread), it is possible that your data will be read in an inconsistent state (for example, half the world has been updated, but not the other half).

To maintain consistency, you will probably have to make sure no reading occurs while you're writing, which is functionally equivalent to doing both things on the same thread.

There are some tricks you can do. For example, have two copies of the world, and while you're reading from one, you write to the other one. This solves some problems, but creates a lot more. For example, your world will always be one frame behind the drawing. Also, you'll be using twice the memory, and you still have to do some synchronization to make sure you switch from one copy of the world to the other correctly.

Writing synchronized multithreaded code is extremely difficult. It always seems easy, but it always becomes much more complicated as you're writing it. Debugging it is also hell (speaking from firsthand experience).

Now, a much simpler, and probably more efficient multithreaded model is not specializing threads, but dividing work across several threads. Create a bunch of independent work items, and assign them to threads to be worked on. If the work items are independent, no complex synchronization is required, and this scales to as many threads as you wish.

Also, one of the most important things you can do to make more responsive games is to use asynchronous I/O. Don't block threads when reading or writing to disk/network. Those threads won't be doing anything else but waiting for I/O to end anyways, and you can still do other useful stuff with them. It requires rethinking a bit your resource loading, but in my experience, it is one of the things that can greatly improve performance and responsiveness in a game.

Besides, why do you want to draw as fast as you can? If you draw at more than 60fps, you will either have tearing, or the graphics adapter will cap you at the monitor's refresh rate. But even if you draw at 1000000 fps, if the world updates are choppy, the game will feel choppy.

---
Tags: game-loop, multithreading
---


# Question
Title: How to apply steering to a physics body correctly when using a physics engine?
I have a top down 2d game that uses a physics engine (Farseer).

I'm using the standard steering behaviors to make the AI move around but I'm not sure the correct way to take the so called "steering force" calculated by the steering behavior and apply it to the physics bodies.

For example:

The steering behavior SEEK returns

```
return desiredVelocity - currentVelocity;

```

So it is returning a difference of two velocities (in meters per second).

I need to convert this into the force (in Newtons) that I need to apply to my physics body, taking into account its mass and acceleration etc.

I know it should be simply but I'm getting confused! :)

# Answer
Your bodies have a current 2d velocity : `vcx`, `vcy`. You desire a new velocity: `vnx`, `vny`. Correct? Now force translates into `acceleration/mass` (and velocity indirectly).

```
vnx - vcx = fx/m * t;
fx = m*(vnx - vcx)/t

```

So you need to know the duration of time force will be applied. Lets say a frame? Calculate the delta time of the frame.

Do the same with axis `y`.
> 1 votes

---
Tags: 2d, physics, farseer-physics-engine, steering-behaviors
---


title: making a cone roof look hollow

text:
# Question
Title: making a cone roof look hollow
How can I make a cone roof look hollow when viewed from underneath?

I am trying to create a cone shaped roof, but the cone does not look much like a roof, the edges of the roof seem to blend with the rest of the cone.

How can I make the cone look more like a "roof"? is making it look hollow the best way?

This is how I am drawing the cone:

```
glPushMatrix();
    glTranslatef(0.0, 0.0, 2.5);
    glColor3f(255, 0.0, 0.0);
    glutSolidCone(1.75, 1, 32, 16);
glPopMatrix();

```

This is what my scene looks like:

Here is my complete source code:

```
// gcc -o snowman snowman.c -framework GLUT -framework OpenGL

#include <stdlib.h> // standard definitions
#include <math.h> // math definitions
#include <stdio.h> // standard I/O

// include files are in a slightly different location for MacOS
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

// escape key (for exit)
#define ESC 27

// Camera position
float x = 0.0, y = -5.0; // initially 5 units south of origin
float deltaMove = 0.0; // initially camera doesn't move

// Camera direction
float lx = 0.0, ly = 1.0; // camera points initially along y-axis
float angle = 0.0; // angle of rotation for the camera direction
float deltaAngle = 0.0; // additional angle change when dragging

// Mouse drag control
int isDragging = 0; // true when dragging
int xDragStart = 0; // records the x-coordinate when dragging starts

void changeSize(int w, int h)
{
    float ratio =  ((float) w) / ((float) h); // window aspect ratio
    glMatrixMode(GL_PROJECTION); // projection matrix is active
    glLoadIdentity(); // reset the projection
    gluPerspective(45.0, ratio, 0.1, 100.0); // perspective transformation
    glMatrixMode(GL_MODELVIEW); // return to modelview mode
    glViewport(0, 0, w, h); // set viewport (drawing area) to entire window
}

void drawSnowman()
{
    // Draw body (a 20x20 spherical mesh of radius 0.75 at height 0.75)
    glColor3f(1.0, 1.0, 1.0); // set drawing color to white
    glPushMatrix();
        glTranslatef(0.0, 0.0, 0.75);
        glutSolidSphere(0.75, 20, 20);
    glPopMatrix();

    // Draw the head (a sphere of radius 0.25 at height 1.75)
    glPushMatrix();
        glTranslatef(0.0, 0.0, 1.70); // position head
        glutSolidSphere(0.25, 20, 20); // head sphere

        // Draw Eyes (two small black spheres)
        glColor3f(0.0, 0.0, 0.0); // eyes are black
        glPushMatrix();
            glTranslatef(0.0, -0.18, 0.10); // lift eyes to final position
            glPushMatrix();
                glTranslatef(-0.05, 0.0, 0.0);
                glutSolidSphere(0.05, 10, 10); // right eye
            glPopMatrix();
            glPushMatrix();
                glTranslatef(+0.05, 0.0, 0.0);
                glutSolidSphere(0.05, 10, 10); // left eye
            glPopMatrix();
        glPopMatrix();

        // Draw Nose (the nose is an orange cone)
        glColor3f(1.0, 0.5, 0.5); // nose is orange
        glPushMatrix();
            glRotatef(90.0, 1.0, 0.0, 0.0); // rotate to point along -y
            glutSolidCone(0.08, 0.5, 10, 2); // draw cone
        glPopMatrix();

    glPopMatrix();

    // Draw a faux shadow beneath snow man (dark green circle)
    glColor3f(0.0, 0.5, 0.0);
    glPushMatrix();
        glTranslatef(0.2, 0.2, 0.001);  // translate to just above ground
        glScalef(1.0, 1.0, 0.0); // scale sphere into a flat pancake
        glutSolidSphere(0.75, 20, 20); // shadow same size as body
    glPopMatrix();

    glPushMatrix();
        glTranslatef(-1.0, 1.0, 0.0);
        glRotatef(90.0, 1.0, 0.0, 0.0);
        glScalef(1.0, 40.0, 1.0);
        glColor3f(1.0, 1.0, 0.0);
        glutSolidCube(0.125);
    glPopMatrix();

    // Draw the roof posts using cylinders
    GLUquadricObj *quadratic;
    quadratic = gluNewQuadric();

    // post 1
    glPushMatrix();
    glTranslatef(1.0, 1.0, 0.0);
    glRotatef(0.0, 0.0, 1.0, 0.0);
    glColor3f(1.0, 1.0, 0.0);
    gluCylinder(quadratic, 0.075, 0.075, 2.5, 32,32);
    glPopMatrix();

    // post 2
    glPushMatrix();
    glTranslatef(1.0, -1.0, 0.0);
    glRotatef(0.0, 0.0, 1.0, 0.0);
    glColor3f(1.0, 1.0, 0.0);
    gluCylinder(quadratic, 0.075, 0.075, 2.5, 32,32);
    glPopMatrix();

    // post 3
    glPushMatrix();
    glTranslatef(-1.0, -1.0, 0.0);
    glRotatef(0.0, 0.0, 1.0, 0.0);
    glColor3f(1.0, 1.0, 0.0);
    gluCylinder(quadratic, 0.075, 0.075, 2.5, 32,32);
    glPopMatrix();

    // post 4
    glPushMatrix();
    glTranslatef(-1.0, 1.0, 0.0);
    glRotatef(0.0, 0.0, 1.0, 0.0);
    glColor3f(1.0, 1.0, 0.0);
    gluCylinder(quadratic, 0.075, 0.075, 2.5, 32,32);
    glPopMatrix();

    // draw roof using a cone
    glPushMatrix();
        glTranslatef(0.0, 0.0, 2.5);
        glColor3f(255, 0.0, 0.0);
        glutSolidCone(1.75, 1, 32, 16);
    glPopMatrix();

}

void update(void)
{
    if (deltaMove) { // update camera position
        x += deltaMove * lx * 0.1;
        y += deltaMove * ly * 0.1;
    }
    glutPostRedisplay(); // redisplay everything
}

void renderScene(void)
{
    int i, j;

    // Clear color and depth buffers
    glClearColor(0.0, 0.7, 1.0, 1.0); // sky color is light blue
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Reset transformations
    glLoadIdentity();

    // Set the camera centered at (x,y,1) and looking along directional
    // vector (lx, ly, 0), with the z-axis pointing up
    gluLookAt(
            x,      y,      1.0,
            x + lx, y + ly, 1.0,
            0.0,    0.0,    1.0);

    // Draw ground - 200x200 square colored green
    glColor3f(0.0, 0.7, 0.0);
    glBegin(GL_QUADS);
        glVertex3f(-100.0, -100.0, 0.0);
        glVertex3f(-100.0,  100.0, 0.0);
        glVertex3f( 100.0,  100.0, 0.0);
        glVertex3f( 100.0, -100.0, 0.0);
    glEnd();

    // Draw 36 snow men
    for(i = -3; i < 3; i++)
        for(j = -3; j < 3; j++) {
            glPushMatrix();
                glTranslatef(i*7.5, j*7.5, 0);
                drawSnowman();
            glPopMatrix();
        }

    glutSwapBuffers(); // Make it all visible
}

// processNormalKeys: ESC, q, and Q cause program to exit
// pressSpecialKey: Up arrow = forward motion, down arrow = backwards
// releaseSpecialKey: Set incremental motion to zero
//----------------------------------------------------------------------
void processNormalKeys(unsigned char key, int xx, int yy)
{
    if (key == ESC || key == 'q' || key == 'Q') exit(0);
}

void pressSpecialKey(int key, int xx, int yy)
{
    switch (key) {
        case GLUT_KEY_UP : deltaMove = 1.0; break;
        case GLUT_KEY_DOWN : deltaMove = -1.0; break;
    }
}

void releaseSpecialKey(int key, int x, int y)
{
    switch (key) {
        case GLUT_KEY_UP : deltaMove = 0.0; break;
        case GLUT_KEY_DOWN : deltaMove = 0.0; break;
    }
}

void mouseMove(int x, int y)
{
    if (isDragging) { // only when dragging
        // update the change in angle
        deltaAngle = (x - xDragStart) * 0.005;

        // camera's direction is set to angle + deltaAngle
        lx = -sin(angle + deltaAngle);
        ly = cos(angle + deltaAngle);
    }
}

void mouseButton(int button, int state, int x, int y)
{
    if (button == GLUT_LEFT_BUTTON) {
        if (state == GLUT_DOWN) { // left mouse button pressed
            isDragging = 1; // start dragging
            xDragStart = x; // save x where button first pressed
        }
        else  { /* (state = GLUT_UP) */
            angle += deltaAngle; // update camera turning angle
            isDragging = 0; // no longer dragging
        }
    }
}

int main(int argc, char **argv)
{
    printf("\n\
-----------------------------------------------------------------------\n\
   Controls \n\
  - Drag mouse left-right to rotate camera\n\
  - Hold up-arrow/down-arrow to move camera forward/backward\n\
  - q or ESC to quit\n\
-----------------------------------------------------------------------\n");

    // general initializations
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(1200, 800);
    glutCreateWindow("OpenGL/GLUT Sampe Program");

    // register callbacks
    glutReshapeFunc(changeSize); // window reshape callback
    glutDisplayFunc(renderScene); // (re)display callback
    glutIdleFunc(update); // incremental update
    glutIgnoreKeyRepeat(1); // ignore key repeat when holding key down
    glutMouseFunc(mouseButton); // process mouse button push/release
    glutMotionFunc(mouseMove); // process mouse dragging motion
    glutKeyboardFunc(processNormalKeys); // process standard key clicks
    glutSpecialFunc(pressSpecialKey); // process special key pressed
                        // Warning: Nonstandard function! Delete if desired.
    glutSpecialUpFunc(releaseSpecialKey); // process special key release

    // OpenGL init
    glEnable(GL_DEPTH_TEST);

    // enter GLUT event processing cycle
    glutMainLoop();

    return 0;
}

```

# Answer
> 1 votes
I recommend using more modern openGL programming. You method using the matrix stack and glutSolidCone is difficult to maintain, to test and to customize.

To give the feeling of volume of your cone, you should use classical painting techniques : lighting (written using a simple shader, this can still look very cartoon-like) or paint the edges (using the GL\_LINES drawing mode on the boundary edges).

---
Tags: opengl
---


# Question
Title: Online RTS Game Architecture for Mobiles
We came up with an idea for a real-time strategy game for mobile devices that can play with other players over a network. I'm trying to plan out the architecture/protocol required for such as system. Some other related questions (,) mention that P2P is the way to go for RTS games. The problem is that most mobile phones cannot open TCP ports to allow incoming connections, so a central server would be required to relay messages between the players. Another issue that is mentioned on the linked questions is the difference in floating point operations and random number generators, etc among different platforms (Our game would run on iOS and Android for example) so running the game simulation on each device may not be optimal. I could run the game simulation on a server and have it broadcast updates, but simulating/broadcasting up to 200 units per game would be quite expensive especially when multiple people are using the same server to play games. The server's performance might drop significantly with more than a few hundred people using it.

I'm currently thinking the central server would be the best method, but would require a lot of server power. I'm looking for any suggestions on a architecture/protocol that would work for this game and any insight on the issues I mentioned with existing protocols.

# Answer
**Random number generator:** you actually want a pseudo-random number generator that will give the same result for each player at the same situation. There are several ways to implement it, for example you may make the player agree a seed over the network then generate the pseudo-random number from that seed. Or you hash somehow the current game state and use the hash as a random number. This of course implies that the hashed components of the states are guaranteed to be the same with each player.

**Floating-point differences:** this depends on how tolerant you wish to be against floating-point errors. Firstly, you must decide the maximum allowable error that data can have to be consistent between each player. Then you have to synchronize this data. You may have different options:

* If synchronizing, synchronize as soon as possible to have minimal erroneous feedback to the player or synchronize every second to save bandwidth?
* Do computations on the server, or let the devices do computations and let the server “merge” conflicting computations, or let the devices do computations and merge conflicting information from other devices together (you may be interested in the notion of conflict-free replicated data type for the notion of “merging”) ?

**Server overload:** to avoid it - letting the server only relay messages seems reasonable. Then you need to decide a way to merge conflicting data, for example by using an a identifier of who made the modification, and letting the parameter controlled by a player A and computed by the device player A have authority. This is only a quick answer and there are so many possibilities! Google for 'consistency', you may find good advice.
> 0 votes

---
Tags: networking, mobile, client-server, rts
---


# Question
Title: How to blend bullet sprite from white to yellow in libgdx
Does anyone have a clue that will make my bullet sprite fade from yellow to white? As the bullet is created it will be white but when it trails on it will turn yellow. Any ideas how? Is it a simple process or does it require a lot of code writing?

# Answer
You could change the color of the sprite batch when it is drawing the bullet, and then back to white, like this:

```
public void render(float delta) {
    batch.begin();
    // some rendering
    worldRenderer.renderBullets(batch);
    // some other rendering
    batch.end();
}

```

And, in `renderBullets()` of the world renderer you do the following:

```
public void renderBullets(final SpriteBatch batch) {
    for (final Bullet bullet : world.getBullets()) {
        if (bullet.position.x > <certain x pos> || bullet.position.y > <certain y pos>
           || bullet.position.x < <certain x pos> || bullet.position.y < <certain y pos>) {
            batch.setColor(Color.YELLOW);
        }
        batch.draw(bullet.texture, bullet.position.x, bullet.position.y);
        batch.setColor(Color.WHITE);
    }
}

```

Explaining the code above: You first iterate through all the bullets you currently have.

Then, depending in which direction you are shooting, you need to check the bullet position, relative to some certain position close to the starting position of rendering your bullet, so you know when to tell the sprite batch it is time to tint the bullet texture color to yellow. The "\>" and "\<" checks are meant to cover the possibilities of shooting in the right and up directions and in the left and down directions respectively, depending on your implementation.

You then set the batch color to YELLOW, so this will tint the rendering of the bullet texture. After the bullet has been rendered, you restore the WHITE color of the batch, to let it render other stuff in normal way.

Hope this works for you. If you have questions, please let me know.
> 2 votes

---
Tags: java, libgdx, color
---


# Question
Title: Field of view determination with partially opaque cells
I'm currently implementing the field of view of a player in a 2D-grid based game. I've chosen a standard ray tracing algorithm because he really fits the features needed in my game.

However, the cells aren't just opaques or transparents. **They can be "partially opaques"**, which means that they decrease the length of the line of the sight more than the others (we don't see as far in water than in the air!). Concretely, the player has a given "vision potential", and each cell has a "vision cost". For each cell crosses by the ray during the ray tracing, I decrease the vision. When it hits zero, I stop the ray.

Things are OK here. But this algorithm leads to some artefacts, as described in the last part of this document:

> Ok, we have thrown rays all aroung our @, flagging each cell as visible. When we move aroung the dungeon, we notice some artifacts appearing on some walls, especially when the @ is near the wall.
>
> Since we stop the ray as soon as it reaches a wall, when the ray is almost parallel to the wall, there may be some missing wall cells in the resulting potential visible set. \[...\] The issue is due to the fact that the ray should keep going until it reaches the other side of the wall and not stop on the first cell. But this is not possible since we have only a boolean 'lightThrough' information and not the wall orientation.
>
> Fortunately, there is a trivial trick which will allow us to remove those artifacts without adding more information on the cell. It is based on a simple observation : if the player sees a ground cell, he sees the wall behind it. \[...\]
>
> Thus, our post-processing algorithm consist of :
>
> * loop through all cells of the visible map.
> * if the current cell is a hidden wall and is directly behind a visible ground cell (depending on the region the current cell is in), we can flag it as visible.
>
> The result : on the left, the PVS \[potential visible set\] without the post-processing step. The yellow arrows show the missing cells. On the right, the PVS with the post-processing step.

The document suggests a post-process treatment, but it obviously doesn't work in my situation. What can I do instead?

# Answer
Fundamentally I think this is a problem with the grid-based ray casting being a pretty inaccurate and granular approximation of the 'real' thing you're trying to simulate. No matter what you'll do you'll run into problems.

Instead of thinking about it in terms of the specifics of the iteration and implementation, think of it as if your world was actually made of blocks which are the size of your grid squares.

You are casting rays as if they were going through the centre of each block. And you're modelling visibility drop as if a partially opaque block was made of some material which acted like depth fog (i.e. the visibility drop from passing through the block was proportional to the amount of block the ray passed through).

Let's assume you are standing and looking at a block 2 north and 2 east of your position. If you look at the corner of the block closest to you (the SW corner), you actually have ~1.414u of block to look through. If you look at the NW or SE corners, your vision ray passes through **no block at all**. It's a fundamentally flawed approximation to model visibility loss in this way. The correct way to model it would I think be to raytrace to each corner of each cell instead, and use the maximum of the 4 values. I'm guessing that is rather too expensive, and if you're stuck using an integral/Bresenhams raytrace then it simply won't be possible.

I'm also assuming that you're setting the cell visibility (i.e. how bright the cell is) based on the visibility level of the ray as it enters that cell. So a ray passing through fully transparent air sets all the cells to 100% visible, then when it hits an opaque wall the entry visibility is 100% (so the wall is fully visible) but the exit visibility is 0% (so no cells afterwards are visible).

If this case is indicative of your problem:

What you're seeing is probably made worse by the inaccuracy of the Bresenham traversal meaning that some cells appear blocked when they're actually not. I suspect what's really happening is that your visibility drop through a block isn't actually taking account of how much of a cell the ray covers. Bresenham's doesn't give you an anti-aliased line, it either hits a cell or it doesn't. But if the calculation was done at the proper resolution, you'd see that some cells have a long stretch of line passing through them, and other cells have only a short stretch (because the ray line just clips the corner of the cell). You need to make the visibility drop proportional to the length of the line in the cell with that degree of opacity. If the line just clips the corner of the 90% opaque cell, it should lose much less visibility than if it goes from corner to corner across the diagonal. To get that information you need the fractional portion of the ray traversal, i.e. you need to do the floating point math to calculate the line properly. Even then that won't fix your problem, because you're still calculating visibility at the centre of the cell rather than across the visible faces of your cell blocks, but it'll get you closer.

If you don't want to do that, I think you can get a decent workaround that won't impact on your system too much. Every time a ray terminates in a grid cell due to loss of visibility, **and the grid cell is not fully opaque**, then mark the grid cells just beyond as visible, at the same visibility level as the ray was when it terminated. If you later visit one of those cells with a direct ray-trace and find they're **more** visible, then you use the higher visibility value.

For 'just beyond', I mean one more in each direction. If the ray you're casting has any northward component, mark the cell to the north as visible, if it has any eastward component mark the cell to the east as visible, etc.

What that will do is cause a bit of visibility bleeding, such that a visible partially opaque cell will cause others nearby to also become visible, at a higher level than they should properly get.
> 3 votes

---
Tags: 2d, mathematics, algorithm
---


# Question
Title: Why can't I swap fixtures on collision in Box2D?
I'm trying to swap the fixtures associated with a body after colliding with a specific obstacle.

I can listen to the collision event by extending `b2ContactListener`. I tested it with a trace and it's working. My listener function in the main game class calls a `Player` method that makes the swap. But it's just not working.

The body is stored in `public var _body:b2Body;` in the `Player` class.

The method I'm calling goes like this:

```
public function changeFixture():void {
    var newShape:b2CircleShape = new b2CircleShape(1);
    var myFixtureDef:b2FixtureDef = new b2FixtureDef();
    // Here I set density, friction, restitution, etc... Not important now...
    myFixtureDef.shape = newShape;

    _body.DestroyFixture(_oldFixture);
    _body.CreateFixture(myFixtureDef);

    // I know the method is called because this works
    trace('Yay! I'm working!');
}

```

What might be wrong?

# Answer
After all, everything was (almost) correct. The problem is you can't change the physics during callback. All I had to do was delay it to the next game cycle.
> 2 votes

---
Tags: box2d, actionscript-3, starling
---


# Question
Title: How can I fix my sprite being rotated 90 degrees more than toward the mouse?
I am trying to get a Sprite in LibGDX to look at the player's mouse. Here's the code I have (mind you, I am using JRuby):

```
target = mouse_position.sub(spatial.position)
rotation = MathUtils.atan2(target.y, target.x)
spatial.rotation = rotation * MathUtils.radiansToDegrees

```

This is definitely doing *something*, but it's not completely correct. Here's a GIF of what it looks like in action:

Where am I going wrong?

# Answer
Turns out my sprites weren't being drawn at the correct position, so their rotation was happening incorrectly. Let the lesson be *Always Draw At Your Sprite's Origin Because Bad Things Will Happen If You Don't Know What You're Doing.*
> 2 votes

# Answer
Add this to your `Sprite` creation:

```
spatial.rotate90(false);

```

This will rotate the sprite's texture 90 degrees. From the docs:

> Rotates this sprite 90 degrees in-place by rotating the texture coordinates. This rotation is unaffected by setRotation(float) and rotate(float).
> 1 votes

---
Tags: mathematics, libgdx, mouse, trigonometry, ruby
---


# Question
Title: How can I convert screen coordinatess to world coordinates in OpenTK?
I'm making a windows forms application with opengl view. I need to get the mouse coords converted to the opengl world coords. Well, my Y coord gets converted wrong. It's hard to explain, so here is the video: http://tinypic.com/r/23sal8k/6. I'm constantly pressing left mouse button and the red dot should be where the mouse is(but it isn't). Here is the code:

```
    private void glview_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            Point worldCoords = convertScreenToWorldCoords(e.X, e.Y);
            shitx = worldCoords.X;
            shity = worldCoords.Y;
        }
    }

    // functions:
    public static Point convertScreenToWorldCoords(int x, int y)
    {
        int[] viewport = new int[4];
        Matrix4 modelViewMatrix, projectionMatrix;
        GL.GetFloat(GetPName.ModelviewMatrix, out modelViewMatrix);
        GL.GetFloat(GetPName.ProjectionMatrix, out projectionMatrix);
        GL.GetInteger(GetPName.Viewport, viewport);
        Vector2 mouse;
        mouse.X = x;
        mouse.Y = viewport[3] - y;
        Vector4 vector = UnProject(ref projectionMatrix, modelViewMatrix, new Size(viewport[2], viewport[3]), mouse);
        Point coords = new Point((int)vector.X, (int)vector.Y);
        return coords;
    }
    public static Vector4 UnProject(ref Matrix4 projection, Matrix4 view, Size viewport, Vector2 mouse)
    {
        Vector4 vec;

        vec.X = 2.0f * mouse.X / (float)viewport.Width - 1;
        vec.Y = -(2.0f * mouse.Y / (float)viewport.Height - 1);
        vec.Z = 0;
        vec.W = 1.0f;

        Matrix4 viewInv = Matrix4.Invert(view);
        Matrix4 projInv = Matrix4.Invert(projection);

        Vector4.Transform(ref vec, ref projInv, out vec);
        Vector4.Transform(ref vec, ref viewInv, out vec);

        if (vec.W > float.Epsilon || vec.W < float.Epsilon)
        {
            vec.X /= vec.W;
            vec.Y /= vec.W;
            vec.Z /= vec.W;
        }

        return vec;
    }

```

# Answer
> 1 votes
Finally, I got this fixed. I just changed

```
mouse.Y = viewport[3] - y;

```

to

```
mouse.Y = y + (ClientRectangle.Height - glview.Size.Height);

```

still not very accurate but not very bad.

# Answer
> 1 votes
I have exactly the same problem and have used your code. I think I fixed it fully now.

```
in ConvertScreenToWorld()
change
mouse.Y = viewport[3] - y;
to
mouse.Y = y;

in UnProject()
change
vec.Y = -(2.0f * mouse.Y / (float)viewport.Height - 1);
to
vec.Y = 2.0f * mouse.Y / (float)viewport.Height - 1;

```

then call it like convertScreenToWorldCoords(e.X,ClientRectangle.Height - e.Y);

it's very precise too bye!

# Answer
> 0 votes
I changed

```
-(vec.Y = 2.0f * mouse.Y / (float)viewport.Height) - 1;

```

to

```
-(vec.Y = 2.0f * mouse.Y / (float)viewport.Height) + 1;

```

and it works.

---
Tags: c#, mouse, opentk
---


# Question
Title: How to reduce/remove graphical artifacts?
## Question

I'm working on a side-scrolling game that has a 2D grid for rendering to the screen. I'm using OpenGL, and I've optimized my game so that nothing invisible is attempted to be drawn.

As of now, I create a grid based off of my game's window size. Each tile in the grid takes up 32x32 pixels. This grid is made up of square primitives, and each is drawn using an individual *vertex buffer object*. When the window is resized, the grid changes as well.

My games updating thread will constantly feed images into this grid, and this is what creates my game's scenery.

I've implemented a mechanism for user input to move this grid around (simulating character movement); however, I notice a visual artifacts of slightly slanted horizontal lines that flicker across the screen. They are about 20 pixels in height.

**Example of the artifact:**

In the image above, you can see the black line that crosses the entire image. This is the artifact I'm receiving.

I'm curious what are the possible causes for this type of visual artifact. My grid is constantly moving back and forth and reapplying the textures to each square during each iteration of my game loop (update thread). However, I see no reason why something like this would appear.

* **Does anyone have an idea what could be happening here?**
* **Does anyone know how to minimize graphical artifacts in general?**

I am using the fixed-function pipeline right now, so I bet that there would be a huge improvement after moving to using shaders. However, I'm not convinced that this alone will solve my problem.

---

## Code Snippets

Originally I didn't want to share code, but I'll give some snippets of where all the interesting stuff is happening. For each snippet, I'll explain where it is used and how it connects to other snippets.

**Grid Movement**
The grid is moved by passing the movement amount to this function. The algorithm in here simply forces the grid location to wrap around a box that has the corners (-1, -1) and (0, 0). That way, emptiness is never seen around the grids border. I send the user input to this function. This function is called on my game's **updating thread**.

```
@Override
public void move(double x, double y) {
    //First, obtain only the integer parts of each coordinate.
    double moveX = (x%1);
    double moveY = (y%1);

    //Determine new location for the grid.
    double endX = (location.x + moveX);
    if(moveX >= 0) //Moving right
    {   if(endX >= 0) endX--; }
    else //Moving left
    {   if(endX < -1) endX++; }

    double endY = (location.y + moveY);
    if(moveY >= 0) //Moving right
    {   if(endY >= 0) endY--; }
    else //Moving left
    {   if(endY < -1) endY++; }

    location.x = endX;  //location stores the new coordinate for the grid (bottom-left)
    location.y = endY;
}

```

**Grid Rendering**
This function renders the grid by iterating through each square VBO that is inside of it. It applies the correct texture, translates the square, then draws it. This function is called on my games's **rendering thread**.

```
public void render(GL2 gl){
    for(int yIndex = 0; yIndex < NUM_BLOCKS_Y; yIndex++) {
        for(int xIndex = 0; xIndex < NUM_BLOCKS_X; xIndex++) {
            Square tmpSquare = squares.get(yIndex * NUM_BLOCKS_X + xIndex);
            tmpSquare.setTexture(blockIDs[xIndex][yIndex]);
            tmpSquare.moveTo(location.x + xIndex, location.y + yIndex);
            tmpSquare.render(gl);
        }
    }
}

```

---

## Debug Notes

I also went ahead and did a couple test runs to see if I could find anything interesting. Here's what I learned:

* First of all, the reason the line in the picture above is black is because that is what my **glClearColor** is set to. I changed the clear color, and that changed the artifact's color too.
* Also, my rendering thread is separate from my updating thread. And the updating thread is fixed at a desired FPS. When I set to **50 FPS**, in other words, 50 updates per second, and when I change the movement speed to be **50, 25, 12.5, or 6.25**, the grid does not shift back and forth because it catches the edge of the box mentioned above. When I set the updater to **30 FPS**, and the movement speed to **60, 30, 15, 7.5, or 3.75**, the grid still does not change. Since the grid isn't bouncing back and forth, I don't receive the gap that appears in between the rows as before. NOTE: The jaggedness reappears when setting to half of **6.25 @ 50FPS**, or half of **3.75 @ 50FPS**; and the jaggedness appears when not moving by a **2^x * FPS**.

It seems to me that when the movement speed is set so that the grid moves back and forth, not all of the square positions are moving fast enough.

# Answer
> 1 votes
## Solution

Well, the problem is that neither or the code snippets are synchronized. As mentioned before, I have two threads interacting with my grid: the updating/rendering threads. What appears to be the issue is that my rendering thread draws part of the grid (starting from the bottom-left). And then, the updater moves the grid while the grid is being drawn. After the grid is modified in the rendering thread completes the drawing, but at the new location. This causes the horizontal split to occur in the grid.

**Corrected Functions**

```
@Override
public synchronized void move(double x, double y) {
    //...
}

public synchronized void render(GL2 gl){
    //...
}

```

It makes sense that the movement of the grid never broke when using a movement speed of **2^x * FPS**. This is because the grid location never ends up in the middle of the box with the corners (-1, -1) and (0, 0). While although the image is still not synchronized, it does not contain the horizontal line artifact.

# Answer
> 0 votes
Well with so few information on your computations, I'd say your polygon are badly shifted because you're not moving the viewport, but changing the coordinates at every view translation, which is painful. But do you ?

You need to debug here, to see the actual X,Y(,Z,W)coodinates of your vertices before rendering and then if they are wrong, to seek down the incriminating code and fix it.

---
Tags: opengl, 2d, graphics-programming
---


# Question
Title: How can I switch two GameObects in an array in Unity?
I'm putting together a match-3 as my first unity project and I'm having some trouble with switching two GameObjects. I thought I had it working, but I was running into strange issues. I hunted them down and found that my code below does NOT copy the script values of the original tiles when I instantiate them.

For instance, I switch a blue tile and a yellow tile. All stuff directly in the object instantiate correctly (right place, right color tile), but the code in my script that determines which it should be goes back to the default so behind the scenes they both think they are red tiles.

```
void SwitchTile(Vector2 start, Vector2 end)
    {

        GameObject tempStart = (GameObject)Instantiate(tiles[(int)start.x, (int)start.y]);
        DestroyImmediate(tiles[(int)start.x, (int)start.y]);

        tiles[(int)start.x, (int)start.y] = (GameObject)Instantiate(tiles[(int)end.x, (int)end.y]);
        DestroyImmediate(tiles[(int)end.x, (int)end.y]);
        tiles[(int)end.x, (int)end.y] = (GameObject)Instantiate(tempStart);

        Destroy(tempStart);

    }

```

How can I clone a GameObject with all of it's components also correctly cloned in unity? Or is there a better way of switching GameObjects in an array in unity?

# Answer
Making my comment into an answer.

You don't want to keep destroying and creating new objects. It's both more complicated than it should be and way less efficient. Instead you should just swap places of `GameObject`s (or more specifically of references to these objects) like this:

```
GameObject tmp = tiles[(int)start.x, (int)start.y];
tiles[(int)start.x, (int)start.y] = tiles[(int)end.x, (int)end.y];
tiles[(int)end.x, (int)end.y] = tmp;

```
> 5 votes

---
Tags: unity
---


title: Normal Map Issues

text:
# Question
Title: Normal Map Issues
I'm experiencing a very strange result in my very simple normal map implementation on iOS 7 - OpenGL ES 2.0. I'm only using the bare parameters necessary and I'm also skipping on all the tangent and bi-normal stuff, since the object is a flat quad in the background that's not going to move.

The quad is placed in the center and fills the entire screen. The light source is placed directly above it and there's no falloff calculation. The normal map itself is baked out from 3ds max using a noise map as displacement/height-map. So the result looks right I guess, however, it's split diagonally (see below)... why?

Here's my vertex Shader, I believe the parameters are self explanatory:

```
attribute vec4 a_pos;
attribute vec2 a_tex_coord;

uniform mat4 u_projection;
uniform mat4 u_model_view;
const vec4 u_light_position = vec4(0.0,0.0,1.0,1.0);

varying vec4 v_world_pos;
varying vec2 v_tex_coord;
varying float v_distance;

void main(void) {
  v_world_pos = u_model_view * a_pos;
  v_distance = length(u_light_position - v_world_pos);
  v_tex_coord = a_tex_coord;//(a_tex_coord + u_texture_offset) * u_texture_multiplier;

  gl_Position = u_projection * v_world_pos;
}

```

and the fragment shader

```
uniform sampler2D u_texture;

varying vec4 v_world_pos;
varying vec2 v_tex_coord;
varying float v_distance;

const vec4 u_light_position = vec4(0.0,0.0,1.0,1.0);

void main(void) {
  vec3 light_vector = normalize(u_light_position - v_world_pos).xyz;
  float light_diffuse = max(dot(normalize(texture2D(u_texture, v_tex_coord).rgb * 2.0 - 1.0), light_vector), c_zero);
  gl_FragColor = (vec4(1.0,1.0,1.0,1.0)) * light_diffuse;
}

```

and this is the weird result i get, why would this happen? I believe it's here

```
float light_diffuse = max(dot(normalize(texture2D(u_texture, v_tex_coord).rgb * 2.0 - 1.0), light_vector), c_zero);

```

but I couldn't get better results by removing the scaling of the rgb value...

EDIT:

When rotating the mesh the light remains at the bottom right half of it:

EDIT2:

I've downloaded a normal map online which seems to give the right results, on the left of the picture below the normal map seems to behave as expected even when rotating (that is as correct as it can with this simplified method). The one on the right side is the old texture result when I change my shader diffuse calculation to this:

```
  float light_diffuse = max(dot(normalize(normalize(texture2D(u_texture, v_tex_coord).rgb) * 2.0 - c_one), light_vector), c_zero);

```

Which looks almost right, but there is still that slight shadow that remains on the top left...

So I am gonna check my export settings again, but I still can't explain that shadow.

# Answer
I finally found the error. It was just wrong export settings, I just didn't expect that to have this sort of impact. In 3ds Max I changed the projection options -\> normal map space -\> red: right to red: left

What a gigantic waste of time.
> 2 votes

---
Tags: ios, opengl-es2, fragment-shader, normals, normal-mapping
---


# Question
Title: How to manage grid-based inventory with items larger than 1x1 cell?
Me and my team have been trying to implement some sort of inventory system. We've set our eyes on an inventory system where some items may take up more than one box on the grid system, sort of like the one used in SOTS the pit, like this:

<sub>(source: webguyunlimited.com)</sub>

Notice how some items, such as the gun, take up more than one slot. How can we implement this? This includes checking to make sure that a slot we would like to insert an item in hasn't already been taken up (we may have irregular shaped items too).

# Answer
> 2 votes
Store the position of the top left square of your item in `var position:Array = [x, y]`

Then add to each object an array of couples of ints representing the occupied coordinates of the grid, relative to the position of the top left square.

For example, a 1x1 object will have `var size:Array = [[0,0]]`

A 1x3 object (1 square wide and 4 squares tall) will have `var size:Array = [[0,0], [0,1], [0,2]]`

An object shaped like the T piece in Tetris will have `var size:Array = [[0,0], [1,0], [1,1], [1,2], [2,1]]`

Then if you need to check wether a certain position in the grid is free, say \[8,2\] (the position corresponding to the piece of meat in your picture) you can use a method like

```
function checkFree (x:int, y:int):Boolean {
    foreach (var item:Item in inventory) {
        foreach (var square:Array in item.size) {
            if (item.position[0] + square[0] == x && item.position[1] + square[1] == y)
                return false //position is occupied
        }
    }
    return true
}

```

Then, to see if an object will fit in a particular position:

```
function checkFit (item:Item, x:int, y:int):Boolean {
    foreach (var square:Array in item.size) {
        if (!checkFree(x + square[0], y + square[0]))
            return false
    }
    return true
}

```

I used this in my tetris game, I think it will do for your inventory too :)

# Answer
> 0 votes
In my Torchlight clone demo, I just stored the inventory as a 2D array.

Each item specified `inv_size_x` and `inv_size_y` with a default of 1/1, but I could set for example:

```
item->setInvSize(1, 4); // example, a sword that is tall

```

Now I cheated a little since my bag also used sizing like this (for inserting to the bag, I used a brute force method to find the first space that would fit the item). I implemented the interface via events, so each "tile" in my inventory would receive an `OnDragIn`, `OnDragOut`, `OnClick` event. I would have an object `Event` passed through it, and a member `Event.item // null if no item`. From there I could check if my sword fit inside of an empty space by bruteforce-checking each sword tile with each inventory tile. I would do this on all 3 events, giving the user some visual feedback on my `OnDragIn` and `OnDragOut` and enforcing it on my `OnClick`.

Your implementation will vary, so I kept this as generic as possible.

---
Tags: inventory
---


# Question
Title: How should I pause a rotation when my character collides with a gameObject?
My character always moves forward and when he enters a turn(Trigger) this is what happens:

```
if(other.CompareTag("TurnLeft"))
{
    // Rotates the character in 90 degrees in 6 seconds.
    MoveObject.use.Rotation(transform, Vector3.down * 90.0, 6);
}

```

But when he contacts with the ("StageColliders"), he keeps rotating, even though he doesn't change his position. I practically need him to pause rotating when he hits ("StageColliders") and continue when he's free of collision. Something like this would be ideal.

```
if(other.CompareTag("StageColliders"))
{
    // Pause the rotation above.
}

```

I found the MoveObject script here http://wiki.unity3d.com/index.php?title=MoveObject in case someone's curious.

# Answer
You can add a pause to the code you've copied. Add some booleans to the top (sorry I don't do UnityScript, so syntax may be poor/inaccurate).

```
static var pauseRotation : Boolean;
static var pauseTranslation : Boolean;

```

And use these inside the while loops of the Translation and Rotation methods. For example, inside the Rotation method:

```
while (t < 1.0) {
    if(!pauseRotation) {
        t += Time.deltaTime * rate;
        thisTransform.rotation = Quaternion.Slerp(startRotation, endRotation, t);
    }
    yield;
}

```

Then create methods for setting the pause:

```
function SetRotationPause(setPauseRotation : Boolean) {
    pauseRotation = setPauseRotation;
}

```

And create a similar one for movement.
> 1 votes

---
Tags: unityscript
---


# Question
Title: Isometric to screen, screen to isometric for irregular projection
I have isometric assets that unfortunately can't change and need to work out the projection for those. Here is how a tile looks like:

The tile image width/height ratio is `0.(6)` (`height/widht = 1.5`). Since this is isn't the standard(2:1) isometric ratio, how can I work out the iso-screen/screen-iso coordinate conversion functions ?

# Answer
Having recently done a pixel to tile, tile to pixel conversion I understand this can get difficult quickly. You have a ratio of 0.6, usually the ration is 0.5, is this correct?

Also there are a number of ways to draw your tiles, diamond (chess board), staggered (Civ type game) etc.

Here is an answer to a similar question made by coobird (better than i ever could)

https://stackoverflow.com/questions/892811/drawing-isometric-game-worlds

Here is a more in depth article that you should be able to use the work out the answer you need.

http://www.lingoworkshop.com/Articles/Isometric\_Game\_1.php

Good luck :)
> 4 votes

# Answer
The best explanation I have found of Orthographic/Cartesian to Isometric conversion is from this article.

```
BLOCK_SIZE = [64, 32]

def orth_to_iso(x, y):
    ''' Converts cartesian to isometric cordinates '''

    try:
        xx = (x - y) * (BLOCK_SIZE[0]/2)
        yx = (x + y) * (BLOCK_SIZE[1]/4)
    except Exception:
        xx = -1
        yx = -1

    return [xx, yx]

def iso_to_orth(x, y):
    ''' Converts isometric to cartesian coordinates '''

    try:
        xx = (x / (BLOCK_SIZE[0]/2) + y / (BLOCK_SIZE[1]/2)) /2
        yx = (y / (BLOCK_SIZE[1]/2) -(x / (BLOCK_SIZE[0]/2))) /2
    except Exception:
        xx = -1
        yx = -1

    return [xx, yx]

```
> 2 votes

# Answer
Not being able to see the code or textures its difficult but if its not the tile itself being occluded then split the textures into two, ie if its a tile with a building on then draw the tile (at a 2:1 ratio) then 'layer' the building on top of that tile. This should work and you should be able to hold that 2,1 ratio.
> 1 votes

---
Tags: isometric, coordinates
---