title: Indexed Drawing in OpenGL not working

text:
# Question
Title: Indexed Drawing in OpenGL not working
I am trying to render 2 types of primitives- \- points ( a Point Cloud ) \- triangles ( a Mesh )

I am rendering points simply without any index arrays and they are getting rendered fine. To render the meshes I am using indexed drawing with the face list array having the indices of the vertices to be rendered as Triangles. Vertices and their corresponding vertex colors are stored in their corresponding buffers. But the indexed drawing command do not draw anything.

The code is as follows-

Main Display Function:

```
    void display()
    {
        simple->enable();
        simple->bindUniform("MV",modelview);
        simple->bindUniform("P", projection);

        // rendering Point Cloud
        glBindVertexArray(vao);

        // Vertex buffer Point Cloud
        glBindBuffer(GL_ARRAY_BUFFER,vertexbuffer);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,0);

        // Color Buffer point Cloud
        glBindBuffer(GL_ARRAY_BUFFER,colorbuffer);
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,0,0);

        // Render Colored Point Cloud
        //glDrawArrays(GL_POINTS,0,model->vertexCount);

        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
        // ---------------- END---------------------//

        //// Floor Rendering
        glBindBuffer(GL_ARRAY_BUFFER,fl);
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,0);
        glVertexAttribPointer(1,4,GL_FLOAT,GL_FALSE,0,(void *)48);

        glDrawArrays(GL_QUADS,0,4);
        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
        // -----------------END---------------------//

        //Rendering the Meshes
        //////////// PART OF CODE THAT IS NOT DRAWING ANYTHING ////////////////////
        glBindVertexArray(vid);
        for(int i=0;i<NUM_MESHES;i++)
        {
            glBindBuffer(GL_ARRAY_BUFFER,mVertex[i]);
            glEnableVertexAttribArray(0);
            glEnableVertexAttribArray(1);
            glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,0);
            glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,0,(void *)(meshes[i]->vertexCount*sizeof(glm::vec3)));

            //glDrawArrays(GL_TRIANGLES,0,meshes[i]->vertexCount);
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mFace[i]);
            //cout<<gluErrorString(glGetError());
            glDrawElements(GL_TRIANGLES,meshes[i]->faceCount*3,GL_FLOAT,(void *)0);

            glDisableVertexAttribArray(0);
            glDisableVertexAttribArray(1);
        }

        glUseProgram(0);
        glutSwapBuffers();
        glutPostRedisplay();
    }

```

Point Cloud Buffer Allocation Initialization:

```
        void initGLPointCloud()
        {
            glGenBuffers(1,&vertexbuffer);
            glGenBuffers(1,&colorbuffer);
            glGenBuffers(1,&fl);
            //Populates the position buffer
            glBindBuffer(GL_ARRAY_BUFFER,vertexbuffer);
            glBufferData(GL_ARRAY_BUFFER, model->vertexCount * sizeof (glm::vec3),
                    &model->positions[0], GL_STATIC_DRAW);

            //Populates the color buffer
            glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
            glBufferData(GL_ARRAY_BUFFER, model->vertexCount * sizeof (glm::vec3),
                    &model->colors[0], GL_STATIC_DRAW);

            model->FreeMemory();    // To free the not needed memory, as the data has been already
                                    // copied on graphic card, and wont be used again.
            glBindBuffer(GL_ARRAY_BUFFER,0);
        }

```

Meshes Buffer Initialization:

```
        void initGLMeshes(int i)
        {
            glBindBuffer(GL_ARRAY_BUFFER,mVertex[i]);
            glBufferData(GL_ARRAY_BUFFER,meshes[i]->vertexCount*sizeof(glm::vec3)*2,NULL,GL_STATIC_DRAW);
            glBufferSubData(GL_ARRAY_BUFFER,0,meshes[i]->vertexCount*sizeof(glm::vec3),&meshes[i]->positions[0]);
            glBufferSubData(GL_ARRAY_BUFFER,meshes[i]->vertexCount*sizeof(glm::vec3),meshes[i]->vertexCount*sizeof(glm::vec3),&meshes[i]->colors[0]);
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mFace[i]);
            glBufferData(GL_ELEMENT_ARRAY_BUFFER,meshes[i]->faceCount*sizeof(glm::vec3),
                &meshes[i]->faces[0],GL_STATIC_DRAW);

            meshes[i]->FreeMemory();
            //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
        }

```

Initialize the Rendering, load and create shader and calls the mesh and PCD initializers.

```
void initRender()
{

            simple= new GLSLShader("shaders/simple.vert","shaders/simple.frag");

            //Point Cloud
            //Sets up VAO
            glGenVertexArrays(1, &vao);
            glBindVertexArray(vao);

            initGLPointCloud();

            //floorData
            glBindBuffer(GL_ARRAY_BUFFER, fl);
            glBufferData(GL_ARRAY_BUFFER, sizeof(floorData),
                    &floorData[0], GL_STATIC_DRAW);

            glBindBuffer(GL_ARRAY_BUFFER,0);

            glBindVertexArray(0);
            //Meshes
            for(int i=0;i<NUM_MESHES;i++)
            {
                if(i==0) // SET up the new vertex array state for indexed Drawing
                {
                    glGenVertexArrays(1, &vid);
                    glBindVertexArray(vid);
                    glGenBuffers(NUM_MESHES,mVertex);
                    glGenBuffers(NUM_MESHES,mColor);
                    glGenBuffers(NUM_MESHES,mFace);
                }
                initGLMeshes(i);
            }
            glEnable(GL_DEPTH_TEST);
        }

```

Any help would be much appreciated, I have been breaking my head on this problem since 3 days, and still it is unsolved.

# Answer
> 1 votes
Firstly, in your call to `glDrawElements` you pass `GL_FLOAT`. This should be one of `GL_UNSIGNED_BYTE`, `GL_UNSIGNED_SHORT`, or `GL_UNSIGNED_INT` (depending on the type of `faces`). I imagine you would get an `GL_INVALID_ENUM` returned from `glGetError`.

Secondly, in the line:

```
glBufferData(GL_ELEMENT_ARRAY_BUFFER,meshes[i]->faceCount*sizeof(glm::vec3),
             &meshes[i]->faces[0],GL_STATIC_DRAW);

```

