# Question
Title: Translating a terrains position using input in Unity 3D C#
I am trying to make a terrain in Unity move, but im having trouble. Here's the code i have.

```
using UnityEngine;
using System.Collections;

public class NewScript : MonoBehaviour {

Camera camera;

Transform Terrain;
// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update () {
    Terrain.Translate(new Vector3(500, 500 ,500));
}
}

```

now i would suspect that the terrain would just keep translating its position but it doesnt budge. How do i make a terrain move, or if you cant, how can i make the camera move and preferably with input. I am familiar with the XNA framework, is there a way to implement the input from XNA into unity?

# Answer
> 4 votes
First (and I only say this because you are new to Unity), make sure you have the script attached to your Terrain GameObject (drag it from the project window and release it on top of the terrain GameObject in the Hierarchy). Then you can access the terrains transform in the script. Note that this will actually work for any GameObject including Prefabs, Cameras, and Terrain (try attaching the script to a Cube and point your Camera at it).

```
using UnityEngine;
using System.Collections;

public class AnyObjectMover : MonoBehaviour {
    // Use this for initialization
    void Start() { }

    // Update is called once per frame
    void Update() {
        // If you don't see this in update you did not attach your script.
        Debug.Log("moving object 5 units in every direction.");

        // transform = the transform of the object this script is applied to.
        transform.Translate(new Vector3(5, 5, 5));
    }
}

```

---
Tags: c#, unity, movement, input, unityscript
---


title: Smoothly move between bodies

text:
# Question
Title: Smoothly move between bodies
I'm not sure if the title is correct (please comment if it is not). I have a sprite (rectangle body), and I'm applying force on it to make it move from left to right and then go backward. The platform consists of a few rectangle blocks of same size, lined up, with no distance between them . What they form is a perfectly straight line. The platform can be flat or sloped.

**What I want**

The sprite moves smoothly forward and backward on the platform.

**What actually happens**

The sprite is sometimes clogged at the point it moves from one block to another, even there is no space between blocks at all. Also sometimes at that point a collision is registered.

I have tried to search and found something called "internal corners", but have no clue how to fix this problem. Is there a way to get around? Thanks!

# Answer
> 1 votes
The problem is illustrated as such:

The moving object "sinks" into the ground slightly. This may be gravity, this may be slight errors in precision, it doesn't matter.

While moving right, the bottom of the player collides with the vertical edge of the right tile, catching so to speak on its corner.

The fix is to remove this internal edge. Since the moving object can't be between two tiles, that edge is irrelevant. The only edges that the moving object can collide with are external edges, such as the top edge in this example.

You generally need to post-process your tile map to identify these edges. You can easily examine each tile to see what neighbors it has, telling you if any edge is external (no adjacent tile on that side) or internal/hidden (adjacent tile on that side).

If you write your own simple physics, you can then only check agsinst edges that have the external flag set.

For Box2D, there is something called an Edge Shape and edge chains. You will need to find all external edges and connect them (start with any external edge and then find the next external edge sharing a vertex, until it loops) and build an edge chain accordingly. This is how Box2D deals with this case.

Note that when connecting edges, you may run into a case where a single vertex is shared by more than two edges, like so:

