title: How do you add rotation to particles?

text:
# Question
Title: How do you add rotation to particles?
Today I was working on a particle system and I can't figure out how to give the particle billboards a rotation (so to have them spinning clockwise or counter-clockwise while facing the player). I assume the core of the problem is my complete lack of understanding of trigonometry.

So, first of all, here is my geometry shader that will produce quads that rotate around their center:

```
[maxvertexcount(4)]
void GeometryShaderProc( point VertexShaderInput particle[1], inout TriangleStream<PixelShaderInput> triStream ) {
  PixelShaderInput vertex = (PixelShaderInput)0;
  vertex.Color = particle[ 0 ].Color;
  vertex.Texture = particle[ 0 ].Texture;
  vertex.Position.z = particle[ 0 ].Position.z;
  vertex.Position.w = 1;

  float QuadSizeX = particle[ 0 ].Size.x / ViewportDimensions.x * 0.5;
  float QuadSizeY = particle[ 0 ].Size.y / ViewportDimensions.y * 0.5;

  float a = sin( particle[ 0 ].Position.w ) * QuadSizeX;
  float b = cos( particle[ 0 ].Position.w ) * QuadSizeY;
  float c = cos( particle[ 0 ].Position.w ) * QuadSizeX;
  float d = sin( particle[ 0 ].Position.w ) * QuadSizeY;

  // Left Top
  vertex.Position.x = particle[ 0 ].Position.x - c;
  vertex.Position.y = particle[ 0 ].Position.y - d;
  vertex.Position.z = particle[ 0 ].Position.z;
  vertex.Position.w = 1;
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 0, 0 );
  triStream.Append( vertex );
  // Left Bottom
  vertex.Position.x = particle[ 0 ].Position.x - a;
  vertex.Position.y = particle[ 0 ].Position.y + b;
  vertex.Position.z = particle[ 0 ].Position.z;
  vertex.Position.w = 1;
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 0, 1 );
  triStream.Append( vertex );
  // Right Top
  vertex.Position.x = particle[ 0 ].Position.x + a;
  vertex.Position.y = particle[ 0 ].Position.y - b;
  vertex.Position.z = particle[ 0 ].Position.z;
  vertex.Position.w = 1;
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 1, 0 );
  triStream.Append( vertex );
  // Right Bottom
  vertex.Position.x = particle[ 0 ].Position.x + c;
  vertex.Position.y = particle[ 0 ].Position.y + d;
  vertex.Position.z = particle[ 0 ].Position.z;
  vertex.Position.w = 1;
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 1, 1 );
  triStream.Append( vertex );
}

```

In case it isn't obvious, I'm using the `w` component of the input vector as the input value for the rotation.

So far so great, until I move the camera and the quads aren't facing the camera any more. So, obviously I need to rotate them.

An approach to solving that was quickly found online, so I adjusted the shader:

```
[maxvertexcount(4)]
void GeometryShaderProc( point VertexShaderInput particle[1], inout TriangleStream<PixelShaderInput> triStream ) {
  PixelShaderInput vertex = (PixelShaderInput)0;
  vertex.Color = particle[ 0 ].Color;
  vertex.Texture = particle[ 0 ].Texture;
  vertex.Position.z = particle[ 0 ].Position.z;
  vertex.Position.w = 1;

  float3 planeNormal = particle[ 0 ].Position.xyz - CameraPosition;
  planeNormal.y = 0.0f;
  planeNormal = normalize(planeNormal);

  float3 upVector = float3(0.0f, 1.0f, 0.0f);
  float3 rightVector = normalize(cross(planeNormal, upVector));

  // Left Top
  vertex.Position.xyz = particle[ 0 ].Position.xyz - rightVector + upVector;
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 0, 0 );
  triStream.Append( vertex );
  // Left Bottom
  vertex.Position.xyz = particle[ 0 ].Position.xyz - rightVector;
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 0, 1 );
  triStream.Append( vertex );
  // Right Top
  vertex.Position.xyz = particle[ 0 ].Position.xyz + rightVector + upVector;
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 1, 0 );
  triStream.Append( vertex );
  // Right Bottom
  vertex.Position.xyz = particle[ 0 ].Position.xyz + rightVector;
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 1, 1 );
  triStream.Append( vertex );
}

```

Great! Now my quads are always facing the camera, but they no longer rotate around their center. I *thought* it would be simple enough to combine both approaches, but I just keep failing.

So, how do you do this, properly?

---

After applying the solution proposed by Nathan Reed and fixing a couple of other issues, I've now finally arrived at this version:

```
[maxvertexcount(4)]
void GeometryShaderProc( point VertexShaderInput particle[1], inout TriangleStream<PixelShaderInput> triStream ) {
  PixelShaderInput vertex = (PixelShaderInput)0;
  vertex.Color      = particle[ 0 ].Color;
  vertex.Texture    = particle[ 0 ].Texture;
  vertex.Position.z = particle[ 0 ].Position.z;
  vertex.Position.w = 1;

  float3 planeNormal = particle[ 0 ].Position.xyz - CameraPosition;
  planeNormal = normalize( planeNormal );

  float3 upVector = float3( 0.0f, 1.0f, 0.0f );

  // Rotate up vector around plane normal
  float ux = planeNormal.x * upVector.x;
  float uy = planeNormal.x * upVector.y;
  float uz = planeNormal.x * upVector.z;
  float vx = planeNormal.y * upVector.x;
  float vy = planeNormal.y * upVector.y;
  float vz = planeNormal.y * upVector.z;
  float wx = planeNormal.z * upVector.x;
  float wy = planeNormal.z * upVector.y;
  float wz = planeNormal.z * upVector.z;
  float alpha = sin( particle[ 0 ].Position.w );
  float beta  = cos( particle[ 0 ].Position.w );

  upVector.x = planeNormal.x * ( ux + vy + wz ) + ( upVector.x * ( planeNormal.y * planeNormal.y + planeNormal.z * planeNormal.z ) - planeNormal.x * ( vy + wz ) ) * beta + ( -wy + vz ) * alpha;
  upVector.y = planeNormal.y * ( ux + vy + wz ) + ( upVector.y * ( planeNormal.x * planeNormal.x + planeNormal.z * planeNormal.z ) - planeNormal.y * ( ux + wz ) ) * beta + (  wx - uz ) * alpha;
  upVector.z = planeNormal.z * ( ux + vy + wz ) + ( upVector.z * ( planeNormal.x * planeNormal.x + planeNormal.y * planeNormal.y ) - planeNormal.z * ( ux + vy ) ) * beta + ( -vx + uy ) * alpha;

  float3 rightVector = normalize( cross( planeNormal, upVector ) );
  upVector = cross( rightVector, planeNormal );

  rightVector *= particle[ 0 ].Size.x;
  upVector    *= particle[ 0 ].Size.y;

  // Left Top
  vertex.Position.xyz = particle[ 0 ].Position.xyz - ( rightVector * 0.5 ) + ( upVector * 0.5 );
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 0, 0 );
  triStream.Append( vertex );
  // Left Bottom
  vertex.Position.xyz = particle[ 0 ].Position.xyz - ( rightVector * 0.5 ) - ( upVector * 0.5 );
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 0, 1 );
  triStream.Append( vertex );
  // Right Top
  vertex.Position.xyz = particle[ 0 ].Position.xyz + ( rightVector * 0.5 ) + ( upVector * 0.5 );
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 1, 0 );
  triStream.Append( vertex );
  // Right Bottom
  vertex.Position.xyz = particle[ 0 ].Position.xyz + ( rightVector * 0.5 ) - ( upVector * 0.5 );
  vertex.Position = mul( float4( vertex.Position.xyz, 1.0 ), ViewProjection );
  vertex.TextureCoordinate = float2( 1, 1 );
  triStream.Append( vertex );
}

```

The first problem I had was that the resulting rotation would happen around one corner of the quad, not the center. Another issue was that I was using an approach designed for billboards, which stand on the "ground". So they were never fully rotated at the camera.

Given that the components of the up vector are all one and zero, it could probably simplified further, but for the time being, I wanted to leave it verbose. Hopefully the shader compiler realizes this fact as well.

# Answer
> 3 votes
Probably the simplest way to modify your code to get rotation (roll) is to modify the calculation of `upVector`. Specifically, `upVector` should be rotated around the `planeNormal` axis by the desired roll angle; then the calculation of `rightVector` and all the vertex positions will incorporate the rotation, too.

A convenient formula for this is Rodrigues' rotation formula, which expresses rotation about an axis by an angle in terms of vector operations.

---
Tags: hlsl, directx11, particles, slimdx, geometry-shader
---


# Question
Title: Load character animation on button press - Unity3D
I am new to Unity3D and I am going to develop a simple animation application. There is a human character and there are three button Eg:- "jump", "down" , "roll", I want to bind the animation files with the human character once the player presses the corresponding button. I need your help to know that what are the steps that I need to follow...let me know if anyone has good reference, thank you very much...

# Answer
> 5 votes
First off: There is the unity scripting reference, it is the best tool when creating anything with Unity3d.

> http://docs.unity3d.com/Documentation/ScriptReference/
>
> http://docs.unity3d.com/Documentation/ScriptReference/Input.GetKeyUp.html For input keys read about the Input.GetKeyUp - Returns true during the frame the user releases the key identified by the key KeyCode enum parameter. If you want to have the player walk straight you will want to use the function Input.GetKeyDown

For creating basic character movement, go through official unity3d guides and play around the unity basic assets, which contain the two different character controllers.

```
/// This script moves the character controller forward
/// and sideways based on the arrow keys.
/// It also jumps when pressing space.
/// Make sure to attach a character controller to the same game object.
/// It is recommended that you make only one call to Move or SimpleMove per frame.
var speed : float = 6.0;
var jumpSpeed : float = 8.0;
var gravity : float = 20.0;
private var moveDirection : Vector3 = Vector3.zero;
function Update() {
    var controller : CharacterController = GetComponent(CharacterController);
    if (controller.isGrounded) {
        // We are grounded, so recalculate
        // move direction directly from axes
        moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,
                                Input.GetAxis("Vertical"));
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= speed;

        if (Input.GetButton ("Jump")) {
            moveDirection.y = jumpSpeed;
        }
    }
    // Apply gravity
    moveDirection.y -= gravity * Time.deltaTime;

    // Move the controller
    controller.Move(moveDirection * Time.deltaTime);
}

```