The second parameter should be: `meshes[i]->faceCount*3*sizeof(IndexType)` (where `IndexType` is whatever you have declared `faces` as.

Generally it is a good idea to check `glGetError` after more or less every GL call. You can do this using a macro that logs any errors in debug mode, but does nothing in release mode.

---
Tags: opengl
---


# Question
Title: How to be sure that a target goal in a match 3 game level will not be impossible?
This is clearly not a coding problem but the logical one. I am starting to learn how to make a match 3 game. but there is a question rising in my mind.

when i will set goal to complete the level, how will i know the goal is achievable ?

suppose in a level where i have to collect 5 Red, 12 blue, 9 green objects by matching the same(like farm heros). how would i decide how much moves i need to set to make this goal achievable. i mean it should be challenging but not be impossible.

since the objects spawn in a random whats the surety that there will be enough number of gem in the game to not make impossible.

is there some logical explanation for this, or i just have to test and look out how many moves it takes to achieve the goal.

Is there an algorithm which generates the gems according to target set, or they are generated in random manner?

To be more clear towards my question i am going to take an example of King.com's farm-heros-saga .

In level 9 the target is to collect number of four types of objects 26,26,14,5 respectively. and the maximum number of moves are 22.

now this goal may be achievable and challenging(i mean you can achieve it in two or three trials ) but not impossible.

Now my question is what made those guys so sure that it will not be impossible, how they decided that 22 move will be enough and challenging.

well.. they could have put the maximum number of moves to 5 or 6. but that would surely make it impossible to clear the level. so how they decided to keep move 22 or this.

Are they using static pattern to generate and spawn objects, or ratio of collectible gems is fixed(i.e in total gameplay there will be X%,Y%,Z%,M% of gems respectively ), or there is some other way. I just need some hint what should i look for..

# Answer
> 1 votes
Depending on which random number generator you are using, you should be able to specify a "salt" value. This enables you to generate the same series of gems every time (although they are still random). If you do it this way, you can then run the level lots of times and work out how many moves it should take.

# Answer
> 2 votes
A good algorithm to generate any kind of solvable puzzle is to first generate a solved configuration of the puzzle, and then backtrack a number of valid moves which would lead to this configuration. You can easily control the difficulty by how many moves you perform and you have a valid solution to it. However, keep in mind that there could always be a faster solution than what you generated.

---
Tags: unity, level-design, unityscript, puzzle
---


# Question
Title: different Scenes but each of them loads per frame
well i want to have something like restaurant that divided in 3 sections.and the user can switch between these but every Scene loads every frame.for example the character is in the first section and the player goes to second section and touch a customer and the character starts to go to the second section or have a button for kitchen but when the character goes to kitchen the costumers still load.i don't think that `Application.LoadLevel ();` could help. thanks.

# Answer
> 1 votes
Look at `Application.LoadLevelAdditive`, you can load the scene in parts.

A good idea might be to disable whole sections of the scene that you are not in. For example group the whole scene in one parent gameobject and disable that, or perhaps use a tag for this. You could also use layers, but they're a bit tricky.

# Answer
> 0 votes
If you don't want to use separate levels, you will need to put all of your logic on the same "level" but in different places (within the scene). Then move the camera so that only the things you want to see are visible.

---
Tags: unity, unityscript, scene
---


# Question
Title: Can I use an AI engine written in C++ in my Unity game? If yes, how can I do this?
I am studying some chess and others AI algorithms and the majority of these implementations are made in C and C++, my question is, if I make a chess board and all the graphic thing in Unity, can I make it run with my algorithm written in C++? And how can I make this interface?

Sorry if is it a noob question, I'm just starting at this whole gamedev world.

# Answer
It might be silly, but you could make a small C++ program around the chess library, that takes a simple text board state or movelist as input and returns the AI's selected move. I don't know .net's system libraries off hand, but you can probably start it as a subprocess, send to its stdin and then poll its stdout for a reply. Local sockets are also a possibility..
> 6 votes

# Answer
There are a variety of ways to run code written in other languages in Unity. Most of these are platform specific.

iOS: Since xCode will also compile C++ code, you could add the C++ code to the plugins directory and it will be built when you build the iOS app. You'd then define the function prototypes in C# so they are accessible from Unity. Documentation is here.

The official documentation for a variety of platforms is covered here.
> 3 votes

---
Tags: c++, unity, algorithm, chess
---


title: OnCollisionEnter2D not being called

text:
# Question
Title: OnCollisionEnter2D not being called
I'm fairly new to the world of Unity, and am adding collision detection for the first time through RigidBody2D (as this game is 2D). First of all, here is some relevant information:

* **Unity Version:** 4.2.5f
* **Operating System:** Windows 8.1 Update 1

# The Problem

I have two objects that could collide, let's call one `Bullet` and one `Enemy`. Both `Bullet` and `Enemy` have `RigidBody2D` components attached to them, as well as the following method in an attached script:

```
void OnCollisionEnter2D(Collision2D collision){
    print("Hit!");
}

```

However, nothing is printed to the console (I have checked that `print` works in other situations).

# The Question

What is going wrong here? I must be missing something simple. I have checked that Physics 2D has collisions enabled between layers, I have tried the 3D equivalent to this and still no joy.

# Additional Info

# Answer
> 3 votes
You need to add a `BoxCollider2D` component to your `GameObject`s.

http://docs.unity3d.com/ScriptReference/BoxCollider2D.html

From the Unity docs for `OnCollisionEnter2D`

> Sent when an incoming collider makes contact with this object's collider

A `Rigidbody2D` just tells a GameObject how to interact with the physics engine. It doesn't provide a collider for collision.

From the Unity docs for `RigidBody2D`

> By adding the appropriate collider component, the sprite will also respond to collisions with other sprites.

# Answer
> 0 votes
The problem could be either:

1. You've not marked your moving rigidbody with the right collision detection method. You need continious dynamic rather than discrete if you are moving your object with speed.
2. Are both rigidbodies marked as kinematic? If so the event won't call.

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


# Question
Title: What types of matrices are needed for game and graphics programming?
I am writing a 3D math library for general game development and want to know what type of matrix classes I should include. Is just a 4x4 matrix enough, or must I provide 3x4 and dedicated rotational matrices?

According to this

> In order to use the vector registers of modern CPUs (SSE, Altivec, SPUs) you have to pass 4x 32 bit floats anyway (its a 128 bit register), plus you have to take care of the alignment, usually 16 bytes. So you don't have the chance to safe the space for the 4th component anyway.

and from Game Engine Architecture

> The rightmost column of an aﬃ ne 4 × 4 matrix always contains the vector \[ 0 0 0 1 \]T . As such, game programmers oft en omit the fourth column to save memory. You’ll encounter 4 × 3 aﬃne matrices frequently in game math libraries.

Since 4x3 matrices are just created for convenience and since you need 128 bits to use the vector register, would it be best to just have a single 4x4 matrix class handle all needed matrix operations?

# Answer
Everything is an optimization of the 4x4 matrix when it comes to 3D math. A 3x4 is about saving memory because the last column/row for non-projection matrices is \[ 0 0 0 1 \]. Pure rotational 3x3 matrices are extremely convenient because you can invert them by just transposing them.

For animation and camera systems, quaternions are ideal for lots of reason, and they are essentially just 4-vectors.

There are similar trade-offs with Vector2, Vector3, and Vector4 types.

If you are working on Microsoft platforms at all, take a look at DirectXMath and SimpleMath.

BTW, if you are writing a 3D math library as an educational exercise, that's great. If you are writing it for production use, consider not doing that and using something that already exists. Math libraries are a dime-a-dozen and they are often terrible in terms of performance. Some games end up shipping with 5 different math libraries being used at once, and they are not particularly efficient when used that way.

RE: Updated questions about 128-bit registers

DirectXMath's design, for example, is intended to address this. The 'work-horse' types are XMVECTOR which is always a 4-vector, and XMMATRIX which is always a 4x4 matrix, both of which directly map to SIMD registers on the platform. However, there are a rich set of types for use in data-structures including XMFLOAT2, XMFLOAT3, XMFLOAT4, XMFLOAT3X3, XMFLOAT4X4, XMFLOAT4X3, etc. to facilitate the right trade-offs in storing the data in memory, serializing it from disk, etc. So yes, when the computations are actively going on, you are dealing with 4x4 matrices, but it's not a particularly efficient way to store say 10,000 animation key-frames in memory across an entire game.
> 2 votes

---
Tags: architecture, matrix
---


# Question
Title: HTML5 canvas multiplayer game with node.js and Isogenic engine
I want to create a multiplayer game using Isogenic engine i understand that this technology uses html5 and canvas for rendering graphics in frontend and node.js for backend. I started working on how the game should work and what i need to accomplish what i want. I understand that node.js goes well with noSQL dbs. My question is what should i use SQL or noSQL for the game?

Game will be multiplayer RPG with heavy accent on chatting feature, so i have many thing to store. But i cant figure out which one should i choose. What would be benefits of choosing eather? Maybe i should think about other solution? Any tips would be much appreciated. :)

EDIT: What i actually meant was, can mongoDB store user personal data, like passwords, emails. Is there security issues? Because i know node.js is not the best for communicating with relation databases.

# Answer
> 0 votes
(Answer to the more clarified question in your edit)

MongoDB is perfectly suitable for storing user data, such as emails and passwords. As long as you are taking all the same precautions you'd use for an SQL database (hashing passwords and such,) there should be no additional security issues.

---
Tags: multiplayer, rpg, databases, node.js
---


# Question
Title: Can a sprite(batch) have multiple "costumes" monogame
I am relatively new to game development and would like to know if a sprite can have multiple "costumes" similar to that of MIT's scratch or do I need a different sprite for each costume

# Answer
> 1 votes
You can easily change the texture of something. With something like this

```
myTexture = Content.Load<Texture2D>("filename"); // load the texture

```

Then you can draw it in your draw method with this

```
spriteBatch.Draw(myTexture, Vector2.Zero, Color.White); // draw the texture

```

There is no such thing as a costume in monogame, they are just textures. The workflow in monogame is very different than scratch because there is no built in 'sprite'. You could create a sprite class if you wanted to, but is optional, and you should only do it if you have a good understanding of OOP.

```
class Sprite()
{
    public Texture2D Texture { get; set; }
    public Vector2 Position { get; set;}
} // you can edit this class to be more complex with other properties and methods

```

Then initialize you sprite in you Game1.cs

```
Sprite mySprite = new Sprite();

```

Load your sprite's texture like you would a normal texture in your LoadContent method

```
mySprite.Texture = Content.Load<Texture2D>("filename");

```

And draw your sprite in your draw method

```
spriteBatch.Draw(mySprite.Texture, mySprite.Position, Color.White);

```

---
Tags: monogame
---


# Question
Title: How can I implement a more realistic momentum system in Unity 4.5?
I'm just starting out with Unity and am making a simple environment where there is a sphere and a ramp. When the sphere approaches the ramp everything is fine. As soon as the sphere hits the ramp is where I'm having trouble; the velocity is instantly reduced and when it goes off the end of the ramp, instantly returns to the velocity as though it were on the ground.

I'm not sure if this can be changed by some settings in Unity or I would have to write some code.

Here's the physics code I have so far (in C#):

```
public class PlayerController : MonoBehaviour {
    public float speed;

    void FixedUpdate(){
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        rigidbody.AddForce(movement * speed * Time.deltaTime);
    }
}

```

# Answer
for each object with a `Physics RigidBody` component you can check the Component options in the inspector... and iirc there will be check boxes and input fields to allow you to modify these values directly from the gui (`Gravity Scale, Angular Drag, Drag, etc...`). but if you check the documentation, all of those values also represent properties of that RigidBody component.

so in theory you could grab the RigidBody of your sphere at runtime, and set the `Kinematic` property to false (stoping it from responding to physics temporarily), something like this in C#:

```
 // if you need to grab the component from another object
 sphere.GetComponent<RigidBody>().isKinematic = false;

 // or the way you have it written above is fine if this script is attached to your sphere
 rigidBody.isKinematic = false;

```

then you possibility could perform your own position calculations and when your done turn the physics back on

check out the docs here:

http://docs.unity3d.com/ScriptReference/Rigidbody-isKinematic.html
> 1 votes

---
Tags: unity, physics
---


# Question
Title: What is the optimal way to handle internal matrix data storage for interop with native graphics APIs?
I'm writing a managed (c#) game engine and have stumbled on a bit of a crossroads in design/implementation regarding matrix types.

Matrix types need to be optimized for marshaling to native graphics api wrappers and shader compilers, etc and after viewing the way this is handled in various projects, I'm having a hard time deciding which route would be the optimal way to go.

The problem really arises with the internal storage of matrix data.

SharpDX (a very high quality managed DirectX wrapper) does so by explicitly defining each component as public fields such as:

```
public float M00, M01, M02, M03;
public float M10, M11, M12, M13;
public float M20, M21, M22, M23;

```

I'm assuming that this was done to simplify marshaling and also for faster access to fields during math operations and allows the type to be defined as a structure to be a true value type.

In Math.NET they store the internal representation as a one-dimensional array which still allows for rather simple marshaling but the definition becomes a reference type (class) using value-type semantics.

I also seen another implementation using a multi-dimensional array for the internal storage of data which makes performing operations on the field data more natural by using indexing by row and column but this would add overhead and would make marshaling a bit trickier due to the nature of interop with multi-dimensional arrays.