You want to ensure that the edges with the blue normals are connected, and edges with red normals are connected, but never with the edge with a different color. If you get a list of all edges sharing a vertex, pick the edge on the "other" tile (which you'd do anyway even when only two edges share a vertex, to avoid picking yourself). Then pick the edge who's normal is not your normal in the opposite direction (that can't happen in a sane world, it geometrically makes no sense). That edge is the one you want join with.

---
Tags: physics, box2d
---


# Question
Title: Revolve FlxSprites Around a Central FlxSprite in Flash Game made with Flixel
I have been working on a Flash game made in Flash Builder using the Flixel library. I have been trying to dynamically create a group of FlxSprites , and revolve them around a player controlled class that extends FlxSprite when the player uses a power up.

My thought on how to approach this, was to create a circle, use points on that circle to instantiate the sprites, and then somehow update those sprites to points along that circle during the game's `update` step. But I am not sure what would be the best way to hold information about a circle, or circular path's in ActionScript 3. I assumed that As3Math provided some of the means to do this, and I tried to add one sprite to a circle like this:

```
package
{
    import As3Math.*;
    import As3Math.geo2d.amBoundCircle2d;
    import org.flixel.FlxGroup;
    import org.flixel.FlxState;

    public class ButterflyRing extends FlxGroup
    {
        [Embed(source="../Content/Images/spritesheet_butterfly_32x8.png")] var butterflySprite:Class;
        public function ButterflyRing(playState:FlxState,X:Number,Y:Number)
        {
            //add to super class
            super();

            //create a circle motion path at coordinates x:150, y:150 with a radius of 100
            var butterflyCircle:Math.amBoundCircle2d = new Math.amBoundCircle2d(150,50);

            var circDiameter:Number = butterflyCircle.radius/2;
            var pX:Number = butterflyCircle.center.x + circDiameter
            var pY:Number = butterflyCircle.center.y;

            var butterfly:SpriteButterfly = new SpriteButterfly(pX,pY);
            add(butterfly);

        }

        override public function update():void
        {
            super.update();
        }
    }
}

```

I realize now this is not the correct way to use As3Math, that it is accessible by default and you call it like `Math.pi`. My question is, Does ActionsScript 3 have the means to do this in its code base, or do you have to define your own classes to hold information for a circle, or do you use Math.pi to build circles from scratch? What is a good approach for this? Or does Flixel provide something good for this?

# Answer
I looked at what I think is the AS3Math lib you're talking about. Here is their amCircle2d class.

It doesn't look terribly useful, since it inherits from (amCurve2d)\[https://code.google.com/p/as3math/source/browse/trunk/src/As3Math/geo2d/amCurve2d.as\] but doesn't implement `getPointAtDist`, which, if you fed it a distance a long the circumference of the circle, should theoretically gives you points rotating around the circle's center.

An important concept to understand in order to accomplish this is how trigonometry is related to 2D vectors, and how sine and cosine are related to what's called the "unit circle."

This page has a couple of good gifs showing that relationship.

What those gifs show, is that assuming you have a circle with radius `r` centered at point `(px, py)`, and an angle `t` specifying how far around the circle you want to go, the following is true:

```
xcoord_along_circle = r * cos(t) + px
ycoord_along_circle = r * sin(t) + py

```

It's likely that the as3 `Math` class's sin/cos functions work in radians, so wrap the range to `0..2*Math.pi`.

Another approach is to think of it in terms of physics and orbiting bodies: Uniform Circular Motion (you may have studied centripetal force in high school physics). This page has a nice thorough explanation.

The general idea is that you have a velocity that is parallel to the vector running from your orbiting point to the origin. Then, every step, this velocity is accelerated by a force perpendicular to that velocity (that is, it is the force going from your orbiting point to the origin);

Roughly, in pseudocode:

```
//Init
float fixedFPS = 60.0;
float constantDeltaTime = 1 / fixedFPS;
float radius = 10.0;
Vector2 point = origin + Vector2.UnitX * radius;
Vector2 velocity = origin.y + Vector2.UnitY * radius;

//Every update
velocity += (origin - point) * constantDeltaTime;
point += velocity * constantDeltaTime;

```

I threw together a ProcessingJS example to play with.
> 1 votes

---
Tags: sprites, flash, actionscript-3, flixel
---


title: Using git with XNA

text:
# Question
Title: Using git with XNA
I'm a single developer trying to use Git (I'm told it's much better than SVN) to keep track of my XNA project. Would I copy my project into a bare repository and then add the files? If so, do I need all of them? Also, what do I do with my Content project and files - will Git copy them over each commit/push, massively increasing repo size?

# Answer
With Git you can supply a .gitignore file which can contain wildcards for files that dont need to be stored in the repository. As per your idea of creating the repository and then adding the files, that would definitely work. Just be sure to read up on how git works as it seems a bit backwards in comparison to svn. Look for a program called Git extensions which is essentially a gui wrapper for git that will make things a bit easier.

Git is not so good at binary files so you'll have to include your output xnb files in the .gitignore so that they aren't constantly being updated but your source content should only have to be updated when you actually make changes.
> 3 votes

---
Tags: xna, version-control
---


# Question
Title: What's the appropriate way to define configuration settings of game objects for a proper code accessed via C++?
I defined a lot of configuration and settings of certain types of enemy characters inside header via #define similar to the following.

```
// --- RULES ---
#define MAX_INC_ATTACK_POINT 50
#define MIN_INC_ATTACK_POINT 0
#define MAX_DEF_PERCENT 0.1f
#define MIN_DEF_PERCENT 0.0f

#define PUNCH_ATTACK_POINT 12
#define PUNCHHARD_ATTACK_POINT 15
#define KICK_ATTACK_POINT 12
#define KICKHARD_ATTACK_POINT 15
#define COMBO06_03_ATTACK_POINT 20
#define COMBO06_04_ATTACK_POINT 5
#define COMBO06_04_01_ATTACK_POINT 15

#define START_MAX_HP 100
#define START_INCATTACK_POINT 0
#define START_DEF_PERCENT 0.0f
#define MAX_ULTIMATE 100

```

Anyway, c++ experts tend to not recommend to use global states or global variables at all (if necessary). There're some thoughts about global variables here and here.

Now I want to know what's the proper way to define these kind of values to be accessed via its own specific classes later? Is that a bad design choice if I use like I did it currently?

# Answer
> 4 votes
You should be more data drive as @sharethis suggested. But You should, seriusly, use Lua to get it. Why:

* Lua integrated directly with C and C++
* It allows to have logic in your config file, not only defines.
* Lua is a powerful, fast, lightweight
* When you start to use it, you will want to use more.

E.g, How to load configure file from Lua (working code):

```
#include <cassert>
#include <iostream>
#include <cstdlib>
#include "lua.hpp"

int main( int argc, char * argv[] ){
    // Lua Initialization
    lua_State * L = luaL_newstate();
    assert( L && "Can't create Lua State" );
    lua_gc(L, LUA_GCSTOP, 0);
    luaL_openlibs( L );
    lua_gc(L, LUA_GCRESTART, 0);

    // execute config file
    int ret = luaL_dofile( L, "config.lua" );
    if( ret != 0 ){
        const char * msg = lua_tostring(L, -1);
        if( msg ){
            std::cerr << "Error: " << msg << std::endl;
        }else{
            std::cerr << "Error: (error object is not a string)\n";
        }
        return EXIT_FAILURE;
    }

    // get variables
    lua_getglobal( L, "MAX_ULTIMATE" );
    int val = lua_tointeger( L, -1 );
    std::cout << "MAX_ULTIMATE = " << val << std::endl;

    lua_close( L );

    return EXIT_SUCCESS;
}

```

An the Lua config file (config.lua) is simple as (notice the example logic I included on it):

```
START_MAX_HP = 100
START_INCATTACK_POINT = 0
START_DEF_PERCENT = math.abs( START_INCATTACK_POINT * START_MAX_HP )
MAX_ULTIMATE = START_MAX_HP

WIDTH = 800
HEIGHT = math.floor( WIDTH / 1.333 )

```

For your case, the final solution is put all the variables in a Singleton Class as public members, and load from Lua their values in the constructor.

Spoiler:

> Yo also can, obviously, change Lua for LuaJit, Scheme, Guile, Zangief, whatever.. but get the idea.

# Answer
> 6 votes
If you or another programmer are the only ones tweaking values, and compile times aren't so long as to make hard-coded values a pain to work with (one of the major benefits of data-driven numbers), then there's nothing wrong with what you're doing.

However I would suggest using const ints/floats instead of #defines due to the reasons set out here: https://stackoverflow.com/questions/1674032/static-const-vs-define-in-c

Edit: this question is C++ specific, but most of the same data is there: https://stackoverflow.com/questions/1637332/static-const-vs-define or this one https://stackoverflow.com/questions/112433/should-i-use-define-enum-or-const

# Answer
> 4 votes
The common approach for that are configuration files. They can be of whatever structure you choose, INI or XML for example.

Making use of configuration files makes your game a bit more data driven. So you can make changes to the configuration without recompiling the whole source code. That saves time and moreover, you can divide the work of programmers and game designers who balance the hit points of enemies.

---
Tags: c++, configuration
---


# Question
Title: how to load normals for a model from texture2d?
I know i can do this through custom shaders, but i want to know is it possible to set it through xna itself. As for each effect i have pick normals from a texture2d, i want to change normals of model.

I have done this much, but i don't know how to go further??

```
  foreach (ModelMesh mesh in Home.Model.Meshes)
       {
           if (mesh.Name == meshName)
           {
               foreach (ModelMeshPart part in mesh.MeshParts)
               {
                   VertexPositionNormalTexture[] normals = new VertexPositionNormalTexture[part.VertexBuffer.VertexCount];
                   part.VertexBuffer.GetData<VertexPositionNormalTexture>(normals);

                   Color[] data = new Color[normalMap.Height * normalMap.Width];
                   normalMap.GetData<Color>(data);
               }
           }

       }

```

Thank you

# Answer
> 1 votes
The common reason to use a normal map is to map normal details on the surface of a primitive formed by the vertices. It is not possible to do this mapping in software. You can only change the vertex normals but this will make your mesh incompatible with the normal map if it is in tangent space.

To map the normal map normals to the vertices you first need to extract the uv coordinates from the mesh and then access the normalMap data using these coordinates. To do this correctly you will need to implement bilinear blending by taking the 4 neigbouring values and blending them by the exact coordinate. The next thing you have to do is denormalize the normal by multiplying with two and subtracting 1 =\> mapping 0-\>1 range to -1-\>1 range. Depending on the normal map method you use you either just replace the normal of the vertex, apply it as a delta or apply it in tangent space which is a little bit more complicated.

# Answer
> 0 votes
It looks like all you have to do now is extract the color at the position `data[ (int)(normals.Texture.X * normalMap.Width) + (int)(normals.Texture.Y * normalMap.Height) * normalMap.Width]` and then convert it from a Color to a Vector3.

My code might be a bit off as I haven't run it through a compiler but I am sure you get the idea. Also, I am not really sure why you would want to do this... if you are using a normal map with the hope of doing bump mapping without a custom shader then I am afraid this wont work as all you will be affecting is the normals at the vertices.

---
Tags: xna
---


# Question
Title: Texturing 2D vectorial terrain (or simply masking texture)
I have a procedurally generated terrain, as follows:

It is generated and then built using Farseer Physics, however I haven't found a way to create and apply a mask to texture it properly, I have already played with stencil buffers and pixel shaders but I still have no solution at the moment. How would I do that? Am I going the right direction with stencil and pixel shader? Thank You.

# Answer
> 2 votes
I think the easiest way would be to just create some geometry you can actually texture. Just create a quad (2 triangles) for every segment of your world. This should be straight-forward to texture. To optimize this, you can remove quads that leave the screen during gameplay.

For an idea how you could apply your texture using UV coordinates, see this answer.

# Answer
> 0 votes
taking a different approach i would look to do something similar to http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Random\_terrain.php

essentially find what is below the line and generate a color

---
Tags: xna, farseer-physics-engine
---


title: MonoGame performance better then XNA?

text:
# Question
Title: MonoGame performance better then XNA?
I am currently thinking about porting a XNA game to other platforms using MonoGame. Do I understand this correctly that I can expect the game to render faster even under Windows 7 due to the use of SharpDX?

# Answer
> 2 votes
It's impossible to tell what performs better - as they are both different implementations of a given API set on all different platforms. If you are talking just strictly Windows, there's a few benchmarks you could run by but from personal experience I can tell you that MonoGame has some issues on certain features that will cause slow downs - but overall performance is good.

# Answer
> 1 votes
If your game is fast with XNA it will be as fast with MonoGame. When I did a conversion of my game with a help of MonoGame, the conversion itself (+tests) helped to find places to improve the speed and eliminate some wasteful cycles. You can expect the final size of your app to be 3-4 times bigger than with XNA.

# Answer
> 1 votes
Most of the performance issues I have encountered while using MonoGame are related to unnecessary garbage generation. A lot of these are fixed from time to time but I wouldn't rely on MonoGame to be more performant than XNA as of yet.

It is still valid that if you are targeting any of the platforms that XNA supports and do not require the use of DX11 features, you SHOULD stick to XNA. For any other platform, if you run into performance problems using MonoGame, profile your game and try to find a workaround for the part that is causing slowdowns. Even better, get into MonoGame source yourself, fix whatever problems you find and submit a pull request. This way everyone wins!

---
Tags: xna, xna-4.0, performance, monogame
---


# Question
Title: How to set an EditorGUI foreground color for the light Unity skin?
Writing an asset management GUI as part of our editor tools, I am in some places colouring LabelFields. Working mostly in the dark Pro skin, this seems to work just fine:

```
GUI.color = Color.green;
EditorGUILayout.LabelField("Name", GUILayout.Width(75f));
GUI.color = Color.white;

```

When switching to the light default skin however, this colouring is no longer visible. The usual `GUI.backgroundColor` still functions fine there as it does in the dark skin.

Is this "foreground" colour something specific to the dark Pro skin? If so, is there perhaps another way to achieve a similar effect?

# Answer
No, `foregroundColor` is not specific to Pro skin: it's just that font color in light skin is black.

The way `GUI.foregroundColor` (and all other colors in GUI) works is that it's *multiplied* by whatever color is drawn. But black multiplied by anything stays black, so the setting appears to have no effect.

Fortunately, there are pre-defined editor styles that use white font color in any skin. Use this line:

```
GUI.color = Color.green;
EditorGUILayout.LabelField("Name", EditorStyles.whiteLabel, GUILayout.Width(75f));
GUI.color = Color.white;

```

By the way, in Light skin default `GUI.color` is *not* white, but some kind of gray, I don't know exact RGB values. So to restore default look, you should save this value and restore it later, not just set color to white.
> 1 votes

---
Tags: unity
---


# Question
Title: Ways to "invert Z-axis" in shader-based core-profile OpenGL?
In my hobbyist shader-based (non-FFP) GL (3.2+ core) "engine", everything in world-space and model-space is by design "left-handed" (and to stay that way), so X-axis goes from -1 ("left") to 1 ("right"), Y from -1 ("bottom") to 1 ("top") and Z from -1 ("near") to 1 ("far").

Now, by default in OpenGL the NDC-space works the same but the clip space doesn't, from what I gather, here z extends from 1 ("near") to -1 ("far").

At the same time I want to ideally keep using the "kinda-sorta inofficial quasi-standard" matrix functions for lookat and perspective, currently defined as:

```
func (me *Mat4) Lookat(eyePos, lookTarget, upVec *Vec3) {
    l := lookTarget.Sub(eyePos)
    l.Normalize()
    s := l.Cross(upVec)
    s.Normalize()
    u := s.Cross(l)
    me[0], me[4], me[8], me[12] = s.X, u.X, -l.X, -eyePos.X
    me[1], me[5], me[9], me[13] = s.Y, u.Y, -l.Y, -eyePos.Y
    me[2], me[6], me[10], me[14] = s.Z, u.Z, -l.Z, -eyePos.Z
    me[3], me[7], me[11], me[15] = 0, 0, 0, 1
}

//  a: aspect ratio. n: near-plane. f: far-plane.
func (me *Mat4) Perspective(fovY, a, n, f float64) {
    s := 1 / math.Tan(DegToRad(fovY)/2) // scaling
    me[0], me[4], me[8], me[12] = s/a, 0, 0, 0
    me[1], me[5], me[9], me[13] = 0, s, 0, 0
    me[2], me[6], me[10], me[14] = 0, 0, (f+n)/(n-f), (2*f*n)/(n-f)
    me[3], me[7], me[11], me[15] = 0, 0, -1, 0
}

```

So, for the lookat-part to have my world-space camera (positive-Z) work with lookat (negative-Z) as per this pseudocode:

```
// world-space position:
camPos := cam.Pos
// normalized direction-vector, up/right/forward are 1 not -1:
camTarget := cam.Dir
// lookat-target:
camTarget.Add(&camPos)
// invert both Z:
camPos.Z, camTarget.Z = -camPos.Z, -camTarget.Z
// compute lookat-matrix:
cam.mat.Lookat(&camPos, &camTarget, &Vec3{0, 1, 0})

```

That works well. Moving the camera in all 6 degrees of freedom produces correct on-screen movement and correct new camera world-space coords.

But geometry is still inverted on the Z-axis. When I position two boxes, A at (-2, 1, -2), to appear near-left and B (2, 1, 2) to appear far-right, then A appears far-left and B appears near-right. Z is still inverted here.

Now, these nodes have their own world-space coords and update from those their own model-to-world matrices. I shouldn't invert posZ there as they form a hierarchy of sub-nodes multiplying with their parents transforms and all that. They're still in model or world space, which as per my decree is to remain left-handed.

Their world-to-camera calculation happens on the CPU at my end, not in a vertex shader which just gets a single final (mvp/clip-space) matrix.

When that happens -- multiplication of world-space-object-matrix with clip-space lookat-and-projection matrix -- at that point I need to somehow invert Z.

What's the best way to do this? Or, more generally speaking, what's a common way that works? Do I have to modify the projection to accept left-handed but output-to-GL right-handed? If so, how? And then wouldn't I also have to modify lookat? Is there a smart way to do all this without having to modify the somewhat-standard lookat/projection matrices while also keeping model-transform-matrices in left-handed coords?

# Answer
> 2 votes
One easy way - which would work for inverting any axis - is to apply the inversion function in your vertex shader, like so:

```
// in this example we flip the Z axis
gl_Position = (matrix * position) * vec4 (1.0, 1.0, -1.0, 1.0);

```

The inversion vec4 could be made a shader uniform if you want finer control.

---
Tags: opengl, matrix, coordinates, projection, perspective
---


# Question
Title: How to change Vectors due to change in it's dependent Base Vector?
**PLOT :**

I have been developing a game where the player falls down on Y axis and the camera is a Top-Down view camera. The camera, player (main character in the game) movements etc. have all been implemented based off the idea/notion that the player is falling down Y axis. Hence I used to feed in the vectors based of it. The player is always acted upon gravity.

**DESIGN CHANGE :**

Now after all these months of developing it, I am changing the design. Now the player who was falling down, upon reaching the ground is going to take off and fly parallel to the ground

**PROBLEM :**

As I am changing the entire scenario, it creates a complication with vectors I used to feed in for the camera and player. Also due the constraint that the experience should be exactly similar to that off the "falling towards the ground" I have to change the gravity accordingly. Now how do I accomplish this when I have vectors all over the place based off the top down view. Please forgive if I am confusing you here. Give me a min.

To break it into the most primitive segment - I input Vector A, B etc to the camera and the player when the gravity is (0,-1,0). Now if I change the gravity to (1,0,0), how should I change the Vector A, B etc. Is there a way to formulate the Vectors A, B etc when I know the gravity has been shifted from (0,-1, 0) to (1,0,0). All the vectors are normalized. If you ask me the relationship of Vector A, B etc with the gravity (0,-1,0) - I have to say there is no relationship. As it was a game, I supplied the Vectors on how I need the Player and Camera's to work.

**CODE** :

```
    // The required Force applied in Flap mode
    void ForceToBeApplied()
    {
            //HORIZONTAL FORCE
            if(!HNEXT)
            {
                    rigidbody.AddRelativeForce((Vector3.right) * DeltaTime * LeftDrag * 3);
                    if(LeftDrag < 400)
                            LeftDrag += ToTarget(DefaultDrag,TurnSine);
                    rigidbody.AddForce(2,(-LeftDrag/50),0);
            }

            if(HNEXT)
            {
                    rigidbody.AddRelativeForce((-Vector3.right) * DeltaTime * RightDrag * 3);
                    if(RightDrag < 400)
                            RightDrag += ToTarget(DefaultDrag, TurnSine);
                    rigidbody.AddForce(-2,(-RightDrag/50),0);
            }

            //VERTICAL FORCE
            if(!VNEXT)
            {
                    rigidbody.AddRelativeForce((Vector3.forward) * DeltaTime * UpDrag * 3);
                    if(UpDrag < 400)
                            UpDrag += ToTarget(DefaultDrag,TurnSine);
                    rigidbody.AddForce(0, (-UpDrag/50),-2);
            }
            if(VNEXT)
            {
                    rigidbody.AddRelativeForce((-Vector3.forward) * DeltaTime * DownDrag * 3);
                    if(DownDrag < 400)
                            DownDrag += ToTarget(DefaultDrag, TurnSine);
                    rigidbody.AddForce(0,(-DownDrag/50),2);
            }
    }

```

IF you happen to look into the above module, I add force to the rigidbody. Those forces were added when the gravity was (0,-1,0). Now if I change my gravity to (say) (1,0,0), how should I change the forces applied to the rigidbody.

**TYPE OF APPROACH I THINK :** What if I could create a static class which could take those vectors and convert them to equivalent vectors for the current gravitational force.

**Simple Diagrammatic Expression of The Problem :**

I hope I am clear in the problem I am facing.

Thank you..

# Answer
This is an interesting exercise; here is my solution. I built it only thinking about the math, so there may be many sources for error when you put it to use.

Also, it's ability to solve your problem will depend entirely on your own code, and I bet you will have problems. Next time don't forget: vectors can be magic numbers, too :)

The usage is like so:

1. Every vector that was formerly oriented in the reference frame of A being "Down" now needs to be oriented so that B is "Down".
2. Put A and B into this static function.
3. Use the resultant quaternion to tranform every other Vector3 in your code:

See the vector3/quaternion documentation (oh crap, this ***is*** XNA, right?)

```
new Quaternion reorienter = getVectorReorienter(A, B);
Vector3.Transform(changingVector, reorienter, out changingVector);

```

And also see vector math if you are wondering why these lines do what they do.

```
private static Quaternion getVectorReorienter(Vector3 A, Vector3 B)
{
    //get and keep input's unit directions
    Vector3 unitA = Vector3.Normalize(A);
    Vector3 unitB = Vector3.Normalize(B);

    //get a unit vector perpidicular to A and B
    Vector3 axis = Vector3.Normalize(Vector3.Cross(unitA, unitB));

    //determine if the angles are >, <, or exactly 90deg. apart
    float cos = Vector3.Dot(unitA, unitB);

    //convert dot product result to an angle
    float angle = (float)Math.Acos(cos);

    //create transformation
    Quaternion reoirienter = Quaternion.CreateFromAxisAngle(axis, angle);

    return reoirienter;
}

```
> 2 votes

---
Tags: mathematics, vector, scripting, transformation
---


# Question
Title: JFrame launcher stays open when I'm finished with it
I have written a launcher that prompts the user for their name then starts the game when they hit enter. The launcher looks like this:

But when the user hits enter, this happens:

The launcher stays open.

This is the relevant code in the launcher class:

```
    public void actionPerformed(ActionEvent evt) {
        String text = textField.getText();
        System.out.println(text);
        entered=true;
        Game game = new Game();
        game.start(text);
    }

    public void Launch() {
        //Create and set up the window.

        JFrame frame = new JFrame("Login");
     // maximize the jframe here
        frame.setSize(800,600);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Add contents to the window.
        frame.add(new Launcher());
        //Display the window.
        frame.pack();
        frame.setVisible(true);
        while(entered==true){}
    }

```

And this is for the main method in the game:

```
    public static void main(String[] argv) {
        Launcher launcher = new Launcher();
        launcher.Launch();
    }

```

So how would I go about closing the launcher when the user has no use for it?

I am using a JFrame for the launcher and Lwjgl for the actual game window.

# Answer
> 1 votes
You want to think more about what your actual problem is. Always try to boil down these larger issues into smaller bits. In this case, your JFrame is staying open. That's expected behavior, since you haven't tried to close it!

So the problem isn't that your JFrame is staying open, it's that you don't even try to close it. Check out this question on SO for programmatically closing a JFrame.

---
Tags: java, lwjgl, jframe
---


title: One or multiple VertexBuffers

text:
# Question
Title: One or multiple VertexBuffers
I'm currently working on a personal project where I'm trying to load the levels and all of the geometry from the game "Medal of Honor Allied Assault" into my own C# code-base based on SharpDX.

I managed to do all that, but now that I'm trying to cleanup the code I came across a few questions on which Google and other sites don't give me a clear answer to, hence I'm turning myself to StackExchange once more!

Currently, I'm rendering the whole scene using the following equation: 1 VBO (BSP) + 1 VBO (Terrain) + (1 VBO (Model) * NumberOfModels)

For each VBO, I'm keeping track when and where I have to start a new DrawIndexedPrimitive-call (eg. Texture-swap).

Is my current setup sufficient, or should I put everything into as less VBO's as possible? Or is there a better approach. How about culling which I'm not bothered with just yet, would one massive VBO work better for that than lots of smaller ones?

To give a little more information: some models require 3-4 Texture-swaps, are relatively small (128 vertices to 4k vertices) and I'm currently not even animating them yet.

If I'd go with my feeling, I would give everything its own VBO, arranging vertices in such a way I can batch textures and use instancing techniques, but I'm unsure this the way to go.

Feel free to ask for more information!

# Answer
> 1 votes
At this stage it doesn't really matter too much. I'd say just go with having everything in separate buffers for now, then measure your performance and see how things are.

Buffer swapping is a relatively cheap operation on modern hardware - not free for sure, but still not a *huge* overhead - so you may well find that you run with acceptable performance. On the other hand, putting everything into a single buffer entails some added complexity (prescanning your models at load time to figure how big a buffer you need to allocate, for example) and compromises your ability to be flexible with e.g. on-demand loading, so it may not be worth the tradeoff.

# Answer
> 1 votes
There is no general way of doing this correctly, each game has its own rendering ways due to its own characteristics.

But, typically, FPS games go with high frustum culling, batched geometry, and sorted texture swaps. Ideally, you could instance every same geometry and just pass on some parameters defining what texture to use and so on.

And it's really hard to say what causes a bottleneck in your case. The draw call or the binding of the data to the GPU. You really have to test this and make a profiling chart over what's causing bottlenecks. From there, move on to improve your rendering.

There are some really good papers on how different games have gone with their rendering. This one is from DICE's Battlefield 3. You might get good ideas from that.

http://www.youtube.com/watch?v=KMaL6j7Ry6c

It is a 5 part video.

---
Tags: c#, directx, rendering, vertex, sharpdx
---


title: Rotate Box Sprite With Circle Body

text:
# Question
Title: Rotate Box Sprite With Circle Body
I want to rotate my rectangular sprite with circle body. The problem is the body doest not attached to the centre of the sprite. This was the default behaviour of the body and sprite.

But I want that circle body attached in the bottom of the rectangle and when rotation happen at that time rectangular sprite always attached with the body at the bottom and during simulation it change its angle and position according to this only.

I try to write question in words if I don't able to understand you then know me then I post a picture of my problem here.

Although I know that cocos2d has setAnchorPoint method available so similar task become easily but what about my engine that right now I was using - AndEngine. So be relevant to this game platform.

Also thanks in advance for efforts you take.

# Answer
I found my solution by creating subclass of PhysicsConnector.

```
public class CustomPhysicsConnector extends PhysicsConnector {

    private float flagDisplacement;

    public CustomPhysicsConnector(IShape pShape, Body pBody,
                    boolean pUdatePosition, boolean pUpdateRotation,
                    float flagDisplacement) {
            super(pShape, pBody, pUdatePosition, pUpdateRotation);
            this.flagDisplacement = flagDisplacement;

    }

    @Override
    public void onUpdate(float pSecondsElapsed) {
            final IShape shape = this.mShape;
            final Body body = this.mBody;

            if (this.mUpdatePosition) {
                    final Vector2 position = body.getPosition();
                    final float pixelToMeterRatio = this.mPixelToMeterRatio;
                    shape.setPosition(position.x * pixelToMeterRatio
                                    - this.mShapeHalfBaseWidth, position.y
                                    * pixelToMeterRatio
                                    - (this.mShapeHalfBaseHeight + this.mShapeHalfBaseHeight
                                                    * flagDisplacement * 2f));
            }

            if (this.mUpdateRotation) {
                    final float angle = body.getAngle();
                    shape.setRotation(MathUtils.radToDeg(angle));
            }
    }

```

}

