# Question
Title: How can I get multiple bullets on screen?
I've finally gotten this laser thing to work for my Space Shooter, and so far I've come across a slight problem. I've gotten the laser to position itself at the starting position correctly and move vertically perfectly. Anyway, whenever I hit the space-bar (which is the controls for shooting), it shoots the bullet/laser out, but I have to wait until the bullet clears to shoot another one.

What I want it to do is keep producing bullets until the user releases their hand on the space-bar... here's the code I have so far:

```
if(spacebar)
// this bool variable is set to true once the user presses the space bar
{
    int frame2 = 0;

    if(once2 == 0)
    {
        projectilex2 = x + 19;
        projectiley2 = y + -35;
        //Positions the bullet at the nose of the ship
    }

    if(frame2 == 3)
    {
        frame2 = 0;
    }

    apply_surface(projectilex2, projectiley2, ShootStuff, screen, &lazers[0]);

    frame2 ++;
    projectiley2--;

    once2++;
    if(once2 == 250)
    {
        once2 = 0;
        spacebar = false;
    }
 //This will eventually get better. My shoot function is horrible lol :/
}

```

Does anyone have any ideas as to how I can accomplish this without having to wait for the bullet to clear before I can shoot another one :( ?

# Answer
You really need to have a separate class for your bullets! It will make everything 1000x easier to manage, render and ultimately to answer your question, the ability to keep adding in new bullets when the space bar is held down.

Your class can be as simple as the following (source):

> You could use vectors to create them dynamically.
>
> Example:
>
> ```
> #include <vector>
> using namespace std;
>
> class CBullet
> {
> public:
>     CBullet();
>     ~CBullet();
> };
>
> vector<CBullet *> Bullets;
>
> ```
>
> Then just use something like:
>
> ```
> void Shoot()
> {
>     Bullets.push_back(new CBullet());
> }
>
> ```
>
> And loop through them:
>
> ```
> void DrawBullets()
> {
>     for (int i=0; i<Bullets.size(); i++)
>     {
>         //do stuff here
>     }
> }
>
> ```
>
> But I guess an array of bullets would work just as fine. Personally, I prefer to use vectors.

You will need to add some form of update function to the class to manage the movement and ultimately the collision of your bullet, and if you look at the thread it also shows you a bit further down how to remove bullets from a vector array.

But as a word of advice;

1. Get rid of the magic numbers, http://en.wikipedia.org/wiki/Magic\_number\_(programming).
2. Your naming convention, your variable names should as **clear as water to understand**, "**once2**" & "**frame2** doesn't mean anything in my eyes without a comment or knowing what it's purpose is for. In-fact i can't see personally why you need that last if statement you have. If i could hazard a guess it looks like to be some form of reloading code? As to an example of making your variables clearer, lets take the spacebar boolean you have. Because of your comment, i know that it's changed when the space bar is pressed. To make it clear as crystal however, you can simple change spacebar to something like **"hasSpaceBarBeenPressed"**.

To answer your question:

It seems that you only have 1 instance of your bullet, which gets position at the first time the **spacebar** bool is true. It seems then that because **once2** is incremented and the **spacebar** value is still equal to true, the only time that your 1 bullet instance you have will return to be re-positioned will be when **once2 == 250** which then you reset that **once2** value to 0 and then the **spacebar** bool to false.
> 2 votes

---
Tags: c++
---


title: How to parse & "pack" network commands?

text:
# Question
Title: How to parse & "pack" network commands?
I'm currently creating a game which should be multiplayer (client-server-client), but I'm stuck.

I have been doing crazy things like building a text chain like

```
string networkMessage = userHash+" "+userX+" "+userY+" "+userRotation;

```

but it looks crazy and parsing is also bad

```
string[] pieces = networkMessage.Split(' ');
string userHash = pieces[0];
int userX = pieces[1];
int userY = pieces[2];
float userRotation = pieces[3];

```

So, what is the best way to pack my network commands & parse them on the second side?

Yeah, ehm.. I'm using `TCP` & `StreamReader`/`StreamWriter`

PS: yes, I know that giving client a possibility to set their coordinates is cheating risk and I'll change it later, so server will be more authorative

# Answer
> 5 votes
Given your comment on Blua's answer you should look into two projects: Lidgren and Protobuf-Net. Lidgren is straight-forward and there are multiple tutorials available on how to use it \- ProtoBuf-like packing can be used to provide Lidgren with the network data.

Protobuf is pretty specialized (there is nothing stopping you from using `BinaryReader` or `BinaryWriter` \- but bit-packed is a tiny bit faster and quite a bit smaller). I wouldn't grab the entire library as-is: just the bit packing methods (`VarInt` etc.). Jon Skeet's Implementation (ProtoSharp) is really small and these methods are easy to find within it. Once you have the methods just make your own `BinaryReader`/`BinaryWriter` (I called mine `PackReader`/`PackWriter`) that read and write from the underlying stream. **Avoid `StreamReader` and `StreamWriter` entirely**, `BinaryReader`/`BinaryWriter` are marginally less efficient than ProtoBuf but `StreamReader`/`StreamWriter` are obtusely wasteful and slow for this purpose.

Once you have a writer implementation it's as simple as:

```
// Possibly defined in an interface like IPackSerializable.
public void WriteTo(PackWriter writer)
{
   writer.Write(this.Position);
   // Make some XNA-specific methods. Equivalent to:
   // writer.Write(this.Position.X);
   // writer.Write(this.Position.Y);
   writer.Write(this.Speed);
   writer.Write(this.Name);
}

public void ReadFrom(PackReader reader)
{
   this.Position = reader.ReadVector2();
   this.Speed = reader.ReadVector2();
   this.Name = reader.ReadString();
}

```

# Answer
> 4 votes
I hate C#, what the hell are `StreamWriter` and `StreamReader` supposed to be good for, except luring attention away from the classes that does the useful stuff?

You should use the classes `BinaryWriter` and `BinaryReader`, just by knowing that you will already have grown way better at this.

With the binary classes you can simply write a bunch of floats, integers and strings, and if you run the corresponding read functions in the right order you get all the data back, so for your example you'd just:

```
handle.Write(userHash)
handle.Write(userX)
handle.Write(userY)
handle.Write(userRotation)

```

And then to read the data:

```
userHash=handle.ReadString()
userX=handle.ReadInt32()
userY=handle.ReadInt32()
userRotation=handle.ReadSingle()

```

I also don't like the choice of the polymorphic write method, you have to be careful that the data types you pass to it correspond exactly to the data types you read. Failure to do so does not even result in a runtime error, you simply get garbled data.

**Binary data structures in general**
The string reading and writing use a length prefix, this means that the writer starts out by writing the length of the string as an integer, followed by the plain string. The reader start out by reading the integer, and then read that number of bytes from the string. Thus there is no need for escape sequences or any such bulky workaround know from plain text file types and protocols.

The very same method can be used to build larger data structures. If for instance you'd want to send a variable number of positions followed by some other data you'd start out with an integer telling how many such positions follow, then the data structures for those positions, and then the other data. The reader then know how many such positions to read before continuing with the other data.

If need be you can build such structure in several layers with lists of objects that themselves contain lists of objects etc.

**Considerations**
It may be a good idea to add a little room for expansion of the data format, for instance adding in a byte that must be zero at the end of an object leaves you room for adding one or more optional fields to that object thus making Dataformat v2 a superset of v1. This is mostly relevant for file formats, but I ain't going to say never for streams.

Adding a checksum, or even auto-correcting redundancy may also be a good idea, especially for files. Though TCP and UDP both employ checksums these are rather weak, so very occasionally erroneous data will slip through the internet unless a stronger error check is used.

# Answer
> 0 votes
I think you should use a binary format to avoid a wastw of space.

Shanw Hargreaves proposes the use a PackedVectors: Link

In the Networking Section you have other post:

http://www.shawnhargreaves.com/blogindex.html

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


# Question
Title: How to decide to use OpenGL ES 1.0 or 2.0 for Android?
I started learning some Android development and one of the first things I thought I could make is a simple game. However, I'm faced with one difficult question right off the bat. Should I use OpenGL ES 1.0 or 2.0?

The game I have envisioned will be pretty simple graphically, utilizing 2D(tiled top-down type graphics) and fixed-camera isometric views. I've never used OpenGL in a desktop environment, so I'm oblivious on if shaders will be something I'll use, etc.

According to this page I should use OpenGL ES 2.0 generally for new development. My own phone however just recently(past year) got an update to get it to the required Android 2.2. (I don't even know if it has OpenGL ES 2.0 support)

So basically my question is, will I benefit from any of OpenGL ES 2.0's features over 1.0 and/or is it worth it in terms of compatibility?

# Answer
If you have no or little experience with OpenGL, I would not suggest 2.0.

With OpenGL ES 2.x, you will have to write your own routines for matrix manipulation and write your own shaders. This is a lot of work, a lot can go wrong, and debugging a lot of these things is *very* painful.

Only if you think you'll need some of the features that OpenGL ES 2.0 has should you use it.

**Edit:** If the above isn't enough to scare you away, I suggest you try to make a trivial example in OpenGL ES 1.x and then try to make that same example in OpenGL ES 2.x. You might, for example, draw a rotating cube with a texture applied to it.
> 7 votes

# Answer
Well it depends. I don't have any experience with ES, but the general question is always the same: Old and deprecated fixed-function versus a modern shader-centric approach.

Whereas stephelton is correct in that the old ES 1 API is easier to understand for beginners and it is easier to achieve simple things without understanding the whole API (and it prevents you from becoming one of those guys using shaders without understanding what they're doing), I nevertheless would advise you to start with the modern way of doing real-time graphics right away. Though you may not need the flexibility of shaders at first, it is extremely valueable once you managed the basics. And it is the way to do hardware-accelerated real-time graphics today (and tomorrow).

Whereas compatibility can be a concern (and I don't have an overview over the current stand of ES-devices), on the other hand if using desktop GL you wouldn't artificially limit yourself to GL 1.1 only features, just to support 15 to 20 year old graphics cards. Meaning, progress has to begin somewhere.
> 1 votes

---
Tags: android, opengl-es, mobile, compatibility
---


# Question
Title: Why does my object move faster at 45° than at 90°?
I have objects in my game that move faster at 45 degrees then at 90 degrees.

Each object has:

* Point (x,y) position
* Vector2D (x,y) direction
* Int speed

And what I do during an update, is that a new position is calculated with:

```
position.x += direction.x * speed
position.y += direction.y * speed

```

How do I correct this so that it moves with the same speed at any angle?

# Answer
> 57 votes
This can be explained with the Pythagorean Theorem, which is the following formula:

```
a² + b² = c²

```

In your case, when moving right, you're using (x:1, y:0) which gives us

```
c² = 1 + 0 = 1
c = sqrt(1) = 1.00

```

When moving up and right, you're using (x:1, y:1) which gives us

```
c² = 1 + 1 = 2
c = sqrt(2) = 1.41

```

So as you can see, the length diagonally is longer than the length on the cardinal axes.

As others have mentioned, you should simply normalize your direction vector. If you use XNA, it's done like this:

```
var normalizedDirection = direction;
normalizedDirection.Normalize();
position += normalizedDirection * speed

```

# Answer
> 12 votes
Normalize your direction vector before use.

As explained by MindWorX, this can be simply understood, if your worried about your direction vectors possibly giving you grief, make sure they are unit vectors (magnitude/length of 1).

```
Length(Vector2(1, 1)) == 1.4142135623730951 // first hint of grief
Length(Vector2(1, 0)) == 1

Vector2(1, 1) * 2 == Vector2(2, 2)
Vector2(1, 0) * 2 == Vector2(2, 0)

Length(Vector2(2, 2)) = 2.8284271247461903 // second hint
Length(Vector2(2, 0)) = 2

```

If normalized:

```
normal(Vector2(1, 1)) == Vector2(0.707107, 0.707107)
Length(Vector2(0.707107, 0.707107)) == 1 // perfect

```

# Answer
> 7 votes
How are you calculating your direction? If 45 degrees is `(1,1)`, then it's certainly going to be faster than 90 degrees `(1,0)`.

I suggest you use something like this:

```
direction.x = Math.Cos(angleInRadians);
direction.y = Math.Sin(angleInRadians);

```

To get the angle in radians, you'll have to multiply your degrees with `PI / 180` or even better, use `MathHelper`. Eg.

```
angleInRadians = 45.0 * Math.PI / 180.0; // first method
angleInRadians = MathHelper.ToRadians(45f); //second method

```

# Answer
> 7 votes
Jason,

Rather than having three object attributes,

* Point (x,y) position
* Vector2D (x,y) direction
* Int speed

it is often much easier to combine the direction and speed into a velocity vector. Then you have only two attributes,

* Point (x,y) position
* Vector2D (x,y) velocity

**Updating position**

When you need to update the object's position, it's as simple as:

```
position.x += velocity.x * Δt;
position.y += velocity.y * Δt;

```

where `Δt` is your time delta — or time difference — or time step.

**Updating position and velocity**

It is also very easy this way to handle acceleration (such as from gravity). If you have an acceleration vector, you can update the velocity and position together like this:

```
position.x += (velocity.x * Δt) + (0.5 * acceleration.x * Δt * Δt);
position.y += (velocity.y * Δt) + (0.5 * acceleration.y * Δt * Δt);

velocity.x += acceleration.x * Δt;
velocity.y += acceleration.y * Δt;

```

(This is basically the s = vt + ½at² formula from Physics 101.)

**Applying a speed**

If you want to apply a given speed in some normalized direction, you can set the velocity like this:

```
velocity.x = normalizedDirection.x * speed;
velocity.y = normalizedDirection.y * speed;

```

**Deriving a speed**

And if you need to do the reverse — deriving the speed and direction from a given velocity vector — you can simply use the Pythagorean theorem or the `.Length()` method:

```
speed = velocity.Length();

```

And once the speed is known, the normalized direction can be calculated by dividing the velocity by the speed (being careful to avoid dividing by zero):

```
if (speed != 0) {
    normalizedDirection.x = velocity.x / speed;
    normalizedDirection.y = velocity.y / speed;
} else {
    normalizedDirection.x = 0;
    normalizedDirection.y = 0;
}

```

---
Tags: c#, 2d, physics, geometry
---


title: What are C++ libraries?

text:
# Question
Title: What are C++ libraries?
I am a total beginner in C++ and programming generaly.

I have watched a couple hours of C++ tutorials and read a lot about it (Can anyone recommend some tutorials?), but what I've come across and couldn't understand was Libraries.

I want to develop games in C++ (I think, it seems the most interesting at the moment). I can understand that I need a library for game programming in C++, but I don't know much about libraries, what specifically a library is, or where to find these libraries.

Thank you for your time. This is my first question here. I apologize if it wasn't a proper question for this website, or if the english was bad. I still hope you can give me some kind of answer and/or reponse.

# Answer
> 2 votes
C/C++ libraries are modules of already-compiled code which are accessed through code you will write.

For example, TinyXML is a library that provides a lot of the functionality you would need to parse XML data, allowing you to work with XML without having to write your own parser.

Libraries come in two different flavours: static libraries and dynamic libararies.

* A static library is specifically used at *compile time*, which means the libary must be present in the correct location (often but not always somewhere in your project folder) when you want to compile your C/C++ application, since it is *compiled into* the executable, and indeed, the compiler knows it must be there and will not compile without it. Under Windows, static libraries are usually suffixed `.lib`, while under the \*nixes (includes Android, iOS, MacOS), they are suffixed `.a`.
* A shared library is only required to be present for use at *runtime*. Which means you can compile your code without it. Since a shared library is not actually a part of your application's code (although your application may need it to run without failing), there is a certain overhead, however negligible, in accessing shared libraries (and it *is downright negligible*). When you run your favourite games, you will often see DLL files hanging out in the game's root folder, beside the executable. Those are shared libraries which the executable will need to use when you run it. Under Windows, shared libraries are `.dll`. Under the \*nixes, they are `.so`. There are many differences undoubtedly, but the principle is the same, and most of the time from a coder's point of view they are not noteworthy.

Compiling libaries is another matter, which you can research once you've written a few simple programs in C or C++ and understand the bigger picture a little better. But generally speaking, it isn't too hard and is much like compiling an executable, only the code gets compiled into a non-executable file instead.

---
Tags: c++
---


# Question
Title: Help on 'varying' and 'uniform' keywords in GLSL (OpenGL 4+)
I want to use a shader just for learning purposes but I have a few questions about it.

I have the following code:

**Vertext shader:**

```
const float Eta = 0.66;         // Ratio of indices of refraction
const float FresnelPower = 5.0;

const float F  = ((1.0-Eta) * (1.0-Eta)) / ((1.0+Eta) * (1.0+Eta));

varying vec3  Reflect;
varying vec3  Refract;
varying float Ratio;

void main()
{
    vec4 ecPosition  = gl_ModelViewMatrix * gl_Vertex;
    vec3 ecPosition3 = ecPosition.xyz / ecPosition.w;

    vec3 i = normalize(ecPosition3);
    vec3 n = normalize(gl_NormalMatrix * gl_Normal);

    Ratio   = F + (1.0 - F) * pow((1.0 - dot(-i, n)), FresnelPower);

    Refract = refract(i, n, Eta);
    Refract = vec3(gl_TextureMatrix[0] * vec4(Refract, 1.0));

    Reflect = reflect(i, n);
    Reflect = vec3(gl_TextureMatrix[0] * vec4(Reflect, 1.0));

    gl_Position = ftransform();
}

```

**Fragment shader:**

```
varying vec3  Reflect;
varying vec3  Refract;
varying float Ratio;

uniform samplerCube Cubemap;

void main()
{
    vec3 refractColor = vec3(textureCube(Cubemap, Refract));
    vec3 reflectColor = vec3(textureCube(Cubemap, Reflect));

    vec3 color   = mix(refractColor, reflectColor, Ratio);

    gl_FragColor = vec4(color, 1.0);
}

```

First thing I notice is the `varying` keyword. I couldn't really find out if this is deprecated or not. I'm using OpenGL 4+. So shouldn't that be changed to `in` or `out`?

Other thing is the `uniform` keyword. That means I have to pass a value from my code to my shader right? In this case I have to pass a cubemap. I guess I can figure out how to create one of those later, that's not important right now. But what I do like to know is how to change the value of the variable. I couldn't really find any info about that.

# Answer
> 5 votes
> I'm using opengl 4+.

No you're not. You are using GLSL 1.10. That's what happens when you do not put a `#version` declaration at the top of your shaders.

If you want to use GLSL version 4.10 or 4.20, you have to ask for it: `#version 4.20`.

As for `varying`, yes, that was deprecated in GLSL 1.30 and removed in GLSL 1.40. You should be using `in` and `out`.

> Other thing is the 'uniform' keyword. That means i have to pass a value from my code to my shader right? In this case i have to pass a cubemap. I guess i can figure out how to create one of those later, that's not important right now. But what i do like to know is how to change the value of the variable. I couldn't really find any info about that...

Did you look? The top two hits on Google for "GLSL uniform" explain how they work. "OpenGL uniform" resolves to similarly useful pages.

However, for the record:

A global variable using the `uniform` qualifier means that the value of this variable is set from outside of the shader. The value is "uniform" over the execution of a single `glDraw` call. The API functions that set uniform values for GLSL programs all start with `glUniform`.

`uniform` variables of `sampler` types are special. They represent textures. More details can be found on the wiki.

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


title: Teaching game development with Ruby

text:
# Question
Title: Teaching game development with Ruby
I want to teach game development to kids as part of a course (year-long) involving Ruby. Unfortunately it looks like the game development kits available in Ruby (even in the form of bindings) are pretty limited.

Is the best solution to go with JRuby and use jMonkeyEngine through the JVM? I'd love to have the kids play with creating very basic 3d games. Is there another better solution for Ruby or on the JVM through JRuby?

Average age of kids is probably 9 to 12, with some as young as 5 and as old as 18.

# Answer
> 1 votes
To answer your question, JRuby is probably going to be your most flexible option. An alternative is ruby-processing, but of course that's geared more toward constructing visualizations than efficient game systems.

Is 3D a requirement? A lot more options open up to you without it such as Rubygame, Chingu, Gosu, etc.

---

Now to play devil's advocate, why Ruby over another "beginner-friendly" language?

Python has pyglet. And Panda3D.

And how about Scala? It seems much more friendly to start with compared to Java. Hello World is just this:

```
object HelloWorld {
    def main(args: Array[String]) {
        println("Hello, world!")
    }
}

```

Retains the structure and static typing of Java, but offers less verbose syntax and to option for more dynamic typing and, if you care to get into it, functional programming like you'd get with Ruby blocks. You obviously wouldn't want to throw lambdas around in your game loop, but shader programming has functional characteristics so the learning is still valuable and relevant.

And you can import Java libraries and thus use JMonkey, Slick2D, or whatever you need. It also has a REPL, which I think would be a hugely beneficial educational tool and reason to go with something like Python, Ruby, or Scala.

---
Tags: 3d, jmonkeyengine, ruby, teaching
---


# Question
Title: Why does using multithreading during my load screen increase my load times?
OK, I added a loading screen to my game, and in order for the game able to update and show a loading screen and load stuff in the background I came to the concludsion that I needed to host the loading function on a thread. When I did this, the loading times doubled, if not tripled in length, can anyone thing why this is so?

I set the thread to the highest priority but that hasn't seemed to help (note, this is my first time ever using threads):

```
        gameScreen = new GameScreen(content);

        loadingThread = new Thread(gameScreen.LoadContent);
        loadingThread.Priority = ThreadPriority.Highest;
        loadingThread.Start();

        gameScreen.ScreenState = ScreenState.Loading;

```

**EDIT:**

Loading Screen Class:

```
    Thread loadingThread;

    Screen gameScreen;

    public LoadingScreen(ContentManager content)
        : base(content)
    {
    }

    public override void LoadContent()
    {
        Texture2D background = content.Load<Texture2D>("Screens\\Loading\\Textures\\background");
        Texture2D dropshadow = content.Load<Texture2D>("Screens\\Loading\\Textures\\dropshadow");
        Texture2D logo = content.Load<Texture2D>("Screens\\Loading\\Textures\\logo");

        Sprite background_sprite = new Sprite(background, new Vector2(0, 0));

        int tiles = Variables.SCREEN_WIDTH / dropshadow.Width;

        Sprite dropshadow_sprite_top = new Sprite(dropshadow, new Vector2(0, 0));
        dropshadow_sprite_top.ScaleY(65);
        tiles = Variables.SCREEN_WIDTH / dropshadow_sprite_top.ScaledWidth + (Variables.SCREEN_WIDTH % dropshadow_sprite_top.ScaledWidth == 0 ? 0 : 1);
        dropshadow_sprite_top.TileX(tiles);

        Sprite dropshadow_sprite_bottom = new Sprite(dropshadow, new Vector2(0, Variables.SCREEN_HEIGHT - dropshadow.Height));
        dropshadow_sprite_bottom.ScaleY(65);
        dropshadow_sprite_bottom.Position = new Vector2(0, Variables.SCREEN_HEIGHT - dropshadow_sprite_bottom.ScaledHeight);
        dropshadow_sprite_bottom.TileX(tiles);
        dropshadow_sprite_bottom.FlipY();

        Sprite logo_sprite = new Sprite(logo, new Vector2(Variables.SCREEN_WIDTH - logo.Width, Variables.SCREEN_HEIGHT - logo.Height));
        logo_sprite.ScaleX(45);

        logo_sprite.Position = new Vector2(Variables.SCREEN_WIDTH - logo_sprite.ScaledWidth - 10, Variables.SCREEN_HEIGHT - logo_sprite.ScaledHeight - 10);

        sprites.Add(background_sprite);
        sprites.Add(dropshadow_sprite_top);
        sprites.Add(dropshadow_sprite_bottom);
        sprites.Add(logo_sprite);

        gameScreen = new GameScreen(content);

        loadingThread = new Thread(gameScreen.LoadContent);
        loadingThread.Priority = ThreadPriority.Highest;
        loadingThread.Start();

        gameScreen.ScreenState = ScreenState.Loading;
    }

    public override void Update(GameTime gameTime)
    {
        base.Update(gameTime);
    }

    public override Screen RequestedScreen()
    {
        if (gameScreen.ScreenState == ScreenState.Idle)
        {
            return gameScreen;
        }

        return this;
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        base.Draw(spriteBatch);
    }

```

...

In the GameScreen class:

```
    public override void LoadContent()
    {
        world.LoadContent(content);
        playerRender.LoadContent(content);
        skyRenderer.LoadContent(world, content);

        screenState = ScreenState.Idle;
    }

```

...

In the game1.cs

```
    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);

        Variables.TILE_ALAIS = new GUI.SpriteSheet(Content.Load<Texture2D>("Textures\\Sheets\\terrain"), new Vector2(16, 16));
        Variables.BLOCKSELECTOR_TEXTURE = Content.Load<Texture2D>("Textures\\Sprites\\blockselector");
        OutputBuffer.BUFFER_FONT = Content.Load<SpriteFont>("Fonts\\statusfont");
        Variables.STATUS_FONT = OutputBuffer.BUFFER_FONT;

        screen = new MainScreen(Content);
        screen.LoadContent();

        frameRateCounter.LoadContent(Content);
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        if (screen != screen.RequestedScreen())
        {
            screen = screen.RequestedScreen();
            screen.LoadContent();
        }

        screen.Update(gameTime);
        frameRateCounter.Update(gameTime);
        ProcessInput();

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

        spriteBatch.Begin();
        screen.Draw(spriteBatch);
        //frameRateCounter.Draw(gameTime, spriteBatch);
        spriteBatch.End();

        base.Draw(gameTime);
    }

```

The requested screen function asks the current screen if it should change. The MainScreen.RequestedScreen() just returns LoadingScreen, when then if it has finished building the world and etc. It returns a instance of the game screen class whoose LoadContent method has been threaded.

Any ideas?

# Answer
OK, I fixed my problem - it had to do with me loading the content twice.
> 1 votes

# Answer
If the loading screen is rendering, make sure it is not also locking resources which the loading thread needs to use.

Easy way to tell if the loading screen is chewing up resources due to rendering too often - put a 1000ms Sleep in the render loop of the loading screen, and see if your loading performance comes back to normal.
> 4 votes

# Answer
From the code given there is no definite way of knowing what goes wrong, so this is just a guess and a general piece of advice.

You must make sure that your loading screen use as few resources as possible, it should be a simple rendering task that is run as infrequent as possible. The loading screen thread should itself limit the update rate. Depending on the content it will probably take somewhere between 10 and 30 frames per second to make fluid animation, but typically fluid loading screens ain't that important, so you might go as low as 1 frame per second.

Of course you should also make sure that your threads as far as possible do not need a lock on the same resource, though if they do, the above will greatly limit the damage.
> 1 votes

# Answer
Are you using a DrawableGameComponent? If so, when you add the Component, Initialize and LoadContent get called by the framework.

What I did was have a method that created a component and added it inside a thread.

```
public void InitAndLoadComponent()
{
    gameScreen = new GameScreen(this,content);
    Components.Add(gameScreen);
}

```

Share more of your code and perhaps I can help more.
> 0 votes

---
Tags: xna, c#, performance, multithreading, loading
---


# Question
Title: Creating installer for WinForms XNA with compiled content
I have a Windows Forms application that uses a custom Graphics Device control based on Microsoft's "WinForms Series 1: Graphics Device" sample. The application makes use of a single model (the spaceship model included with the second sample) and its associated texture.

My main project includes a reference to an XNA Game Library project, which contains a Content reference to my Content project. When I build and run the project in either Debug or Release configuration, my model and texture are compiled into XNB format and loaded into the application as expected.

However, when I create an installer (either Windows Installer or ClickOnce) and run it, the content files are not present in any form in the installed location, so obviously I get a runtime exception. I've toggled every option I can find that looks relevant. Am I missing something?

# Answer
> 2 votes
You need to manually include all of your content into the installer. In Visual Studio, right-click on the setup project, then click View, then File System. Under the "Application Folder", add a folder for Content and all of your XNBs, it should look something like this:

As far as I know, there is no way to do this automatically, even if you include the "primary output" of the Content project.

# Answer
> 0 votes
The installer allows you to add a project's output to a location you specify in the file system editor. Try adding the output from the content project. I believe you should be able to put the output from both projects into the same folder.

---
Tags: xna, xna-content-pipeline, windows-forms
---


# Question
Title: Clock hand, how much should I rotate the hand by every frame?
I've got a virtual clock. The clock consists of the actual clock sprite, and a hand to go over it.

I'm able to set how long the clock duration is. Say I set it to: 5 seconds. While the clock time is going, it will eventually stop until it reaches 5 seconds. Until it has reached 5 seconds, the hand will start rotating.

The hand should theoretically be at the same position it was when the clock was initialized. So..the hand should go from 0 degrees to 360 degrees...

The only problem is...I don't know how many degrees I need to rotate the clock by every frame. Like take the 5 seconds for example, how would I know how many degrees the hand needs to rotate based on those 5 seconds, until it has rotated around to 360 degrees?

# Answer
> 8 votes
What you want to do is something called LERP. Stands for Linear Interpolation, and you can do with the follow:

If you know how many seconds have passed, and what is the total, you might do the follow:

`u = total / passedTime`

u is your "progress" variable, on a LERP.

So, as your start value is 0 and the final value is 360, we do the following:

`current = start + final * u`

To your case, we can remap as:

`current = 0 + 360 * u`

That is, if you want to get it state for every frame. If you just want to know how much it has to be increased depending on how many time passed, you can do the following:

`final / total * deltatime`

This is a "specific" LERP case, this is how it is disposed:

deltatime is the time passed since last frame, final is the final value to interpolate(360, in the case), total is the total of the input (5 in the case).

To help you, this is your final formula for your problem:

`360 / 5 * dt`

EDIT:

I've forgotten to mention early, but this last formula will only work because the `total` is given as seconds, and the dt is given as seconds too.

---
Tags: java, rotation, andengine
---


# Question
Title: Character and Weapon animation interaction
If I have two models, for example: some character, and a bow, how do I work with them together in 3DS Max to animate them both (for example, when the character shoots an arrow with his bow, the characters pulls his hand out, the bow is scratching etc).

Also, any guidelines on how to port custom weapon models to UDK?

# Answer
> 2 votes
I'm not sure about UDK but XNA for example can load multiple 3dsmax files and play the animation step by step. I would create 1 3dsmax file with the character shooting the bow, with frame 0 as default pose, frame 1 to 500 (for example) the animation of grabbing an arrow, frame 501 to 1000 to shoot. (frame 1000 is the character in rest stance, like frame 1)

Then I would create a new 3dsmax file and merge this old file, delete the character from it leaving the bow untouched. Next I would create a second file and do the same, but delete the bow and arrow.

Next step is to import the two files into your game, set the coordinates correctly so the character and the bow are aligned correctly. When the user shoots just start playing frame 2 - 1000

The arrow is a different story, when it leaves the bow, all kinds of physics are applied. I would create a new model for this and insert it into your scene as a separate object, on which you can apply game logics (collision detection, physics etc)

For examples on creating animations in 3ds max I suggest a google search.

---
Tags: animation, udk, 3dsmax, character
---


# Question
Title: How to calculate origin and position of a weapon which should be "in hands"?
I'm currently stuck with my game, which is from the top perspective. I'm currently using these sprites for player: (using the second at the top):

And here's what I use for my gun

My problem is that I am not sure how to calculate origin & position to make sure that gun is always in player's hands. This is my code for drawing player and gun

```
spriteBatch.Draw(Textures.Load("player"), new Vector2(playerPosition.X, playerPosition.Y), new Rectangle(35, 2, 27,27), Color.White, player.rotation, new Vector2(playerWidth / 2, playerHeight / 2), 1f, SpriteEffects.None, 1f);
spriteBatch.Draw(Textures.Load("Guns/deagle"), new Vector2(playerPosition.X, playerPosition.Y), null,                   Color.White, player.rotation, new Vector2(playerWidth / 2, playerHeight / 2), 1f, SpriteEffects.None, 1f);

```

With rotation of 0, I'd need to move my gun to `playerPosition.Y + 15` to make sure gun is in guy's hands, but when I do it, it looks fine but as soon as I rotate him, it's even more weird than now.

Here's how it currently looks like, with my specified code above.

https://dl-web.dropbox.com/get/capture-14.mp4?w=40052a2d

All I need is to make sure that gun will be always in guy's hands

# Answer
You need to offset the gun's position based on the rotation of the player. Here's the first formula that comes to mind:

```
x = x + offset*cos(rotation)

y = y + offset*sin(rotation)

```

So in your specific case use this as the gun's position:

```
new Vector2( playerPosition.X + 15 * (float) Math.Cos(player.rotation), playerPosition.Y + 15 * (float) Math.Sin(player.rotation) )

```
> 5 votes

# Answer
I would suggest you treat your sprites as a group of sprites. When rotated, they will all rotate together as a single entity.

This would greatly simplify what you are trying to do. Have a look at: http://msdn.microsoft.com/en-us/library/bb194912.aspx
> 3 votes

# Answer
So here's actually how I solved it:

* I had to apply MindVorX's line of code (origin of weapon should be `Vector.Zero`)
* I had to apply Jannie's logic
* I had to play with multiplier of Sin & Cos

so after all, it looks like

```
        spriteBatch.Draw(
          Textures.Load("player"),
          new Vector2(player.x, player.y),
          new Rectangle(35, 2, 27, 27),
          Color.White,
          player.rotation,
          new Vector2(27 / 2, 27 / 2), // half a player's width & height
          1f,
          SpriteEffects.None, 1f);
        spriteBatch.Draw(
          Textures.Load("Guns/deagle"),
          new Vector2( player.x - 18 * (float) Math.Cos(player.rotation), player.y + 18 * (float) Math.Sin(player.rotation) ),
          null,
          Color.White,
          player.rotation,
          Vector2.Zero, // zero here is important!
          1f,
          SpriteEffects.None, 1f);

```

which results in

Thanks all of you
> 0 votes

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


# Question
Title: How to remove a box2d body when collision happens?
I’m still new to java and android programming and I am having so much trouble Removing an object when collision happens. I looked around the web and found that I should never handle removing BOX2D bodies during collision detection (a contact listener) and I should add my objects to an arraylist and set a variable in the User Data section of the body to delete or not and handle the removing action in an update handler. So I did this: First I define two ArrayLists one for the faces and one for the bodies:

```
ArrayList<Sprite> myFaces = new ArrayList<Sprite>();
ArrayList<Body> myBodies = new ArrayList<Body>();

```

Then when I create a face and connect that face to its body I add them to their ArrayLists like this:

```
face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mBoxFaceTextureRegion);
Body BoxBody = PhysicsFactory.createBoxBody(mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, BoxBody, true, true));

myFaces.add(face);
myBodies.add(BoxBody);

```

now I add a contact listener and an update handler in the onloadscene like this:

```
this.mPhysicsWorld.setContactListener(new ContactListener() {
private AnimatedSprite face2;
@Override
public void beginContact(final Contact pContact) {
}
@Override
public void endContact(final Contact pContact) {
}
@Override
public void preSolve(Contact contact,Manifold oldManifold) {

}
@Override
public void postSolve(Contact contact,ContactImpulse impulse) {
}
});

scene.registerUpdateHandler(new IUpdateHandler() {

@Override
public void reset() { }

@Override
public void onUpdate(final float pSecondsElapsed) {

}
});

```

My plan is to detect which two bodies collided in the contact listener by checking a variable from the user data section of the body, get their numbers in the array list and finally use the update handler to remove these bodies.

The questions are: Am I using the arraylist correctly? How to add a variable to the User Data (the code please). I tried removing a body in this update handler but it still throws me NullPointerException , so what is the right way to add an update handler and where should I add it. Any other advices to do this would be great. Thanks in advance.

# Answer
In JBox2d, to remove at the correct time:

```
public class Main
{
    World world;
    ...

    public void update() //your game loop
    {
        ... //do all actual update loop stuff, including detection of collision/death/destruction
        for (Entity entity : manager.entitiesToRemove)
        {
            world.destroyBody(entity.body); //this might be all you need -- adapt to your own purposes. but you will still need a list such that you remove only at the end of each tick.
        }

        manager.entitiesToRemove.clear();
    }
}

public class Entity
{
    Body body; //body representing this Entity
    EntityManager manager; //set ref via Entity constructor
    ...

    //Call from your contact listener when the entity expires
    //body.userData is set to the Entity representing that body
    //so you can get access to the Entity from the Body, as vice versa.
    public void die()
    {
        manager.removeEntity(this);
    }
    ...
}

public class EntityManager
{
    public List<Entity> entities = new ArrayList<Entity>(); //extant entities
    public List<Entity> entitiesToAdd = new ArrayList<Entity>(); //forthcoming entities
    public List<Entity> entitiesToRemove = new ArrayList<Entity>(); //erstwhile entities <-- the important one for you.
    ...
    public void remove()
    {
        if (!stage.entitiesToRemove.contains(entity))
            stage.entitiesToRemove.add(entity);
            //or just use a Set<Entity>, as dual additions are implicitly prevented.
    }
    ...
    //also add(), and other utility functions for managing entities.
}

```

Use `body.getUserData()` and `body.setUserData()` to read and write `userData` on the `Body`.
> 7 votes

# Answer
If you want to add a `isDead` flag to your user data, just add it to whatever you set as your user data when you create the `Body`.

```
GameObject box = new GameObject(face, boxBody);
boxBody.setUserData(box);

```

Then in `endContact()` flag the bodies you want to be dead as dead:

```
if( a collision happens ) {
    ((GameObject) bodyA.getUserData()).setDead(true);
    ((GameObject) bodyB.getUserData()).setDead(true);
}

```

Then make sure you remove the dead objects in `update()`. Don't do this while the PhysicsWorld is updating:

```
foreach(GameObject go : gameObjects) {
    if(go.isDead()) {
         destroyGameObject(go);
         go.onDestroyed();
    }
}

```
> 2 votes

# Answer
I have similar problem week ago but in C++ and I find solution over the internet! Here is method code that I am using after Box2D world-\>Step and it works:

```
void physics::clean_up() {
std::vector<b2Body *> to_nuke;

b2Body * body = _world->GetBodyList();
for(; body; body = body->GetNext()) {
    gx::sprite * sprite = (gx::sprite *)body->GetUserData();
    if(sprite->is_killed()) {
        to_nuke.push_back(body);
    }
}

std::sort(to_nuke.begin(), to_nuke.end());
// destroying, but skip duplicates!
uint i = 0;
uint size = to_nuke.size();
while(i < size) {
    b2Body * b = to_nuke[i++];
    while(i < size && to_nuke[i] == b) {
        ++i;
    }
    _world->DestroyBody(b);
    b = 0;
}

```

Good luck with porting and have a nice day. I hope you will save your time with this help ;)

edit: the method sprite-\>is\_killed() check if sprite and its physical body is ready to remove.
> 1 votes

---
Tags: android, box2d, andengine
---


# Question
Title: When applying Bloom postprocess, error: "XNA...requires TextureFilter to be Point when using texture format Single."
I have an almost unmodified copy of the bloom sample in my project. I pass it a texture to apply the bloom post process on.

The only modification is that, instead of calling BeginDraw() (to set a render target) in the bloom sample and then doing all of my drawing, I simply do all of my drawing to a rendertarget outside of the bloom sample, and then pass that rendertarget to the bloom sample's Draw() method, which the bloom sample can then use to perform the bloom postprocess.

The texture that I pass to the bloom sample Draw() has format Color, according to the debugger (and by code inspection).

However, on the first draw call in the bloom sample, I get the following error:

The framework produces the error "XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Single."

The code that produces this is as follows:

```
1   public void Draw(RenderTarget2D sceneRenderTarget)
2   {
3       GraphicsDevice gd = Game3.GDM.GraphicsDevice;
4
5       gd.SamplerStates[1] = SamplerState.LinearClamp;
6
7       //gd.SamplerStates[1] = SamplerState.PointClamp;
8
9       // Pass 1: draw the scene into rendertarget 1, using a
10      // shader that extracts only the brightest parts of the image.
11      _bloomExtractEffect.Parameters["BloomThreshold"].SetValue(
12      Settings.BloomThreshold);
13
14      DrawFullscreenQuad(sceneRenderTarget, _renderTarget1,
15                 _bloomExtractEffect,
16                 IntermediateBuffer.PreBloom);

```

If I uncomment line 7 above, then the code runs without error (as point sampling will be enabled), but this should be unnecessary (and is not desired) as all rendertargets involved here are SurfaceFormat.Color -- which is not a floating point format!

Does anyone have any idea what might be going on? Perhaps someone has seen this before, and can give me a clue where to look next.

I have some experience with PIX, but I don't know how to use PIX to debug when the program crashes (basically I only know how to take single frame captures in PIX).

# Answer
> 5 votes
The problem is that although spritebatch only uses texture sampler 0, XNA still complains if texture sampler 1 is set to a floating point format texture.

So when spritebatch was called, to draw using sampler0 as input, XNA produced an error complaining about sampler1 using linear sampling (even though spritebatch wouldn't have used sampler1).

The solution is to make sure that all texture samplers that are bound to floating point textures are set to linear sampling before calling spritebatch.

I.e.:

```
graphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;

```

To me this is pretty silly as it causes unecessary sampler state changes and complexity. Hopefully this is being changed in the next version of XNA.

# Answer
> 1 votes
Something else to keep in mind is there is a bug in XNA4 which will cause this error to come up during device resets. I know your problem is slightly different and already resolved, but perhaps people will discover this page looking for possible solutions related to the same error message caused by slightly different reasons.

http://forums.create.msdn.com/forums/p/63992/392134.aspx#392134

---
Tags: xna-4.0
---


# Question
Title: Android-Handling screen clicks for dynamically moving objects in a view
I have a kind of broad question to ask but I have to start some where so.....What is the best way to handle onscreen clicks for moving objects being drawn on a canvas in a view. Im registering the screen clicks just fine and Im able to get the x and y but when it comes to matching it to an object on screen Im at a loss. I have a really hacky way of traversing through an array of existing objects and checking their onscreen coordinates against the coordinates of each item in the array but its no where near reliable and doesnt work most of the time. when it does work the click ends up not matching the item I clicked on. At the moment this all takes place in a custom view and is being drawn on a canvas but in the future Im going to implement it all in opengl when I have the time.....or the money to pay some one else :0)

Any opinions, links to tutorials, or suggestions would be much appreciated thanks.

# Answer
> 1 votes
I don't think traversing an array of on-screen objects is too hackish because at some level you're going to need to check each clickable area against each click. And it can really be as simple as just taking an array and testing `RectF` against x,y coords using `RectF.contains()`. The alternative is using some space partitioning, like a BSP, but that's almost certainly more than you need.

What might work better for your program, and in particular for Android, is to make a event buffer. You want to keep your processing off the UI thread, so what I've done in the past is make the buffer that acts as a go-between. On the UI thread, the buffer receives incoming events and stores them and that's all. Then in my game thread, when my main loop iterates through the objects, each one just tests against the stored event in the buffer. At the end of the loop, the event in the buffer is cleared.

As for reliability, you might be running into emulator speed issues. The emulator is slow and takes a little while (sometimes like 0.1 seconds for me) to register touch events. By the time the code gets the event, the objects have moved. This part may be easier to debug on a real device. If, on the other hand, you have stationary objects, then it's probably just buggy code. `logcat` is your bff.

---
Tags: android, html-canvas, view
---


# Question
Title: How to get smooth circular input from a thumbstick in XNA?
I have a mouse-based game that I'm trying to get to work nicely with the Xbox gamepad. My major issue is trying to get the cursor to move smoothly like it does with the mouse. Using GamePadDeadZone.IndependentAxes makes it hard to move at slight angles, so I switched to GamePadDeadZone.Circular.

It turns out that the values that I'm getting from the controller are diamond shaped instead of being circular. Pushing all the way up gives me (0,1), and pushing right gives me (1,0), but pushing to the top-right gives me (.7,.7).

This leads to a quite noticeable slowdown when traveling at angles. My game requires the player to move carefully at times and quickly at others, but it's near impossible because you'll move faster or slower depending on the angle of the thumbstick. How can I get truly circular data back?

# Answer
What you describe actually sounds it *is* giving true circular data. If it's circular and the maximum radius is 1, then pushing top-right at exactly a 45-degree angle should give you (0.7071, 0.7071). (That number is sqrt(0.5)).

If you're getting a slowdown when traveling diagonally, then I presume something else is going on. How are you using the controller values to move the player? If you use it as a 2D vector to set the player's velocity, you should get the same speed in all directions. Note that if you had (1, 1) for the vector the player would actually move 40% faster when going diagonally.

If what you *want* is for the vector to come out as (1,1) - which might be the right choice for your game; I wouldn't know - then I think you can do this by calculating the radius and then scaling the vector to make the biggest component equal to the radius, like:

```
r = sqrt(x*x + y*y);
maxComp = max(abs(x), abs(y));
if (maxComp > 0) {
    x *= r / maxComp;
    y *= r / maxComp;
}

```

This should retain all sensitivity but map the circle to a square, so the output will be within \[-1, 1\] on each axis and you'll be able to get to all four corners of the box.

Lastly, note that a common way to improve sensitivity is to square the length of the joystick vector, which makes small deflections smaller, while leaving bigger deflections alone. You could do this by removing the `sqrt` on the equation for r above.
> 5 votes

# Answer
First, .7,.7 is circular shaped, not dimaond shaped. Do the math of how long a vector is form 0,0 to sqrt(.5),sqrt(.5) which is your .7,.7. It is exactly 1.0.

Next, some Xbox 360 controllers return absolute values of 1,1 in the corners, such as my MadCatz, and some controllers return .7,.7, such as the official Microsoft controllers that come with the system. You must take this into account, or else 3rd party controllers will allow your character to move faster in your game, effectively becoming a hack.

Thirdly, also be sure to read my "Multidirectional XNA Games Control Tip" article, http://xona.com/2010/05/03.html, in case you are coding for smooth motion 360 degrees. If you don't take this into account, you'll lock at 12,3,6,9 directions. Good for some games, bad for most multi-directional shmups. I've even seen pro XBLA games make this brutal mistake, and far too many XBLIG games do. **EDIT :** I mention this to explain both the proper usage of `GamePadDeadZone.Circular` as well as solve an all too common problem.
> 2 votes

# Answer
Just off the top of my head try something like the below.

```
x += .3(1 - |x - y|)
y += .3(1 - |x - y|)

```

The closer x and y are the more it will push the the value outwards hopefully making a shape close enough to circle. This will only work if x or y is positive so make it -= for whichever one is a negative value.
> 0 votes

---
Tags: xna, xbox-controller
---


title: Move Sprite from A(x,y) to B(x1,y1);

text:
# Question
Title: Move Sprite from A(x,y) to B(x1,y1);
I have a sprite with an UpdateHandler that can change it's position every 0.1 seconds.

My Question is , given the Sprites current position, how can I move it to another position(like from 10,10 to 250,250).

I found out the rotation angle for my sprite like this:

```
double alfa = (float) Math.atan2(endY - startY, endX - startX) * 180 / PI;

```

And an example of moving the position is:

```
sprite.setPosition(sprite.getCurrentX()+1, sprite.getCurrentY());

```

This would move my sprite every 0.1 seconds to the right. I need to make it work between any 2 points.

Thanks!

# Answer
All you need to do is calculate the delta's (difference) between the old position and the new position and then choose in how much time you want to change the position.

For example: X1 = 0, X2 = 100, then deltaX = X2-X1 = 100. Y1 = 50 Y2 = 0, deltaY = Y2-Y1= -50.

Now You want to object to move there in 10 seconds and the update step is every 1 second. So you divide the deltas by 100, since there are 10 steps in 1 second * 10 gives 10 seconds in 100 steps.

So this will be what's in your update step

sprite.setPosition(sprite.getCurrentX()+ deltaX/100, sprite.getCurrentY() + deltaY/100);
> 3 votes

---
Tags: game-mechanics, movement
---


# Question
Title: How to linearly transform vertices for large coordinate systems
Alright, so I'm working on a space game and well, I want it to have a lot of space! So I need a large coordinate system and for my rendering pipeline to not suffer from "vertex jittering" due to floating point rounding errors introduced in the world to view space matrix transformation.

So far I'm having some luck with a technique discusses in GPU Pro that was used for Just Cause 2. However, it's not quite there. It looks like the "world" (including the player's ship) is orbiting around my camera instead of the camera adjusting it's orientation and position to stay behind the player's ship when it rotates. It doesn't do this with the traditional World x View x Projection transformation.

Anywho, the technique basically merges the world and view space's translation matrices by translating directly to the object's offset from the camera.

The transformation is

objectScale x objectRotation x objectOffsetFromViewPosition x viewRotation x Projection

Where the offset is a translation matrix built from the object's world position - view position.

I've always built my view matrix simply using the XNA library's XMMatrixLookAtLH() function so I'm thinking I might be missing another vital aspect of the view matrix transformation. My view rotation matrix at the moment is only built from a quaternion representing the camera's orientation.

What am I missing or what is the correct way to build this transformation?

# Answer
Alright, it looks like I solved my problem. The modified transformation presented in the question was correct. However, I was able to remedy the odd rotational movement by inverting the view's rotational matrix. (I realized the camera was rotating in the opposite direction than I wanted)

Final transformation order

**Scale x Rotation x camOffset x InvertMatrix(viewRotation) x projection**

As for jittering due to floating point errors in dealing with my coordinate system and placing objects (such as the camera), I ended up using 64 bit ints instead of 32 bit floats. Now I can be accurate down to a millimeter across a coordinate system as large our solar system. (and with more precision if needed!)

This idea was provided with the help of some GDSE users in the chat room and this page.

As for the depth buffer, this too experiences floating point issues in the form of z-fighting with large distant astral bodies. To remedy this, I render through two different passes based on their distance from the camera. Astral bodies that won't present issues for my depth buffer are ran through my standard pipeline while distant bodies are rendered using a painter's algorithm without writing to the depth buffer.
> 1 votes

---
Tags: mathematics, matrix, coordinates, linear-algebra
---


title: How do I call  glVertexPointer in Java?

text:
# Question
Title: How do I call  glVertexPointer in Java?
I'm trying to convert the following code to Java:

```
glVertexPointer( 3, GL_FLOAT, 0, &(mesh.m_PositionBuffer[0]) );

```

Where `mesh::mPositionBuffer` is `std::vector<glm::vec3>`;

How would I make a similar call to `glVertexPointer` with a first index to the position buffer?

# Answer
You should look at the overload set in the documentation. Probably the candidate you're interested in would be the glVertexPointer overload that takes a FloatBuffer, which you'd fill with the components of the mesh's position vertices.
> 3 votes

---
Tags: c++, opengl, java, lwjgl, porting
---


# Question
Title: In my map editor, how can I make the tiles "stick" at 32 pixels multiples?
I have a problem with making map editor in XNA. I'm making a 2D tile based map editor.

The problem is, I need every tile I put in map editor to be X: 0, or X: 32, or X:64 and so on, not 1.10, 2.99, 5.62, etc. You see, it has to be exactly i\*32 tiles, where i is whatever number, not decimal. Thank you if you help.

# Answer
> 5 votes
The easiest way to "snap" coordinates to a grid is this:

```
    int objX = (int) Math.Floor(mouseX/tileWidth)*tileWidth;
    int objY = (int) Math.Floor(mouseY/tileHeight)*tileHeight;

```

# Answer
> 0 votes
I like the solution here, but I'm currently using

```
                            // for example 100 - (100 % 32 (which is 4)) = 94
Vector2 placementPosition = mousePosition
               - new Vector2(mousePosition.X % 32, mousePosition.Y % 32);

```

which works perfectly, too

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


# Question
Title: How can I save my game state so it can be resumed when my application resumes?
I've found that after resuming my game the whole engine is reloaded and application is reinitialized. I want to save engine state and in "onResume," resume the game process from where it left off.

I've tried to save the engine (mEngine) and then after resume the game in "onLoadEngine" return saved engine. I think it is a bad solution and it doesn't work anyway.

What is the best solution for resuming my game (after the power key was pressed, for example) in AndEngine ?

# Answer
> 4 votes
Since the game state is going to be specific to your game, there isn't built in functionality for this in the engine. One solution would be to write the state information you want to keep to an XML file. Likely you'd want to load this saved state in your `onStart()` function. But really that's up to you and how you want your game to behave.

There's a blog post about the flow between states, and when to save and load states: http://www.andengine.org/forums/post25660.html#p25660

And information on how to read/write a file: http://www.anddev.org/write\_to\_and\_read\_from\_a\_file-t3173.html

# Answer
> 0 votes
This tutorial will help:
https://jimmaru.wordpress.com/2011/09/28/andengine-simple-android-game-tutorial/

---
Tags: android, andengine
---


# Question
Title: Is it better to track rotation with a vector or a float?
In XNA, you can see that to draw a rotated sprite with SpriteBatch, you'll need a float describing the angle in radians.

I'm used to making games in OpenGL. I just want a rapid prototyping environment in XNA, but I'm a little lost. It's my preference to always use Vectors to store my rotation, to do vector math, et cetera.

So my question is: in XNA, is better to keep a vector for your rotations, and each frame transform to a float angle, or just keep the float angle itself? If I prefer the vector, what would be my drawbacks compared to just using a float?

# Answer
You can always convert from vector to angle or vice-versa. You might want to run some tests and profile the running code to see which direction of conversion is faster, if that makes a difference.

Someone else here said you can't add or subtract a fixed angle from a vector. You actually can, of course, using matrix multiplication:

**Addition of angle θ**

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

```

**Subtraction of angle θ**

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

```

Whether or not that is faster than updating θ and rederiving x and y from θ is something you would have to execute in an actual program to know for sure, but in the case where θ is constant, it's very likely going to be faster.

That said, keeping angles as vectors will subject them to magnitude drift due to accumulated floating-point arithmentic rounding error which occurs during repeated iterations. So depending on how your library works, you may need to normalize your direction vector after each step or after every say 1000 steps. You don't want it to shrink to zero after a billion iterations, or grow to infinity. So the question is: Does your library automatically normalize your angle vector, or does it assume a magnitude of 1?

If you can afford the memory, it might be advantageous to store the angle both ways, updating both together, and then at any instant use whichever form is most convenient in your code.

If you can afford the CPU cycles, then in my experience it's easiest just to store the angle as a single value. Will you be applying angular acceleration to your angular velocity? If so, then that is another benefit to storing the information as an angle rather than a 2D vector.
> 7 votes

# Answer
A float is harder to work with, as I have discovered during the last few months. Applying things like physics, forces or flocking algorithms require a Vector to work with. The only thing you can do with a float that you can't do with a Vector, is add or subtract a fixed angle from it. I would use Vectors and calculate the angle as needed, even every frame if that's what was required.
> 3 votes

# Answer
Good for you for using a Vectors. Although angles & trig do work well for 2d, they do not work so well for 3d. If you ever make that transition, and you are already accustom to using vectors and linear algebra instead of angles and floats, your transition will be much smoother and easier.
> 1 votes

# Answer
Ideally, it is better to be using quaternions to represent rotations. Vector based rotations have the problem of getting to something called "gimbal lock". However Quaternions are not susceptible to that. Here are more details: Quaternion and Rotation Primer (Courtesy: Ogre3D's Wiki).

EDIT: It's also easy to convert a quaternion to a rotation matrix for transformation. And also be able to store scaling factors (if it interests you). If you do not require scaling factors to be part of your rotation quaternion, you can always 'normalize' the quaternion.
> 0 votes

---
Tags: xna, 2d, vector, rotation
---


# Question
Title: How can I "capture" the section of my sprite sheet that I want to draw in Java?
I'm working on a puzzle game, I've implemented a sprite class that uses an array of images and cycle through the array to draw each frame as required. This works fine!

Here's the original code:

```
    String number;
    Image sprite;
    ArrayList <ImageIcon> spriteAnimation = new ArrayList();
    int _imageCount = 0;
    int _animationStart = 0;

   public Sprite(String spriteType, int totalFrames){

        for(int x =1; x <= totalFrames; x++){
          spriteAnimation.add(new ImageIcon("Images/" + spriteType + "/" + spriteType + x + ".png"));
          System.out.println("Added " + spriteType + x + ".png to the ArrayList");

        }

    }

    public void updateSprite(){

        sprite = spriteAnimation.get(_imageCount).getImage();

        System.out.println("image count is " + _imageCount);

        if(_imageCount < spriteAnimation.size()-1){

           _imageCount += 1;

       }else{

           _imageCount = _animationStart;

       }

    }

    public Image getSprite(){

      return sprite;

      }
}

```

However, after researching the difference between using the method above and using a single sprite sheet (there must be a good reason to use a sprite sheet I thought, and I was right) I've decided to use a single sprite sheet to represent all sprites in my game.

While I fully understand the principle of using the sprite sheet, I cannot get my head around actually drawing the selected part of the sprite sheet. I thought there might be a constructor in the ImageIcon or Image classes that would allow me to do something like pass in the size of the image to be drawn, the x and y co-ordinates to start at and the original sprite sheet as arguments - but apparently not. I'm obviously looking in the wrong place.

I would be very grateful if someone could advise me on how to do this in Java.

# Answer
> 0 votes
OK, as per Jannie Pieters suggested links, I have resolved the issue. I should have been looking at BufferedImage instead of Image and ImageIcon. Here is my revised class:

```
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.*;

/**
 *
 * @author mal
 */
public class Sprite2 {

    int _imageCount = 0;
    int _animationStart = 0;
    int _spriteSize;
    int _frameCount;

    BufferedImage[] sprites;

   public Sprite2(String sheetName,int frameCount, int columns, int rows, int frameSize){

       _frameCount = frameCount;

      try{

       BufferedImage spriteSheet = ImageIO.read(new File("Images/" + sheetName + ".png"));
       buildSprites(spriteSheet, columns, rows, frameSize);

      }catch(IOException e){

           System.out.println("Image not found: Sprite2.java line 50");

       }

    }

    public void triggerUpdate(){

        System.out.println("image count is " + _imageCount);

        if(_imageCount < _frameCount-1){

           _imageCount += 1;

       }else{

           _imageCount = 0;

       }

    }

    private void buildSprites(BufferedImage spriteSheet, int columns, int rows, int frameSize){

        sprites = new BufferedImage[25];

        for(int x = 0; x < columns; x++){

            for(int y = 0; y < rows; y++){

                sprites[(x * 5) + y] = spriteSheet.getSubimage(
                x * (frameSize + 1),  // my sprite software adds 1 pixel border to each frame
                y * (frameSize + 1),
                frameSize,
                frameSize
                );
            }

        }

    }

 public BufferedImage getSprite(int imageNumber){

    return sprites[imageNumber];

 }

  public BufferedImage getSprite(){

    return sprites[_imageCount];

 }
}

```

This works perfectly, now all I need to do is re-design the rest of the game, port it to android, market it well and make millions!

sorted!

Lots of new concepts for me to study here.

---
Tags: java, graphics, spritesheet
---


# Question
Title: Telling which side of a voxel was hit by an object
In XNA, I have an axis-aligned BoundingBox representing the object's hit box, and a Vector3 representing the object's velocity. I also have a *stationary* 1x1x1 axis-aligned BoundingBox representing a voxel. Using `object.box.intersects(voxel.box)`, I can tell that they intersect. However, I do not know which side of the voxel was first hit by the object.

I am assuming you can just take the direction from the center of the player to the center of the voxel and use that to determine which face it hit. However, my brain is not working right now and I can't figure out the math.

I already know how to respond when you learn which face was hit (from my previous question). I just don't know how to figure out which face the player hit.

# Answer
You can always check each face that can collide. Since the bounding boxes are AA, you'll have these collision scenarios: (`->` indicates collision, X\_Plus represents the YZ plane on the X plus side of the box)

* Box1\_X\_Plus `->` Box2\_X\_Minus
* Box1\_Y\_Plus `->` Box2\_Y\_Minus
* Box1\_Z\_Plus `->` Box2\_Z\_Minus
* Box1\_X\_Minus `->` Box2\_X\_Plus
* Box1\_Y\_Minus `->` Box2\_Y\_Plus
* Box1\_Z\_Minus `->` Box2\_Z\_Plus

You can narrow the choices to half by checking if one box is further along an axis than the other. For example, if Box1 is at x=1 and Box2 is at x=5, there's no way that the Xminus side of Box1 could be colliding with the XPlus side of Box2, so you can remove it from the options.

I'm not sure exactly what would work, but you could do it something like:

```
public Face GetCollisionFaceOfPlayer(Vector3f voxelPos, Player player) {
    if(player.x < voxelPos.x) {
        //See if player Xminus is close enough to voxel XPlus
        if(Abs((player.Position.x - player.Width/2) - (voxelPos.x +.5f)) < PreDeterminedCollisionBufferDistance)
            return Face.XMinus;
    }
    else {
        //See if player XPlus is close enough to voxel XMinus
        if(Abs((player.Position.x + player.Width/2) - (voxelPos.x -.5f)) < PreDeterminedCollisionBufferDistance)
            return Face.XPlus;
    }
    //Other faces

}

```

Or you can keep track of the distances for all the faces it could be and return the minimum.
> 2 votes

# Answer
If the box is axis aligned you can simply take the highest absolute value of the three coordinates of the box centre to player vector. The collision is along that axis, and the coordinate is either positive or negative depending on which side of the box the player collided with.

If the player figure is an axis aligned box it's pretty simply to take it's size into consideration, say for instance it's 2 units high and 1 by 1 units wide, then you simply subtract half of the player boxes respective dimension from the absolute centre to centre distance before comparing. So you'd be looking for `max(abs(distanceX)-.5, abs(distancey)-1, abs(distanceZ)-.5)` (Of course set up as a series of `if` clauses so that you not only get to know the maximum value, but also which one of them constitute this.)
> 0 votes

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


# Question
Title: Generating a map in runtime for a simple top-scrolling racing game
I'm creating a simple top-scrolling racing game. The concept is quite simple - the player controls the car, which goes on a dynamically generated field with square blocks. Once the car hits a car, the game ends.

My first implementation was simply to put a few random blocks in each row being generated on the top of the screen, but this does lead to maps where going through is impossible.

What is the best algorithm for generating such type maps? My platform of choice is XNA and C#, if that's important.

EDIT: Here's an illustration: (pic)

In this case, there's no possible way for the player to pass.

# Answer
> 4 votes
You will have to do some pathfinding. I'd suggest something like this: Choose grace distance, the shorter, the harder the game may be. When you add a new row fist find out in what places the player may be after travelling the grace distance. You can use an A\* search algorithm to find the group of points efficiently, then you remove any point that doesn't have a path through the currently generated rows from the group. Now you generate a new row and check that all the points in the group have a path all the way through the new row, if some of them doesn't you will have to regenerate the row.

Edit:
The pathfinding is very simple in this case, as the car can only occupy one of 8 different positions per row, so your pathfinding will never have to branch beyond 8 positions. You simply incrementally check what positions the car can reach in the next row, from the positions it may occupy in the previous row.

Edit:
Strike the A\* reference, I better just refer to Dijkstra, almost the same but seems easier to understand.

# Answer
> 7 votes
Rather than try to generate a field to play in that you need to check to keep valid for play, instead generate a path the vehicle can follow, then randomly add obstructions to the parts of the map not filled in by the vehicle path generated.

1D Brownian motion: (http://classes.yale.edu/fractals/randfrac/brownian/Brownian3.html)

If you use low frequency brownian motion for the car path, filling in cells as not-obstructable, you can then simply have a low probability function for selecting whether each non filled cell is occupied/obstructed.

This will always lead to a game that can be played, but it can also be tuned to have sparse or dense obstructions patterns. You could even have the density function be brownian too ;)

# Answer
> 2 votes
Just use the last 'top-row' as reference, and generate a valid row from there (for each block, pick one at random, if it's invalid, do it again). Now valid is something you'll have to define, but my guess is 'valid' would be reachable from any of the three neighboring blocks from the reference row.

# Answer
> 1 votes
Quick idea written during compile-time(curse you c++):

When placing a block make sure that the top half of the map has three columns next to each other which are free. Do that by summing up the number of black squares in each column. Then iterate through the column sums three at a time.

First check will sum column 0 1 2.

If sum equals 0 tag chunk 0 as free.

Next check will sum 1 2 3.

If sum equals 0 tag chunk 1 as free

After that 2 3 4

If sum equals 0 tag chunk 2 as free.

etc.

After placing a wall check that at least one of your previously tagged chunks are empty. Redo procedure until at least one is left empty.

This method leaves you with an option for easy and hard mode where easy mode checks entire map for free spaces instead of just top half. Also, by setting an upper limit of wanted empty chunks you can increase the difficulty. Hard diff would mean that one or two chunks are allowed to be free at any time.

Hope you understand what I mean.

# Answer
> -1 votes
i know im really really REALLY late but wouldnt the simplest way to do this be to change the car so that its only 1 block thick? leaving only an incredibly small chance that the game will give you something impassable?

---
Tags: maps, side-scroller
---


# Question
Title: How can I get a list of sprites which are being drawn in the current viewport using XNA?
Just starting out using XNA to draw 3D scenes and have a question about determining which objects are currently visible.

If I load many thousands of sprites and shapes in a scene, then render the current view from a camera, is it possible to actually find (e.g. list to a text file) the IDs of those visible objects?

I guess another way to ask this is to say: how can I get a list of objects (e.g. sprites) which are being drawn in the current viewport?

# Answer
You can check if the object's bounding is inside of the camera frustum.

you have the class BoundingFrustum that can manage intersections with BoundingBoxes or BoundingSpheres.
> 3 votes

# Answer
To go along with @Blau's answer, here is the MSDN documentation for BoundingFrustrum and related classes/methods:
http://msdn.microsoft.com/en-us/library/bb313876.aspx
> 0 votes

# Answer
To determine if a draw call rendered any pixels on screen what you need is an occlusion query.

You'll also need to do some extra work to get accurate results, as if you render a far away object first, then a nearby object afterwards that covers it will say both rendered pixels. The solution to that is to render everything in a near-far order.

Also note that you want to read the result of the query a frame or so after you issue it, to give the GPU enough time to output the result. If you don't wait it can affect performance significantly.
> 0 votes

---
Tags: xna, sprites
---


# Question
Title: How to achieve graphics like those in Spy Mouse
I'm really interested in making a new application for iPhone, and I have some experience in objective-c. My main problem is the visual part. I want to have graphics like in Spy Mouse. Could this be achieved using simple 2D graphics? Or would I need to use 3D, and just show it from this perspective?

# Answer
This is simple 2D graphics. If you don't have access to Photoshop, download GIMP, look up tutorials on YouTube or try google. Creating graphics like these takes creativity and some art skills, but it's absolutely not out of your reach. There's alot of tutorials on creating buttons or text with the effects used in the picture you posted, they'll teach you how to use layers and you should be able to piece together the effect you'll like.

You're starting out, so it'll take alot of time to create even the basic sprites, but don't get discouraged. All i can tell you is that the hardest part of this job, as an untrained artist, is to stay within a style you chose. Do pay attention to this and don't rush your work.
> 11 votes

# Answer
I see no reason that this could not be acomplished in a 2D environment using sprites. In fact, depending on implementation, gameplay, etc it might be easier to do with 2D and sprites.

It sounds to me like your problem is art work. You sound like a programmer, and that means that you *need* and artist. Or, you need to become an artist yourself.

With the correct assets (2D sprites, tilemap, etc) in place, making a game look like the screenshot you've attached is going to be a piece of cake (realitivly speaking and all other things being equal).
> 3 votes

---
Tags: 2d, 3d, iphone, graphics
---


title: Create a car sound with frequencies

text:
# Question
Title: Create a car sound with frequencies
Im trying to create a car game in c sharp! Im now trying to figure out a way to get some sounds into the game! For example, the acceleration sound of the car.

I recently tried to add a 5 second-sound of a real car accelerating, but I don't think its the right way to do it. Because then i have to start from the beginning all the time of the clip when i accelerate.

Is there maybe some way to work with frequencies? To send a frequency to the speakers and then just increase it when I accelerate (And to make it sound like a car)

I've heard about PWM, could that be something?

Thanks!

# Answer
> 4 votes
This is not a simple task, most decent solutions involve writing DSP code, multiple channels and custom samples as seen in some of the thread @Noctrine linked.

If you're unfamiliar with audio programming the most simple suggestion I can make is that you try taking 2-3 channels and mixing them based on engine speed.

Channel 1..3 containing low, medium and high frequency loops and percentage of each channel playing based on how close the engine speed is to the sample.

Once that's working you can tweak that based on heavy acceleration or rapid braking.

The advantage to DSP coded solutions is that all this work is handled algorithmically with frequency shifting and filters and more dynamic effects are possible.

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


# Question
Title: How would I implement an endless road the player runs down?
I want to create the illusion that a man is running down a long road i.e. this pic

http://camlinecambridgelimited.web.officelive.com/images/road%20graphic1.jpg

If you have played Temple Run on the iPhone, it's the same principle, but instead of a temple it's a normal road.

I want to know how this is implemented. For example, do I just repeat this road image in a loop?

# Answer
I would draw a single textured quad on the ground (i.e. lying on the XZ plane), as big as the visible area should be, and then play around with the vertices **texture coordinates** (with the **texture addressing mode set to wrap**) in order to automatically take care of both texture *repetition* and texture *scrolling*.

1. For *repetition* instead of setting your vertical texture coordinate from \[0 to 1\], set it from \[0 to N\] where N is the number of times you'd like the texture to repeat. Adjust this value depending on how tall your quad is in comparison to your texture height.
2. For *scrolling* I'd simply scroll the vertical texture coordinate, so that instead of ranging from \[0 to N\] it would range from \[inc to N+inc\] with the value of *inc* being incremented or decrement each frame. From time to time I'd wrap *inc* back to the origin in order to prevent overflow/underflow.

---

**EDIT** I just tried implementing this exactly as I described (but in XNA) and it worked quite well. See **this video** of the demo. Source code **here** for those interested.

---

For instance, with N equal to 3 you would get something like the image below (I've painted the middle section in red so that you can see where the repetition occurs). Then, simply changing the value of *inc* would make the road scroll in one direction or the other, depending on whether you incremented or decremented it.
> 16 votes

# Answer
If you want to make an endless road "for real", you create three surfaces and have them loop as each surface moves outside of view. Place the surfaces end to end in world space and move them all towards the camera. As the nearest end moves off camera, reset its position to the end of the furthest surface.

If you want to implement it as a sprite with the illusion of movement, you need to create a number of different textures, which should look something like this:

As the view moves forwards loop through the textures in order.
> 1 votes

# Answer
Repeating the image is a good idea. Figure out how many repetitions need to be visible on screen, and draw the image that number of times. As the road scrolls, there will be a point where one image is completely behind the camera and thus invisible. At that point, you want to move that image from behind your feet to the far end of your finite image strip.

While we're at it, you'll get the best effect out of it by mimicking the unsteady perspective of a running man. Record a movie of you running from the perspective of your eyes, and study it.
> 0 votes

---
Tags: 3d, ios, graphic-effects
---


title: Valve Source Engine / UDK and CUDA

text:
# Question
Title: Valve Source Engine / UDK and CUDA
Do any games use the GPU for more game tasks than just rendering, as a way to reduce the game's load on the CPU? I'm most interested in games which use either Valve's Source engine or the UDK.

Is it possible/effective to even do such a thing?

# Answer
> 2 votes
Neither of the engines you mention provide access to GPGPU (General Purpose GPU) support.

UDK in its current architecture never will, because it allows no access to low-level languages (other than DLLBind, which has other limitations)

There is talk that Source Engine will be upgraded with DirectCompute support (DirectX's GPGPU solution) some time in the next year, but very little to substantiate these rumours.

---
Tags: udk, nvidia, valve, source-engine
---


# Question
Title: Is it possible to run other doom3 engine based games using the open sourced version of the engine?
Other than the doom3 mods, is it possible for example to run Quake 4 or Prey using the game data?

Let's say that I purchase Quake 4 or Prey (or any other idTech 4 game) can I just point to the game data path and run it with the source code? Is there any modification needed? If so, what is it?

# Answer
> 5 votes
Doubtful. Almost certainly these games involved some code changes, whether minor or major. It would be very unusual if Quake 4 or Prey shipped with the *exact* Doom 3 code-base, replacing only the art assets and scripts. I'd be surprised if the Doom 3 code will run these games correctly. But since Quake 4 and Prey have not themselves been open-sourced (and may never be), you may be out of luck, unless you feel up to the task of reverse-engineering any code modifications that were made.

---
Tags: c++, open-source
---


# Question
Title: Why does my GLSL 1.20 shader not work with an OpenGL 4.0 driver?
I'm just starting out with OpenGL on Linux. In order to write future-proof code, I explicitly wrote code for OpenGL 4.0 Core Profile in the first place, thus the shaders are GLSL 4.0.

That worked fine on a recent notebook with an AMD graphics card using the fglrx driver, which supports OpenGL 4.0. I then tried to run this code on another box with an Intel card, whose driver only supports OpenGL 2.1. That failed, obviously.

I then rewrote the shaders in GLSL 1.20, without changing the C++ code at all. Now it works on the Intel box, but on the AMD notebook, it displays nothing (except for glClearColor).

That confuses me. The code checks glGetError() periodically, so an error in the shader compilation would have been caught.

My only idea would have been that I accidentally created a GL 4 core context (instead of a compatibility context) on the AMD box, but the context is created by SDL 1.2, which (says the documentation) can create compatiblity contexts only.

Can anyone see what the problem is, or give hints on how to debug this? For reference, I'm attaching all shaders. (They're pretty trivial; as I said, I'm just starting.)

```
#version 120 (vertex shader)
uniform mat4 ModelMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ProjectionMatrix;
attribute vec4 in_Color;
attribute vec4 in_Position;
varying vec4 pass_Color;
void main(void) {
    gl_Position = (ProjectionMatrix * ViewMatrix * ModelMatrix) * in_Position;
    pass_Color = in_Color;
}

#version 400 (vertex shader)
layout(location=0) in vec4 in_Position;
layout(location=1) in vec4 in_Color;
out vec4 ex_Color;
uniform mat4 ModelMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ProjectionMatrix;
void main(void) {
    gl_Position = (ProjectionMatrix * ViewMatrix * ModelMatrix) * in_Position;
    ex_Color = in_Color;
}

#version 120 (fragment shader)
varying vec4 pass_Color;
void main(void) {
    gl_FragColor = pass_Color;
}

#version 400 (fragment shader)
in vec4 ex_Color;
out vec4 out_Color;
void main(void) {
    out_Color = ex_Color;
}

```

# Answer
You might need to bind your vertex attribute id's to your shader, look at glGetAttribLocation. In your 4.0.0 version you have the layout statement telling it what will be in what id's. The program needs to know that "in\_Position" is for attribute 0. It's possible that your implementation will default to using the first attribute as vertex coordinates and the 2nd as color. But it might not either. I'm not sure what the standards say about the default states, it might be up to the implementation or vary depending on what version your context is.

Here's the code I use to get a log of the shaders/programs.

```
// For shaders
int length = 0;
glGetShaderiv(shader_id_, GL_INFO_LOG_LENGTH, &length);
std::vector<GLchar> shader_log(length);
glGetShaderInfoLog(shader_id_, length, &length, &shader_log.front());

// For programs
int length = 0;
glGetProgramiv(program_id_, GL_INFO_LOG_LENGTH, &length);
std::vector<GLchar> program_log(length);
glGetProgramInfoLog(program_id_, length, &length, &program_log.front());

```

If your trying to make stuff run on multiple OpenGL versions. I recommend that you make a class that deals with all your shaders in one place. That way you can just call shaders.usePhong(), shaders.setPrimaryColor(glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));

That will allow you to take advantage of things like:

* Subroutine uniforms (there basically function pointers for GLSL so you can have 1 big shader that does everything without having to put a bunch of if statements that slow things down).
* Uniform Buffer Objects (share data between all your shaders).

Having the central control object will allow you to fall back to the old ways of doing things. usePhong could either change which uniform subroutine is set or change which shader is in use depending on what is supported.

Setting variables could either update the shared buffer object for all shaders or set the uniform variable on the shader (although you have to keep track of which shader will need that variable and if you need to resend that stuff when you swap to a different shader.).

You can also look at using #include in your GLSL sharers. It's not in core yet but is an ARB extension so it works on at least nvidia (not sure about AMD). If you don't have it on the platform you can have your shader loading code do a quick search and insert the code manually, if you do have it then you need to load the files into OpenGL's "named strings" in advance. That way you can write 1 bit of shader code and #include it either inside a routine function or a separate shader.

You might even want to go further and write some code that will generate the correct shaders wrapping code for your supported extensions.
> 5 votes

---
Tags: opengl, glsl, linux
---


# Question
Title: Problems with 3D rotation when creating a 3D skeleton
I am writing a simple BVH parser in C# using the XNA framework. At the moment I have managed to parse in all the data and my goal is to find out the global coordinates of all the joints in the skeleton.

The problem I am encountering is that the bones don't seem to take into account the rotation of its parents. For instance, if I move my lower leg, I would expect my foot to change orientation as well and keep the same angles between the foot and the lower leg. What I am noticing is that the translation of the bone joints is correct, but the global rotation of a bone is the same as the local rotation of the bone. The picture below might help you understand what the problem is:

note: there is a mistake in the pic captions, it should read "the left upper leg is rotated around the z-axis" not the x-axis.

I would have expected the lower leg portion to also be rotated by 1 radian as a result of its parents' change in orientation.

So the code is as below (I am using XNA and C#):

```
foreach (Bone b in bones)
{
            //Calculate the local transform matrix
            b.localTransform = Matrix.CreateTranslation(b.Offset) * Matrix.CreateRotationZ(MathHelper.ToRadians(b.z)) * Matrix.CreateRotationY(MathHelper.ToRadians(b.y)) * Matrix.CreateRotationX(MathHelper.ToRadians(b.x));
            Bone parent = b.parent;
            if (parent != null)
            {
                //Calculate global transform matrix
                b.globalTransform = parent.globalTransform * b.localTransform;
                b.location = b.globalTransform.Translation;
                lines.Add(new Tuple<Vector3, Vector3>(parent.location, b.location));
            }
}

```

Each bone assumes its parents global transformation is correct as the list is ordered so the parents always come before the children. The root bone has no rotations and no offset and has its global transform already set based on this. I am wondering what I am doing wrong here?

I have done a simple example using only 2D:

```
Matrix bone1 = Matrix.CreateTranslation(new Vector3(3, 0, 0)) * Matrix.CreateRotationZ(1);
Matrix bone2 = Matrix.CreateTranslation(new Vector3(3, 0, 0)) * Matrix.CreateRotationZ(1);

lines.Add(new Tuple<Vector3, Vector3>(Vector3.Zero, bone1.Translation));
lines.Add(new Tuple<Vector3, Vector3>(bone1.Translation, (bone1 *bone2).Translation));

```

Drawing this onto the screen shows what I expect. The 1st bone is rotated 1 radian around the origin, 2nd bone is rotated 2 radians around the origin.

I am using the below as a reference for parsing and interpreting the BVH data: http://www.dcs.shef.ac.uk/intranet/research/resmes/CS0111.pdf

# Answer
I'm not sure how your 3D input data works, but I think your local matrix should be:

```
 b.localTransform = Matrix.CreateRotationZ(MathHelper.ToRadians(b.z)) * Matrix.CreateRotationY(MathHelper.ToRadians(b.y)) * Matrix.CreateRotationX(MathHelper.ToRadians(b.x)) * Matrix.CreateTranslation(b.Offset);

```

This is my code for this 2d bone editor:

```
 //-----------------------------------------------------------------------------------------------------------------------
        public void UpdateLocal( )
        {
            Vector2 traslation = Translator.GetValue();
            float rotation = Rotator.GetValue();
            Vector2 scale = Scalator.GetValue();

            Matrix mTraslation, mRotation, mScale;
            Matrix.CreateTranslation( traslation.X, traslation.Y, 0, out mTraslation );
            Matrix.CreateRotationZ( rotation, out mRotation );
            Matrix.CreateScale(scale.X, scale.Y, 1 , out mScale );
            Matrix.Multiply( ref mScale, ref mRotation, out Local );
            Matrix.Multiply( ref Local, ref mTraslation, out Local );
        }

        //-----------------------------------------------------------------------------------------------------------------------
        public virtual void UpdateTransformTopToDown( )
        {
            global_counter++;
            SpecialUpdateTransformTopToDown( );
        }

        //-----------------------------------------------------------------------------------------------------------------------
        protected virtual void SpecialUpdateTransformTopToDown( )
        {
            if ( counter == global_counter ) return;

            counter = global_counter;

            UpdateLocal( );

            if ( Parent != null )
            {
                 Matrix.Multiply( ref Local, ref (Parent as BoneData).Absolute, out Absolute );
            }
            else
            {
                Absolute = Local;
            }

            foreach ( BoneData child in _children.OfType<BoneData>() )
            {
                child.SpecialUpdateTransformTopToDown( );
            }
        }

```

And this is my code to animate Warcraft3 models, (based in MagosX War3ModelEditor code):

```
public void BuildTransformMatrix(Intervalo Time, Camara Camara)
    {

        Vector3 TranslationVector;
        Vector4 RotationVector;
        Vector3 ScalingVector;

        TranslationVector = Translation.GetValue(Time);
        RotationVector = Rotation.GetValue(Time);
        ScalingVector = Scaling.GetValue(Time);

        Matrix mPivotPoint = Matrix.CreateTranslation(PivotPoint);
        Matrix mScaling = Matrix.CreateScale(ScalingVector);
        Matrix mRotation = Matrix.CreateFromQuaternion(RotationVector.ToQuaternion());
        Matrix mTranslation = Matrix.CreateTranslation(TranslationVector);

        Matrix mPivotPointInverse = Matrix.Invert(mPivotPoint);

        Transform = mPivotPointInverse * mScaling * mRotation * mPivotPoint * mTranslation;

        if (Parent != null && Parent.NodeId != -1)
        {
            Transform = Matrix.Multiply(Transform, Parent.Transform);
        }

        foreach (BaseNode child in Children)
        {
            child.BuildTransformMatrix(Time, Camara);
        }
    }

```
> 0 votes

---
Tags: xna, mathematics, graphics, animation
---


# Question
Title: 3D tilt angle for an arrow in archery game
How can I calculate the angle of rotation/tilt of an arrow in 3D?

When I say angle I mean the angle the arrow takes when it flies through the projectile path.

I am using logic given in the below link to calculate the location in the 3D space

http://babek.info/libertybasicfiles/lbnews/nl130/proj3d.htm

and also OpenGL for rendering

# Answer
Simplistically the arrow will always lie tangent to the curve described by its trajectory. The tangent to any curve is simply the derivative or the slope of the curve at the point of the tangent.

To calculate this take the inverse tangent of (y1-y)/(x1-x) and repeat for the other planes to get the 3 required angles in 3D. (y1 and x1 are simply y and x values one time or distance step in advance of y and x)
> 3 votes

# Answer
Take a look at this answer, remeber that in this case the 2D and 3D are quite the same thing since your arrow trajectory (probably) lies on a plane.
> 2 votes

---
Tags: physics
---