The SharpDX way seems ideal, as it makes the matrix types blittable and seems like it would be faster, however, being a value type would make it have a larger footprint (which I'm assuming is why most operations defined in SharpDX matrices have both pass-by-value and pass-by-ref functions defined).

In that light, it makes sense to define my matrix types as reference types so that only references are being passed, but then that makes interop a bit more challenging.

Being for a game engine, performance and memory footprint take priority over elegance though, so am I right in assuming SharpDX's approach would be best for my scenario?

# Answer
> 1 votes
I posted recently a response to a similar question https://stackoverflow.com/questions/24231389/struct-or-class-for-matrix-4x4-object

Basically valuetypes are the way to go for storing matrices, more benefits than downsides. You may also organize a matrix to be more GPU friendly by transposing the fields directly into the matrix struct (SharpDX is not doing this requiring a transpose of the final result before uploading it to the GPU) as HLSL matrix packing order is by default column major.

---
Tags: c#, graphics, optimization
---


title: cost of texture change vs color change

text:
# Question
Title: cost of texture change vs color change
How would I go about determining the difference in cost between changing the render color of an object every frame vice changing the texture (same sheet, just changing the source rectangle) every frame?

I ask because right now i'm changing the alpha every frame on about 300-400 objects, and i'm wondering if it isn't cheaper to just simulate that with a couple of frames and cycling through them.

# Answer
> 2 votes
i do believe changing the color would be much less resource intensive, however the performance depends more on the number of different textures used.

check out this article for a few good bits of ingenuity when it comes to managing textures and performance

http://www.gamasutra.com/view/feature/131768/understanding\_and\_using\_opengl\_.php?print=1

my take aways were pretty obvious:

* to get best performance load your textures from the disk to memory into objects once, then access them
* you may see performance increase (hardware dependent) by sorting those objects to draw all similar textured objects together.

as long as your only loading the `X textures` once and not `X textures` once for each `N objects` i think your test should prove worth while.

---
Tags: opengl, textures, sprites, rendering, color
---


# Question
Title: Rotating a vector around a vector in 3D space
I am trying to rotate a moon around a planet (the planet is also rotating around an axis) but I am having trouble doing so.

I tried to make the model move through space like so:

```
@Override
public void render() {
moon.getInstance().transform.setToTranslation(moon.center.x + 0.5f, moon.center.y + 0.5f, moon.center.z);
}

```

I know that this wil not give me the correct (or indeed any) rotation, but the model doesn't even move. When I use `moon.getInstance().transform.setToRotation(1f, 0, 0, 10f)` it does rotate (around its axis) so I assumed that I could use `.setToTranslation` the same way.

So, my question is actually two questions:

1. How can I move a model in 3D space
2. How can I let it move around a certain vector, following a circular path

# Answer
Short answer: by smart compositing rotation and translation. In the image below you can see the process (radius r is distance of your planet from star).

* If you rotate the moon by rot\_m degrees(updated in main loop), it will circle the origin point.
* If you first rotate and then translate by radius *r* it will circle in right distance but wont follow your target planet.
* If you both rotate and translate and *then* rotate again by same angle as your planet, it will circle both the planet and the origin point appearing it circles your planet. I also strongly advise you not-to use relative transformations unless you really need it (speed vector) so you can keep track where those objects are and update rotation angle in Update() function (probably setTo... in your library).

Then, you can move whole system in your world as you see fit. In pseudo code:

```
struct System
{
   Moon moon; //or array if you got more
   Planet planet
   void Translate(vec3 tranlastion);
} Earth;
void System::Translate(vec3 tranlastion)
{ /*translate all componenets of the system if you want to move it!*/}

```

in draw() method:

```
Earth.moon.Rotate(Earth.moon.rotation, 0.f, 1.f, 0.f) //or any other axis
Earth.moon.Translate(Earth.planet.distance_from_sun, 0.f, 0.f);
Earth.moon.Rotate(Earth.planet.rotation,0.f, 1.f, 0.f);
//you should understand how to transform planet and system correctly by now

```

int Update() method:

```
Earth.moon.rotation += deltaRot_m;
Earth.moon.rotation %= 360;
Earth.planet.rotation += deltaRot_p;
Earth.planet.rotation %= 360;

```
> 1 votes

---
Tags: mathematics, libgdx, rotation, vector
---


# Question
Title: Two pass blur shader using libgdx tile map renderer
I am trying to apply the following technique: blur effect using two pass shader to my libgdx game using the **OrthogonalTiledMapRenderer**. The idea is to blur the background wich is also a tilemap but rendered with another camera with a different zoom applied.

Here is a screen capture without effect:

Using the OrthogonalTiledMapRenderer sprite batch like this:

```
backgroundMapRenderer.getSpriteBatch().setShader(shaderBlurX);
backgroundMapRenderer.render(layerBackground);

```

I get the following render:

Wich is ok for X blur pass. I then try using frame buffer object like in this example. But the effect seems to be too much zoomed:

I may be messing up with the camera and the zoom factor. Here is the code:

```
    private ShaderProgram shaderBlurX;
    private ShaderProgram shaderBlurY;

    private int FBO_SIZE = 800;
    private FrameBuffer targetA;
    private FrameBuffer targetB;

```

---

```
    targetA = new FrameBuffer(Pixmap.Format.RGBA8888, FBO_SIZE, FBO_SIZE, false);
    targetB = new FrameBuffer(Pixmap.Format.RGBA8888, FBO_SIZE, FBO_SIZE, false);

```

---

```
    targetA.begin();
    Gdx.gl.glClearColor(1, 1, 1, 0);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    backgroundMapRenderer.render(layerBackground);
    targetA.end();

    targetB.begin();
    Gdx.gl.glClearColor(1, 1, 1, 0);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    backgroundMapRenderer.getSpriteBatch().setShader(shaderBlurX);
    backgroundMapRenderer.render(layerBackground);
    targetB.end();

    TextureRegion back = new TextureRegion(targetB.getColorBufferTexture());
    back.flip(false, true);

    backgroundMapRenderer.getSpriteBatch()
        .setProjectionMatrix(backgroundCamera.combined);
    backgroundMapRenderer.getSpriteBatch().setShader(shaderBlurY);
    backgroundMapRenderer.getSpriteBatch().begin();
    backgroundMapRenderer.getSpriteBatch().draw(back, 0, 0);
    backgroundMapRenderer.getSpriteBatch().end();

```

I know I am making something the wrong way, but I can't find any resources about applying two passes shader using tile map renderer.

Does someone know how to achieve this?

# Answer
> 1 votes
I've been facing a similar problem recently and all was a matter of 'world' units vs pixel units.

Which units are you using for the camera and/or viewport? In case you defined such dimensions with 'world' units you should draw your *back* TextureRegion specifing the corresponding size in 'world' units.

```
backgroundMapRenderer.getSpriteBatch().draw(back, 0, 0, SCREEN_WIDTH_IN_WORLD_UNITS, SCREEN_HEIGHT_IN_WORLD_UNITS);

```

---
Tags: libgdx, tilemap, fragment-shader, blur
---


# Question
Title: 'Resetting' Google Play Games Services so app forgets it previously connected (so it shows confirmation screen again)
When I first integrated Google Play Games Services into my app, it came up with a 'confirmation screen', something like:

***App Name* wants to connect to Google Play Game Services**

I don't recall the exact wording.

While Alpha testing my app, one of my users has discovered a potential issue where he presses 'cancel' at that point instead of connecting. I would like to try to resolve this issue, but I can't recreate it because I can't work out how I can get that confirmation screen again!

I have implemented a 'log out' button in my app and that works, but when subsequently connecting, it just goes ahead without displaying the confirmation screen again. Any ideas how I can force that screen to show again for testing?!

# Answer
> 5 votes
Follow these steps to "deauthorize" an app with G+ sign-in:

1. Open the `Google Settings` app on your device.
2. Next select the `Connected apps` option.
3. Find your app in the list and select it.
4. Finally click the `Disconnect` button.

A confirmation/warning will be displayed. Note that it says it can take up to an hour for the process to be completed.

After doing this your next sign-in attempt should re-request access for G+ sign-in.

Edit (screenshot of Google Settings):

---
Tags: android, google-play, google-play-services
---


title: What's this draw function doing?

text:
# Question
Title: What's this draw function doing?
Can someone please explain whats going on in this code written by Paul Irish?

I did not understand the draw().

```
function draw() {

    var time = new Date().getTime() * 0.002;
    var x = Math.sin( time ) * 192 + 256;
    var y = Math.cos( time * 0.9 ) * 192 + 256;
    toggle = !toggle;

    context.fillStyle = toggle ? 'rgb(200,200,20)' :  'rgb(20,20,200)';
    context.beginPath();
    context.arc( x, y, 10, 0, Math.PI * 2, false );
    context.closePath();
    context.fill();

}

```

# Answer
I will explain it line by line:

```
var time = new Date().getTime() * 0.002;

```

`new Date().getTime()` returns the current time in milliseconds (1 second = 1000 milliseconds). This is multiplied by 0.002 to scale the time -- slow it down, in this case.

```
var x = Math.sin( time ) * 192 + 256;

```

Scaling down the time is important, because it is used in this calculation as an angle. If it changes too fast, the angle will change too fast, too (wrapping around at 2pi, i.e. every ~6ms in real time, or every ~3s in scaled time). Therefore, the individual circles would be drawn far away from each other if the time would not have been scaled.

`Math.sin(time)` returns the sine for the given angle, i.e. a value in range `[-1;1]`, changing continuously over time. This value is multiplied by 192, so that the result is in range `[-192;192]`. Adding 256 yields `[64;448]`. Therefore, the x coordinate for this circle will change infinitely over time from 64 to 448 to 64..., following the sine curve.

```
var y = Math.cos( time * 0.9 ) * 192 + 256;

```

Here, the time is scaled some more, so that the circles are vertically closer together. Except that, the computation is analog to that from above, but this time the cosine curve is used, which only changes the starting value of the y coordinate relative to the starting value of the x coordinate (you will get a very similar result using sine here, too).

```
toggle = !toggle;

```

This toggles a boolean every time the function is called.

```
context.fillStyle = toggle ? 'rgb(200,200,20)' :  'rgb(20,20,200)';

```

The drawing color is determined by checking that boolean. Therefore, blue and yellow circles are drawn in succession.

```
context.beginPath();
context.arc( x, y, 10, 0, Math.PI * 2, false );
context.closePath();
context.fill();

```

Finally, this is the drawing code, using all the computed values.
> 4 votes

---
Tags: 2d, mathematics, javascript
---


title: AddRelativeForce not working correctly

text:
# Question
Title: AddRelativeForce not working correctly
I am stuck on the code for couple of days but couldn't figure it out. Therefore I turned out to look the answer here but couldn't find any that match the requirement Hope some One might help

here is the code

```
/*  Part1
 *Step Horizontal Movement
 * Use to get left and right movement
 */
if(Input.GetKey ("right")||Input.GetKey ("left")){
    moveDir.x = Input.GetAxis("Horizontal"); // get result of AD keys in X
}
rigidbody.velocity = moveDir * speed;

/*Part2
 *Continuse Forward Movement
 */
if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
{
    moveDir.z = Input.GetAxis("Vertical");
    rigidbody.AddRelativeForce(moveDir*50);
}

```

I have a Cube with added rigidBody Component. When pressed left or right key the cube should move in that direction and when key is released it should stop Part one when run commenting part2 code runs correctly

the other movement that I am trying to achieve is the cube should move continuously.But the thing is when pressed up key it should increase the magnitude and when released it should maintain the magnitude and move constantly.This is also achieved successfull with the part2 code by commenting part1 code But when but run without commenting any of them part1 results are correct but part2 does not provide correct result which was obtained by commenting part1 code

Is there any other way to obtain the same reult

# Answer
> 1 votes
Your primary problem is when you modify the velocity directly:

```
rigidbody.velocity = moveDir * speed;

```

Here, your `moveDir` variable is only getting its `x` value set, so the `z` value is zero. That means that whatever you did to change the velocity later on in the code, gets erased the very next frame when you use the above line of code.

You can either not alter the velocity directly, by using forces to move left/right, or you can make sure you include the existing forward velocity when changing the left/right velocity. Something like:

```
Vector3 newVelocity = moveDir * speed;
newVelocity.z = rigidBody.velocity.z;
rigidbody.velocity = newVelocity;

```

---
Tags: unity, physics, rigid-body-dynamics
---


title: How are grids made?

text:
# Question
Title: How are grids made?
I've been looking at tutorials and researching forums and such but I still can't understand how the grids are made. I get confused at parts like this.

```
for (int x = 0; x < Size.x; x++) {
   for (int z = 0; z< Size.z; z++) {
        Instantiate(PlatPrefab, new Vector3(x+platX,platY,z+playZ), Quaternion.identity);
    }
 }

```

i get confused at the `for` stuff that I see in a lot of grid code. Basically I just want to know how grids are made in a proper code example in c# and how the code itself works not just how to write it. The type of grid would be in 3d.

# Answer
You likely want to start with something simpler than creating a game if you get stuck at `for` loops. Here's the basic idea for creating a grid, you pretty much have everything you need.

```
for (int x = 0; x < 8; x++) {
   for (int z = 0; z < 8; z++) {
        Instantiate(SquareObject, new Vector3(x,0,z), Quaternion.identity);
    }
 }

```

This is a nested loop example. When looking at a grid, imagine you want to place something inside each square. An algorithm for making sure you touch each square would be similar to the above. You can think of `x` as a column position and think of `y` as a row position. That means for any `x`, `y` pair, you have the coordinates of a grid location. For example, the very bottom left square in a grid would be x:0, y:0. The one to the right of that would be x:1, y:0. Like so:

The nested `for` loops are going to iterate through and give you each pair of `x` and `y` coordinates possible. This gives you the position of every square inside the grid.

Now that we're getting every position, we can do something with it. That's what the `Instantiate` call is doing. It's creating an object at each grid position. In this case, it's placing a prefab called `SquareObject`. It's setting the position of the object with: `new Vector3(x,0,z)`. As the image shows above, those position spaced in a grid fashion.
> 4 votes

---
Tags: c#, unity, grid
---


# Question
Title: How do commercial games engines organise the index/vertex buffers?
Preface: This question is going to be coming from a Direct3D point-of-view, because that's what I'm familiar with.

Obviously we incur a slight overhead every time we change the vertex or index buffers in Direct3D (i.e. with `IASetIndexBuffer`). But I suppose if we allocate one giant index/vertex buffer we'll end up having to manage the memory manually, and sort of end up with a fragmentation problem (or pauses while we swap all the data around).

So how do commercial engines load/unload data? I'm sort of leaning towards a 'package' based approach, so a 'package' of models has its own vertex/index buffer that we can load/unload as the package is no longer needed; and then try to draw all instances from the same package together.

But I'd be interested to hear what the accepted/standard way of handling this is?

# Answer
There are a number of different techniques for organizing the data, and many games use a mix of them.

For static geometry, it's best to have fewer individual IBs and VBs.

Traditionally games are 'level' based which means the assets for a section of play are loaded and then the game play begins. To minimize load-times, the information is ideally organized to support this (i.e. load everything for the level as fast as possible without seeking around on the media/disk), possibly replicating information between levels. In this approach, one scheme is to have a large VB and IB for a model or a series of models, and then submit subsets from that to draw.

For the Xbox 360 / PS 3 generation, the amount of RAM was quite small relative to the size of the games, so engines became 'streaming' oriented which means they load content dynamically as the player moves through them. This is also called an 'open-world' approach. In this approach, the challenge is 'chunking' the geometry into bits you can load based on spatial hints. Another challenge particularly for 32-bit platforms is ensuring that memory doesn't become fragmented (or even virtual address space fragmentation) over a long period of time--level-based games often reset memory between levels, something streaming engines can't do as easily. Therefore, packing into a fixed size or set of fixed sizes for the IBs/VBs which were allocated and reused as a pool is helpful.

For the Xbox One / PS 4 generation, there's a lot of RAM to work with relative to earlier consoles, and a lot of extra cores, so many games are aggressively compressing their assets and then using "extra" CPU cores to decompress them in the background. With 64-bit virtual address space, there is less concern about virtual address space fragmentation. This approach keeps load times low, packs assets well for digital download, and supports ‘open-world’ rendering. Here the pool approach to managing IBs/VBs is used.

There is also dynamic geometry submission which is often used for terrains, deformable/destructible models, etc. It is not an efficient in terms of GPU bus bandwidth, so games often have a mix of both static and dynamic geometry. In this case, the Direct3D Map DISCARD update pattern typically means you are only using a single IB/VB (or for multithreaded rendering scenarios, dual IB/VB which you swap filling/rendering each frame).
> 15 votes

---
Tags: directx, vertex-buffer, index-buffer
---


title: Loading and storing content efficiently

text:
# Question
Title: Loading and storing content efficiently
So for example I have a class called `TypingKeyboard`. It allows you to display a string while it's being typed by the computer with sounds. I need one in the menu, for the title. And one for the credits, and some in-game. So loading every sound and storing it to the RAM for every instance of `TypingKeyboard` is not very efficient.

So, I want to make a class that already holds these sounds, then call it when I need it, so I don't have to load everything.

How do I design this? I mean, how do you get these sounds loading and then make them accessible without initializing a class for it?

# Answer
Game assets like sounds are usually best managed if preloaded in advance. You don't want the user to experience a delay in the sound effects every time a sound has to be loaded.

You should implement a `ResourceCache` helper that manages game resources for you. Then things like sounds could be preloaded at each level start and unloaded when the level ends. This is a very good approach if your game is not huge.

```
// This class will probably be a singleton, so I made the methods 'static'.
class ResourceCache {

    // Call when level loads
    public static void PreloadResource(string resourceName);

    // Call when level ends
    public static void UnloadAllResources();

    // Find a previously loaded resource
    public static Resource FindResourceByName(string resourceName);
}

```

Then in the level load section:

```
void LoadLevel()
{
    ResourceCache.PreloadResource("foo.mp3");
    ResourceCache.PreloadResource("bar.mp3");
    ...
}

```

Now anywhere in the game, you can:

```
// No loading is done, just a cache/map lookup.
// "bar.mp3" was loaded at level start by PreloadResource().
Resource barSound = ResourceCache.FindResourceByName("bar.mp3");

```

And when a level ends, you can clear the resource cache:

```
ResourceCache.UnloadAllResources();

```

The cache should eventually use some management policy like LRU to handle scenarios when you want to load more data than what can fit into memory. Then the cache can evict old resources to make room for new ones. If you have the cache interface in place, adding a "real" caching scheme becomes very easy.
> 3 votes

# Answer
What you are looking for is the Object Pool pattern which provides reusability and efficient memory usage. At the initialization level of the application, you simply create the instance and give it to the object pool. When you need to use it, pop it from the pool and send it back to the pool after you finish. In this way, you don't have to instantiate a new component.

The object pool may be a static class which holds unique id's for each kind of reusable component. So, in order to pop a sound from the pool, you just call Pool.getObjectById(SoundType.Type).
> 0 votes

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


title: Questions about the obj file format

text:
# Question
Title: Questions about the obj file format
I'm wirting my first OpenGL Application for Android at the moment and now I get stuck on the ObjectLoader for obj files. I have some qestions to this file format and I can't an answer on the internet for this. Maybe it is easier if we go throught all these questions with an example file:

```
#Cube file - has no texture
mtllib dice_material.mtl

v 0.475013 0.999999 -0.066651    # 1
v 0.457026 0.999999 -0.067220    # 2
v 0.439582 0.999999 -0.067505    # 3
...
vn 0.000000 1.000000 0.000000    # 1
vn 0.000000 0.999969 0.000000
vn 0.000000 0.778466 0.627674
...
f 1//1 11//1 14//1 2//1          # the first 1 references to the first v right?
f 2//1 14//1 15//1 3//1          # the first 2 references to the second v right?
f 3//1 15//1 16//1 4//1

```
* Can I assume that allways the verticies v are on the head of the document (after some comments) followed by the texture coordinates (tv) and the normales (vn)?
* If an object has a texture does the obj file allways have the texture coordinates? If not how can I calculate them on my own?
* If the object has a texture is it required that the object has a material too or can an object have a texture without a material?
* If the file contains the texture coordinates do the polygons (f) must contain the texture coordinates? Or is `f 1//1` a valid polygon too if the file contains the texture coordinates?

# Answer
1: Im not 100% sure, but those 3d-softwares i know WILL write all the vertices before the faces

2: No not everytime and you cant calculate them

Edit: Of course, if it has a texture it will have texture-coordinates (if your 3d-modeling-software doesnt suck :D )

3: You cant put an texture directly on the mesh, you can only put an material on the mesh which itself uses an material, so there is no way that there is a texture but no material. (Speaking from 3D-Modeling software. how you render then is up to you, you dont need to read the material-data if you dont want to, just load the texture and use it)

4: i dont really understand?! f 1/1/1 2/2/2 3/3/3 Every block (1/1/1 is one block) is one single point, 3 of them make a triangle. the first number is the vertex-index (for 'v') the second is the texturecoordinate-index (for 'vt'), and the third one is the normal-index (for 'vn')

The vertex-index is the only one which is really needed. you could just use only vertex-indices: f 1 2 3 you could also use vertex-indices and texture-indices f 1/1 2/2 3/3 or vertex-indices and normal-indices: f 1//1 2//2 3//3

You can read http://en.wikipedia.org/wiki/Wavefront\_.obj\_file for more Informations, im sorry, my english isnt good enough to explain this better :/
> 2 votes

---
Tags: obj
---


# Question
Title: XNA - Autodeploy .exe of game upon succesfull commit to GIT
I know of ClickOnce which creates an .exe file so a user can play my XNA game.

However, I have to manually go through a wizard in order to create this file.

I would like for the new .exe to be created upon a successful commit of the code to GIT (ie. all my tests pass and the build succeeds) and for this file to be deployed on my Amazon AWS server so users can instantly download the 'new version' each commit.

Is this possible? I've been taking a look at Jenkins which seems to do what I want (Automated builds) but seems as though it's only for JAVA software.

Thanks for any info :)