And now in CustomSprite class I have to implement in following manner.

```
setRotationCenter(getWidth() * 0.5f, getHeight() * 0.6f);
            angelBody = PhysicsFactory.createBoxBody(mPhysicsWorld, getX()
                            + getWidth() * 0.5f, getY() + getHeight() * 0.6f, pScale * 64f,
                            pScale * 60f, 0f, BodyType.StaticBody, fixtureDef);
angelBody.setUserData(Constants.USERDATA_ANGLE);
            mPhysicsWorld.registerPhysicsConnector(new CustomPhysicsConnector(this,
                            angelBody, true, true, 0.1f));

```

Now I can rotate and change position of body attached to the sprite because by default it is attached to the centre but using this it is possible to set it any position.

Here I posted answer for other users because I don't want other users waste time on same thing.
> 2 votes

---
Tags: box2d, flash, cocos2d, andengine, cocos2d-x
---


# Question
Title: What kind of project management should a solo developer project use?
I’m working by myself on a game project whose development could be separated into 3 independent parts (map generation, the “overworld” engine, and the battle engine), but as the development progresses, I am not sure how I should be dealing with the management of this project, especially concerning these 3 points:

1. Is it worth using a version control system, since I’m working solo?
2. Should I use a formal method to register planned features / bugs (I just remember what needs to be done for now)?
3. The most important question: How can I know what to develop first? Now that the very basics are done, I know the list of features to code, but I don’t know in which order I should do it.