> http://docs.unity3d.com/Documentation/ScriptReference/CharacterController.Move.html

For tutorials I have once found an entire tutorial, how to script a unity3d rpg game in C# from scratch.

> http://www.youtube.com/watch?v=H7UF3wga5W0
>
> http://Digitaltutors.com have some awesome tutorials on unity covering all basics. (They are paid)
>
> http://www.youtube.com/user/BurgZergArcade?feature=watch You could start by watching some of the vids on this channel, they are free and there are over 50 hours of C# scripting lessons, they youtuber explains carefully everything.

Good luck

EDIT:

I have missed the part where you wanted to make an "Animation", so if you want to move your character around you should use the physic vector3 functions that I mentioned before. In case you meant playing back a pre-made animation from some external 3d graphic program you should take the animation from the project view drag and drop it on the item that is supposed to be animated. The function is called Animation.Play

> http://docs.unity3d.com/Documentation/ScriptReference/Animation.Play.html

```
 // Plays the walk animation - stops all other animations in the same layer
    animation.Play("walk");
    // Plays the walk animation - stops all other animations
    animation.Play("walk", PlayMode.StopAll);

```

---
Tags: unity, animation, character
---


title: Immediate GUI - yae or nay?

text:
# Question
Title: Immediate GUI - yae or nay?
I've been working on application development with a lot of "retained" GUI systems (below more about what I mean by that) like MFC, QT, Forms, SWING and several web-GUI frameworks some years ago. I always found the concepts of most GUI systems overly complicated and clumsy. The amount of callback events, listeners, data copies, something to string to something - conversions (and so on) were always a source of mistakes and headaches compared to other parts in the application. (Even with "proper" use of Data Bindings/Models).

Now I am writing computer games :). I worked with one GUI so far: Miyagi (not well-known, but basically the same Idea as all the other systems.)

It was horrible.

For real-time rendering environments like Games, I get the feeling that "retained" GUI systems are even more obsolete. User interfaces usually don't need to be auto-layouted or have resizable windows on-the-fly. Instead, they need to interact very efficiently with always-changing data (like 3d-positions of models in the world)

A couple of years ago, I stumbled upon "IMGUI" which is basically like an Immediate Graphics mode, but for user interfaces. I didn't give too much attention, since I was still in application development and the IMGUI scene itself seemed to be not really broad nor successfull. Still the approach they take seem to be so utterly sexy and elegant, that it made me want to write *something* for the next project using this way of UI (I failed to convince anyone at work :(...)

let me summarize what I mean by "retained" and "immediate":

Retained GUI: In a separate initialization phase, you create "GUI controls" like Labels, Buttons, TextBoxes etc. and use some descriptive (or programmatical) way of placing them on screen - all before anything is rendered. Controls hold most of their own state in memory like X,Y location, size, borders, child controls, label text, images and so on. You can add callbacks and listeners to get informed of events and to update data in the GUI control.

Immediate GUI: The GUI library consists of one-shot "RenderButton", "RenderLabel", "RenderTextBox"... functions (edit: don't get confused by the *Render* prefix. These functions also do the logic behind the controls like polling user input, inserting characters, handle character-repeat-speed when user holds down a key and so on...) that you can call to "immediately" render a control (doesn't have to be immediately written to the GPU. Usually its remembered for the current frame and sorted into appropiate batches later). The library does not hold any "state" for these. If you want to hide a button... just don't call the RenderButton function. All RenderXXX functions that have user interaction like a buttons or checkbox have return values that indicate whether e.g. the user clicked into the button. So your "RenderGUI" function looks like a big if/else function where you call or not call your RenderXXX functions depending on your game state and all the data update logic (when a button is pressed) is intermangled into the flow. All data storage is "outside" the gui and passed on-demand to the Render functions. (Of course, you would split up the big functions into several ones or use some class abstractions for grouping parts of the gui. We don't write code like in 1980 anymore, do we? ;))

Now I found that Unity3D actually uses the very same basic approach to their built-in GUI systems. There are probably a couple of GUI's with this approach out there as well?

Still.. when looking around, there seem to be a strong bias towards retained GUI systems? At least I haven't found this approach except in Unity3D and the original IMGUI community seems to be rather .... .. quiet.

So anyone worked with both ideas and have some strong opinion?

Edit: I am most interested in opinions that stem from real-world experience. I think there is a lot of heated discussions in the IMGUI-forum about any "theoretical weakness" of the immediate GUI approach, but I always find it more enlightening to know about *real-world* weaknesses.

# Answer
Nay. I've done paid gamedev work on an awful 'retained mode' GUI and on an awful 'immediate mode' GUI and although both made me want to tear my eyes out, the retained mode approach is still clearly the better one.

The downsides of immediate mode are many:

* they don't make it easy for artists and designers to configure the layout;
* they make you mix logic with presentation;
* they make it harder to have a single consistent input model;
* they discourage complex controls of dynamic data (eg. list views);
* layering becomes very awkward (eg. if I call RenderComboBox, the drop-down box can't possibly render yet because it needs to go above the rest of the window - same for tool-tips)l
* configuring rendering style ends up being done with globals (ick) or extra function arguments (ick);
* performance can be poor because calling all these functions to query values that may or may not have changed tends to create many small objects, stressing the memory manager;
* ...and I can't even imagine how painful it would be to allow someone to drag bits the GUI around and re-order them. You'd have to maintain a data structure telling you where to render everything - which is much like rewriting a retained mode system yourself.

Immediate mode GUIs are tempting for lone programmers who want a quick HUD system, and for that purpose they are great. For anything else... just say no.
> 39 votes

# Answer
As someone with five or six years of actual experience with IMGUI on the desktop, I feel obligated to defend it. All of the responses (and the question itself) are based on a very restricted definition of IMGUI, and there seem to be a lot of questionable claims being made.

A lot of it originates from the assumption that an IMGUI library can't retain any data under-the-hood. This isn't true at all. A sophisticated IMGUI library will in fact retain about as much data as an equivalent RMGUI library. The difference is that an IMGUI library mostly **caches** results, whereas an RMGUI library maintains authoritative state. In IMGUI, the application provides a function that takes the current model state and produces a GUI for that state. This is the authoritative definition of the GUI. The library is responsible for making sure that the on-screen GUI matches the result of that function. This doesn't mean that it needs to fully evaluate that function each frame and fully rebuild the GUI. That's the point of caching.

With this view of IMGUI, you can in fact do advanced layout, and the performance is quite reasonable. You can also retain actual authoritative state if it makes the interface easier. The point of IMGUI is not to make the application retain everything. The application probably doesn't want to have to store the position of every scrollbar and the expanded/collapsed state of every tree node. The point is to be able to procedurally specify the contents of those tree nodes and their very existence.

I would go through and respond to all the IMGUI criticisms point by point, but I don't really understand a lot of them. Most of them seem to stem from some fundamental belief that IMGUI is hackish and RMGUI is well-structured, which I guess stems from the above misunderstandings. There's no inherent reason that IMGUI libraries should have trouble with complexity or have to be littered with globals or mix logic with presentation. I will say that the advantages of IMGUI become less important the more artist-driven your content is, but I'm not sure why it would actually be worse for artist-driven content. (I don't personally use artist-driven content, aside from style sheets for things like colors, font/border sizes, etc., but I don't see why it would be harder to implement than for RMGUI.)

In my mind, IMGUI is unquestionably a good thing. It gives you a much better model for reasoning about your GUI. It becomes much more functional and reactive, and you minimize the amount of mutable state that you have to reason about. On the other hand, implementing a sophisticated IMGUI library is quite a challenge, and definitely more difficult than implementing an equivalent RMGUI library. It's a tradeoff between library complexity and application complexity. If you're planning on building complex apps (or even a lot of simple apps), the tradeoff is very good. If you're doing this for one single app, and it's pretty simple, you'll probably achieve your goal faster with RMGUI.

In any case, good luck!
> 42 votes

# Answer
> The GUI library consists of one-shot "RenderButton", "RenderLabel", "RenderTextBox"... functions that you can call to "immediately" render a control (doesn't have to be immediately written to the GPU. Usually its remembered for the current frame and sorted into appropiate batches later).

I would go so far as to say that this doesn't constitute a GUI library. It's just a bunch of rendering functions.

Rendering the GUI is the *easiest* part of making a GUI. Take a text box for example. I'm going to assume the easiest possible case: a simple single-line entry text box.

`RenderTextBox` will just draw a text box. It will do some simple text measurement and draw the glyphs on the screen. It will *not*

* Detect that the user has clicked the mouse in the control and move the cursor to the proper location in the string.
* Detect that the user double-clicked the mouse in the control and select a block of text.
* Detect that the user pressed the "Home" key and move the cursor to the front of the text.
* Detect that the user pressed a valid key and modify the string accordingly. If text was selected, the selected portion will be replaced with the inserted text.

I can keep going, but I think my point is clear. If you want to use `RenderTextBox` to draw a text box, all you will get is a static, non-functional text box. Any actual *functionality* must be implemented by you.

Doing text measurement and drawing glyphs? That's the *easy* part of GUI work. GUI stands for "Graphical User Interface". The last two words, where you take input from the user and do something with it, are the hard part.

Game players expect GUI controls to work reasonably. In a PC-style environment (ie: mouse and keyboard), if players see a text box, they expect it to work like a regular text box. They expect to be able to move around in it with arrow keys, jump to the front and end with home and delete, select letters in it, etc.

That means you're going to have to implement all of this UI code. You have to test what control was clicked. You then have to do something based on which control was clicked. You have to have the concept of an "active" control, the one that gets keyboard input. Different controls must respond differently to different types of user interaction.

Basically, you're going to need a `TextBoxWindow` class.

Let's say you're implementing a game options screen. So you have your different groups of options: gameplay, graphics, sound, controls, etc. So you have a list of different groups on the left side of the screen. Each group brings up a series of controls that the user can manipulate. What happens when the user presses the Tab key?

Well, it depends on what control is active. If one of the group controls is active (was most recently clicked), then it moves to the next group. If instead one of the controls *within* the group is active, then it moves to the next control in that group. That's how the system is intended to work.

So not only must an active control process keyboard input, it must now farm any unprocessed input to the control that *owns* it. Either that, or the controls must be in some kind of linked list, so that it can go back and forth. That means there needs to be default behavior in each control.

This sounds more and more like a retained GUI, doesn't it? The only difference is that... *you* are the one doing the hard work. Using someone elses GUI is *supposed* to be a way to do less work. But the effort it takes to make a GUI respond as the user *expects* is non-trivial.

Remember: the UI isn't for you, it's for your *users*. It's for the player. It should behave as they expect it to. And if it doesn't, then *you* have failed.

> User interfaces usually don't need to be auto-layouted or have resizable windows on-the-fly.

That is a limited and limiting thought.

I could give the spiel about different games having different UI needs, that some games *do* need resizeable windows and so forth. But there's a much bigger problem.

Your kind of thinking leads to the Gratuitous Space Battles problem.

If you've never played that game, it's a cheap, indie, and very GUI-heavy game. The actual gameplay is all done in the GUI (it's a "setup the units and watch them fight" kind of game). The problem?

**THE GUI CANNOT BE RESCALED!**

Oh, this is fine if you're using a normal monitor or have normal eyesight. But if you're me, for example, who runs a ridiculously huge monitor (one so big that you have Windows scale up the size of all text so you can actually read it), this is *terrible*. The text is microscopic. There's no way to change the font size.

Granted, GSB is a GUI-based game, so it's absolutely inexcusable for them. A GUI-lite game can probably get away with it.

Never assume that your user is looking at their game *exactly* as you are. To do so is folly.

Having a GUI system that can rescale itself to the user's resolution, a truly resolution-independent GUI, requires layout to be part of the GUI system itself. If you're not going to provide that, then your text is going to appear tiny on someone's giant monitor. This is *not* a good thing.

So I would say that your thinking on this subject is shortsighted. You *do* need that stuff. You need what retained GUIs provide. Oh, you may not need *everything* any particular GUI system provides. But you need some of it.

The boilerplate work you need to do to get data to the system is a small price to pay next to having reasonable assurance that the user can interact with controls correctly and that it will resize itself to fit the player's needs.

You might be able to get away with an immediate-mode GUI if you don't take much user input from the player. But that'd be about it.
> 16 votes

# Answer
A while ago IMGUIs also caught my interest, as a test I wrote a couple of tutorials to familiarize myself with the techniques (start here if you're interested, but it's not much more than C#/XNA + the original 'tutorial' here).

I really liked IMGUIs for a short while because the info they display is always up-to-date and correct (since there is no state you always feed to actual data). But in the end I lost interest so normally now I use retained GUIs again.

In the end I thought that the immediateness of the GUI made it harder to separate the GUI from the data and at times I tried to decouple things more by introducing some state, breaking the elegance of IMGUIs. I also don't think that writing code for retained GUIs is more work than writing code for IMGUIs and I like that retained GUIs can be fired and forgot about, and I really like events :).

However, every time someone mentions IMGUIs something inside me wants to try again, and try harder to get it right, because there really is some elegance in there, I'm just not 100% sure if it will always make your job easier. I'd say try it out, maybe try as I did and write some tutorials (I find the best way to learn new techniques is by explaining them to others).
> 9 votes

# Answer
I worked a lot with Unity3D GUI system, which works just as you described. And I must say, I hate it with a passion.

"Immediate" approach works really good in some cases. First, when you only need a couple of buttons and labels - think shooter HUD, for example. Creating them with "retained" approach is not very hard, but its super-easy with UnityGUI. Second case is when you need to stuff lots of controls on screen, but do not really care about layout. Especially when exact controls are only known at runtime. This is not actually useful in any game, but really helpful when making tools running inside Unity editor.

However, any half-complex GUI - for an (MMO)RPG or a strategy game, for example - inevitably turns into a horrible mess of indecipherable code, full of special cases and breaking in tons of ways. When building such a GUI, you usually have pretty specific layout that must work for any resolution and be able to show whatever data you send its way. You need things like, for example, moving some buttons lower to make way for longer text. With "retained" GUI, you can have a control that does that automatically. With "immediate" mode, *there are no* controls, so you have to do everything explicitly.

Another problem with UnityGUI (not sure if it happens to all immediate mode GUIs) is that, for example, a `Button()` call works without considering any other GUI calls. So, if one button is on top of another, a click will press *both* buttons at the same time. This is definitely not what user expects, so this adds another special case to handle.

To live with all this, I've always written my own wrapper around UnityGUI that turns it into a "retained" mode system: controls that store their own state and just call required `GUI` functions every frame for me.

I can't say that "immediate" mode is *definitely* worse than "retained", but I certainly feel much better working in "retained" mode.
> 8 votes

# Answer
I am going to defend IMGUI here because some of the problems that were listed previously can be solved if you are willing to write the code for it. Additionally if you do write the code for it you then have a robust library that is re-usable and only very rarely requires modification.

* loading GUI from schema

perhaps at first it seems that artists do not have a lot of flexablity with IMGUI, this is solved or improved with loading GUI layout from an xml or JSON schema.

* menu layer draw calls

this problem is solved with sorting, you should create UI Manager class that sorts the order of draw, I solved this problem in C# XNA with moveable, click-able panels that draw on top of each other. I can post pseudo code if asked.

* list boxes

can you draw strings from an array? can you define rectangle areas from the height and width of the fonts of those strings? can you create a ratio of the size of your scroll button by the height of all those rectangles added together? Then you are halfway to creating a listbox with a scrollable button to move up or down. I thought it was going to be hard, but it turned out to be much more simple than I thought. no buffers, no states, no callbacks involved.

* separating data from GUI

don't let the individual panels, buttons, boxes hold the data. I know that at my first attempt of IMGUI was immediate but only in the graphic sense. I made the mistake of retaining data on the UI. It was almost a philosophical shift to think differently on where to place and modify data via the UI changes.

* GUI from SDKs

this is the limit and functionality of the SDK's code, not yours. I find that SDK UI (Hammer, Unity, UDK) is almost a new language to learn anyway. In fact they are similar to me as Windows.Forms, both are set up for the broadest possibility and therefor have some extra weight in complexity.

and lastly watch this \> http://mollyrocket.com/861
> 7 votes

# Answer
> User interfaces usually don't need to be auto-layouted or have resizable windows on-the-fly. Instead, they need to interact very efficiently with always-changing data (like 3d-positions of models in the world)

It depends on the genre and game in question. A good inventory management system is vital for most any RPG. You going to want something that handle layouts for you, supports scroll bars, drag n' drop, tooltips, and other features much easier to implement using Retained GUI.

I can't think of a way to drag n' drop with an immediate GUI that doesn't take a lot juggling or user state saving such as changing the Z buffer temporarily and storing time info to rule out a click that happened to move a bit.

But from a design perspective I have trouble imagining a world without my GUI events. Also an Immediate GUI is not compatible with OOP forcing you to resort to procedural programming.

The simplicity afforded by immediate GUIs comes at the cost of additional complexity in your code that grows rapidly as the complexity required by you UI increases; where as a good retained GUI is more complex originally but scales better. So below a certain point of complexity a immediate GUI is adequate but for most situations I'd rather a retained GUI.
> 4 votes

---
Tags: gui
---


title: Fixing my button in flash?

text:
# Question
Title: Fixing my button in flash?
I am writing a small point and click adventure game for my friend, (and I need the practice) and I cannot figure out why I keep getting this error message. Basically what happens is when I run the program in Macromedia Flash it comes up with an output window saying:

```
Scene=Scene 1, Layer=Layer 1, Frame=1: Line 1: Statement must appear within on handler
btn

```

The buttons will also not switch to the frame I have told it to go to. I don't have enough rep to post photos so I have posted two on Imgur.

This link here shows the code I have imputed: https://i.stack.imgur.com/ChFgg.jpg

This link here shows the error message that I get when I try to run my program: https://i.stack.imgur.com/w0ddk.jpg

I have tried finishing the frames that the code is directed too but have had no luck. I have also tried running the SDK "Check Syntax" and came up with no problems. I suspect that it is not incorrectly written code, but is just missing something. Any ideas?

# Answer
> 1 votes
I believe that instead of the line

```
btnjump.onRelease = function() {

```

you should have the line

```
on (release) {

```

---
Tags: flash
---


# Question
Title: Dealing with "jumping" sprites: badly centered?
Thing is, I've used darkFunction Editor as a way to get all the spriteCoordinates off a spriteSheet for each individual sprite, and parse the .xml it generates inside my game. It all works fine, except when the sprites are all similarly sized, but when a sprite changes from a small sprite into a big one, such as here:

When from walking from some direction, to attacking, it starts "jumping", appearing glitchy, because it's not staying in the same correct position, only doing so for the right attacking sprite, due to the drawing being made from the lower left part of the rectangle.

I think someone experienced will immediately recognize the problem I mean, if not, when I return home soon, I will shoot a little youtube video demonstrating the issue!

So the question is: what possible solutions are there? I've thought that some sort of individual frame "offset" system might be the answer, or perhaps splitting, in this case, the sprite in 2: the sword, and the character itself, and draw sword according to character's facing, but that might be overly complex. Another speculation would be that there might be some sort of method in LibGdx, the library I'm using, that allows me to change the drawing center (which I looked for and didn't find), so I could choose from where the drawing starts.

# Answer
> 2 votes
To "choose from where the drawing starts" in libgdx, you use the function:

```
batch.draw(texture, x, y, srcX, srcY, srcWidth, srcHeight)

```

where (x,y) is the onscreen coordinate you want to start drawing at, and (srcX,srcY) is the texture coordinate you would like to draw from.

---
Tags: java, animation, sprites, libgdx
---


title: 2D Water top surface profile

text:
# Question
Title: 2D Water top surface profile
I am trying to create the effect of the water surface thickness with a vertex-fragment shader.

I am in a 3D game environment but It's a scroll view so a "2D" view. Here is a good tutorial of creating such effect in real 2D using fragment shader.
But this can't be used in my case I think. For the moment I have only a plane were I apply refraction.

And I want to apply the water thickness effect. But I don't know how to do it.
I am not trying to create some water deformation/displacement using vertex for the moment, this is not the point.

I don't know if it's possible with a simple quad maybe should I use an object like this.

Here are some examples.

I don't have any idea on how to create this effect.

Thanks a lot !

\[**EDIT**\] Added Rayman water effect to have a better reference of the effect.

# Answer
> 1 votes
Have a value in the shader that specifies wetness. Smaller than 0 means air, greater than 1 means water, and in between means meniscus.

Here is some pseudo code:

```
vec2 uv2 = bigWaves(uv); // modify the texture coords to create a wavy water effect
float wetness = (uv2.y - 0.1) * 100;

if( wetness<0.0 )
{
    gl_Fragment = texture2D(screen_texture,uv); // is air - no refraction or effect
}
else if( wetness>1.0 )
{
    vec2 uv3 = smallWaves(uv2); // modify the texture coords to create a ripply water effect
    gl_Fragment = texture2D(screen_texture,uv3); // is water - with refraction
}
else
{
    gl_Fragment = vec4(1,1,1,1); // solid white meniscus
}

```

This is the simplest I can make it. If it were me, I would do something a bit more complicated to antialias the meniscus and apply more refraction there or something, but I can't tell you what because it would take aesthetic iterations. Also, I would tint and blur the water sample. But I'll leave all that up to you.

---
Tags: opengl, unity, directx, shaders, hlsl
---


# Question
Title: Is it feasible for a Server to send nothing more than a tile-based area to a Client?
To start, I have a good amount of background in networking (hardware, routers, ex.) but very little knowledge past the basics of network programming. This may seem like a stupid question, but I want to know what I am getting myself into while fathoming the implementation of multiplayer in my game.

I am creating a tile-based world, which is generated through a simple 2D Array. Let's say something like World\[100\]\[100\], for simplicity's sake.

Currently, the render method only renders the tiles based on the resolution of the window, plus one tile (for smooth rendering during movement.) No matter how large the world is, (10x10, 1million x 1million) the rendering is flawless in performance.

The gameplay needs nothing more than to know what is in the currently visible (rendered on screen +1) and at the most possibly SOME information of tiles in an area around the player.

So anything more sent by the Server wouldn't be the full tile information. Ex. Items laying on the ground, ground type, trees, etc. would not be important in the area outside the player's view, but would only be what the Client/Player needs to know about in those tiles. (Ex. Ultima Online's 'incoming names' where players could know a Character \[player or monster\] was just beyond the tiles in their rendered view.)

I do not know very much about networking, so perhaps as I learn this might answer my question. However, I am curious if this is a feasible solution or if the idea is simply laughable.

The information being sent would be about a 10x15 area of tiles, and each tile holds information about what is on the tile. More efficiently, everything would be an Object, where the tile holds all the Objects on the tile. Ex. Tile\[4\]\[4\] holds Sword#23452, Rock2, Tree5, Player3, Monster4.

Empty tiles would send nothing more than terrain type \[Grass, Sand, Water\] if not already loaded during Initialization/Load. Some tiles would have a handful of objects \[Tree2, Sword#924, Gold, Corpse, Rock3\].

So I cannot imagine that a tile would have very much information to send to the Client from the Server, since the Client mainly only needs to know the Texture that needs to be loaded and Position to place it on screen. Position being only two integers and Texture being one integer for a list of files to tell the client to render.

At the craziest, the Server would have to send 150 tiles with information of only a handful of Objects OnLOAD, and from then on update only changes to tiles (if any) and any new tiles (10 to 15 everytime a player moves in a direction) and the direction of movement for characters on screen (so the client can simulate smooth movement between tiles).

I assume I am correct in thinking this is an incredibly low amount of information being sent over the internet or between peers, so it should have little problems with performance even over laggy connections? Or am I so ignorant of networking that my mind will be blown when I finally get around to opening up my book on multiplayer networking?

If it is a very low amount of information being sent between Client/Server, would it make more sense to simply load the entire World on Initialization? Or 'Map' if the World is excessively large. And then after LOAD, send only tiles which are updated?

I am still pondering how I should specifically deal with data. The book I am using as reference wants me to have a Linked List, where I add and remove objects, so everything is a bool. "Is there a Character? Is there a Tree?"

I was thinking of a different approach, such as a container which holds objects, and Server logic that sends only what is required to tell the Client what to render. Possibly with objects that hold networking information within itself, which is sent out when called for by the Server.

# Answer
You are on the right track.

Consider Minecraft. Minecraft only loads the areas (also called chunks) immediately surrounding players. This is how the server is able to run without running out of memory, and why clients don't get bogged down from network traffic.

> If it is a very low amount of information being sent between Client/Server, would it make more sense to simply load the entire World on Initialization? Or 'Map' if the World is excessively large. And then after LOAD, send only tiles which are updated?

This is exactly what you should do. Only send the data that you need to send.

1. When a client joins, send it a chunk of the tile map (or all if it, if you're dealing with small areas)
2. When the player tries to modify a tile, send that data to the server.
3. When a tile changes state, send a packet with that information to all relevant clients.

If you're just sending a 2D array of tile IDS, the size of the data can be very low, especially if you have less than 256 different tile types. In that case, you could use a single byte (or unsigned char). So if you're sending 100x100 tiles to the player, and each tile only consists of a single byte... You get the idea. It is not a lot of data.

The Minecraft community has done a wonderful job documenting its protocol: http://mc.kev009.com/Protocol

http://www.minecraftwiki.net/wiki/Classic\_server\_protocol
> 6 votes

# Answer
It is generally a good idea to only send the information to the client which is supposed to be shown to the player. Following this principle reduces network traffic and prevents cheating.

But keep in mind that when the player moves their character, you certainly want to start the move on the client-side before receiving the confirmation from the server to make the game appear less laggy and more responsive. That will likely mean that you also want to start scrolling the screen to an area which isn't loaded yet. This forces you to leave this part of the map blank and replace it with the actual world when it has loaded. That would be quite an immersion-breaker. For that reason you should preload the area in a certain radius around the players screen.

The size of the preloaded area depends on how fast your players can move and how long their average latency will be.
> 3 votes

# Answer
The amount of data you are sending from the Server to the Client can be INCREDIBLY insignificant. If this is all you need to send, I would vehemently suggest loading as much as you can on Load, so it is even less data required. The amount sent on load will be small enough to justify the load time, the memory usage will be nearly non-existent unless your world is ridiculously oversized, and you will need to update almost no data at all.

I imagine you could also do some neat tricks to optimize lag prediction which compensates for the average delay a user experiences, allowing for predictable movement with characters.

Also prioritizing the insignificant data with Character movement and Character actions/reactions being highest in priority can help to make sure even laggy players feel very little lag.
> -1 votes

---
Tags: networking, multiplayer, tiles, tilemap, world-design
---


title: Lightning Effect PyGame

text:
# Question
Title: Lightning Effect PyGame
I want to create a Lightning Effect Like http://www.youtube.com/watch?feature=player\_embedded&v=mmU2GAYGVSU for my game.

The following **blog** explains it briefly but I am not able to understand the following line:

```
midPoint += Perpendicular(Normalize(endPoint-startPoint))*RandomFloat(-offsetAmount,offsetAmount);

```

**UPD**: I went through older question posted at gamedev.stackexchange and found following explanation:

---

```
Normalize(endPoint-startPoint):

```

That line gets a unit vector (vector of length 1) from startPoint to endPoint

---

```
Perpendicular(Normalize(endPoint-startPoint))

```

then gets a vector perpendicular to that (i.e. at right angles to the line)

---

I want to know whether python has inbuilt function for

* Getting a unit vector (vector of length 1) from startPoint to endPoint
* Getting a vector perpendicular to that (i.e. at right angles to the line)

# Answer
> 3 votes
Pygame has a vector math module. There you have the methods normalize and rotate, which you can use to construct unit and perpendicular vectors respectively.

http://www.pygame.org/docs/ref/math.html

---
Tags: pygame
---


# Question
Title: Farseer: Shooting a ball in a certain angle?
How can I shoot a ball in a certain angle? When I press the Space key, the ball should be shot in a 45 degree angle. How can I do that?

# Answer
> 3 votes
```
float angle = MathHelper.ToRadians(45);
float power = 20; // <- tunable value

Vector2 direction = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));

fixture.Body.ApplyLinearImpulse(power * direction);

```

The above applies an instantaneous force to the object. You could also set `Body.LinearVelocity` directly.

To check for the space key being pressed (rather than held down), you want to do something like this:

```
 KeyboardState keyboardState = Keyboard.GetState();

 if(keyboardState.IsKeyDown(Keys.Space) && lastKeyboardState.IsKeyUp(Keys.Space))
 {
     // apply the impulse here
 }

 lastKeyboardState = keyboardState; // store this between frames

```

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


title: Check for Updates

text:
# Question
Title: Check for Updates
How would you make your game check for updates at the beginning of startup, and if there are any updates, how would you make them install? Thanks in advanced

# Answer
> 4 votes
Seeing as this is XNA, the simplest method is probably to use **ClickOnce**. This has built-in support for managing updates for you.

See the tutorial on MSDN, which points out where in the ClickOnce wizard you can set up automatic updates (you can also modify these settings in the project properties later on).

# Answer
> 2 votes
One simple method is to provide a 'launcher' that checks for an update using the HTTP protocol, downloads it with HTTP, installs it and then starts the game.

**1)** User starts the game (which is actually the launcher). The launcher downloads and parses some kind of manifest file that details the available updates. The manifest may look something like this pseudo XML:

```
<update version="2" from="1">
    <url>http://www.example.com/version_0_2.zip</url>
</update>
<update version="3" from="2">
    <url>http://www.example.com/version_0_3.zip</url>
</update>
<update version="3" from="1">
    <url>http://www.example.com/version_0_1_to_0_3.zip</url>
</update>

```

The manifest has enough information for the launcher to update the game from it's current version to the latest version. In this example the latest update is version 3 and there are files to download to update the game from version 1 and version 2 installs. The above XML also tells the launcher that if the user has version 1 it can update immediately to version 3 by downloading the correct update archive.

If you are going to publish frequent updates, you will definitely want to write some tools to generate the manifest and archives automatically.

**2)** If the currently installed version is older than the latest update then download the required update over HTTP. Show a progress bar or something to keep the user occupied! Once the download has completed, decompress the files to where they should be. The update files are simply archives with all the files that have changed between versions. Decompress them over any existing files.

**3)** Launch the game.

If your aim is to publish on Steam, the App Store or Google Play then most of this is handled for you.

This is a very basic framework, you might also consider:

* Allowing the user to skip updating.
* Only checking for updates every N hours or days.
* Check that the user has enough drive capacity to install the update BEFORE downloading it.
* Check that the user has permissions to modify existing files or create new ones where the game is installed.
* Pre and post update scripts or executables. i.e. The latest update changes the save file format. The pre-update script backs up the existing saves and the post-update script converts the old saves to the new format. This could be implemented in the game engine itself.
* If the update is content only and doesn't modify the game's executable file, the game engine itself might handle the the decompressing during startup.
* Instead of the update archives containing every file that has been modified or added, you could instead use a diff tool to create the updates and the launcher would patch the changes into the exiting files. See also Delta encoding. Depending on the files being diffed and patched, this can greatly reduce the size of the updates.
* The update archives might themselves contain another manifest file with more detailed updating instructions that the launcher can understand.
* A method made popular with the Quake engine was for each update to come in sequentially numbered archive files, and the engine only loaded an asset from the highest numbered archive it was found in. i.e. game01.zip and game02.zip both contained an asset called explosion.wav, but the engine would only load the (newer) explosion.wav from game02.zip. If game03.zip was later added with a newer explosion.wav file, it would be used instead.
* Because you chose to use HTTP instead of inventing your own protocol, when your game becomes uber-popular you can benefit from a content delivery network hosting your updates.

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


# Question
Title: How do I scroll to follow my sprite in the physical world?
I am using andengine to make a game where a sprite (player) is going up across the stage, and I want the camera to stay centred on the sprite the entire time.

This is my world so far:

```
final Rectangle ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2, vertexBufferObjectManager);
final Rectangle roof = new Rectangle(0, 0, CAMERA_WIDTH, 2, vertexBufferObjectManager);
final Rectangle left = new Rectangle(0, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager);
final Rectangle right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager);

final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef);

/* Create two sprits and add it to the scene. */

this.mScene.setBackground(autoParallaxBackground);

this.mScene.attachChild(ground);
this.mScene.attachChild(roof);
this.mScene.attachChild(left);
this.mScene.attachChild(right);

this.mScene.registerUpdateHandler(this.mPhysicsWorld);

```

The problem is that when the sprite reaches the top wall, it crashes. How can I fix this?

# Answer
you could make an int that will cause the map image to scroll for every pixel you move

```
ex: public int map_x = 0;

then when you draw the image

drawImage(map, map_x, 0, null);

now create a key listener.

if(key_IsDown)
{
   if(rightkey)
   {
      map_x=map_x+2;// this moves the map when you hit the right key, so when your man
      moves, the map will scroll behind him, making the character seem to move throughout
      the level.
   }
   //other keylisteners here below.
}

```

so you could have your sprite move, but when your sprite moves on his x axis, the map will scroll through the opposite way in its x axis.

this is how I make my simple 2d Mario type games, very simple method.
> 0 votes

# Answer
You are asking two different things in the title and body of your question. The answer to the question in the title is: use `camera.setChaseEntity`
> 0 votes

# Answer
There is a body called roof. If the player has a body, that is why it crashes. You can just not attach the roof or change its position.
> -1 votes

---
Tags: andengine
---


# Question
Title: How do I eliminate black bar artifacts in AndEngine/TMX plugin?
I used AndEngine gles1 along with the tmx plugin to generate my background maps. The image width is not fit to my virtual device, so I increased the tmx image size. Here is my code for the camera width and Camera Height:

```
CAMERA_HEIGHT = 320;
final DisplayMetrics displayMetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
float aspectRatio = (float) displayMetrics.widthPixels / (float) displayMetrics.heightPixels;
CAMERA_WIDTH = Math.round(aspectRatio * CAMERA_HEIGHT);

```

But it shows me black bars as follows:

# Answer
I ran into the same problem, and I don't believe that those black bars are caused by the way you're calculating your camera. For some reason, the way AndEngine and its TMX plugin handle sprite sheets causes artifacts like that unless your sprite sheet is designed with at least a one pixel "gutter" between the cells. I reworked the spritesheet using this gimp plugin and that fixed the issue.
> 1 votes

# Answer
Other option is to use this fixer provided by Nicolas. You need to download the code and compile it. Due to the nature of the fixer, don't use it if you tiles use any alpha channel.
> 0 votes

---
Tags: android, tiles, andengine, tilemap
---


# Question
Title: Sprite not rotating around its centre after Scaling at its centre
If I scale a sprite at its centre, then try to rotate it around its centre as well, the rotation does not occur around its centre.

If you need to rotate, for example a scaled ball,the way its working it is set the scale center at the top left (0,0) set the scale that you want, and then set the rotation center to the middle of the scaled sprite, and then apply the rotation modifier.

```
blaBloBliSprite.setScaleCenter(0, 0);
blaBloBliSprite.setScale(0.667f);
blaBloBliSprite.setPosition(557, CAMERA_HEIGHT / 2 - blaBloBliSprite.getHeightScaled() / 2);
blaBloBliSprite.setRotationCenter(blaBloBliSprite.getWidthScaled() / 2, blaBloBliSprite.getHeightScaled() / 2);

```

But I want to scale a sprite at its centre as well.

Is there any way of doing it?

# Answer
You are setting rotation center in the world, not on the sprite. So if you set rotation centre to (0, 0) the sprite will rotate around left corner of the screen. You must set the rotation center similar to this:

`float centerX = sprite.getX() + sprite.getWidth() / 2;`
> 1 votes

# Answer
There isn't enough information to solve this - we have no idea what any of those functions do. Is this custom software? Is it technology from someone else?

I don't understand why one even needs a "scale center". It all seems like an overly complicated piece of tech for something so simple.

Try setting the rotation centre with the unscaled width/height. It's extremely likely that the technology does the rotation **before** scaling. As such, you're scaling the centre twice which would offset your centre and cause the bad rotation and possibly positioning.
> -1 votes

---
Tags: sprites, rotation, andengine
---


# Question
Title: AndEngine - Moving Rectangle using Accelerometer
I'm learning how to create games with this great engine and I'm trying to put my knowledge in order to create a simple game. My first goal is to make a Rectangle moving using accelerometer and create levels using xml parser.

Only the second step works. In fact my player rectangle remains stuck on the screen. I noticed that if I put all my code in a BaseActivity class all works fine, but obviously I would to create few classes to make my game organized and to follow object orientation paradigm. Here is my classes and my first "try" level xml layout.

GameActivity:

```
public class GameActivity extends BaseGameActivity implements IAccelerationListener {

private Camera camera;
private ResourcesManager resourceManager;
static PhysicsWorld mPhysicsWorld;

@Override
public EngineOptions onCreateEngineOptions() {
    // TODO Auto-generated method stub
    camera = new Camera(0, 0, 800, 480);
    EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(800, 480), camera);
    mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);

    engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);

    return engineOptions;
}

@Override
public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) throws Exception {
    ResourcesManager.prepareManager(mEngine, this, camera, getVertexBufferObjectManager());
    resourceManager = ResourcesManager.getInstance();
    pOnCreateResourcesCallback.onCreateResourcesFinished();
}

@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
        throws Exception {
    SceneManager.getInstance().createGameScene(pOnCreateSceneCallback);

}

@Override
public void onPopulateScene(Scene pScene,
        OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
    // TODO Auto-generated method stub

}

@Override
public Engine onCreateEngine(EngineOptions pEngineOptions){
    return new LimitedFPSEngine(pEngineOptions, 60);
}

@Override
protected void onDestroy(){
    super.onDestroy();

    if (this.isGameLoaded())
        System.exit(0);
}

@Override
public void onAccelerationAccuracyChanged(AccelerationData pAccelerationData) {
    // TODO Auto-generated method stub

}

@Override
public void onAccelerationChanged(AccelerationData pAccelerationData) {
    final Vector2 gravity = Vector2Pool.obtain(pAccelerationData.getX()*3, pAccelerationData.getY()*3);
    this.mPhysicsWorld.setGravity(gravity);
    Vector2Pool.recycle(gravity);
}

@Override
public void onResumeGame() {
        super.onResumeGame();
        this.enableAccelerationSensor(this);
}

@Override
public void onPauseGame() {
        super.onPauseGame();
        this.disableAccelerationSensor();
}

}

```

ResourceManager:

```
public class ResourcesManager {

public static final ResourcesManager INSTANCE = new ResourcesManager();

public Engine engine;
public GameActivity activity;
public Camera camera;
public VertexBufferObjectManager vbom;

public void loadMenuResources(){
    loadMenuGraphics();
}

private void loadMenuGraphics() {

}

public void loadGameResources(){
    loadGameGraphics();
    loadGameFonts();
}

private void loadGameFonts() {

}

private void loadGameGraphics() {

}

public static void prepareManager(Engine engine, GameActivity activity, Camera camera, VertexBufferObjectManager vbom){
    getInstance().engine = engine;
    getInstance().activity = activity;
    getInstance().camera = camera;
    getInstance().vbom = vbom;
}

public static ResourcesManager getInstance(){
    return INSTANCE;
}

}

```

SceneManager:

```
package com.indies.fatescape;

import org.andengine.engine.Engine;
import org.andengine.ui.IGameInterface.OnCreateSceneCallback;

public class SceneManager {

private BaseScene gameScene;
private static SceneManager INSTANCE = new SceneManager();
private SceneType currentSceneType = SceneType.SCENE_GAME;
private BaseScene currentScene;
private Engine engine = ResourcesManager.getInstance().engine;

public enum SceneType {
    SCENE_GAME,
}

public void setScene(BaseScene scene){
    engine.setScene(scene);
    currentScene = scene;
    currentSceneType = scene.getSceneType();
}

public void createGameScene(OnCreateSceneCallback pOnCreateSceneCallback){
    gameScene = new GameScene();
    gameScene.registerUpdateHandler(GameActivity.mPhysicsWorld);
    currentScene = gameScene;
    pOnCreateSceneCallback.onCreateSceneFinished(gameScene);
}

/*
 * setScene(SceneType sceneType) which takes care about displaying another scene and keeping track of it
 * by storing references of the displayed scene and its type
 */

public void setScene(SceneType sceneType){
    switch (sceneType){
    case SCENE_GAME:
        setScene(gameScene);
        break;
    default:
        break;
    }
}

public static SceneManager getInstance() {
    return INSTANCE;
}

public SceneType getCurrentSceneType() {
    return currentSceneType;
}

public BaseScene getCurrentScene() {
    return currentScene;
}

```

}

GameScene:

```
public class GameScene extends BaseScene {

private PhysicsWorld physicsWorld;

private static final String TAG_LEVEL = "level";
private static final String TAG_ENTITY = "entity";
private static final String TAG_ENTITY_ATTRIBUTE_TYPE = "type";
private static final String TAG_ENTITY_ATTRIBUTE_X = "x";
private static final String TAG_ENTITY_ATTRIBUTE_Y = "y";
private static final String TAG_ENTITY_ATTRIBUTE_WIDTH = "width";
private static final String TAG_ENTITY_ATTRIBUTE_HEIGHT = "height";

private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_BRICK = "brick";
private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLAYER = "player";

private Body playerBody;
private Rectangle player;

@Override
public void createScene() {
    createPhysics();
    createBackground();
    loadLevel(1);
}

@Override
public void onBackLeyPressed() {

}

@Override
public SceneType getSceneType() {
    return SceneType.SCENE_GAME;
}

@Override
public void disposeScene() {

}

private void createBackground() {
    setBackground(new Background(Color.BLUE));
}

private void createPhysics(){
    physicsWorld = GameActivity.mPhysicsWorld;
}

private void loadLevel(int id){
    final LevelLoader levelLoader = new LevelLoader();
    final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(0, 0.01f, 0.5f);

    levelLoader.registerEntityLoader(TAG_LEVEL, new IEntityLoader() {

        @Override
        public IEntity onLoadEntity(String pEntityName, Attributes pAttributes) {

            return GameScene.this;
        }
    });

    levelLoader.registerEntityLoader(TAG_ENTITY, new IEntityLoader() {

        @Override
        public IEntity onLoadEntity(String pEntityName, Attributes pAttributes) {

            final Rectangle levelObject;
            final int x = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_X);
            final int y = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_Y);
            final int width = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_WIDTH);
            final int height = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_HEIGHT);
            final String type = SAXUtils.getAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_TYPE);

            if(type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_BRICK)){
                levelObject = new Rectangle(x, y, width, height, vbom);
                Body body = PhysicsFactory.createBoxBody(physicsWorld, levelObject, BodyType.StaticBody, FIXTURE_DEF);
                physicsWorld.registerPhysicsConnector(new PhysicsConnector(levelObject, body, true, false));

                return levelObject;
            } else if(type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLAYER)){
                player = new Rectangle(x, y, width, height, vbom);
                playerBody = PhysicsFactory.createBoxBody(physicsWorld, player, BodyType.DynamicBody, FIXTURE_DEF);
                physicsWorld.registerPhysicsConnector(new PhysicsConnector(player, playerBody, true, true));

                return player;
            } else
                throw new IllegalArgumentException();
        }
    });

    try {
        levelLoader.loadLevelFromAsset(activity.getAssets(), "level/" + id + ".lvl");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

```

BaseScene:

```
public abstract class BaseScene extends Scene {

protected ResourcesManager resourcesManager;
protected Engine engine;
Activity activity;
protected Camera camera;
protected VertexBufferObjectManager vbom;

public BaseScene(){
    resourcesManager = ResourcesManager.getInstance();
    engine = resourcesManager.engine;
    activity = resourcesManager.activity;
    camera = resourcesManager.camera;
    vbom = resourcesManager.vbom;

    createScene();
}

// Abstraction

public abstract void createScene();
public abstract void onBackLeyPressed();
public abstract SceneType getSceneType();
public abstract void disposeScene();

}

```

Layout:

```
<?xml version="1.0" encoding="utf-8"?>
<level width="1000" height="780">
        <entity x="0" y="0" width="20" height="20" type="player"/>
    <entity x="100" y="100" width="100" height="30" type="brick"/>
    <entity x="200" y="200" width="50" height="30" type="brick"/>
</level>

```

# Answer
Your application is waiting for the signal that the `onPopulateScene` step has finished. You never send the signal, so it never starts. Change your `GameActivity` class like this:

```
@Override
public void onPopulateScene(Scene pScene,
        OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
    pOnPopulateSceneCallback.onPopulateSceneFinished();
}

```

This should do the trick!
> 0 votes

---
Tags: android, physics, andengine, xml
---


# Question
Title: Get Unity to read in objects name without the need to hard code
I'm trying to get away from having to hard code in the names of objects I want my code to use.

For example, I'm use to do it this way:

```
    TextAsset test = new TextAsset();
    test = (TextAsset)Resources.Load("test.txt", typeof(TextAsset));

```

What I want to know, is there a way to have so that when I drag my test.txt file onto my object in Unity, my code automatically gets the name of that object?

I'm wanting to do this so once I write the code, I don't need to back in and change it should I wish re-use it.

# Answer
> 3 votes
Yes, if you have a GameObject in the scene you can make a public field of the type TextAsset that can be changed in the editor.

For example, this is an array of TextAssets:

```
class ItemReader : MonoBehavior
{
    public TextAsset[] DataFiles;
}

```

After attaching the containing script to an object in the scene, the result looks like this:

# Answer
> 0 votes
You cant use Resources.Load without using a string, i dont think that Resources accept any overload arguments.

Have u tried to define a public variable (so you can assign your object via editor) and than use it instead of strings?

Something like:

```
using UnityEngine;
using System;

public class test : MonoBehaviour {
public TextAsset tx;

    void Start()
    {
     Debug.Log(tx.name);    }
    }

```

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


# Question
Title: Neverending game development: how do I finish my game?
I have started developing my first iPhone game with Cocos2D in May 2012 after quitting my job as Bioinformatician in an important research center. Before quitting **I spent six months studying some basics of Objective-C and Cocos2d**. I moved back to my parents place leaving an important relationship in a different country and leaving all my friends and "social life" there.

Since then I stayed "locked" (trying of course to build some social life and to have healthy daily walks) in my room developing a game for iPhone. **Has been more than a year now and I haven't finished yet**. I spent a big big sum of money in graphics and music and involved lot of people that are now waiting for the release. They keep asking "when will you finish?" and I say "I am nearly there". The reality is that I "think" I am nearly there but then I have bugs to solve and thing I thought would take a week to develop take 2 weeks or more (the Pi greek rule..).

The reality is that **I am fed up with coding**. If I was coding with 100% of focus and motivation I could probably finish it in little time but I see that my performance are quiet weak in this period.

I start to feel depressed as soon as I start coding. I have been away from keyboard for two weeks and I felt like getting back to real life. Now that I am back coding with only my screen on the horizon I feel like that I really have to finish and that to do so I have a neverending mountain still to climb. Bugs to solve and more importantly some bits of the game structure still to implement.

It feels like being on top of the Everest, with no oxygen and a small invisible path to follow.

**My questions:**

* Anyone there that felt the same?
* Any advice (apart of "keep calm and carry on")?

# Answer
Have people play it. The last little bit of the game's development can leave even a skilled developer feel helpless, as they scavenge over and over to get the last bits of the game done. Take a deep breath, get something working, organize a to-do list of remaining elements, and get it to "good-enough" condition. Then release it.

If there's anything you missed on your checklist, you'll find it and (hopefully) patch it quickly. Having solid feedback that (a) yes, you got something done, and (b) you still needed work here, here and here, is a good way to get yourself motivated to keep working, and out of the blue funk of the prerelease.

Also, imagining a slow drum beat helps the psychological torment of "neverending" development. Relax. Keep rhythm. Cruise. Don't look towards the end. You'll get there eventually, if you just keep moving.
> 6 votes

---
Tags: game-industry, productivity
---


# Question
Title: Which is better: More puzzle apps in Store or more puzzle levels in a single app
The Question: Given a freemium model (ad-supported with in-app-purchase of additional levels/hints)... are chances of overall success better with a single puzzle app with lots (but varied) levels/playing-styles, OR... multiple apps, each app focused on a singular theme/playing-style?

Scenario: Our puzzle engine can support multiple types of puzzles based on the puzzle-piece styles. While the game mechanics are roughly the same, changing the puzzle piece changes the visual aesthetic of the app and gameplay somewhat. The puzzle piece imparts a theme of sorts to the puzzle. Sorry for the lack of further specifics.

I feel that multiple apps will allow us to market the different content more easily. I worry though that spreading the content over say, 4 different apps might limit the playing life of each individual app (the app content is mathematically limited). At which point you hope that cross-promotion will guide your player to the additional app/content.

Are there any precedents here? I've assumed that with the freemium model having more apps in the pipeline is always a good thing. But having your 4 apps on a single player's device sounds challenging.

# Answer
> 2 votes
At the risk of sounding hackneyed, I think you have to ask yourself if your interest is in making *money* or in making *games*.

If your primary goal is just to extract as much money from this project as possible and you don't really anticipate going back to the well, then there is a coherent case to be made for going the 'SEO route', splitting the game up into several different titles promoted in different ways to optimize your possible monetization.

On the other hand, if you're legitimately interested in shipping the *next* game too, and in having a consistent customer base for your titles, then IMHO it behooves you to do what's 'right' for your customer base, and if you see this conceptually as a single game with perhaps several different sub-modes (which it sounds as though you do), then it's very likely your players will see it as a single game too, and if they think you're trying to drain them for their money by splitting it up then they'll be less inclined to check out your next project.

Both approaches *are* crapshoots; to be blunt, you're going to have to get more than a little lucky to make any money either way, and either approach *can* potentially give you the 'winning lottery ticket' that makes you the next Gung Ho. But trying to build a community around your games has the potential to give you *several* draws at the lottery, with building odds each time as the community from one game checks out the next and brings a new group of people with them; it's IMHO the approach more likely to lead to any real success in the long run.

# Answer
> 3 votes
I can't give a precise answer, but there are a few balancing considerations to think about:

* More variety and options within a single app is good. Everyone loves variety, and it might lead to the game being kept installed longer.
* However, if they game gets *too* big, taking up too much local storage or increasing load times, it will likely be better to split up the apps. Some mobile games are meant for quick fun when you have just a couple of minutes to spare: prolonged loading times may mean that users just don't get a chance to play.
* App discoverability / marketing strategy: If you have multiple apps, it is statistically more likely that one of them will get picked up and become popular. However, if you have one bigger/broader app, it is more likely to get featured status and maintain "momentum" (remaining on top downloads for longer periods of time).

Just personal opinion as an end user with no hard data to back it up. I have not developed a mobile game yet, but I have been thinking about this subject a lot.

# Answer
> 1 votes
You could go with the multiple types of puzzle in a single game, if it is going to be the freemium only with a single app you might get the chance to reach to top 100 apps. If you divide it into hundreds they will be less popular but more likely they will be spotted by someone using a random search because of the number.

If you take the game "Pou" it has become popular because it has a wide variety of games inside of one app. Puzzles and other time killers, they haven't split those time killers into ten apps.

I recently downloaded a game called Chicken Revolution from Itunes where you play a chicken warrior or something like that.

The game offered me some kind of in-game reward for downloading some other game from their arsenal. I downloaded it and it has turned out to be a copy of the game I downloaded earlier, the game systems stayed the same only sprites of chickens were replaced by zombies. The zombie revolution~ also had an option for me to earn money from downloading some other game. After that, it turned out that there were over 10 games based on the same game logic, systems with only names and art swapped. I personally dislike such situations, and eventually I haven't paid for the game.

---
Tags: marketing, puzzle, levels, appstore
---


# Question
Title: Include deprecated OpenGl "immediate mode" context in OpenGl 4?
I'm working on an app that uses immediate mode in all of it's draw routines and I'd like to keep those functions intact when updating our graphics drivers to OpenGl 4.

My intention is to get the app functioning on 4.x and then convert the code to use VBOs.

I've read there's a way to load a more "full" context that includes deprecated libraries but I have not found an actual implementation to base mine off of.

# Answer
You can attempt to create a context with the compatibility profile. However, you aren't guaranteed to be able to *succeed*.

As a practical matter, all Windows and Linux drivers will provide compatibility profile support. OSX does not. But then again, OSX doesn't support OpenGL 4.x either, so you can't use it either way.
> 6 votes

# Answer
This will depend entirely on the drivers. Since immediate mode is deprecated, it's up to the hardware manufacturers if they want to support it or not (mostly not).

I suggest you reverse your process and convert to VBOs first. Then upgrade and get the remainder of your OpenGL function calls updated to work with 4.x.

There are libraries out there that attempt to emulate immediate mode, but I don't think integrating more libraries into your code is a step you want to take if your final goal is VBOs.
> 0 votes

---
Tags: opengl
---


# Question
Title: Mixing Javascript with C++ for mobile development?
I have a few games for the iPhone, Android, and Windows 8 that I built using native C++. This works great but is really limiting when I try to create menus and start screens.

I have read about rapid development using jQuery Mobile and Phonegap but have never used any of these frameworks. However there looks to be an advantage using this to ceate my game menus and simple screens.

Is it possible to mix my existing C++/OpenGL game code with JavaScript used for simple navigation, obviously this would need to compile into a native binary for iOS, Android, and BB. Is this possible?

I am all ears to any of the following to solve this; a framework, technique, or any approach that can make this happen.

# Answer
See the PhoneGap Plugins Wiki page.

For Android you write an Java plugin that wraps your native C++ code via JNI and then you can use that as a plugin for PhoneGap. For iOS, you'd write an Objective-C++ wrapper. Other platforms have their own native interfaces, which generally you can use as a shim between PhoneGap/JavaScript and C++. There are other technologies similar to PhoneGap that likely work the same way. I'm not aware if you can directly bind native C++ with the PhoneGap API, but if you can, the documentation should describe how; otherwise you're going to have to write a platform-specific shim.
> 2 votes

---
Tags: c++, android, javascript, ios, mobile
---


# Question
Title: Are July and August bad months to release an iPhone game?
After one year of indie game development I end my development cycle in summer time. I spoke recently with a marketing advisor and I was told me that I should never release something over the summer as everyone (especially in southern European countries) tends to go on holiday and not to read blogs/magazine etc..

I am not 100% sure about this as I personally would still read a tech magazine on the beach :).

Are there some statistics available on best time periods to release an iPhone game?

I am aware that many big companies tend to release games in the period between October/November but I can't afford waiting that long.

# Answer
> 3 votes
Some companies target to release their titles **around Christmas**. Other companies target **E3**. There's a lot of buzz around E3 and it is coming soon. So it might be actually a good time to release in summer. And of course, when people go on holiday nowadays, they take their iPhones to the beach and they might just need something to play when they are sunbathing.

Edit:

1. you might want to read this article: Mobile Development Lesson Learned: Ship Now!
2. Not indie games, but big games are released every month
3. XBOX market indie games sorted by release date, they are released all the time too...

# Answer
> 2 votes
No month is a bad time to release a game, if the game is good.

It is more important to not release at the same time of competing games, such as releasing your clone of Angry Birds at the exact same time as a AAA release like Angry Birds 2: The New Birds.

Pay attention to what is going on, and release when the game is ready to release and you feel people will notice your game. Pay attention to what popular blogs and game sites are discussing, as releasing during a media dry spell can be great for publicity.

# Answer
> 1 votes
"Releases" or "launches" only make sense (and those conventional rules only apply) *if a lot of people are expecting your product*. I notice AAA developers and large studios releasing games around just before Christmas (such as Mario Bros Wii and Mario Kart) so that might matter (because these games do make a great Christmas gift).

But if nobody's ever heard of you or your company, then you're releasing it into a very big place with a lot of things (other apps) already moving around and taking up space. You can hope your app catches on by word of mouth or by advertising yourself, but it doesn't matter *when* you release it. I think there is just too much going on for that kind of thing to *matter* \- what really matters is how good your app is. You won't fail *because* you released in August.

---
Tags: iphone, game-industry, release
---


# Question
Title: Is the Manhattan distance monotonic when used as heuristic function?
I have a square-based map. Only horizontal and vertical movement is allowed (no diagonals). Movement cost is always 1.

I'm implementing an A\* algorithm on that map, using the Manhattan distance as a distance heuristic. Is this heuristic consistent? Can I can avoid checking `g(node)` against nodes that are in the CLOSED set?

Edit: By consistent I mean monotonic.

# Answer
To actually answer your question: the manhatten distance is consistent when you're constrained to moving vertically/horizonally along an unweighted grid *(this can be easily shown by the definition on wikipedia)*. So yes, in your case you can avoid rechecking nodes in the closed set.

However, once you allow diagonal or any-angle movement, manhatten distance becomes nonadmissible because it overestimates diagonal costs, which necessarily means it's not consistent.
> 12 votes

# Answer
Yes, the Manhattan distance between two points is always the same, just like the regular distance between them. You can think of the Manhattan distance being the X and Y components of a line running between the two points.

This image (from Wikipedia) illustrates this well:

The *green* line is the actual distance.

The *blue*, *red* and *yellow* lines all represent the same Manhattan distance (12 units). No matter what combination of movements *up* and *right* you draw from the bottom-left point to the bottom-right, you'll get the same total Manhattan distance.
> 31 votes

# Answer
In extension of Byte56's answer I would like to point out, that in your specific data set, using the *Manhattan Distance* as your heuristic function will actually always be a *perfect heuristic* in the sense that it will always return the *actual path cost* (assuming there is nothing "blocking" the paths).

You should also note, that all nodes in the correct direction (either horisontally or vertically) will yield the same expected distance (because there are many equally short paths to the goal). You should be aware that your priority queue (open set) should, in case of tied priorities, dequeue the latest added node first (LIFO - Last In First Out). By doing so you will only examine the nodes which will end up in the *optimal path*. If you examine equally suitable nodes in a FIFO (First In First Out) manner, you will effectively be examining **all** nodes which are part of a best path. This problem arises because there are multiple equally good paths to the goal node.
> 6 votes

# Answer
I'm not sure what do you mean by "always" consistent. Is the Manhattan distance on a fixed grid independent of the path taken? Yes, as Byte56's answer said.

However, for example, Manhattan distance is not invariant under rotations. E.g., the Manhattan distance (L1-norm) between the origin and a point `(10,10)` is `|10-0| + |10-0| = 20`. However, if you rotate your coordinates by 45 degrees (so now your fixed point lies along one of the directions of the grid), you'll now find the same point is now at `(10sqrt(2),0)`, so has a Manhattan distance to the origin of `10sqrt(2)~14.14`.
> 4 votes

---
Tags: tiles, path-finding, geometry
---


# Question
Title: Most efficient way to draw vertex with OpenGL
I am writing an OpenGL 3D game. There will be tons of triangles for terrain and objects in use.

I am studying from the OpenGL official guide and the first presented method is to call a function `glVertex` after the `glBegin` for each vertex you want to draw.

However this method sounds quite antique and inefficient when you have to draw thousands of triangles. I guess there are methods to store in the graphic card memory the information that does not change at every frame so that when you render each frame that information is already there. While for more "unstable" information probably you have to send new vertex data every frame and so a different tecnique might be more efficient.

Coming to my question: I would like a clear explanation of the most modern and efficient OpenGL functions and tecniques used to send vertex information to the hardware and to give instruction to render.

What are the best ways and OpenGL tools to send the order to render vertex data that seldom changes during the frames (i think of terrain and objects) and what it the best way to send vertex data that changes a lot during frames?

# Answer
> 21 votes
Broadly, the answer is "it depends." The way one would send particle updates is quite a bit different than the way you would send a series of GPU-skinned models.

**Vertex/Index Buffers**

In the general sense, though, everything these days is done with a VBO (*vertex buffer object*). The old immediate-mode API (`glBegin`/`glEnd`) is probably just implemented as a fat wrapper around the driver's internal vertex buffer system.

For static objects, create a static VBO and fill it with your vertex data. If any of the vertices are shared (usually the case), you probably also want to create an index buffer. That both reduces the need to send the same data more than once for changing meshes (potentially saving on transfer bandwidth) and on processing (saving on vertex shading time). Note that you draw with different functions when making indexed vs non-indexed draws.

For dynamic objects, do the same, albeit with a dynamic set of buffers.

**Advanced Notes**

For larger pieces like terrain, you probably won't to break up the mesh into multiple pieces. Making the GPU render a hundred million triangles when only two hundred thousand of them are visible is a huge waste, especially if they're unsorted and there's lots of overdraw and wasted fragment shader invocations. Break up the mesh into large chunks and then only render those that are within the view frustrum. There's also various more advanced culling techniques you can use to weed out chunks that might be in the frustrum but are entirely behind a hill or building or something. Keeping draw call count down is good, but there's a balance to be had (which you have to find for your specific app/hardware) between minimizing draw calls and minimizing the drawing of hidden geometry.

One of the key things to keep in mind with a GPU buffer is that you cannot write to it while the GPU is reading from it. You need to let the driver know that it's okay to *discard* the old copy of the buffer (when it's done) and to give you a new one (if the old one is busy). There is of course for a long time was no function is OpenGL to do this (now there is InvalidateBufferData for GL 4.3 and some older implementations as an extension). Rather, there is a non-standard but common behavior most drivers implement. Do this to discard the buffer before updating it:

```
glBindBuffer(GL_ARRAY_BUFFER, my_vbo);
glBufferData(GL_ARRAY_BUFFER, 0, NULL, GL_DYNAMIC_DRAW);

```

Of course change `GL_ARRAY_BUFFER` and `GL_DYNAMIC_DRAW` to the appropriate values for the buffer. Static buffers won't be updated (or shouldn't be) so you're unlikely to need to worry about discard for such a buffer.

Note that it might be faster to use `glBufferData` or `glBufferSubData` or it might be faster with `glMapBuffer`. It really depends on the driver and hardware. Current generation PC hardware will probably be fastest with `glBufferData` but test to be sure.

Another technique is to use *instancing*. Instancing allows you to make a single draw call that draws multiple copies of the data in a vertex/index buffer. If you had, say, 100 identical rocks then you would want to draw them all in one go rather than making 100 independent draws.

When instancing you need to put per-instance data in another buffer (like each individual's object position). This can either be a *uniform buffer* (*constant buffer* in D3D terminology) or a *texture buffer* or a per-instance vertex attribute. Again, which is faster depends. Per-instance attributes are probably faster and definitely way easier to use, but many common GL implementations still don't support `glBindingAttribDivisor` so you'll have to see if it's available to use and if it really is faster (some older drivers emulated instancing by appending buffers and it ended up being slower to use instancing on them than to make independent draw calls and there's no standard way to find out... the joys of using OpenGL).

There are also algorithms for *vertex cache optimization*, which is the act of ordering vertices/indices in your buffers to play will with the vertex cache on modern GPUs. A GPU will only run the shader for a vertex then cache it in the vertex cache but it might have to be evicted too early to make room for other vertices. (Say, two triangles both share a vertex but there are 100 other triangles drawn between them; the shared vertex will probably end up being wastefully evaluated by the vertex shader twice.)

Some of these features require a new-enough version of GL or GLES. GLES2 did not support instancing, for example.

**Always Profile**

Again, if you care about performance, test each possible method and see which is faster for your app on your target hardware. Not only will different hardware/drivers from different manufacturers be different but some whole classes of hardware are innately different. A typical mobile GPU is a very different beast from a typical discrete desktop GPU. Techniques that are "best" on one will not necessarily be best on another.

When it comes to performance, *always be a skeptic*.

---
Tags: c++, opengl, graphics-programming
---


# Question
Title: XNA 4.0 thick triangle strip to fix aliasing issues upon rotation
My triangle strip based lines are disappearing intermittently when I rotate my camera around the X axis.

I was advised that this is due to aliasing issues and that "At a certain angle when its edge is facing the camera your strip will disappear." So, I was told to give the strip some thickness.

Can someone tell me the best way to do this? Would it be to draw two strips directly on top of each other? This doesn't seem to solve the problem but perhaps I am doing it wrong.

# Answer
Triangles are planar, meaning they do not have thickness. What you seem to be describing is a graphics technique called back-face culling, which basically allows the winding pattern for a triangle to define its normal, and that normal pointing into or out of the view frustum is able to determine whether it is drawn or not. XNA allows you to customize this.

You may be able to get them to draw using that, but you don't likely want to use that for your game. You should be thinking in 3D, start by drawing a cube, which will give you depth in your drawing.
> 1 votes

---
Tags: xna, 3d, xna-4.0
---


# Question
Title: Calculate object coordinates from window coordinates using inverse projection matrix
What I am trying to to is placing 3D Objects (A Sphere) in the world when I click there.

I am using a perspective projection so the first step after calculating the canonical clip coordinates from window coordinates is to reverse the perspective transformation:

```
    void addSphere(int screenX, int screenY) {
    // invert y axis
    screenY = screenHeight - screenY;

    // determine depth of the pixel
    GLfloat z;
    glReadPixels(screenX, screenY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z);

    // transform x and y to canonical clipping space
    GLfloat x = -1 + (screenX / (float)screenWidt) * 2;
    GLfloat y = -1 + (screenY / (float)screenHeight) * 2;
    std::cout << "<" << x << "," << y << "," << z << ">" << std::endl;

    // now we reverse the projection which means we have object coordinates
    // given the MODELVIEW Matrix is identity
    glm::vec4 center = glm::vec4(x, y, z, 1);
    center = inverseProjection * center;
    std::cout << glm::to_string(center) << std::endl;

    // add the sphere centered at the calculated position
    Sphere *sp = new Sphere(center);
    sphereList->push_front(sp);
}

```

The big question is what do I insert for the forth value for the center vector? As far as I see there is no method to get the transformed w value from the framebuffer.

# Answer
As it is normalized clip coordinates (x/w, y/w, z/w, 1) that are finally mapped to the viewport, 1 is the correct w value.

Your z coordinate however is wrong, because while in clip coordinates, z is in \[-1,1\], this range is then linearly mapped to the range set by glDepthRange (usually \[0,1\]).

Also after inverse projecting, you probably need to homogenize your coordinate, i.e. divide by the resulting w value.
> 3 votes

# Answer
You should not read a depth value for this.

You need to use both the inverse projection matrix (to transform to view space) then the inverse camera matrix (to transform to world space). Transform your NDC point (x,y,0,1) to view space using the inverse projection matrix. Set the depth to your near plane depth, remembering that typically OpenGL apps uses a negative Z axis for forward view vector, so you probably want `-nearZ`. Then transform from view to world space using the inverse camera matrix. Your point is now in world space on the camera's near plane.

This should be enough to do a ray cast (from the camera's position through the transformed point on its near plane) to find a ground plane to create your objects on, or you can normalize and scale this vector to put the sphere at some specific distance from the camera.
> 4 votes

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


title: Level Pacing in a Mobile Game

text:
# Question
Title: Level Pacing in a Mobile Game
I've been creating a small little mobile game on and off for a while now.

Having got all the game mechanics in place I'm now trying to figure out how to organise these into levels to get satisfying pacing.

Are there any good guidelines for this? Or articles on it?

I've got a few variables that I can play with that can make the game more interesting and varied for example:

* Number of entities to deal with
* Number of kinds of entities
* Directions they come from.

I just don't have much of a clue how to pace it.

# Answer
This question should help if your game teaches several skills to the player:

How do I elegantly teach players how to play?

Otherwise, it's just a matter of smoothly increasing complexity, by adding more entity, interesting combos, etc.
> 1 votes

# Answer
I don't think there are any books, articles or papers on this topic. The best you can do is to get as many similar games as you can and play them. Find what works well, what doesn't. Use the variables you already have and experiment.

I am doing the same with my game. I picked a couple of the most popular games using similar concepts. Having a couple of beta testers is good as well - just employ your family and friends.

---

Without knowing what are you actually making, it's hard to say how you should pace it. From your description I'd guess it's a Desktop Tower Defense type of game. There's plenty of them out there...
> 1 votes

---
Tags: game-design
---


title: How to decide on game ideas in a team

text:
# Question
Title: How to decide on game ideas in a team
Me and 3 other friends want to make an indie title together. We all have ideas for what game we want to make, but we are facing the dilemma of making a decision on which idea we choose to actually bring to life. Naturally, everyone feels his/her own idea is the best, lol.

Has anyone been in a similar situation? How did you resolve the issue? We though of perhaps starting a poll and having the public opinion make the decision for us, but that puts our ideas out for grabs (i.e. someone may steal them :P). If you haven't been in this situation but still have an opinion/suggestion, please voice it!

# Answer
> 4 votes
Each of you make a small quick and dirty prototype, or draft a design doc. Everyone plays each others games, or reads design docs of each others.

Everyone votes on the game they want to make. Nobody should vote for their own idea. Ties are settled by a 1d20 roll.

This has the benefit of everyone actually analyzing the validity of their idea. And once you decide, you have something already made to roll forward with.

You should be happy to have such problems. Have fun.

# Answer
> 2 votes
I'd say to prototype the toy (not the game, just the part that don't have an "end") of every idea.
Don't need to polish too much, nor have music or menu. Remember, it's just a toy prototype.

Play for a while with every one of them, if it feels good, it's a good candidate.

Just remember to account for complexness...
A complex game to build probably won't work, while a simpler one, with focused objective, is way easier to finish, polish and even play.

# Answer
> 0 votes
Do you want to make the game for yourselves as a hobby project or do you want to monetize the final product? If it is the former, go with Byte56's aproach. But if it is the latter, you should involve other people in the decision as well. Like that TV show where people present their startups to the millionaires and ask for cash, you should create a group of people (jury) who play games and present them your prototypes/draft documents.

Based on their feedback, you can decide, or at least you can decide the ties. You can also create an online survey and send to all your "facebook friends".

You can involve the whole team to create each prototype. This is to avoid the artist's prototype looking fancy but static and programmer's prototype ugly but playable...

---
Tags: dev-groups
---