# Answer
You want a git post-commit or post-push hook to invoke your build chain automatically every-time those things happen.

http://git-scm.com/book/en/Customizing-Git-Git-Hooks

(Or you could use Jenkins? Same thing, but more complex. Though you might like those features.)

Simply google "automated clickonce" to see that click once is not intended to be automated. You need another tool for that. msbuild, which is what visual studio uses internally, can build visual studio projects on the command line.

https://stackoverflow.com/questions/1841435/is-it-possible-to-automate-a-clickonce-deployment

https://stackoverflow.com/questions/6319274/how-do-i-run-msbuild-from-the-command-line-using-windows-sdk-7-1
> 1 votes

---
Tags: c#, xna-4.0, automation, build-process
---


title: Planet terrain not connecting properly

text:
# Question
Title: Planet terrain not connecting properly
I'm trying to generate some simple planets in OpenGL using libnoise (including noiseutils), but the terrain is not correctly connecting where the sphere "completes itself" and I was wondering if someone could explain to me why this is happening and/or point me in the direction to solving this little problem.

I'm generating spheres with a slightly adapted version of this algorithm, with this being my full code:

```
static void GenerateSphere( VertexBuffer& vertices, IndexBuffer32& indices, uint rings, uint sectors, float radius, const HeightModule* heights )
{
    static const double pi   = glm::pi<double>();
    static const double pi_2 = glm::half_pi<double>();

    // texture-coordinate conversion helpers
    const float rr = 1.0f / float( rings   - 1 );
    const float ss = 1.0f / float( sectors - 1 );

    // clear buffers
    vertices.Clear();
    indices.Clear();

    // iterate through each ring and sector to create the vertices
    float height = 0;
    Vertex v;
    for ( uint r = 0; r < rings; ++r )
    {
        for ( uint s = 0; s < sectors; ++s )
        {
            // calculate point
            glm::vec3 point(
                float( cos( 2 * pi * s * ss ) * sin( pi * r * rr ) ),
                float( sin( -pi_2 + pi * r * rr ) ),
                float( sin( 2 * pi * s * ss ) * sin( pi * r * rr ) )
            );

            // set vertex data
            height = radius + heights->GetHeight( s, r );
            v.TexCoord = glm::vec2( s * ss, r * rr );
            v.Normal   = point;
            v.Position = point * height;
            vertices.Add( v );

            // set index data
            indices.Add( r * sectors + s );
            indices.Add( r * sectors + ( s + 1 ) );
            indices.Add( ( r + 1 ) * sectors + ( s + 1 ) );
            indices.Add( ( r + 1 ) * sectors + s );
        }
    }
}

```