# Answer
I would use:

### 1. Code management

GIT (and the awesome reference), a distributed source code manager, for managing my code, and host it on GitHub as a private project if I want to keep it off limits.

*(There are A LOT of options here, just google for source code management, you don't even NEED to use GitHub or any other website, Git will work just fine on your local computer, but using GitHub will make the pain of managing backups a lot easier.*

*If you have two computers you can create a repository on one that you'll call your backup machine, then you clone that repository over the local network and use it for development, when you're done with a feature you can push it to the backup machine and you'll have a 1:1 backup!)*

### 2. Issue & Feature management

I would use Trello or GitHub's built-in issue management to keep track of bugs and things to do.

### 3. Have a Design Process

I would design my game first;

1. first in my mind,
2. then on paper,
3. then probably use GameMaker or PyGame to prototype my idea, and iterate over 1-3 until I have something that I enjoy playing.

### 4. Use my Prototype as a Guide and Develop my Game

Then I would put my prototype aside and pick a platform I wish to develop for. Then look for existing engines and pick the one that's the best fit for my game idea. Then I would make clear goals for my project, structure them into small tasks and then begin working to finish the tasks. When you've reached this state, you'll most likely find that you have your own way of working that suits you the best, so go with that!

There are several different methodologies/philosophies that you can apply on your development style, XP, Waterfall, etc. Just go with the one you feel makes you progress the fastest.

### 5. Have a lot of Game Testers!

When you have something playable, ask your immediate friends to try it out! Make it easy for them to help you by setting up quick installer packages if they're running Windows or write some shell script that can automate the process for them if they're using Linux/Mac. Take much care in the feedback of your testers, and don't forget to inform them about your game design and what kind of game it is you're trying to build.

### 6. Make a website for my game

As soon as I have something going well I would probably make a website for my game - to keep my creativity and content flowing when it can't be applied to the progress of my game, for instance, if I'm focusing on my studies or need a break from development!

If I use GitHub, I would set up a project page for my game, otherwise host a WordPress/Jekyll blog or something similar and write my posts with that.

This will keep yourself motivated as well as having a place to refer potential gamers/testers to!

### 7. Join contests

There are lots of game dev contests going on almost all the time. I would try to join one of these with my game if the rules permit. This increases motivation and makes everything even more fun - who doesn't like winning!

*(If you are developing under a strict deadline, you can skip this point at least.)*
> 59 votes

# Answer
I would strongly suggest using a version control system, even if you work alone. It can save you a lot of time, once you accidentally delete something or make a bigger change, only to realize later it was a bad idea and you have to undo al the changes.

**Edit**: There are many free source control solutions.

* I have used the VisualSVN Server, which is easy to set up and use under Windows.
* There also are online alternatives like GitHub, SourceForge or Google Code. The upside is you don't have to set up and maintain a repository and your data is in the cloud; the catch is, you can't freely host closed-source projects.

As for bug and feature tracking: If you already have a larger audience that might be interested in beta-testing your game, reporting bugs and requesting features, go ahead.
If, however, there is only a handful of such people (or none at all), it's unnecessary.

And as for development priorities - that's for *you* to decide. Who should know better what to do in a project than its only developer?
> 13 votes

# Answer
> Is it worth it using a version control system, since I’m working solo?

I think so. Its pretty trivial to set up and I've had multiple times I've gone crazy with the refactoring or done something else stupid and the ability to rollback my changes has saved e tons of time. Plus if its hosted on a server then you have a backup of our code in case anything goes wrong.

> Should I use a formal method to register planned features / bugs (I just remember what needs to be done for now)

I don't think its necessary. I would keep a written list of what you intend to do though just to make sure you don't forget a minor bug, plus I find it helps you get started again after taking a break from coding.

> The most important question: how can I know what to develop first? Now that the very basics are done, I know the list of features to code but I don’t know in which order I should do it.

Take that list above, close your eyes, and randomly poke it. Work on whatever feature you finger is on. Unless items depend on each other its more important just to keep the flow going than making sure things happen in any particular order.
> 7 votes

# Answer
## Definitely use version control

Version control is like a safety net for a tightrope walker: it frees you up to attempt crazy things. A big refactor deleting huge chunks of code is no problem if you can easily revert. It's even less so if you're on an experimental branch in your repo and can decide not to merge it back in.

If you don't have this kind of freedom, you're likely to leave commented-out code sitting around everywhere for fear that you might need it.

I'd put in a vote for Git. The syntax is a bit odd, but two great things about it are:

* **Low overhead**. Change into a folder and type `git init` and you're ready to start checking stuff in. If you decide you don't want to version control it after all, `rm -rf .git` in that folder and it's not a Git repo anymore.
* **Distributed via SSH**. Git is distributed, meaning you can have multiple full copies of your repo (all the history, etc) in various places, and keep them in sync. You can set up another Git repo on any machine where you have SSH access, then add that other repo as a remote. After that, anytime you want to back up just `git push` to that repo.

That's a big advantage over, say, Subversion, where the whole repo lives on one machine and that machine has to be running a Subversion server.

Mercurial may have these same points in its favor, but I haven't used it.
> 5 votes

# Answer
1. Yes! Since you are asking I am guessing that you are well adopted with revision control system. Its a must!
2. Regarding your second question, there are formal method of registering *bugs* and you should use it. For planning features I think taking any less formal route wont hurt(when you are working alone)
3. Do those features first that will make your game come alive. Give a sense of how the final game play is going to be.
> 3 votes

# Answer
1) Yes, of course. I recommend Mercurial via BitBucket and TortoiseHg. BitBucket is free for up to 5 users and since it is hosted in cloud it adds you some piece of mind (no need for backups).

2) Bugs should be fixed before implementing new features. I would use simple accessible TODO list to track things - pending/done. You might just use a plain text file, just do not forget to add it to your source control repository.

3) Do what you want to do on any given day, while keeping in mind that delivering something playable by end-user is a primary objective. E.g. if you are tired of getting physics right, work on rendering or maybe add some missing unit tests for that AI.

Chunks of work should be small enough to be done in about a couple of days. It is crucial to keep yourself motivated and avoid burnout.

If architecture is done properly you should be able to easily add an modify parts of the engine/game without affecting multiple others (otherwise start with some refactoring :).
> 3 votes

# Answer
1) As everybody says: YES (I'd even say, rent a cheap online one)

2) Keep a simple list or if your project grows big and you get beta testers, install Mantis Bug Tracker

3) I don't know, but I'll tell you how I'm doing it: Develop the least interresting and/or hardest things first. Repeat until everything is done. That way development just gets funnier and easier (and you won't hit that problem you just can't solve too late if ever that would happen).
> 2 votes

# Answer
Thanks for asking this question. This is exactly what I am doing currently.

1) Version control: It is must. Right now, I am maintaining manual backup. It is useful atleast when something which was working great has suddenly throwing errors (or not functioning as expected). I compare versions and often find silly mistakes (mostly commenting something)

2) I created a word document and listed all the feature my game going to have in a categorical order and with multi level indents listing sub features (and client/server related or what ever is applicable).

3) After the list I got (which wont be complete usually, keeps get something added to it) I think of my game flow and hightlight all the points which are necessary for me to make the game running and start doing them. I mark yellow meaning work in progress. green when completed. orange to indicate tobe improved or has some known bugs

hope this helps
> 1 votes

# Answer
1.) It is worth using version control for any project. Even very small ones if you already know how to use one. I have used Subversion for years on Linux and Windows with TortoiseSVN. Even when making a small (\<500 line) project I'll create a repository for it so I can undo changes, track what I was doing if I abandon the project for a while, etc.

2.) Depends on how large the project is going to be. If you're planning to play-test with a team and distribute, it is probably worth having a bug tracking system. I'm currently working solo (although I have an artist) on a project that is over 20k lines, and I just keep my to-do list in a text file that is also in my SVN repository. Although I don't exactly have a need to share it with others just yet, so not having bug tracking fits my needs for now. I wouldn't worry about it until there is a need. The worst that can happen is you'll have to enter whatever bugs you've already written down and remove/revise the ones you fixed. When you start losing mental track of your notes, get a bug tracker.

3.) Plot it out on paper. Start with what you want your finished game to be, write down the gist of it. Then break it down into what it will take to make it: collision detection? network code? types of players and monsters? class hierarchies? Work backward from your vision so that you get a clear idea of how to build it from the ground up. I presume you're using an object oriented language. The most crucial step in starting off would be getting those class hierarchies set up in a sensible way. Try your damnedest to have absolutely no multiple inheritance (although sometimes it's unavoidable), plot out the class relationships in a diagram editor (I use Dia), etc. Basic principals go a long way in avoiding headaches later.
> 0 votes

---
Tags: project-management
---


title: OpenGL accepted image formats

text:
# Question
Title: OpenGL accepted image formats
I am just starting out with OpenGL, so I need a little help understanding how textures are loaded. When I look at the OpenGL manual, it gives a list of accepted image formats, e.g.