VertexBuffer and IndexBuffer32 are simple wrappers for their OpenGL counterparts, and HeightModule is a wrapper for some libnoise and noiseutils functions (like NoiseMap, NoiseMapBuilderSphere, and some noise modules).

To illustrate what I mean by heights not matching where the sphere "completes itself," here is a screenshot:

As you can see on the left, the vertices do not quite reach each other (it's like this all the way from pole to pole) and the texture coordinates are messed up on the connecting lines. The blue line you see on the right extends from the origin all the way to the north pole, and after some debugging I've found that all of the vertices generated when r == 0 are the same with the position being \[0,-radius,0\] and the normal being \[0,-1,0\] (the texture coordinates appear to the correct though, as they all differ). I suspect the terrain problem is caused by this, but I have no clue how I would go about fixing that.

# Answer
The algorithm you referenced is horribly broken. It is not clear why it hasn't been redacted.

There are multiple issues here, but basically you need to generate the right set of vertices and connect them properly.

You generate `rings*sectors` different vertices. This is incorrect. You should have `rings*sectors+2`. When `r = 0`, `sin( pi * r * rr ) = 0`, and `sin( -pi_2 + pi * r * rr ) = sin(-pi/2) = -1`. Thus you generate `sectors` many vertices at the south pole. Instead, you need to start `r=1` in your loop. This means you will have one ring less in your mesh, but that one ring was actually a pole. The `rings` variable now means the number of rings of faces in the mesh, not the number of vertex rings. The line going to the north pole comes from the fact that you never generate a north pole vertex, because of the loop test such that `r` never becomes `rings` (only `rings-1`), and so `r * rr` is never `1.0f`.

The mismatch comes from the fact that you reference vertices which you never set. We have already seen that the number of vertices is `rings*sectors`. Thus valid indices are `0...rings*sectors-1`. On the iteration `r=rings-1` and `s=sectors-1`, you add an index `( r + 1 ) * sectors + ( s + 1 ) = rings*sectors+sectors`, which is clearly out of bounds.

**The Fix**

Split your code into two loops. The first generates the vertices, and the second generates the indices. The first should look like:

```
auto addpoint = [&](uint r, uint s) {
        glm::vec3 point(
            float( cos( 2 * pi * s * ss ) * sin( pi * r * rr ) ),
            float( sin( -pi_2 + pi * r * rr ) ),
            float( sin( 2 * pi * s * ss ) * sin( pi * r * rr ) )
        );

        // set vertex data
        height = radius + heights->GetHeight( s, r );
        v.TexCoord = glm::vec2( s * ss, r * rr );
        v.Normal   = point;
        v.Position = point * height;
        vertices.Add( v );
};
for ( uint r = 1; r < rings; ++r )
{
    for ( uint s = 0; s < sectors; ++s )
    {
        addpoint(r,s);
    }
}
addpoint(0,0); // south pole
addpoint(rings, 0); //north pole

```

This generates the rings in indices `[0, (rings-1)*sectors)`, and the south and north pole at `(rings-1)*sectors` and `(rings-1)*sectors+1`. Now we need to generate the indices for triangles in three parts: those around the south pole, those in the regular rings, and those around the north pole.

```
auto getindex = [&](uint r, uint s) -> uint {
    if(r == 0) return (rings-1)*sectors;
    if(r == rings) return (rings-1)*sectors + 1;
    if(s == sectors) return (r-1) * sectors;
    return (r-1) * sectors + s;
};

```

Acceptable arguments for `getindex` are `[0,rings]` and `[0, sectors]`, with "ring 0" being the south pole, "ring `rings`" being the north pole. Note also that the indices for ring 1 are `[0,sectors)`, so we need `r-1`. Note that the sphere wraps on itself, so that `getindex(r, 0) == getindex(r, sectors)`. That is, if we go all the way around the sphere, we get back to the same exact point, so we use the same index. Now our index generation is straightforward:

```
for(uint r = 0; r < rings; r++)
    for(uint s = 0; s < sectors; s++) {
         if(r != rings-1) {
             indices.Add(getindex(r,s));
             indices.Add(getindex(r+1,s));
             indices.Add(getindex(r+1,s+1));
         }
         if (r != 0) {
             indices.Add(getindex(r+1,s+1));
             indices.Add(getindex(r,s+1));
             indices.Add(getindex(r,s));
         }
}

```

(Use triangles. Quads are obsolete.)

This needs some explanation. First, we went back to starting `r` at zero. Now we have `rings` horizontal loops of triangles, so we will need `r` to take on `rings` many values. Further, we need to pass the values zero through `rings`, inclusive, to `getindex` to connect something to all the vertices we defined. We do that by letting `r` represent the lower of the two vertex rings we are connecting on each iteration. `s` then represents where we are within each ring. Note because of the test in `getindex`, when `s = sectors-1` we connect the last vertices at the end of the ring back to the first ones, ensuring no gaps.

Second, we have these crazy `if`'s. Around the poles, we do not need quads. Because the pole is a single point, we can just connect each pair in ring `1` to the pole with a single triangle. We see in the second `if` that the triangle is `getindex` applied to `(r+1,s+1)`, `(r,s+1)`, and `(r,s)`. For most rings, this is one half of the quad. For the bottom ring, when `r = 0`, `(r,s+1)` and `(r,s)` are the same vertex: the south pole. We can see that if `r = 0`, then `getindex` always returns the same thing, regardless of `s`. So in the bottom ring this triangle is degenerate, we might as well not generate it. The same logic holds for the other `if`: those triangles will be degenerate on the last ring, near the north pole.

It is possible to rewrite this code to generate a triangle strip, but I won't derive that here.
> 2 votes

---
Tags: opengl, terrain
---


# Question
Title: What is the point in using API such as Open GL or DirectX when there are game engines?
I was wondering why today programmers place so much emphasis on API like DirectX, and even OpenGl. As far as I know, you'd need thousands of lines of code to make a simple 3D game using one of the aforementioned. But with game engines like Unity, the process is simplified and you can pretty much drag around shapes to create the graphics in lieu of programming it. So what I wanted to know: why is knowing APIs DirectX more preferable than being knowledgeable in Unity, other than the fact that with an API you can code it to be portable on other systems. To me it's like choosing Assembly over a high level language like C. Sure, with assembly I'll really understand what's happening at machine level, but it's take a lot longer to write programs using it and it would be a lot harder to debug.

# Answer
Using your own analogy: Why did people make COBOL? Why did people make C++ if C was around? Why did they make PHP? Why did they make Python? Ignoring the fact that some of those implementations are written in C themselves, this is the same thing.

Some people want to make their own languages for new purposes and to do that you need to start with the graphics APIs. Other people want to learn how they work -- similar to implementing your own C compiler.

In some cases it's a personal case of NIH: "My engine will be better than Unity's!". In other it's appropriateness -- building a 2d game like Monkey Island in Unity3D is probably more difficult than rolling your own simple engine. And finally you need to remember that Unity is a very large API to build upon with a lot of functionality. It's a lot of effort to learn it all, and some people feel that effort is better spent making their own simpler engine.
> 3 votes

# Answer
I can speak only for my self, but I implement my engine for sake of implementing it. It is fun for me. Plus the time spent learning an engine is roughly equal to implementing it yourself.
It also gives you absolute control over the engine and you can specialize it for your task more easily (you would have to read pretty much everything about an engine, read and understand all code to be able alter it).
> 2 votes

# Answer
Sometimes for compactness a self-made engine ( Despite thousands of lines of code ) can be more compact than a pre-made engine due to the fact that unused features can be removed.

Also keep in mind that if you write your own engine from scratch, you'll know all the ins and outs of it. If you ever want to add a feature or change something, you can!

Some engines can also be very restrictive of what you can do with them or even if you can publish it for money.

The best part about creating your own engine is the knowledge that you can look back on a game and say made it 100% yourself.
> 2 votes

# Answer
cf.

> What is the point in designing your own car (e.g. to take part in an F1 race) if there are existing car manufacturers who will sell you cars that already work?

I looked over some other answers here and in the proposed dupe questions and one point not really being championed is that **creating your own system affords you more technical (and, as a consequence, creative) control.**

The car analogy falls well short because cars are all hardware plus the user, here we're talking about middleware software. Which is just a part of the software. Which usually has to accommodate combinatorial variations of hardware, as well as completely unskilled users.

Anyway, the point is that ABC game engine, no matter how attractive its feature set, was not designed with **you** in mind. For example, an Unreal engine was designed with an Unreal Tournament game in mind. Unless it is open source, usually you will have no idea how it works.

Of course that may be just fine and dandy, depends on what you're setting out to do.

BTW this is not any sort of a jab at the Unreal engine (the latest iteration of which these days can rightfully be said to be *unreal*. It's freaking beautiful). Modern engines like Unreal and Unity (and many others) are making huge leaps and bounds toward supporting anything you could realistically expect to build.

The fundamental idea for my answer remains the same and I expect this to be true for a while until paradigms start to shift in game development and computer programming. At the end of the day, writing your own game engine allows you to (in a simple straightforward way) generate machine code which is is not littered with tons of dynamic branches to support dynamic, general capabilities. Call it bloat or call it a feature, this is just how it works.

I envision software middleware in the distant future that has deep compiler integration and we will continue to be able to enhance software optimization capabilities while retaining ease of use for content artists and developers.
> 1 votes

---
Tags: game-design, software-engineering
---


# Question
Title: Why does this no longer render the "test tri"?
So I got this code about rendering a shaded tri using sharpDX ...

```
var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None);
var vertexShader = new VertexShader(device, vertexShaderByteCode);
var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None);
var pixelShader = new PixelShader(device, pixelShaderByteCode);

var layout = new InputLayout(
    device,
    ShaderSignature.GetInputSignature(vertexShaderByteCode),
    new[]
        {
            new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
        });

var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
    {
        new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
        new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
        new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
    });

```

As with all demos they are often not very modular and over wordy, but also I wanted to play with other ways of rendering in these simple scenarios before I move on to more complex things.

So I updated the code to this ...

```
var vertexShader = new VertexShader(device, ShaderBytecode.CompileFromFile("Shaders/Coloured.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None));
var pixelShader = new PixelShader(device, ShaderBytecode.CompileFromFile("Shaders/Coloured.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None));
VertexPositionColour[] data = new VertexPositionColour[]
{
    new VertexPositionColour { Position = new Vector4(0.0f, 0.5f, 0.5f, 1.0f), Colour = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) },
    new VertexPositionColour { Position = new Vector4(0.5f, -0.5f, 0.5f, 1.0f), Colour = new Vector4(0.0f, 1.0f, 0.0f, 1.0f) },
    new VertexPositionColour { Position = new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), Colour = new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }
};

var vertices = Buffer.Create(device, BindFlags.VertexBuffer, data);

```

And now the test triangle no longer renders. Could anyone tell me why?

# Answer
Ah ok I didn't think I needed the input layout any more Changing the second example to include this ...

```
vertices = Buffer.Create(device, BindFlags.VertexBuffer, data);

var inputLayout = new InputLayout(
    device,
    ShaderSignature.GetInputSignature(vertexShaderByteCode), new[]
        {
            new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
        });

device.ImmediateContext.InputAssembler.InputLayout = inputLayout;

```

... fixes the problem.

But that raises the question of why I can't do this ...

```
vertices = Buffer.Create(device, ref data, VertexPositionColour.BufferDescription);

```

It says there are some invalid args. Hmmm DX is a strange world!
> 0 votes

---
Tags: rendering, directx11, sharpdx
---


# Question
Title: C# - Collision Detection problem with platforms on Monogame(XNA)
So I am having issues with my platformer that I am developing. I can detect collisions fine when there are a line of parralel blocks or even single blocks. The issue I have is when blocks form an L shape. \[\] for example.
\[\]

When my character runs into the wall, he sort of just squeaks through and gets zoomed out. I've tried using an else statement that just sends him back a couple pixels back, but it doesn't work because I don't think it accounts for one of the two blocks. Each block is it's own object.

Any help?

This collision code is in my Player class. This is the only detection I have so far in the game. I attempted to use and adjust code from a breakernoid tutorial I found somehwere, and I realized that the code doesn't totally work for what I am doing.

```
public void checkYCollisions(block[] platforms)
    {

        if (position.Y >= 700)
            grounded = true;
        else
            grounded = false;

        float Xradius = Width / 2;
        float Yradius = Height / 2;
        block collidedPlatform = null;

        foreach (block p in platforms)
        {
            if ((position.X > (p.position.X - p.Width / 2 - Xradius )) &&
                (position.X < (p.position.X + p.Width / 2 + Xradius )) &&
               (position.Y > (p.position.Y - p.Height / 2 - Yradius )) &&
                (position.Y < (p.position.Y + p.Height / 2 + Yradius)))

            {
                collidedPlatform = p;
                break;
            }
        }
        //collisions work for all side of blocks.
        if (collidedPlatform != null)
        {
            if ((position.Y <
                (collidedPlatform.position.Y - collidedPlatform.Height / 1.5 /*+ radius*/)))
            {

                grounded = true;

            }

            else if ((position.Y   >
                (collidedPlatform.position.Y + collidedPlatform.Height / 2 )))
            {
                if(y_vel < 0)
                    y_vel *= -1;
                //player1.direction.Y = -1.0f * player1.direction.Y;
            }

            else
            {
                x_vel *= -2;
            }
        }

```

I am guessing the issue is because I only have one collided block selected at any time. So I don't really know how to fix it that I can have two blocks selected. Note, once again, this code works for all blocks that are by themselves, or just a horizontal(same x position) line of blocks. It's just that L situation where I run into a corner.

# Answer
Instead of checking a single block for collision, you could keep a list of blocks and then iterate through the list and perform collision responses for each block in the list. Like this:

```
public void checkYCollisions(block[] platforms)
{
    if (position.Y >= 700)
        grounded = true;
    else
        grounded = false;

    float Xradius = Width / 2;
    float Yradius = Height / 2;
    List<block> collidedPlatforms = new List<block>();

    foreach (block p in platforms)
    {
        if ( /* p contains position */ )
        {
            collidedPlatforms.Add(p);
        }
    }

    foreach (block b in collidedPlatforms)
    {
        // perform collision responses
    }
}

```

One thing I would recommend is looking into the Rectangle structure. It contains methods for testing if points or other rectangles intersect or are contained within the rectangle itself.
> 1 votes

# Answer
Here's my pseudo-code:

1. When the player updates, get the position he *wants* to go. If it doesn't change, do nothing.
2. Get the nearest blocks for that position, store them in an array or something.
3. Go through that list / array, check for collisions
4. If it collides, tweak the player's position until it doesn't collide with the block. For example, the player glitches through the block by 5 pixels, you just subtract the 5 pixels.
5. Make that tweaked position the players position.

You can just skip step 2, but sometimes doing step 2 is easier.
> 0 votes

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


# Question
Title: Getting Target position at the time of shooting
I have a bullet that has to hit a constantly moving enemy.

So, in BulletScript, I have declared a Transform

```
public Transform enemy;               //and assigned enemy object to it that is continuously moving and changing its position

```

Now, when I try to use `enemy.position` in bullet script so as to hit it, `enemy.position`gives the position at which the enemy started and not the position at which it was when bulletprefab was shot.

How can I get the updated position of enemy object every time bulletprefab is instantiated.

# Answer
> 1 votes
How are you retrieving the value of enemy? It is assigned at compile time, or retrieved at runtime?

My advice would be to declare it as a GameObject, assign its value at runtime and then access its Transform value.

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


title: OpenGL UseProgram() fails

text:
# Question
Title: OpenGL UseProgram() fails
I have a rather strange exception on my application using OpenTK on Linux (ArchLinux with Mono 3.2.8) with `GL.UseProgram()`. I wrote a class to combine multiple files to one program:

```
public sealed class Shader : IContent
{
    public string Name
    {
        get { return name; }
    }

    readonly string name;
    readonly ShaderElement[] elements;
    int programId;

    public Shader(string name, params ShaderElement[] elements)
    {
        this.name = name;
        this.elements = elements;
        this.programId = -1;
    }

    public void Compile()
    {
        programId = GL.CreateProgram();
        for (int i = 0; i < elements.Length; i++)
        {
            var info = new FileInfo(elements[i].File);
            if (info.Exists)
            {
                int shaderId = GL.CreateShader(elements[i].Type);
                using (var reader = info.OpenText())
                    GL.ShaderSource(shaderId, reader.ReadToEnd());
                GL.AttachShader(programId, shaderId);
            }
            else
                throw new FileNotFoundException("Shader file not found.", info.Name);
        }
        GL.LinkProgram(programId);
    }

    public void Apply()
    {
        if (programId == -1)
            throw new InvalidOperationException("Compile() has to be called before Apply()");
        GL.UseProgram(programId);
    }
    public void Unapply()
    {
        GL.UseProgram(0);
    }

    public void Dispose()
    {
        GL.DeleteProgram(programId);
    }
}

```

My sample shader is very short because I try to understand how OpenGL works:
Vertex:

```
precision highp float;

void main()
{
    gl_FrontColor = gl_Color;
    gl_Position = ftransform();
}

```

Fragment:

```
precision highp float;

void main()
{
    gl_FragColor = gl_Color * (1-clamp(gl_FragCoord.z - 0.05, 0, 1));
    gl_FragColor.w = 1;
}

```

A sample call for `Apply()`:

```
public override void Draw(double interpolation)
{
    GL.MatrixMode(MatrixMode.Modelview);
    GL.LoadMatrix(ref translate);
    GL.MatrixMode(MatrixMode.Projection);
    GL.LoadMatrix(ref projection);
    GL.Color3(Color.Red);
    simpleShader.Apply();
    sphere.Draw();
    simpleShader.Unapply();
}

```

Running the application under Windows does not generate any exception.
The following is crashing running under Linux:

```
First call of Draw()
 -> First call of Shader.Apply()
 -> Draws geometry for first frame
 -> First call of Shader.Unapply()
Second call of Draw()
 -> Second call of Shader.Apply()
    -> GL throws InvalidOperation Error.

```

Any ideas why Windows behaves different to Linux and how this can be resolved?

# Answer
After you compile and link the shader program you should validate and check the compile and link status'. Anyway, you don't even seem to be compiling the shader sources. Do that and make the checks and it should work.

The Compile() function should look more like this:

```
public void Compile()
{
    programId = GL.CreateProgram();
    for (int i = 0; i < elements.Length; i++)
    {
        var info = new FileInfo(elements[i].File);
        if (info.Exists)
        {
            int shaderId = GL.CreateShader(elements[i].Type);
            using (var reader = info.OpenText())
                GL.ShaderSource(shaderId, reader.ReadToEnd());
            GL.CompileShader(shaderID);
            //get compile status with glGetShaderiv(shaderID, GL_COMPILE_STATUS, &status);
            GL.AttachShader(programId, shaderId);
        }
        else
            throw new FileNotFoundException("Shader file not found.", info.Name);
    }
    GL.LinkProgram(programId);
    GL.ValidateProgram(programID);
    //get link status with glGetProgramiv(programID, GL_LINK_STATUS, &status);
    //get validate status with glGetProgramiv(programID, GL_VALIDATE_STATUS, &status);
}

```

And if an error occurs get the error logs and print them somewhere. You can get the logs by calling

```
glGetShaderInfoLog(shaderID, maxLen, &len, &log);

```

or respectively

```
glGetProgramInfoLog(programID, maxlen, &len, &log);

```

References:

glCompileShader()

glGetShaderInfoLog()

glGetProgramInfoLog()

glGetShaderiv()

glGetProgramiv()

glValidateProgram()
> 1 votes

# Answer
I have been using OpenTK with mono on Fedora and have not seen that error. Your example uses some C# features I'm not familiar with, and I don't know what is in your draw sphere, so I have created a simple example that works on Linux below.

Although only a triangle is drawn, it uses the shaders, and I enabled and disabled the shader programs as you have in your example above.

I assume you already have a `GLControl` you can pass into this function. My program sets up a 512 x 512 `GLControl` like this before calling the test function:

```
int w = GlControl1.Width;
int h = GlControl1.Height;
GL.MatrixMode (MatrixMode.Projection);
GL.LoadIdentity ();
GL.Ortho (0, w, 0, h, -1, 1); // Bottom-left corner pixel has coordinate (0, 0)
GL.Viewport (0, 0, w, h); // Use all of the glControl painting area

using System;
using System.Text;
using System.Drawing;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using System.Windows.Forms;

namespace OpenTkTestNamespace
{
    public class StackExchangeTestsClass
    {
        public StackExchangeTestsClass()
        {
        }

        static string VertexShader =
        "float;" +
        "attribute vec4 vPosition;" +
        "void main()" +
        "{" +
            "gl_Position = vPosition;" +
        "}";

        static string FragmentShader =
        "float;" +
        "uniform vec4 vColor;" +
        "void main()" +

        "{" +
            "gl_FragColor = vColor * 1.0 / 256.0 + 1.0 / 256.0 * vec4(gl_FragCoord.x, gl_FragCoord.y, gl_FragCoord.z, 1);" + // (1-clamp(gl_FragCoord.z - 0.05, 0, 1));" +
        "}";

        static int programId;

        static OpenTK.GLControl GlControl;

        static bool setup_complete = false;

        public static StringBuilder Test(OpenTK.GLControl GlControl_in)
        {
            StringBuilder result = new StringBuilder();
            if (setup_complete == false)
            {
                GlControl = GlControl_in;
                Compile();
                result.AppendLine("Compile Complete");
                setup_complete = true;
            }

            Apply();
            result.AppendLine("Apply Complete");
            DrawSomething();
            Unapply();
            result.AppendLine("UnApply Complete");
            Apply();
            result.AppendLine("Apply Complete");
            DrawSomething();
            Unapply();
            result.AppendLine("UnApply Complete");
            return result;
        }

        public static int loadShader(ShaderType type, String shaderCode)
        {
            int shader_ok;
            // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
            // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
            int shader = GL.CreateShader(type);

            // add the source code to the shader and compile it
            GL.ShaderSource(shader, shaderCode);
            GL.CompileShader(shader);
            GL.GetShader(shader, ShaderParameter.CompileStatus, out shader_ok);
            if (shader_ok == 0) {
                MessageBox.Show("Failed to compile " + shaderCode);
                //fprintf(stderr, "Failed to compile %s:\n", filename);
                //show_info_log(shader, glGetShaderiv, glGetShaderInfoLog);
                //glDeleteShader(shader);
                return 0;
            }

            return shader;
        }

        public static void Compile()
        {
            int VshaderId = loadShader(ShaderType.VertexShader, VertexShader);
            int FshaderId = loadShader(ShaderType.FragmentShader, FragmentShader);
            programId = GL.CreateProgram();
            GL.AttachShader(programId, VshaderId);
            GL.AttachShader(programId, FshaderId);
            GL.LinkProgram(programId);
            int program_ok;
            GL.GetProgram(programId, ProgramParameter.LinkStatus, out program_ok);
            if (program_ok == 0)
            {
                MessageBox.Show("Failed to link " + program_ok.ToString());
            }
        }

        public static void Apply()
        {
            if (programId == -1)
                throw new InvalidOperationException("Compile() has to be called before Apply()");
            GL.UseProgram(programId);
        }

        public static void Unapply()
        {
            GL.UseProgram(0);
        }

        static int mColorHandle;

        // Set color with red, green, blue and alpha (opacity) values
        static OpenTK.Graphics.Color4 color = new OpenTK.Graphics.Color4(0.5f, 0.5f, 0.5f, 1.0f);

        private static void DrawTriangle()
        {
            //GL.MatrixMode(MatrixMode.Modelview);
            //GL.LoadIdentity();
            GL.Color3(Color.Yellow);
            GL.Begin(BeginMode.Triangles);
            GL.Vertex3(0.0, 1, -1);
            GL.Vertex3(-1, -1, 0);
            GL.Vertex3(1, -1, 1);
            GL.End();
        }

        public static void DrawSomething()
        {
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // get handle to fragment shader's vColor member
            mColorHandle = GL.GetUniformLocation(programId, "vColor");

            // Set color for drawing the triangle
            GL.Uniform4(mColorHandle, color);

            DrawTriangle();

            GlControl.SwapBuffers();
        }
    }
}

```

Hope that helps.
> 0 votes

---
Tags: shaders, linux, opentk
---


# Question
Title: Press multiple switches to unlock the door
I made 2 scripts, one that is a switcher and one that checks if object is switched (Switch, SwitchCheck).

Switch script (it's on 2 objects that are switches and both objects have colliders with IsTrigger checked):

```
public var IsPressed : boolean = false;

function OnTriggerStay (){
    if (Input.GetKeyDown(KeyCode.JoystickButton1)){
        IsPressed = true;
        Debug.Log("Switch activated");
    }
}

```

---

SwitchCheck script (it's on door that should be opened)

```
public var Switch1 : Switch;
public var Switch2 : Switch;

function Update()
{
    if (Switch1.IsPressed && Switch2.IsPressed)
    {
        Destroy (gameObject);
    }
}

```

Now, he problem here is, that it "does" kind of work...after I press the button like 20 times. My question is, did I write something wrong?

# Answer
You should not use GetKeyDown inside the OnTriggerStay. It should only be called from the Update method. Therefore, you need to implement OnTriggerEnter and OnTriggerExit to check whether the condition is satisfied or not by holding a flag something like 'triggered'. Inside the Update method of Switch1 and Switch2, you need to check the flag; if it is true, then, you get the input.

```
public var IsPressed : boolean = false;
public var triggered : boolean = false;

function OnTriggerEnter() { triggered= true; }
function OnTriggerExit()  { triggered= false;}

function Update()
{
    if (triggered && Input.GetKeyDown(KeyCode.JoystickButton1))
        IsPressed = true;
}

```
> 1 votes

---
Tags: unity, javascript, input
---


title: Conditional Defines and HLSL

text:
# Question
Title: Conditional Defines and HLSL
Is it possible to use project level conditional defines in hlsl code?

I'm trying to conditionaly compile a shader using MonoGame Content Procesor. Depending on project type (ie. Windows, Windows8...) different shader models should be used. Pragma directives are supported. The code:

```
#if WINDOWS
   PixelShader = compile ps_3_0 PixelShaderFunction();
#else
   ...

```

... doesn't work as WINDOWS is interpreted as false. Judging from the article on Gamasutra this should work. This answer on Gamedev lists constants which should be defined when using MonoGame.

I've also tried adding constants into csproj manually (in content project, then in dummy content compiler csproj).

Is there something I'm missing?

My sln structure is as follows:

1. MonoGameContentProject - holds .fx file
2. MonoGameDummyProject - has content reference to content project, builds .fx file
3. WindowsProject - has a link to dummy project xnb file in the windows build directory

# Answer
> 2 votes
Mono should behave the same way as .Net and the MSDN has this to say on preprocessor instructions ...

When the C# compiler encounters an #if directive, followed eventually by an #endif directive, it will compile the code between the directives only if the specified symbol is defined. Unlike C and C++, you cannot assign a numeric value to a symbol; the #if statement in C# is Boolean and only tests whether the symbol has been defined or not.

So it may be that the #define WINDOWS definition has not been made yet. I'm looking to see if I can find something useful on this.

Interesting secondary point but not really what you are after ...

https://stackoverflow.com/questions/473354/quote-needed-preprocessor-usage-is-bad-oo-practice

Could you perhaps take another approach?

Possible solution: Your syntax may not be quite right try something like this ...

```
#if (WINDOWS)
  // some WINDOWS-specific code here
#endif

```

EDIT: In light of my missing the fact that this is a shader problem I figured I should add this ...

Conditional defines based on environments are only possible on the CPU, to have such differences in shaders you need to create different versions of your shaders then conditionally choose them in your CPU code in which situation the above syntax should work.

In short: such preprocessor instructions are not possible in shader code.

# Answer
> 0 votes
I don't think you can directly, but you might consider writing a simple preprocessor and creating a custom build step.

---
Tags: hlsl, monogame
---


# Question
Title: Is there any Lua API that works with C# for PC & XBox 360 Development?
I am reading a book on Game Development in which they show you how to make scripts for your game in Lua. They program Lua and use it from C++, but I was wondering if there is a library or API to use Lua from C#: specifically from XNA to develop games for PC **and** XBox 360?

# Answer
> 6 votes
This is were I would point you (http://www.xnua.com/xna\_lua\_xnua), but it hasn't been updated for a long time.

C# is great language, and could in a sense be used as a scripting language within your c# game. Nick Gravelyn has created some nice tutorials about tile engine (http://blog.nickgravelyn.com/downloads/#tileengine) and used a custom scripting engine to fire off dialog. He has also has a basic example when he learned about the "yield" keyword: http://blog.nickgravelyn.com/2010/02/the-magic-of-yield/

# Answer
> 2 votes
If you're looking for scripting in C#, definitely take a look at IronPython. It's not just a python API for C#, it is actually a completely separate python implementation which compiles to the same CLR assembly (with the same performance) that C# does, but can be interfaced with as a scripting language. Any Lua wrapper for C# would be much slow due to the overhead of Marshalling.

# Answer
> 2 votes
As Sean said, IronPython is worth looking at. IronPython is actually one of a few dynamic language implementations for .NET targeting the Dynamic Language Runtime (DLR). There is at least one open source project aimed at implementing Lua on the DLR (like this one), but I'm not sure if there are any implementations near completion. A well-implemented set of DLR bindings for Lua should provide performance on par with IronPython and IronRuby, and would be much faster than a Lua wrapper. For the sake of comparison, IronPython generally performs better than CPython (sometimes significantly better).

**Note:** As ElementCy states below, DLR languages are generally not supported on the Xbox 360. However, there *is* an "interpreted mode" in the DLR. I don't know enough about it to say for sure, but it might be possible to get IronPython (or other DLR language implementations) to run on the Xbox 360 in interpreted mode, though performance would certainly suffer. It might be worth asking someone on the DLR team whether they know this to be possible. If not, the Xbox 360 *should* get Reflection.Emit support as part of upcoming Silverlight support. If and when that happens, I imagine getting the DLR up and running on the Xbox 360 won't be a problem.

# Answer
> 2 votes
The best solution I could give you is to just script in C#. You can compile them at runtime when you target windows and compile them before hand for the xbox. (as a dll)

That would be the easiest solution. You could also do it in VB.NET or any .NET language. (not sure about the scripting ones though) Basically, I'm saying to have your scripts in their own dll. You can have them compile at runtime on Windows. (do you really want them to do this on the xbox 360?, you can't update your games on there, at least I don't think so)

I can understand your frustration, I wanted to use Lua as well.

To sum it up: 1) Have it built at runtime on Windows 2) Build it before hand for the Xbox 360

That's what I recommend.

# Answer
> 1 votes
1. Lua interpreter is unmanaged, AFAIK, so you can't get it to work on Xbox with XNA
2. You can use **Javascript** interpreter called Jint which does not rely on DLR and **works on Xbox**.

# Answer
> 0 votes
It doesn't technically answer your question (doesn't work on the xbox), but LuaInterface allows Lua integration with C# relatively painlessly.

# Answer
> 0 votes
Just to update this question, I spent the last day doing some extensive searching, and I've found that using UniLua (made for use with unity, pure C# implementation) is the best and most effective option for getting Lua on Xbox. I stripped it down, took out all the Unity material, and it works great.

I also added some functionality found in LuaInterface by overloading the \[\] operator for LuaState, and such.

CFWLua

I hope this was useful.

---
Tags: c#, xna, lua, xbox360, pc
---


# Question
Title: Object reference not set to instance of an object Unity3D c#
```
public class player
{      public projectile pro;
       pro = GetComponent<projectile>();
    void Update()
    {
        GameObject go = GameObject.Find("enemy");
        Transform playerTransform = go.transform;
        Vector3 posi = playerTransform.position;
        pro.Target = posi;             // getting error here
        Instantiate(bulletprefab, position, Quaternion.identity);
    }
}

```

Target is present is Projectile class and is Vector3 only, how to fix this error?

# Answer
You can't put or execute statements during the class declaration. Why is projectile public? If you are assigning the variable from the editor, delete the third line and assign it. Otherwise, make it public and assign it manually from the Awake method.

```
public class Player : MonoBehaviour
{
    private Projectile pro;

    private void Awake()
    {
        pro = GetComponent<Projectile>();
    }

    private void Update()
    {
         //update statements...
    }
}

```
> 2 votes

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


# Question
Title: C# - Monogame- Collision Detection Sprite walking through platforms
I am blanking on the logic here. How do I get it so that my sprite doesn't run through a block. It only repels if the center of the player sprite is higher than the bottom of the block.

But when it is lower, it walks right through. It gets lower because my jump function or my grounded function is a bit funky. Anyway, how do I get it so that a player can't go underneath a block unless the sprite is not touching the block at all.

Here is the collision code in my player class, the one that does the collision detection.

```
public void checkYCollisions(block[] platforms)
    {

        if (position.Y > 700)//this is my ground with no blocks.
            grounded = true;
        else
            grounded = false;

        float Xradius = Width / 2;
        float Yradius = Height / 2;
        block collidedPlatform = null;
        List<block> collidedBlocks = new List<block>();

        foreach (block p in platforms)
        {
            if ((position.X > (p.position.X - p.Width / 2 - Xradius )) &&
                (position.X < (p.position.X + p.Width / 2 + Xradius )) &&
               (position.Y > (p.position.Y - p.Height / 2 - Yradius  )) &&//on top
                (position.Y < (p.position.Y + p.Height / 2 + Yradius   )))//below

            {
                collidedBlocks.Add(p);

            }
        }
        //collisions work for all side of blocks.
        foreach (block p in collidedBlocks)
        {
            if (p != null)
            {
                if ((position.Y <
                    (p.position.Y - p.Height / 2 /*+ radius*/)))//landing on a block
                {

                    grounded = true;

                }

                else if ((position.Y >
                    (p.position.Y + p.Height / 2 /*- Yradius*/))) //jumping up into a block
                {
                    if (y_vel < 0)
                        y_vel *= -1;
                    //player1.direction.Y = -1.0f * player1.direction.Y;
                }

                 else if ((position.X <
                (p.position.X + p.Width / 1.5 /*+ Xradius*/))) // one of the sides
                 {
                     x_vel *= -2;
                 }

                 else if ((position.X >
                     (p.position.X - p.Width / 1.5 /*+ Xradius*/))) // other side
                 {
                     x_vel *= -2;
                 }

            }
        }
    }

```

Note that I have tried to remove YRadius in the the if loops at separate occurences, and it works to no avail because my guy will not hit the ceiling.

# Answer
As I suggested in a comment on your other question (and as Tyyppi\_77 suggested), you should look into the Rectangle structure. If you utilized it, then your collision code could be as simple as this:

```
public void checkYCollisions(block[] platforms)
{
    // assume player and block both contain a Rectangle property called "Bounds"
    // that represent each's bounds

    if (this.Bounds.Y + Bounds.Height > 700)
        grounded = true;
    else
        grounded = false;

    List<block> collidedBlocks = new List<block>();
    foreach (block p in platforms)
    {
        if (p != null && p.Bounds.Intersects(this.Bounds))
        {
            collidedBlocks.Add(p);
        }
    }

    foreach (block p in collidedBlocks)
    {
        // p won't be null

        Rectangle overlap = Rectangle.Intersect(this.Bounds, p.Bounds);

        // overlap now contains the amounts (X and Y) by which the player's
        // bounds and the block's bounds overlap and you can use that to
        // perform your necessary collision responses
    }
}

```
> 1 votes

---
Tags: collision-detection
---


# Question
Title: Switching a project written in Lua to a compiled language
I am experimenting with game development in Lua using the Love2D framework, and while it works fine, I am getting tired of using a dynamic scripting language. I would like to have better performance, misspellings caught at compile time, and the ability to create efficient data structures for things like 2D vectors.

I thought about some alternatives:

C++ should be very efficient, but it also would make me have to worry about low-level details like manual memory management, and compiling for different platforms.

Java is cross-platform, but as far as I know it does not support pass-by-value data structures, which I would really like. There are also the claims of it being large and slow, but I'm not sure how valid they are.

C# seems to have similar advantages and disadvantages to Java, plus it only officially supports Windows, which makes me hesitant since I mainly use Linux and would like my program to be cross-platform.

So, if my ideas about one of those languages is wrong, or you have other suggestions, I would be interested to find out.

# Answer
> 2 votes
> C++ should be very efficient, but it also would make me have to worry about low-level details like manual memory management, and compiling for different platforms.

Modern C++ highly discourages manual memory management. You should instead use smart pointers like `unique_ptr` and allocation functions like `make_unique` and never manually allocate or deallocate memory, aside from the implementation of certain very low-level routines (which you don't often need to do). You do need to think about memory management a bit harder than you do in Lua in terms of proper lifetime management, but that's a good thing IMO.

> C# seems to have similar advantages and disadvantages to Java, plus it only officially supports Windows, which makes me hesitant since I mainly use Linux and would like my program to be cross-platform.

Microsoft *officially* recommends Mono for non-Windows platforms. Mono is quite capable, up-to-date, and complete. It even has various features and advantages that Microsoft's C# does not. Unity is a well-known very popular game engine that makes heavy use of Mono and runs on Windows, Linux, OS X, iOS, Android, Flash, and even HTML5 (without plugins).

C# does *not* have the same disadvantages as Java. It supports value type semantics (though it's statically part of the type based on whether it's declared as a `class` or a `struct`), supports "real" generics, and via Mono even supports native SIMD usage.

C# is probably the best choice for you. There's even things like NLua which would help you gradually or partially port your code.

# Answer
> 1 votes
About c++: You dont really need to worry about memory management. Ofc you handle memory yourself, but its not as hard as in C. In C++ you just allocate your memory by creating a Object (new xyz();) and free this memory by deleting it (delete var;). No more manual malloc() and stuff)

About Java: Java supports Call-by-value with primitives and Call-by-reference with Objects. WHY do you need call-by-value with objects? This is just not needed and slow as shit. if you REALLY want to copy the instance to pass it in you just can copy the Instance yourself befor calling the method. And Java isnt that slow. It was slow in earlier versions but now its almost as fast as C++, sometimes even faster. But ofc, if you really optimize the shit out of c++, then c++ will beat java. but overall, java is fast.

---
Tags: c#, c++, java, lua
---


title: Game testing solutions?

text:
# Question
Title: Game testing solutions?
I have a unity web browser game. Since I'm working on a small company with limited machines which are all of either 2GB RAM or 4 GB RAM with decent processors. I'd like to know if there are any web based or software 'solutions' to test the game with low configuration both hardware and network bandwidth.

And, I have tried cross-browser testing solutions, But I didn't see any solution with the option of testing a browser game made for the unity web player .

# Answer
> 3 votes
Try to use Unity community or just Open Alpha and get free testesr who will play the gamef or you.

# Answer
> 3 votes
Have you thought of making your game Open Source and giving it out for people to test? If that would ruin things for you, have you thought of asking in popular gaming forums for testers? Posting a few screenshots can quickly attract a lot of players; most of which won't like your game. However, that is good. You can get a lot of information as to the flaws in your game from exit polling those users.

I vehemently encourage getting closed alpha testers for your game. Those who like it, will certainly help you test in future versions as well as secure a following.

# Answer
> 0 votes
Why don't you go for some game testing farm, they can do your work very easily... however before that you must look for free solutions... all the best..

Alax, Game tester at GameCloud

---
Tags: unity, browser-based-games, testing
---