```
GL_UNSIGNED_BYTE_3_3_2
GL_UNSIGNED_SHORT_5_6_5
GL_UNSIGNED_SHORT_5_5_5_1
GL_UNSIGNED_INT_10_10_10_2
//and a few others...

```
* Can I have a RGB texture with a `GL_UNSIGNED_SHORT_8_8_8_8`, or do I have to pad the image so that it is RGBA (or maybe it doesn't matter either way...)?
* What is the purpose of all the other internal formats (`GL_R16` or `GL_RGBA32I`) if there is no corresponding image format type (like the ones listed above) to load that type of texture?
* Oh, and one other question. Is there a maximum texture size? Or I guess, if there is no maximum size, is there an optimal size for how large textures can be?

# Answer
1. Yes. You specify the image format separately from the internal image format and OpenGL does the conversion for you. If your image data is an array of unsigned shorts with RGB values and you want to store it internally as unsigned shorts RGBA, you would use the following parameters for `glTeximage2D`: `glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT, data)`. `GL_RGBA16` means to internally store it as RGBA components of 16 bits each (size of a short), `GL_RGB` means you're passing in data for red, green, and blue channels in that order, `GL_UNSIGNED_SHORT` means the data you're passing in is an array of unsigned shorts.
2. OpenGL can internally store textures with a number of different formats, regardless of how you pass the data in. You can pass in an RGB image and internally store it as `GL_R16` and it will store only the red channel with 16 bits per pixel.
3. You can get an estimate of maximum texture size with `glGetIntegerv(GL_MAX_TEXTURE_SIZE, &size)`, but to get maximum supported size you have to use proxy textures as described in the OpenGL FAQ. In terms of optimal texture size, try and keep your textures as powers of two and under the maximum texture size.
> 2 votes

---
Tags: opengl, textures
---


title: Receiving server data inside game loop

text:
# Question
Title: Receiving server data inside game loop
I'm planning on how my multiplayer game client game loop should work. While I'm convinced that server should be moved from game loop into it's own thread, I'm not sure what should I do about receiving server data. To me most logical approach would be something like this:

```
protected override void Update(GameTime gameTime)
    {
        receiveServerData(); //may receiving data lag the game?
        updateWorld();
        processInput();
        sendClientMovementToServer();
    }

private void receiveServerData()
    {
        NetIncomingMessage msg;
        while ((msg = netClient.ReadMessage()) != null)
        {
            // ...
        }
    }

```

But I'm afraid that reading incoming data inside game loop can lag the game if processing too much data, so here's my question: Is it good idea to process incoming server data inside game loop, or should create thread for receiving this data instead? And if so, how should I do it?

# Answer
I think you're correct to be concerned about this approach. You should think of the data you're receiving from the server as coming in at different speeds, at different times, and sometimes not at all, so you really want the handling of data from the server to happen asynchronously from your game update.

I recommend you look into the observer design pattern. The idea is that rather than call a receiveServerData() (regardless of whether data is coming in), you want to create a network listener that reacts when server data arrives.
> 2 votes

---
Tags: xna, xna-4.0, networking, multiplayer, multithreading
---


# Question
Title: Implementing multithreaded loading screens
Ok, I have fairly little multi-threading experience, but i have done a similar thing before without issue...but this has me stumped.

This is in C++, Directx9 Visual Studio...

My game basically runs in one thread, apart from loading screens. When I want to load a new game, I fire up a new thread which goes through and does all of the simulation and asset loading stuff. Meanwhile, the original (base) thread displays an animated loading screen. Once the loading is finished, the loading thread sets a flag in tjhe loading screen saying it's done, and during the loading screens Draw() it spots the flag, ends the 'loading' thread, and starts the main game.

All of this works perfectly, in debug and release.

Except fullscreen...

For some reason, if I run the game in fullscreen mode, it goes wrong. The game hangs at the end of loading, and it looks like the flag in the loading screen is never getting set. if I force a debug break into the base thread, it seems to always be inside the D3D flip().

I can't see what I'm doing wrong. The loading thread does zero rendering. It creates some directx assets but never uses them. The flag I'm using to communicate between threads is a simple int, and it's read/write should thus be atomic. I've done a very similar thing in my previous games with no problems, but this has me stumped. Should I really be using CriticalSections etc for something this simple? Help!

# Answer
> 3 votes
A quick google on the subject turned up this: Object Creation with Multithreading (Windows) It is for DX11 and not DX9, but the basic gist is that, DX is only under certain conditions thread safe.

DX behaves "radically" different in windowed and full screen modes. (In windowed mode DX sort of wait on WM\_PAINT, but in full screen it renders away.) This probably unearths a race condition in your code and DX. My experience is, (though mostly with openGL,) that you want to interact with the graphic context only in the thread that created it.

My advice is that you implement the disk to memory operation in your worker thread and keep the actual upload to video mem in the main thread. (My code often has an implicit upload/free in the rendering subsystem.)

# Answer
> 1 votes
Flag variables that are accessed from multiple threads need to be declared as volatile, so the compiler doesn't optimize away the memory accesses and cache them in registers.

For something more complicated than a simple flag, more complex synchronization (e.g. a critical section) is generally required.

Also note that unless you use D3DCREATE\_MULTITHREADED (which can badly affect performance) accessing the D3D device from multiple threads without using your own synchronization isn't safe.

---
Tags: c++, directx, multithreading, loading
---


# Question
Title: SpriteBatch.Begin() making my model not render correctly
I was trying to output some debug information using DrawString when I noticed my model suddenly was being rendered like it was inside-out (like the culling had been disabled or something) and the texture maps weren't applied

I commented out the DrawString method until I only had SpriteBatch.Begin() and .End() and that was enough to cause the model rendering corruption - when I commented those calls out the model rendered correctly

What could this be a symptom of? I've stripped it down to the barest of code to isolate the problem and this is what I noticed.

Draw code below (as stripped down as possible)

```
        GraphicsDevice.Clear(Color.LightGray);
        foreach (ModelMesh mesh in TIEAdvanced.Meshes)
        {
            foreach (Effect effect in mesh.Effects)
            {
                if (effect is BasicEffect)
                    ((BasicEffect)effect).EnableDefaultLighting();
                effect.CurrentTechnique.Passes[0].Apply();
            }
        }

        spriteBatch.Begin();
        spriteBatch.DrawString(spriteFont, "Camera Position: " + cameraPosition.ToString(), new Vector2(10, 10), Color.Blue);
        spriteBatch.End();

        GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        TIEAdvanced.Draw(Matrix.CreateScale(0.025f), viewMatrix, projectionMatrix);

```

# Answer
> 10 votes
`SpriteBatch` will change the following render states. Even if you don't specify any in your `Begin` call - it will use its own defaults:

```
GraphicsDevice.BlendState = BlendState.AlphaBlend;
GraphicsDevice.DepthStencilState = DepthStencilState.None;
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
GraphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;

```

When you want to draw 3D models, you will want to set:

```
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

```

And, if your 3D models have wrapping UV coordinates:

```
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

```

This information comes from this blog post.

# Answer
> 0 votes
I also had this problem, but the code

```
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

```

resolved the problem.

---
Tags: xna, spritebatch
---


# Question
Title: How to attach a sprite to a TMXTiledMap at a particular coordinate, in AndEngine?
I am trying to add a sprite at a "grid" location on the tiled map. The TMX tiled Map is like a grid, and you can access the size of the grid by calling `mTMXtiledMap.getTileRows()` and `mTMXtiledMap.getTileColumns()`.

I want to add an object at grid location, say (2, 5). My tileMap is of size (10,10).

How can I do that? There is no function like `mTMXTiledMap.addChild(int x, int y, Entity mEntity)`.

I would appreciate any suggestions!

# Answer
Just cheat:

Make a method that converts grid coordinates to scene coordinates and then place the sprite at the scene coordinates. *I.e.*, just multiply the column by the tile width and the row by the tile height. Boom, you're done.

Sidenote: I'm assuming you want to add the sprite dynamically, as opposed to just changing the map, but yes, if you always want that sprite there, you should just add it to the map using Tiled as Savlon suggested.
> 0 votes

---
Tags: andengine, tilemap, grid
---


# Question
Title: How to implement bullet physics in libgdx
I am new at game development want to know that how can I implement bullet physics in libgdx. I searched lot of things on Internet but nothing found worthy.

# Answer
> 2 votes
As I mentioned in my comment above, this question is a bit overbroad, but here's the source code for the JNI bullet engine in libgdx. And here's the wiki. The Bullet User Manual is a pdf file located in the root of the Bullet Physics SDK, which might make a good place to start.

You'll need to add gdx-bullet.jar and gdx-bullet-natives.jar to your desktop project, and gdx-bullet.jar to your Android project. You’ll also need to copy the libgdx-bullet.so files from the extensions/gdx-bullet/armeabi and armeabi-v7a folders to your Android project’s libs/armeabi and armeabi-v7a folders of course.

And there's this from the google codebase:

> Setting up Bullet with libgdx To use bullet physics in your project, you’ll need to add gdx-bullet.jar to your main project. Alternatively you can add the gdx-bullet project to the projects of the build path of your main project.
>
> For your desktop project you’ll need to add the gdx-bullet-natives.jar to the libraries.
>
> For your android project you’ll need to copy the armeabi/libgdx-bullet.so and armeabi-v7a/libgdx-bullet.so files to the libs folder in your android project.
>
> Bullet isn’t supported for GWT at the moment.
>
> Initializing Bullet Before you can use Bullet, you’ll need to load the libraries. This can be done by adding the following line in your create method:
>
> `Bullet.init();`

There's a good deal more information at the links provided above.

---
Tags: java, android, libgdx, bullet-physics
---


# Question
Title: Scaling and rotating texture onto another texture by raw buffer data
I've been messing with C++ AMP and OGRE in attempt to make writing to/altering textures to my liking easier on my behalf. In this I've been trying to draw a texture onto my "dynamic" texture with strange results. It appears that a solid 3/4 of my image is cropped off and it's driving me mad as I cannot seem to find the fix.

Here's a video of the problem: http://www.youtube.com/watch?v=uFWxHtHtqAI

And here's all of the necessary code for the sake of understanding even though the kernel is really where the issue at hand rests:

# DynamicTexture.h

```
#define ValidTexCoord(x, y, width, height) ((x) >= 0 && (x) < (width) && (y) >= 0 && (y) < (height))

void TextureKernel(array<uint32, 2> &buffer, array_view<uint32, 2> texture, uint32 x, uint32 y, Real rot, Real scale, bool alpha)
{
    Real
        c = cos(-rot) / scale,
        s = sin(-rot) / scale;
    int32
        //e = int32(sqrt((texture.extent[1] * texture.extent[1]) + (texture.extent[0] * texture.extent[0])) * scale * 0.5F),
        dx = texture.extent[1] / 2,
        dy = texture.extent[0] / 2;

    parallel_for_each(buffer.extent, [=, &buffer](index<2> idx) restrict(amp)
    {
        int32
            tex_x = int32((Real(idx[1] - x) * c) - (Real(idx[0] - y) * s)) + dx,
            tex_y = int32((Real(idx[1] - x) * s) + (Real(idx[0] - y) * c)) + dy;

        if(ValidTexCoord(tex_x, tex_y, texture.extent[1], texture.extent[0]))
        {
            if(!alpha || (alpha && texture(tex_y, tex_x) != 0))
            {
                buffer(idx) = texture(tex_y, tex_x);
            }
        }
        else
        {
            buffer(idx) = 0x336699FF;
        }
    });
}

template<typename T, int32 Rank>
void SetKernel(array<T, Rank> &arr, T val)
{
    parallel_for_each(arr.extent, [&arr, val](index<Rank> idx) restrict(amp)
    {
        arr(idx) = val;
    });
}

class DynamicTexture
{
    static int32
        id;

    array<uint32, 2>
        buffer;

public:
    const int32
        width,
        height;

    TexturePtr
        textureptr;

    DynamicTexture(const int32 width, const int32 height, uint32 color = 0) :
        width(width),
        height(height),
        buffer(extent<2>(height, width))
    {
        SetKernel(buffer, color);

        textureptr = TextureManager::getSingleton().createManual("DynamicTexture" + StringConverter::toString(++id), ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TextureType::TEX_TYPE_2D, width, height, 0, PixelFormat::PF_A8R8G8B8);
    }

    ~DynamicTexture()
    {
    }

    void Texture(TexturePtr texture, uint32 x, uint32 y, Real rot = 0.F, Real scale = 1.F, bool alpha = false)
    {
        HardwarePixelBufferSharedPtr
            pixelbuffer = texture->getBuffer();

        TextureKernel(buffer, array_view<uint32, 2>(texture->getHeight(), texture->getWidth(), (uint32 *)pixelbuffer->lock(HardwareBuffer::HBL_READ_ONLY)), x, y, rot, scale, alpha);

        pixelbuffer->unlock();
    }

    void CopyToBuffer()
    {
        HardwarePixelBufferSharedPtr
            pixelbuffer = textureptr->getBuffer();

        copy(buffer, stdext::make_checked_array_iterator<uint32 *>((uint32 *)pixelbuffer->lock(HardwareBuffer::HBL_DISCARD), width * height));

        pixelbuffer->unlock();
    }

    void Reset(uint32 color)
    {
        SetKernel(buffer, color);
    }
};

int32
    DynamicTexture::id = 0;

```

# main.cpp

```
void initScene()
{
    dynamictexture = new DynamicTexture(window->getWidth(), window->getHeight());

    TextureManager::getSingleton().load("minotaur.jpg", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TextureType::TEX_TYPE_2D, 0);
}

bool frameStarted(const FrameEvent &evt)
{
    static Real
        ang = 0.F;

    ang += 0.05F;

    if(ang > Math::TWO_PI)
    {
        ang = 0.F;
    }

    dynamictexture->Reset(0);
    dynamictexture->Texture(TextureManager::getSingleton().getByName("minotaur.jpg"), dynamictexture->width / 2, dynamictexture->height / 2, ang, 4.F, true);
    dynamictexture->CopyToBuffer();

    return true;
}

```

As you can see, the dynamic texture is the size of the window (which in this case is 800x600) and the minotaur.jpg is 84x84. I'm simply placing it at half the width and height (center), rotating it by ang (radians), and scaling it to 4x.

In the kernel itself, I simply followed a 2D rotation matrix (where x and y are offset by the parameters 'x' and 'y'):

```
x' = x cosθ - y sinθ
y' = x sinθ + y cosθ

```

Also note that idx\[1\] represents the x value in the array and idx\[0\] represents the y because it's arranged in the manner that `value = buffer[y + (x * height)]` (or something along those lines, but just know it's in the correct format).

Thanks for any and all help!

Regards, Tannz0rz

# Answer
> 0 votes
I found the solution thanks to this guy: https://sites.google.com/site/ofauckland/examples/rotating-pixels

```
const Real
    HALF_PI = Math::HALF_PI;
const int32
    cx = texture.extent[1] / 2,
    cy = texture.extent[0] / 2;

parallel_for_each(buffer.extent, [=, &buffer](index<2> idx) restrict(amp)
{
    int32
        tex_x = idx[1] - x,
        tex_y = idx[0] - y;
    Real
        dist = sqrt(Real((tex_x * tex_x) + (tex_y * tex_y))) / scale,
        theta = atan2(Real(tex_y), Real(tex_x)) - angle - HALF_PI;

    tex_x = int32(dist * sin(theta)) + cx;
    tex_y = int32(dist * cos(theta)) + cy;

    if(ValidTexCoord(tex_x, tex_y, texture.extent[1], texture.extent[0]))
    {
        buffer(idx) = texture(tex_y, tex_x);
    }
});

```

---
Tags: c++, textures, rotation, ogre, gpu
---


# Question
Title: Distance between two points with staggered isometric coordinate system
I don't think this exact question has been asked already (I've done a lot of searching but come up empty).. I am trying to work out what would be described as the 'L0 Tile' distance between two points in my game in tiles.

My coordinate system is as below:

And this is the effect I'm looking for when calculating distance from a central point:

The problem is I keep running into boundary conditions when trying to come up with a better solution than just 'walking' between the two positions and counting the steps.

The code I have at the moment only works if the direction between the two points is perfectly vertical, horizontal or diagonal:

```
if( fIsVertical )
{
    // Vertical distance calculation

    nDistance = nYDifferenceTiles / 2;

}
else if( fIsHorizontal )
{
    // Horizontal distance calculation

    nDistance = nXDifferenceTiles;
}
else
{
    // Diagonal distance calculation (slightly more headache-prone)

    bool fIsPerfectDiagonal = false;

    if( nYDifferenceTiles % 2 == 0 )
    {
        // Irrespective of W or E path these values are always the same

        if( nXDifferenceTiles * 2 == nYDifferenceTiles )
        {
            fIsPerfectDiagonal = true;
        }
    }
    else
    {
        // Values for X when Y is odd are slightly different..

        if( fNorthWestOrSouthWest )
        {
            // Handle the West paths
            if( nXDifferenceTiles == ( nYDifferenceTiles - std::floor( nYDifferenceTiles / 2.0 ) ) )
            {
                fIsPerfectDiagonal = true;
            }
        }
        else
        {
            // Handle the East paths
            if( nXDifferenceTiles == ( nYDifferenceTiles - std::ceil( nYDifferenceTiles / 2.0 ) ) )
            {
                fIsPerfectDiagonal = true;
            }
        }
    }

    // Now we've calculated whether we are on a perfect diagonal
    // line from the origin we can decide how to calculate the distance

    if( fIsPerfectDiagonal )
    {
        // If exact diagonal this works well
        nDistance = std::max< int >( nYDifferenceTiles, nXDifferenceTiles );
    }
    else
    {
       // ? - problem
    }
}

```

So in the diagram below, the green tiles are correctly calculated but for the red ones I have to fall back to my quick and nasty code to walk the distance.

Despite trying a good few things I'm still no closer to having a simple and quick way of calculating the distance. I'm sure this problem has to have been addressed before and that I'm missing something probably obvious. Please help! :)

# Answer
> 1 votes
Answering question to provide full solution building on the answer from AtkinsSJ (thanks a lot for the nudge in the right direction) to address a couple of edge cases.

```
if( fIsNorthOrSouthWest )
{
    // Special case when the second position is to the left of the first

    if( rPos1.m_y % 2 == 0 )
    {
        nDistance = static_cast< int >( std::floor( ( nYDifferenceTiles / 2.0 ) + nXDifferenceTiles ) );
    }
    else
    {
        nDistance = static_cast< int >( std::ceil( ( nYDifferenceTiles / 2.0 ) + nXDifferenceTiles ) );
    }
}
else
{
    if( rPos1.m_y % 2 == 0 )
    {
        nDistance = static_cast< int >( std::ceil( ( nYDifferenceTiles / 2.0 ) + nXDifferenceTiles ) );
    }
    else
    {
        nDistance = static_cast< int >( std::floor( ( nYDifferenceTiles / 2.0 ) + nXDifferenceTiles ) );
    }
}

```

# Answer
> 3 votes
Let xDiff be the difference between the x coordinates, and yDiff be the difference between the y coordinates.

The tile distance is ( yDiff/2 + xDiff ) rounded up to the nearest integer.

# Answer
> 0 votes
What about distance=*min*(dx,dy) ?

Assume the center (0,0) is cx,cy and x,y is the tile you want to test.

Then dx=cx-x and dy=cy-y.

# Answer
> 0 votes
You can declare a matrix witch contains each isometric cell, then calculate the distance between the two points in the matrix, just like this: dist=sqrt( ( (x1 - x2 ) * ( x1 - x2 ) ) + ( ( y1 - y2 ) * ( y1 - y2 ) ) )

...sorry for the spelling.

---
Tags: 2d, isometric, 2.5d
---


# Question
Title: How do I get the child of a unique parent in ActionScript?
My question is about targeting a child with a unique parent. For example. Let's say I have a box people can move called `box_mc` and 3 platforms it can jump on called:

* Platform\_1
* Platform\_2
* Platform\_3

All of these platforms have a child element called hit.

* Platform\_1
    + Hit
* Platform\_2
    + Hit
* Platform\_3
    + Hit

I use an array and a `for each` statement to detect if `box_mc` hits one of the platforms childs.

```
var obj_arr:Array = [Platform_1, Platform_2, Platform_3];
for each(obj in obj_arr){
   if(box_mc.hitTestObject(obj.hit)){
      trace(obj + " " + obj.hit);
      box_mc.y = obj.hit.y - box_mc.height;
   }
}

```

obj seems to output the unique parent it is hitting but obj.hit ouputs hit, so my theory is that it is applying the change of y to all the childs called hit in the stage. Would it be possible to only detect the child of that specific parent?

# Answer
> 1 votes
You should make use of the `hitArea` property of your platforms (AS3 docs).

So first make the `hit` children the hitArea of your platforms, like so:

```
var obj_arr:Array = [Platform_1, Platform_2, Platform_3];
for each(obj in obj_arr){
   obj.hitArea = obj.hit;
}

```

Then you can detect collisions with your platforms like so:

```
for each(obj in obj_arr){
   if(box_mc.hitTestObject(obj)){
      // collision occured
   }
}

```

The collision test will be between your `box_mc` and your platforms, but the shape of the `hit` object will be used as collision shape of your platform.

---
Tags: actionscript-3
---


# Question
Title: Path-finding with obstacles that can be destroyed
There are several buildings on the map with size n * n， and a lot of tiles of obstacles that can be destroyed. Suppose I put one soldier on (x,y) of the map, the soldier can reach a building by moving and destroying the obstacles. I need a way to figure out the best choice for the soldier and because there might be a lot of soldiers I hope this process can use as little computing resources as possible. I have come up with path finding and K-D tree finding the nearest neighbor, but neither fits well, since K-D tree works with no obstacles and path-finding needs to traverse a lot building. Besides, the destroying obstacles will affect those have made one path plan.

# Answer
> 5 votes
A\* and other standard path finding algorithms let you assign costs for each move. You simply need to assign an appropriate cost to destroying an obstacle that represents how long it would take to destroy it.

When an obstacle is destroyed, you may want to recalculate paths for all moving units, as they may now have a more efficient way to reach their destination.

---
Tags: ai, path-finding, maps
---


# Question
Title: Why do I get an error "exit() redefinition" while using OpenGL?
I am using Visual C++ 2010 and I get the following errors:

```
1>d:\visual c++\vc\include\stdlib.h(353): error C2381: 'exit' : redefinition; __declspec(noreturn) differs
1>d:\glut-3.7.6-bin\include\gl\glut.h(146) : see declaration of 'exit'

```

In my project I have 3 files. Here are the includes from each of them.

Main.cpp

```
#include<iostream>
#include "BmpLoader.h"
#include<glut.h>

```

BmpLoader.h

```
#include<stdio.h>
#include<glut.h>
#include<Windows.h>

```

BmpLoader.cpp

```
#include "BmpLoader.h"

```

As far as I know, I receive this error due to the include order. I have tried so far several arrangements of the includes, but haven't figured out the proper arrangement.

What library combination causes this error and what include order should I use in order to prevent it?

# Answer
> 4 votes
The problem is that `glut.h` defines a new `exit()` function, which overrides the one in `stdlib.h` (included by `Windows.h`). This problem has also been addressed on Stack Overflow here.

The solution is to include `Windows.h` *before* `glut.h`.

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


title: Simulating building stress

text:
# Question
Title: Simulating building stress
I need to simulate the effects of adding supporting materials to a building structure for a genetic algorithm in a block-based world. Essentially I am planning to use a genetic algorithm to optimise the viability of a structure for a game in Java.

I've tried looking around for examples of algorithms, but so far have only come up with JBullet. How would the stress be calculated from a list of materials and their properties?

# Answer
I imagine you're looking to do something like this (starting at 3:04)? From a game called StarForge.

Essentially, you need to simulate the basic forces of stress:

1. **Compression** \- Generally simulated by calculating the amount of force being applied to an object and its "squishy-ness". When the compression gets too high you can have materials crumble, crumple or shatter.
2. **Shear** \- This is a force across cross section. You can limit this to just a few pre-selected cross sections. This is the force that will cause objects to deform under stress (eventually breaking).
3. **Tension** \- Essentially the opposite of compression. This is measured by calculating the amount of force *pulling* on an object. So having an entire structure suspended by a single cube would cause that coupling to break.

All in all, this is going to be *very* math heavy and will likely take a lot of optimizations to get working in a performance friendly way. Calculating stresses like this in real time is a lot easier when you're just dealing with simple cubes, but it'll still be a challenge without a good amount of engineering knowledge.
> 1 votes

---
Tags: java, physics, algorithm, simulations
---


# Question
Title: Merging InputProcessor and GestureDetector
I'm planning to make a simple soccerball app. When I attempt to drag the ball, I use the **touchDragged()** from **InputProcessor** to move the ball left or right. Next, while holding before releasing, I use the **fling()** from the **GestureDetector** to set the power. However, when I'm trying to set the input processor of both the implementing **InputProcessor** and the **GestureDetector**, it didn't work. Moreover, whenever the last time you set the input processor and that would be either the two of them. Why?

# Answer
> 2 votes
To be clear, you're calling:

```
Gdx.input.setInputProcessor(processorX);

```

twice? It just sets a global variable, so that's why only one sticks.

To support multiple input processors simultaneously, you want an `InputMultiplexer`. You can add multiple `InputProcessor` instances to the multiplexer and it will pass events to them in the order the processors were registered.

However, I think you'll still run into problems because both of your input processors are trying to "eat" the same input events (touch events). One of them will consume the events, leaving the other with nothing. Unless you can separate where on the screen each input processor owns (e.g., if the power-setting is a separate area of the screen from the soccer ball). Or, you could build your own multiplexer that knows which "mode" the game is in, and forwards events to the appropriate input processor. Its hard to say without more concrete information about your system.

---
Tags: java, libgdx, input, gestures
---


# Question
Title: Incorrect colour blending when using a pixel shader with XNA
I'm using XNA 4.0 to create a 2D game and while implementing a layer tinting pixel shader I noticed that when the texture's alpha value is anything between 1 or 0 the end result is different than expected.

The tinting works from selecting a colour and setting the amount of tint. This is achieved via the shader which works out first the starting colour (for each r, g, b and a) :

```
float red = texCoord.r * vertexColour.r;

```

and then the final tinted colour :

```
output.r = red + (tintColour.r - red) * tintAmount;

```

The alpha value isn't tinted and is left as :

```
output.a = texCoord.a * vertexColour.a;

```

The picture in the link below shows different backdrops against an energy ball object where it's outer glow hasn't blended as I would like it to. The middle two are incorrect as the second non tinted one should not show a glow against a white BG and the third should be entirely invisible.

The blending function is NonPremultiplied.

Why the alpha value is interfering with the final colour?

# Answer
This is the best blend function I've found to achieve the results I wanted. I ended up rejigging the render function for the game so that each object can decide which BlendState it wants to use.

This is the BlendState I used, it's the same as NonPremultiplied except AlphaSourceBlend is changed from Blend.SourceAlpha to Blend.One:

```
BlendState alphaBlend = new BlendState()
{
    AlphaBlendFunction = BlendFunction.Add,
    AlphaSourceBlend = Blend.One,
    AlphaDestinationBlend = Blend.InverseSourceAlpha,

    ColorBlendFunction = BlendFunction.Add,
    ColorSourceBlend = Blend.SourceAlpha,
    ColorDestinationBlend = Blend.InverseSourceAlpha
};

```
> 1 votes

---
Tags: 2d, xna-4.0, fragment-shader, blending, alpha
---


# Question
Title: Pick and Drop the Ball Testing Without Replicating the Physics Frame
I am making a program that pick, drag, and drop the ball. In real life, once you pick the ball and drop it, whenever the available object is (what you see is what you get) will only be picked and dropped again and again. However, in the game program, there is something that at first you did pick and drop the ball. When you did the second time, something hit like some sort of an "invisible object" and the physics frame (in pink) is replicating while the frame in green is the wall and the floor. Take a look at these pictures.

***Before picking up and drop a ball for the first time...***

***When the ball in dropping... (Showing in pink frame for physics frame)***

***When picking up the second time, the previous pink physics frame did not come off and ended hitting something invisible.***

So tell me, did I made something wrong in this **touchDown()** code or not? I have observed something here after I run in debug mode.

```
@Override
public boolean touchDragged(int screenX, int screenY, int pointer)
{
    // TODO touchDragged

    float change_x = (Gdx.input.getX()/(cv.getPhysicsCamera().viewportWidth))*5000;
    float change_y = (Gdx.input.getY()/(cv.getPhysicsCamera().viewportHeight))*15;

    x = ((change_x/cv.getPhysicsCamera().viewportWidth)/2) - (rc.getSoccerBallWidth()/2);
    y = (((cv.getPhysicsCamera().viewportHeight) - (change_y/2)) - (rc.getSoccerBallWidth()/2));

    Vector3 touch_point = new Vector3(change_x, change_y, 0);
    cv.getPhysicsCamera().unproject(touch_point);

    // Set new body frame.
    ballDef.type = BodyType.DynamicBody;
    ballDef.position.set(x, y);

    ballBody = wc.getWorld().createBody(ballDef);
    ballBody.setActive(false); // --> Allows you to display a cursor for dragging without letting your soccer ball to fall off while holding.

    return true;
}

```

# Answer
Ideally, you'd assign your ball a physics body and update that instead of creating a new physics body every time the user picks up the ball.

E.g. call `wc.getWorld().createBody(ballDef);` only once when you init the game and only move it to the position of the ball.
> 2 votes

---
Tags: libgdx, physics
---