# Question
Title: XNA - Static classes from game libraries executing after content pipeline extensions, how to avoid the problem?
Alright, formulated this way I'm sure it sounds obscure, but I'll do my best to describe my problem.

First, let me explain what's wrong with my real source code.

I'm making a platformer, and here are the current components of my game: a *Level*, which is holding its own grid of tiles and also the tile sheets and a *Tile*, which just keeps the name of its tile sheet and index within the tile sheet. **All these are within a separate XNA game project, named GameLib.**

Here is how my levels are formatted in a text file:

`x x . . . . .`

`. . . b g r .`

`. . . . . . .`

`X X X X X X X`

Where `.` represents an empty tile, `b` represents a blue platform, `X` represents a block with a random color, etc.

Instead of doing all the work of loading a level within the *Level* class, I decided to take advantage of the content pipeline extension and create a LevelContentPipelineExtension.

As soon as I started, I quickly realized that I didn't want to hard-code 20+ lines of the kind:

```
if (symbol == 'b')
    return new Tile(/*...*/);

```

So, in the hope of at least centralizing all the content creation into one class, I made a static class, called *LevelContentCreation*, which holds the information about which symbol creates what and all this kind of stuff. **It also holds a list of all the asset paths of the tile sheets, to load them later on. This class is within my GameLib game library project.**

The problem is, I'm using this *LevelContentCreation* static class in both my Level class (to load the actual tile sheets) and my content pipeline extension (to know which symbol represents what tile)...

And here's how my *LevelContentCreation* class looks like:

```
public static class LevelContentCreation
{
    private static Dictionary<char, TileCreationInfo> AvailableTiles =
        CreateAvailableTiles();

    private static List<string> AvailableTileSheets { get; set; }

    /* ... rest of the class */
}

```

Now, **since the *LevelContentCreation* class is part of the game library, the content pipeline extension tries to use it but the call to CreateAvailableTiles() never happens and I'm unable to load a Level object from the content pipeline.**

I know this is because the content pipeline executes before the actual compilation or something like that, but **how can I fix the problem?**

I can't really move the *LevelContentCreation* class to the pipeline extension, because then the *Level* class wouldn't be able to use it... I'm pretty lost and I don't know what to do... I know these are pretty bad design decisions, and I'd like it if somebody could point me in the right direction.

Thank you for your precious time.

*If anything is not clear enough or if I should provide more information/code, please leave a comment below.*

---

A little more information about my projects:

* **Game** \- XNA Windows game project. Contains references to: Engine, GameLib and GameContent
* **GameLib** \- XNA game library project. Contains references to: Engine
* **GameContent** \- XNA content project. Contains references to: LevelContentPipelineExtension
* **Engine** \- XNA game library project. No references.
* **LevelContentPipelineExtension** \- XNA content pipeline extension. Contains references to: Engine and GameLib

I know close to nothing about XNA 4.0 and I'm a little bit lost about how content works now. If you need more information, tell me.

# Answer
In cases where you are using singletons, static classes, or global variables, 99% of the time what you should really be using is a game service. Game services are used when you want one instance of a class available to all other classes, but the tight coupling of the other options gives you a funny taste. Services also don't have the instantiation problems that you've seen, they're more reusable, and they can be mocked *(if you care about automated unit-testing)*.

To register a service, you need to give your class its own interface. Then just call `Game.Services.AddService()`. To later use that service in another class, call `Game.Services.GetService()`.

In your case, your class would look something like this:

```
public interface ILevelContentCreation
{
    void SomeMethod();
    int SomeProperty { get; }
}

public class LevelContentCreation : ILevelContentCreation
{
    private Dictionary<char, TileCreationInfo> availableTiles =
        CreateAvailableTiles();

    private List<string> AvailableTileSheets { get; set; }

    public void SomeMethod() { /*...*/ }
    public int SomeProperty { get; private set; }

    /* ... rest of the class ... */
}

```

At some point at the start of the program, you'd have to register your service with `Game.Services`. *I prefer to do this at the start of `LoadContent()`, but some people prefer to register each service in that class's constructor.*

```
/* Main game */
protected override void LoadContent()
{
    RegisterServices();

    /* ... */
}

private void RegisterServices()
{
    Game.Services.AddService(typeof(ILevelContentCreation), new LevelContentCreation());
}

```

Now whenever you want to access your `LevelContentCreation` class in any other class, you would simply do this:

```
ILevelContentCreation levelContentCreation = (ILevelContentCreation) Game.Services.GetService(typeof(ILevelContentCreation));
levelContentCreation.SomeMethod(); //Tada!

```

---

As a side note, this paradigm is known as Inversion of Control (IoC), and is widely used outside of XNA development as well. The most popular framework for IoC in .Net is Ninject, which has nicer syntax than the Game.Services methods:

```
Bind<ILevelContentCreation>().To<LevelContentCreation>(); //Ninject equivalent of Services.AddService()
ILevelContentCreation levelContentCreation = kernel.Get<ILevelContentCreation>(); //Ninject equivalent of Services.GetService()

```

It also supports dependency injection, a form of IoC which is slightly more complex, but much nicer to work with.

**\[Edit\]** Of course, you can get that nice syntax with XNA too:

```
static class ServiceExtensionMethods
{
    public static void AddService<T>(this GameServiceContainer services, T service)
    {
        services.AddService(typeof(T), service);
    }

    public static T GetService<T>(this GameServiceContainer services)
    {
        return (T)services.GetService(typeof(T));
    }
}

```
> 11 votes

# Answer
I actually found a way to fix the problem: I removed the static class and made it a normal class. This way I'm sure the right statements get executed at the right time.

I wished I had not wasted your time like so but I actually got the idea of doing so by reading the comments/answers.

Thank you anyway.
> 1 votes

# Answer
Have a look at this: http://msdn.microsoft.com/en-us/library/bb447745.aspx

For level layout i'd just put a function inside my Level class called "LoadFromFile(string name)". Because if you want to add support for custom maps in your game later, you will have to save and load the levels from your own file format anyway.

You could also still create a content importer, to load from the included assets and also from user provided files. Look at this page for more information about how to create an importer

http://msdn.microsoft.com/en-us/library/bb447743.aspx
> 0 votes

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


# Question
Title: How do you add equipment to a 3D character model using XNA/Blender?
I've watched quite a few Blender tutorials, but I have yet to see examples of how to swap out sub-models. So my question is, how do you swap out equipment on a character model? Specifically I’d like to be able to dynamically add/swap clothing and items held by a character model in XNA. Ideally the items would follow the bone structure of the character model.

For example; starting with a naked character in XNA, I’d like to be able to have the character hold an axe and wear chainmail that follows the character’s animations. I’d also like to be able to switch this equipment for a sword and plate mail at any time during the game. I’d rather not create a model for each equipment combination. Is there some way to just add the bones (say a sword bone) and meshes of one model to another model bone (say a right hand bone)?

Thanks…

# Answer
> 13 votes
For items that are carried by the character like a sword, shield or similar, you can create a special hand-bone, where you attach the new item/geometry at runtime.

When it comes to different armors/clothing, this is going to be slightly more complicated. An approach that is widely used (I think also by WoW) is using segmented models:

You model your character with all different armor and cloth-pieces as sub-meshes (in blender, you would use vertex-groups for that). Then you just toggle the visibility (or attach) the needed parts and hide (or detach) the unneeded parts. All the parts will share the same skeleton.

You can also achieve a lot of different looks by just swapping the texture.

---
Tags: xna-4.0, blender
---


# Question
Title: What are some good combinations of libraries?
Lately I have been working on a game that i plan to make online. I have used different libraries to make this game as far as i could, but I feel that I should rethink on how Im sertting this game up, so I planned to start over. The libraries that I have used are SFML, OpenGL, and Bullet Physics, along with GLM to load the models.

But the problem is that the 3D graphics arent working with the Physics correctly...

So my main question is:

What would be a good combination of libraries to make an online game with? Im sure that many people have good combinations of libraries for making a game.

The libraries that I would need are ones that fit the criteria of making a simple 3d game(online):

3D Graphics(including a model loader of some sort(if it works with blender that would be even better. I would also like compatability, If Theres one that fits DirectX(at least 9) and OpenGL, then that would be good)

2D Graphics(I liked SFML, so it its possible to get something that works with SFML, that would be nice)

Networking(a way to connect multiple clients to a server/database)

and Physics(Ive worked with Bullet Physics, but I cant find a model setup that would fit with said physics)

Also if there are any other libraries that work well with these I would like to know. Any answers would be very helpful. and details would be even nicer =)

Thanks in advance. -Molma

# Answer
> 4 votes
> But the problem is that the 3D graphics arent working with the Physics correctly...

Pretty much any pair of graphics and physics libraries will work together. If you haven't managed to get OpenGL graphics and Bullet physics working, you probably just have a bug there which can be fixed.

# Answer
> 1 votes
I'm just going to go put Unity out there. It is, bluntly, amazing at everything you put. Except the networking (No idea, I'm afraid), and weaker on the 2D.

---
Tags: opengl, c++, directx9, sfml
---


# Question
Title: Determining player.isFalling() through change of y?
I'm currently using Box2D and my character is a bunch of fixtures in Box2D. I was wondering if, to determine if a player is falling, detecting a change in Y position would be appropriate?

Are there maybe other ways that I'm not thinking of? How is this sort of thing usually detected?

# Answer
(From my comment.) I am not familiar with Box2D, but normally a physics engine should give you ways to check the normal of a collision.

If it is 'up' this means your player is standing on something, and should be able to jump.

Inversely if he is not colliding, or if none of the collision normals are pointing 'up' then he is falling.
> 9 votes

# Answer
You need two booleans, `isColidingWithGround` and `isJumping`

When the user presses the jump button, if `isColidingWithGround` is `true`, and `isJumping` is false, then call `jump()` which sets `isJumping` to `true`

If the player's `y` velocity is positive then `isJumping` equals `false`

If the player is coliding with the ground, then isColidingWithGround equals `true`, else `isColidingWithGround` equals `false`.

Sometimes the player is still in contact with the ground after the initial jump impulse, and I find that with using these two flags, it prevents jump() from being called multiple times when jump is pressed.
> 3 votes

# Answer
The way I handle this is each player has an `isJumping` boolean which, when they jump, is set to `true`. When they collide with a surface, I check if it's something they could jump off of and other stipulations such as are they standing flat, etc. and set it to `false`.

Then, when they try to jump, if the surface they're on is good and `isJumping == false` I allow them to jump, otherwise they can't jump. I think this is better than calculating collisions every time you want to see if they're jumping.

**Edit**
As @BlueRaja pointed out below, if the user walks off the edge, `isJumping` will still be `false`. You can fix this with the Contact Listener's `EndContact` method (see sect 9.4 Box2D docs. You just need to set the `isJumping` property to `true` when the collision with the world ceases.
> 2 votes

# Answer
Move all relevant components in your "bunch of fixtures" (which together make the player) downward by a small amount, and check for collisions with anything you consider possible to jump off of. If there is no collision, the player is falling. Otherwise, he isn't. Don't forget to move the components back up by that same amount.

If your character is humanoid, you should probably move and check only the feet of the character, as otherwise your character may end up being able to jump even when standing on his head!
> 0 votes

# Answer
This may or may not apply, but we would detect a difference between jumping/landing and falling so we knew when to swap to a falling animation, do damage for falling too long (not too far ;)) and the like.

It was pretty much done by tracking how long a object was without a reference point. Anything on the ground, or any other object, had a reference to what it was standing on.. Not standing on anything? Then you were in the air, and after 1-2 seconds, you were 'falling' instead of gracefully landing :)
> 0 votes

# Answer
Very naively and simply, you could check if the player has a y-velocity (velocity, not speed) which is \> 0, assuming you're using (0,0) as top left.
> 0 votes

---
Tags: c++, physics, box2d
---


# Question
Title: A cool way of doing Z-index for XNA components?
I am trying to render some elements in my game. First, I render the textures (the textures of the textboxes themselves etc). Then I render the primitives (borders around controls etc). Then I render the text.

However, by doing so, this gives a weird result in my user-interface when showing tooltips (by hovering over a textfield), as seen in the screenshot below.

Due to the order of drawing, borders around the window are drawn after textures, which (for the tooltip that appears when my mouse is over the textfield) makes it look weird.

# Answer
> 7 votes
If these are each separate `DrawableGameComponents`, you should set the `DrawOrder` property of each component so that they draw in the correct order.

To make it more manageable as you add more components, the `DrawOrder` should be an `enum`:

```
/* DisplayLayer.cs */
public enum DisplayLayer
{
    Background, //back-layer
    Particles,
    Player,
    MenuBack,
    MenuFront //front-layer
}

public class MyComponent : DrawableGameComponent
{
    public MyComponent(Game game) : base(game)
    {
        this.DrawOrder = (int)DisplayLayer.Background;
    }

    /* etc. */
}

```

---

If this is all being drawn within a single `DrawableGameComponent`, then you should take @Andrew's advice and simply draw them in the correct order. If for some reason you can't do that, you can still have the clarity of `enum`s when using `layerDepth` by simply normalizing the value of the `enum` to be between 0 and 1:

```
/* DisplayLayer.cs */
public enum DisplayLayer
{
    MenuFront, //front-layer
    MenuBack,
    Player,
    Particles,
    Background, //back-layer
    MAX_LAYER   //Do not use this as a layer
}

public void Draw()
{
    spriteBatch.Begin(SpriteSortMode.BackToFront);
    foreach(Thingy thingy in thingys)
        spriteBatch.Draw(/* blah blah */, (float)thingy.DisplayLayer/(float)DisplayLayer.MAX_LAYER);
    spriteBatch.End();
}

```

*(The ordering of the `enum` is reversed because `layerDepth` uses lower numbers for the front-layer rather than the back-layer)*

# Answer
> 6 votes
http://msdn.microsoft.com/en-us/library/ff433989.aspx

```
public void Draw (
         Texture2D texture,
         Vector2 position,
         Nullable<Rectangle> sourceRectangle,
         Color color,
         float rotation,
         Vector2 origin,
         Vector2 scale,
         SpriteEffects effects,
         float layerDepth
)

```

**layerDepth** The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.
For example you have: Form, and in the form labels, buttons
So for children elements you can add to layerDepth some value
For example: Form A have children: Form B and some buttons, Form B have only button
Form A - 1.0
Buttons in form A - 1.5
Form B in Form A - 1.5
Buttons in form B - 2

For Dialogs - you can store some bigger value

# Answer
> 6 votes
I'm going to give the simple and fairly obvious answer, and that is **just draw everything in the correct order in the first place**.

To mock-up an example of what I mean:

```
// Assuming you have sorted windowList by Z-order, using one of the many
// existing sorting mechanisms provided by the framework such as List<T>.Sort().
foreach(var window in windowList)
    window.Draw();

// in your Window class:
public void Draw()
{
    this.DrawBackground();
    this.DrawBorders();
    this.DrawText();
}

```

Is there a particular, compelling reason why you are not already drawing your windows in this way?

---
Tags: xna, xna-4.0
---


# Question
Title: My SFML sprite Move() function: FeedBack?
Hey so I'm making a pong game with SFML and in the process made a function that takes a Time, Speed, Angle of movement, buffer for the movement on the X axis, and buffer for the movement on the Y axis.

I then implemented this function into my custom mySprite class, more specifically into it's update() function which updates its Position using the above function to calculate its new position.

However I'm worried that giving the function the FrameTime() of the Window (the time since the frame was last updated) is not the best choice as the sprites might start jumping around if there's lag between frame updates or other problems.....

Finally I would like to know how my organization, planning, etc is.. **Thanks!**

my **UPDATED, WORKING** Code:

```
   #include<SFML/Graphics.hpp>
#include<SFML/System.hpp>
#include<cmath>
#include<vector>
#    define M_PI 3.14159265358979323846

sf::RenderWindow Window;

template<typename T>
void CalculateMove(T Time, T Speed, T Angle, T& buffX, T& buffY)
{   //Make the degrees positive
    if(Angle<0) Angle= 360+Angle;
    //determine what quadrant of circle we're in
    unsigned int  Quadrant= 1;
    if(Angle>90)  Quadrant= 2;
    if(Angle>180) Quadrant= 3;
    if(Angle>270) Quadrant= 4;

    //anything above 90 would be impossible triangle
    Angle= (float)(Angle-(int)Angle)+(float)((int)Angle%90);

    // calculates x and y based on angle and Hypotenuse
    if((int)Angle!=0){
        if(Quadrant==2 || Quadrant==4) Angle=90-Angle; //The unit circle triangle is flipped otherwise, causing x and y to be switched
        buffY= sin(Angle / 180 * M_PI)/ (1.f/(Speed*Time));
        buffX= sin((180-Angle-90)/ 180 * M_PI)/ (1.f/(Speed*Time));}

    else{// Movement is a straight line on X or Y axis
        if(Quadrant==0 || Quadrant==2) buffX= Speed*Time;
        if(Quadrant==1 || Quadrant==4) buffY= Speed*Time;}

    //Quadrant Factor (positive or negative movement on the axis)
    switch(Quadrant){
    case 1: break;
    case 2: buffX=-buffX; break;
    case 3: buffX=-buffX; buffY=-buffY; break;
    case 4: buffY=-buffY; break;}
};

/////////////////////////////////////////   Mysprite    ////////////////////////////////
class mySprite : public sf::Sprite
{
private:
    float velocity;
    float angle;

public:
    // all the values needed by the base class sprite();
    mySprite(
        const sf::Image& Img,
        const sf::Vector2f& Position = sf::Vector2f(0, 0),
        const sf::Vector2f& Scale = sf::Vector2f(1, 1),
        float Rotation = 0.f,
        const float Angle= 0.f,
        const float Velocity= 0.f,
        const sf::Color& Col = sf::Color(255, 255, 255, 255)):
      Sprite(Img, Position, Scale, Rotation, Col){
        angle= Angle;
        velocity= Velocity;};

    float Velocity(){return velocity;};
    void SetVelocity(float newVelocity){velocity=newVelocity;};
    float Angle(){return angle;};
    void SetAngle(float newAngle){angle=(float)(newAngle-(int)newAngle)+(float)((int)newAngle%360);};

    void Update(){
        float frameTime= Window.GetFrameTime();
        float X=0,Y=0;
        SetRotation(angle);
        CalculateMove(frameTime,velocity,angle,X,Y);
        Move(X,-Y);
    };

    void Accelerate(float PPS){velocity+=PPS;};
    void Turn(float degrees){
        angle=(float)((angle+degrees)-(int)(angle+degrees))+(float)((int)(angle+degrees)%360);};

    void Reflect(float CollAngle){
        SetRotation(-GetRotation());
        angle=360-angle;
        //TODO: factor in the collision angle
    };
};

```

# Answer
> 2 votes
All of your calculations must be implemented independently of time, the frameTime is the correct form to do this. There are different forms to calculate this elapsed time, but you don't worry about this now. With the frameTime you calculates the desired next position of the ball and then you need to calculate collisions and adjust the position if it's necessary.

About the code:

1.- Decide a convention to the variable names and follow it.

"Time" has the first letter uppercase unlike buffX

in c++ usually the first letter of variables is lowercase

2.- Do you think that the function CalculateMove needs to be a template?

I don't think that the type of the parameters will be different to float in the game. If it don't needed, don't use it.

3.- For the cast conversions is better use static\_cast( variable ) form.

Because it's more clear and it can be searched easily.

4.- In c++ the class names usually begins with uppercase.

5.- The constructor has a lot of parameters.

It's better declare a structure with these parameters and pass it by const reference to the constructor. In addition, the constructor of the structure can have the default parameters.

Like:

```
struct SpriteParams
{
      float          m_rotation;
      float          m_angle;

      SpriteParams()
          : m_rotation( 0.f )
          , m_angle( 0.f )
      {}
 };

 // The mySprite constructor
 MySprite::MySprite( const SpriteParams& params );

```

6.- Are you sure that mySprite must inherit from Sprite?

If this class is modelling a paddle, the class must be a paddle and contains a graphics representation ( the sprite )

```
class Paddle
{
     public:
         void update();

     private:
         sf::Sprite  m_sprite;
};

```

# Answer
> 0 votes
For the question about how to stop jittery movement because of frame length, what you might consider doing is rather than feed the time step directly to the update function choose a fixed time step, like this:

```
void Update(){
    static float frameTime += Window.GetFrameTime();
    float X=0,Y=0;
    while (frameTime >= TIME_STEP)
    {
        CalculateMove(TIME_STEP,velocity,angle,X,Y);
        Move(X,-Y);
        frametime -= TIME_STEP;
    }
};

```

(I wouldn't localize this to just the sprite though, I would do this in the main game update loop and have it apply to everything that updates)

---
Tags: c++, graphics, mathematics, sfml
---


# Question
Title: Bringing a Box2D, Physics Enabled game Online?
Lets say, to simplify the problem of online games a bit, my goal would be to run a near identical simulation on multiple computers in sync. Would sending commands be a good idea?

Now if only sending commands is not good, should all the physics entities be sent every half second or so?

I'm wondering this because my game will essentially be a Box2D fighting game. Players can also spawn items, which must be added to the Box2D world.

What I'm wondering is how much and what kind of information should I send over the server?

Should I simply send key presses, and every half second snap back dynamic object positions to where the server thinks they should be?

Any helpful tips / articles regarding this would be a great help!

Thanks

# Answer
There are a few standard approaches for this sort of thing.

The first, is to run all computers in lockstep. That is, no computer computes the physics for a frame until everyone has received the commands issued by all the other players during that frame. This may sound a little silly, but it's actually a pretty good system for games which are only being played on LANs. It keeps everyone in synch (assuming a deterministic game) without having to exchange a lot of data. Downside is that your frame rate is limited by network latency, which makes it pretty impractical for use on the Internet.

The second approach is the "ownership" approach, where every object is *owned* by just one game client. That client is responsible for updating the physics on that object, and all other clients receive information about the object's movements over the network. Locally, they'd either set the object into kinematic mode and explicitly move it around based upon dead-reckoned network data or else perform local physics and correct those physics calculations based upon the dead-reckoned network data. This can be complicated, especially if objects need to be able to change ownership between players mid-game, but it's the standard way to handle this for games played in a peer-to-peer network configuration (as opposed to having a single central server).

The third approach is to have an authoritative server. This is basically the same as the "ownership" approach above, except that the server owns everything, and each client is always either kinematically moving the objects, or moving them via physics and then correcting. Commands from clients get sent to the server, along with a timestamp of when that command was given. The server then retroactively applies those commands, as though they had arrived earlier. (This is complicated to do, and I'm not sure that Box2D will allow you to do it. If not, you can ignore this part)

If you're planning to have a server and to be playable across the internet, then this third approach is probably going to be the way to go. You'll definitely want to be looking up articles on dead reckoning and error correction in order to help hide the pops when updated data arrives from the server, but otherwise what you've laid out seems a pretty reasonable approach.
> 4 votes

---
Tags: c++, game-design, physics, networking
---


# Question
Title: Worth using Box2d for collision but not physics?
I am currently doing some work in cocos2d-x and am thinking about using their box2d implementation for things like collision detection (but not necessarily response), range detection, and other things like that, which are not strictly physics based.

Is it worth doing this? or would I be better off just writing a simple system that does checks based on location/size of my objects?

# Answer
> 2 votes
Seems like a decent idea to me; I've done a very similar thing in a few projects (although with different APIs).

If functionality and performance is acceptable, and it saves you from having to write all that boring collision detection code and focus instead on something that makes your game unique and cool, then I'd say go for it.

---
Tags: box2d, cocos2d-iphone
---


# Question
Title: How to render a texture partly transparent?
Good Morning StackOverflow, I'm having a bit of a problem right now as I can't seem to find a way to render part of a texture transparently with openGL.

Here is my setting : I have a quad, representing a wall, covered with this texture (converted to PNG for uploading purposes). Obviously, I want the wall to be opaque, except for the panes of glass. There is another plane behind the wall which is supposed to show a landscape. I want to see the landscape from behind the window. Each texture is a TGA with alpha channel.

The "landscape" is rendered first, then the wall. I thought it would be sufficient to achieve this effect but apparently it's not the case. The part of the window supposed to be transparent is black and the landscape only appears when I move past the wall.

I tried to fiddle with GLBlendFunc() after having enabled it but it doesn't seem to do the trick.

Am i forgetting an important step ?

Thank you :)

# Answer
> 20 votes
In addition to everything you've stated (textures with alpha channels, drawing the landscape before drawing the wall+window), you also need to do two more things.

First, you need to enable OpenGL's blending functionality:

```
glEnable(GL_BLEND);

```

Second, you need to tell OpenGL how to calculate the colors of blended pixels (which OpenGL calls "fragments", incidentally). In this case, you'll be fine with something simple like this:

```
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

Once blending is turned on, OpenGL will combine pixel colors according to the function parameters you give it in glBlendFunc. Specifically, it will do "source.color * source.alpha + destination.color * (1-source.alpha)", where "source" is the texture you're currently rendering, and "destination" is the color already in the framebuffer (the landscape). So wherever your alpha channel is white, you'll get the wall color, and wherever the alpha channel is black, you'll get the landscape color. If the alpha channel is grey, then you'll get some cross-fade between the two colors.

If your window is fully transparent then there are other ways to do this, where the order in which you draw the two polygons isn't important, but that starts getting into more advanced concepts such as alpha thresholds. Probably not needed for your current situation.

---
Tags: opengl, textures, transparency
---


# Question
Title: Finding next experience level using the square root?
I recently asked this question on how to calculate a level based on experience:

Algorithm for dynamically calculating a level based on experience points?

I am using the following calculation to determine the players level:

```
decimal experience = 1829;
decimal rawLevel = (decimal)(.06 * Math.Sqrt(experience));
decimal level = Math.Floor(rawLevel);

```

For my test, `1829` experience points equates to `2.56600857364117M`, which I floor to level 2.

My question is, how can I figure out how many points it would take to get to the next level based off of the calculation above?

I know the next level is 3, so I would need to figure out how many points equate to level 3 so that I can find the difference. What formula would I use, given the constant .06 above?

**Update: Solution:**

```
int experience = 150777;
decimal rawLevel = (decimal)(.06 * Math.Sqrt(experience));
decimal level = Math.Floor(rawLevel);
decimal nextPoints = (decimal)Math.Pow((double)(level + 1) / 0.06, 2);

```

# Answer
You just need to do the inverse calculations in the inverse order :

```
Exp = (Level / 0.06)²

```

So for level 2, you would need 1111 exp, and for level 3 you would need 2500.

I wrote a small piece of code to see the exp needed for certain levels : the rounding isn't great it's not very nice for a player to see 'Next Level : 64944 Exp'.

What you could do is use a litte trick to make your level exp more 'rounded', just divide and then multiply by 10.

Code Exmaple Here!
> 5 votes

---
Tags: game-design
---


title: DirectX the same across platforms?

text:
# Question
Title: DirectX the same across platforms?
Various versions of DirectX are available on both Windows and Xbox. Are the libraries the same on both platforms? Obviosly I'm talking about the interfaces — such as the ones for working with windows, input, etc —, not their actual implementation.

# Answer
> 5 votes
The APIs available on Windows and the 360 are similar, but they are not the same. It's not really possible to provide more details without running afoul of NDAs, really.

However, you could look at the difference between how XNA operates on Windows and on the 360 for some vague, rough ideas of about the class of differences you may expect to see, at least in terms of how behavior and functionality can differ even though the API remains the same.

---
Tags: directx, xbox360, windows, xbox
---


# Question
Title: How are physics or graphics components typically built in a component-oriented system?
I have spent the last 48 hours reading up on Object Component systems, and feel I am ready enough to start implementing it. I got the base Object and Component classes created, but now that I need to start creating the actual components I am a bit confused. When I think of them in terms of HealthComponent or something that would basically just be a property, it makes perfect sense. When it is something more general as a Physics/Graphics component, I get a bit confused.

My Object class looks like this so far (If you notice any changes I should make please let me know, still new to this)...

```
typedef unsigned int ID;

class GameObject
{
public:

    GameObject(ID id, Ogre::String name = "");
    ~GameObject();

    ID &getID();
    Ogre::String &getName();

    virtual void update() = 0;

    // Component Functions
    void addComponent(Component *component);
    void removeComponent(Ogre::String familyName);

    template<typename T>
    T* getComponent(Ogre::String familyName)
    {
        return dynamic_cast<T*>(m_components[familyName]);
    }

protected:

    // Properties
    ID m_ID;
    Ogre::String m_Name;
    float m_flVelocity;
    Ogre::Vector3 m_vecPosition;

    // Components
    std::map<std::string,Component*> m_components;
    std::map<std::string,Component*>::iterator m_componentItr;
};

```

Now the problem I am running into is what would the general population put into Components such as Physics/Graphics? For Ogre (my rendering engine) the visible Objects will consist of multiple Ogre::SceneNode (possibly multiple) to attach it to the scene, Ogre::Entity (possibly multiple) to show the visible meshes, and so on. Would it be best to just add multiple GraphicComponent's to the Object and let each GraphicComponent handle one SceneNode/Entity or is the idea to have one of each Component needed?

For Physics I am even more confused. I suppose maybe creating a RigidBody and keeping track of mass/interia/etc. would make sense. But I am having trouble thinking of how to actually putting specifics into a Component.

Once I get a couple of these "Required" components done, I think it will make a lot more sense. As of right now though I am still a bit stumped.

# Answer
> 33 votes
First of all, you when build component-based systems, you don't *have* to take the approach of turning *everything* into a component. In fact, you generally shouldn't -- it's something of a neophyte mistake. In my experience the best way to tie together rendering and physics systems in a component based architecture is to make those components little more than dumb containers for the real rendering or physics primitive object.

This has the added advantage of keeping the rendering and physics systems decoupled from the component system.

For physics systems, for example, the physics simulator generally keeps a big list of rigid body objects that it manipulates every time it ticks. Your component system does not mess with that -- your physics component simply stores a reference to the rigid body that represents the physical aspects of the object the component belongs to, and translates any messages from the component system into appropriate manipulations of the rigid body.

Likewise with rendering -- your renderer will have something representing the instance data to be rendered, and your visual component simply holds on to a reference to that.

It's relatively straightforward -- for whatever reason it seems to confuse people, but that's often because they are thinking about it too hard. There's not a lot of magic there. And since it's most important to get things done rather than agonize over the perfect design, you should strongly consider an approach where at least some of the components have defined interfaces and are direct members of the game object, as momboco has suggested. It's just as valid an approach and it tends to be easier to grok.

**Other Comments**

This is unrelated to your direct questions, but these are things I noticed when looking at your code:

Why are you mixing Ogre::String and std::string in your game object, which is ostensibly a non-graphics object and thus should not have a dependency on Ogre? I would suggest removing all direct references to Ogre except in the rendering component itself, where you should do your transformation.

update() is a pure virtual, which implies that one must subclass GameObject, which is actually kind of exactly the opposite of the direction you want to go in with a component architecture. The main point of using components is to prefer aggregation of functionality rather than inheritance.

You could benefit from some use of `const` (particular where you are returning by reference). Also I'm not sure that you really want velocity to be a scalar (or if it, and position, should be present in the game object in the kind of overly generic component methodology you seem to be going for).

Your approach of a using a big map of components and an `update()` call in the game object is quite sub-optimal (and a common pitfall for those first building these sorts of systems). It makes for very poor cache coherency during the update and doesn't allow you to take advantage of concurrency and the trend towards SIMD-style process of large batches of data or behavior at once. It's often better to use a design where the game object doesn't update its components, but rather the subsystem responsible for the component itself updates them all at once. This might be worth a read.

# Answer
> 5 votes
The component architecture is an alternative to avoid the large hierarchies that are achieved inheriting all elements from a same node, and the problems of coupling that leads.

You are showing a component architecture with "generic" components. You have the basic logic to attach and detach "generic" components. An architecture with generic components is more difficult to achieve because you don't know which component is. The benefits is that this approach is extensible.

A valid component architecture is achieved with defined components. With defined I mean, the interface is defined, not the implementation. For example, GameObject can have a IPhysicInstance, Transformation, IMesh, IAnimationController. This has the benefit that you know the interface and the GameObject knows how to deal with each component.

**Responding to the term over-generalizing**

I think that the concepts are not clear. When I say component, doesn't mean that all component of a game-object must inherit from a component interface or something similar. However this is the approach for Generic Components, I think that it is the concept that you name as a component.

The component architecture is another of the architectures that exist for runtime object model. It's not the only and its not the best for all cases, but the experience has demonstrated that has a lot of benefits, like low coupling.

The main feature that distinguishes the component architecture is convert the relation is-a into has-a. For example a object architecture is-a:

Instead of a object architecture has-a ( components ):

There is also property-centric architectures :

For example, a normal object architecture is like this:

* Object1

+ Position = ( 0, 0, 0 )
    + Orientation = ( 0, 43, 0 )
* Object2

+ Position = ( 10, 0, 0 )
    + Orientation = ( 0, 0, 30 )

A property-centric architecture:

* Position

+ Object1 = ( 0, 0, 0 )
    + Object2 = ( 10, 0, 0 )
* Orientation

+ Object1 = ( 0, 43, 0 )
    + Object2 = ( 0, 0, 30 )

It is better the object model architecture? In performance perspective, it's better the property-centric because it is more cache-friendly.

Component is refered to the relation is-a instead of has-a. A component can be a Transformation matrix, a quaternion, etc. But the relation with the game-object is a relation is-a, the game-object doesn't have the transformation because it's inherited. The game-object has ( relation has-a ) the transformation. The transformation is then a component.

The game-object is like a hub. if you want a component that always is there, then maybe the component ( like the matrix ) should be inside the object and not a pointer.

There is not a perfect game-object for all cases, it depends the engine, the libraries that the engine use. Maybe I want a camera that doesn't have a mesh. The problem with is-a architecture is that if the game-object has a mesh, then the camera that inherits from game-object must have a mesh. With componenets, the camera has a transformation, a controller for the movement, and anything you need.

For more information, the chapter "14.2. Runtime Object Model Architecture" from the book "Game Engine Architecture" of "Jason Gregory" deals specifically this subject.

UML diagrams are extracted from there

---
Tags: architecture, physics, graphics, component-based, game-component
---


# Question
Title: Multiplayer XNA without a LIVE account? (PC)
I decided it was time to stick in a bit of multiplayer into my game, but came across my first hurdle when i quickly downloaded an example from the XNA website.

It prompted me with a login to live. However i really DO NOT want my game to use live accounts.

This is PC btw.

Basically i wanted to know, is it possible to have multiplayer with XNA without logging in through a live account?

Also, is it better to stick with the built in XNA networking, or use a totally different library such as lidgren?

# Answer
> 6 votes
This blog post may address your issue to a degree (it's fairly old but I don't think things have changed that much).

If you are only targetting the PC, you don't need to use the networking functionality provided by XNA (which will tend to want Live profiles) -- you can use the standard networking functionality built in C# itself and roll your own networking layer entirely, or use a third party one.

Whether or not that is "better" depends on a lot of factors, but if Live accounts are a deal-breaker for you, using something third-party is probably better in that regard.

---
Tags: xna, multiplayer, xna-4.0
---


title: How to rotate a rectangle?

text:
# Question
Title: How to rotate a rectangle?
I can easily rotate sprites using the Draw method. However I would like to simply rotate a Rectangle (the structure) so that I can get the coordinate of the four corners of the rectangle. How can I do that?

# Answer
> 5 votes
You can't rotate a Microsoft.Xna.Framework.Rectangle. It is by nature an axis aligned structure only.

What do you hope to do with the corners that you want to find? Maybe we could suggest a good way to accomplish your goal.

# Answer
> 2 votes
You can make for all 4 points something like this:

```
public static Vector2 RotateAround(this Vector2 source, Vector2 target, float radians)
 {
 Vector2 fromAround = source - target;
 float postRotationX = (float)(fromAround.X * Math.Cos(radians) - fromAround.Y * Math.Sin(radians));
 float postRotationY = (float)(fromAround.X * Math.Sin(radians) - fromAround.Y * Math.Cos(radians));
 return target + new Vector2(postRotationX, postRotationY);
}

```

**Code From MSDN** http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.aspx

# Answer
> 0 votes
If you want to get the coordinates of the rotated corners, you have to transform the coordinates from the non-rotated space to the rotated space. In other words, you have to multiply them by a matrix. I'm not sure the exact xna syntax, but it should be something like this:

```
float angle = 60;
Matrix rotate = Matrix.CreateRotationZ(angle);
Vector2 transformedPoint = Vector2.Transform(unTransformedPoint, rotate);

```

This will rotate the rectangle about it's top left corner. I'm not sure if that's what you want or not, but you can easily change this by adding a translate transform before the rotate transform to change the rotation origin.

---
Tags: xna, rotation
---


title: Synchronise graphics and logic code

text:
# Question
Title: Synchronise graphics and logic code
I have a procedural approach to the game loop that runs various classes.

it looks like this:

1. continue any in progress animations
2. check for used input
3. apply AI
4. move things
5. resolve events such as collisions
6. draw it all to screen

I have seen a lot of posts about how drawing should be running separately as fast as it can, possibly in another thread.

My problem is that if the drawing runs as fast as it, can what happens if it tried to draw while I'm still applying the AI or resolving a collision? It could draw the wrong thing on screen.

This seems to be a well established idea so there must be an explanation to this problem as I just cant get my head around it. The only solution I have is to update the screen so fast that any errors like that get refreshed before we see them but that sounds hacky.

So how does this work / how would you implement it so that they are in sync but running at different speeds?

# Answer
> 0 votes
This link, suggested by 3nixios, addresses what you're talking about.

The issue that's holding you back is concurrency (threading) and locking, and being aware of that it can be a problem is half the battle.

I suggest reading the accepted answer to the link, but the short version is that you will only draw or update the unlocked items, but before you do you'll ask the program to lock the object/variable. After you are done with it, you'll unlock it.

The wikipedia article on this isn't a bad starting point. http://en.wikipedia.org/wiki/Lock\_(computer\_science)

There are issues around lock contention and dead locks and such, but any good concurrency reference will discuss these in gory detail.

Hope this helps.

# Answer
> 1 votes
**Edit:** Since some people got a bit confused as to what I meant, I'm going to elaborate a bit.

This is called a race condition. You don't go into a lot of detail as to how your game works, but here is what I can offer:

* If you can draw the data-dependent stuff onto a reasonably-sized surface, you can draw once, then keep the surface, and draw it onto the screen while processing. This way you can redraw cursor, HUD, etc onto the screen, but not ruin the game image, since you have it as a separate surface. **Edit:** So the procedure would now be: render onto work\_in\_progress\_surface and blit last\_stable\_surface onto the screen, until you are done with AI and moving things. Now blit work\_in\_progress\_surface onto last\_stable surface and clear it for the next frame. Get user input and repeat. The main idea here is that you keep the last good frame separated.
* You can save the new data in an alternate memory space. Once everything is calculated, just point to the new data and deallocate the old. You might want to / have to split game data into two parts: screen-changers and behind-the-scenes data. Or flag it, however you like. **Edit:** One possible way to implement this is to make a list of all objects that could change in mid-render. Before applying AI and moving things make a deep copy of everything listed, render the old data but modify the new data. When your AI/moving is finished, just deep copy all new data into the normal objects.
* If the AI/moving is guaranteed to be very fast - less than ~200ms where it doesn't bother users, you could just suspend rendering and the UI through a semaphore. Set it to 0 when the renderer is running, then have the AI/moving set it to 1 and wait, when the renderer finishes, it should look at it before starting again. When it sees the 1 it will set it to 2 and stop rendering. The AI/moving will see the 2 and start working. When all render data has been modified, the AI/moving sets it back to 0 and backgrounds. The render thread sees the 0 and resumes rendering. This is how a pretty simple semaphore works, don't skip the extra transitional phase, think about why it's there.

# Answer
> 1 votes
> I have seen a lot of posts about how drawing should be running separately as fast as it can, possibly in another thread.

This is an outdated view of parallelism in game engines. A more modern view would, instead of running simulation and rendering in parallel, parallelise the simulation and rendering separately.

---
Tags: c++, game-loop
---


# Question
Title: How to calculate turn heading to a missile?
I have a missile that is shot from a ship at an angle, the missile then turns towards the target in an arc with a given turn radius. How do I determine the point on the arc when I need to start turning so the missile is heading straight for the target?

**EDIT**

What I need to do before I launch the missiles is calculate and draw the flight paths. So in the attached example the launch vehicle has a heading of 90 deg and the targets are behind it. Both missiles are launched at a relative heading of -45deg or + 45 deg to the launch vehicle's heading. The missiles initially turn towards the target with a known turn radius. I have to calculate the point at which the turn takes the missile to heading at which it will turn to directly attack the target. Obviously if the target is at or near 45 degrees then there is no initial turn the missile just goes straight for the target.

After the missile is launched the map will also show the missile tracking on this line as indication of its flight path.

What I am doing is working on a simulator which mimics operational software. So I need to draw the calculated flight path before I allow the missile to be launched.

In this example the targets are behind the launch vehicle but the precalculated paths are drawn.

# Answer
My math might be a bit wrong, so I have wikied the answer.

I assume you want to do the continually homing scenario - where the missile P1 travelling at a velocity V1 constantly tries to turn toward the player P2; but at a limited turning rate.

1. Determine the vector between the player and the missile.

```
V2 = P2 - P1

```
2. Turn them into unit vectors.

```
V3 = UNIT(V1)
V4 = UNIT(V2)

```
3. Determine the angle between the vectors.

```
a = ARCCOS(V3 * V4) (* indicating dot product)

```
4. Limit the value of the angle between them (remember your trig functions probably work with radians, so try 0.1 as the turning rate).

```
a = SIGN(a) * MINIMUM(ABS(a), MaximumTurningRate)

```
5. Create the new movement vector.

```
V1 = UNIT(V3.x + SIN(a), V4.y + COS(a)) * MissileSpeed

```

**EDIT:** This has no 'starting point' as it is a more robust (and is an easier implementation) for the continually homing scenario. You don't need to find a starting point for a circle - just limit the rate at which the missile can change direction and the rest happens because of the ghost in the machine.
> 9 votes

# Answer
I assume you want to change the direction by changing the launching heading to the target heading then continue straight to the target (a more fun problem should be to hit the target when turning!).

I have to assume that you are able to turn with the same turn radius in all direction (this is a simplification that is hard to see in real missiles).

The simplest solution is to use the **90° bending**: the missile files until its trajectory forms a right angle with the target. if you turn exactly at the 90° point you will miss the target exactly by the turn radius, because you have to take into account the turning itself. The solution is to start to turn exactly "turn radius" meters(?) before reaching the 90° point, then turn forming a (try to guess) 90° arc to go straight to your target.

This solution is not always feasible, for example when you don't have the visibility on the 90° path (buildings or other obstacles).

The good news is that the solution works for every angle (not just the mythical 90°) the trick is to take in account the space needed to turn starting turning before.

How much before? This is why the 90° stuff is the simplest solution...

Let's say that you reach the visibility or the best target heading when the firing path forms an angle of θ° then you should anticipating the turn by:

```
(sec(90° - θ°) + tan(90° - θ°)) * turning_radius

```

...where secant is the reciprocal of the cosine. The proof is trivial and is left to the reader.

Seriously, the formula comes from a simple geometrical construction.

Black line is the firing path, while the thin black line is the same path moved toward the target by turning\_radius units; the same for the red ones that are the target path.

The green segments are turning\_radius in length so you should see that:

AB is the tangent of 90° - θ°

BC is the secant.

Both of the green lines that come from the turning point are turning\_radius in length and are perpendicular to the two paths; meaning that the turning radius is correct and the arc is tangent to both of the paths (as it should be if you make a turn under physical constraints).

Let me know if you see some error.

**EDIT:**

The drawing you are posted shows that there are multiple choices for path even with fixed shooter and target as you can see here:

Once the target is choosed you can apply what i said above with the proper angles.
> 2 votes

# Answer
I'd implement a "steering behaviour" for the missle. The missile has: A velocity(a number), a position(a vector) and a (current)rotation. At each update in your game / at each frame, the missle's rotation is changed just a bit (towards the target). Then the missile is moved forward according to its current rotation and current velocity.

Works for 2D and 3D obviously, since the only difference is an additional dimension.

Another possibility would be to calculate the path of the missile before fiering it. Look up **bezier curves** or **spline**.
> 1 votes

# Answer
I feel like you're solving the wrong problem here. A real-world missile isn't going to worry about where to turn, it's simply going to turn until it's pointed at it's target. The only where-to calculation involved is when to start bringing the controls back to neutral as a real-world missile can't instantly change it's turn rate. That calculation will take only the missile's indicated airspeed as an input value and I would think would be precalculated.
> 0 votes

# Answer
I think the simplest algorithm would just follow two rules:

1. If the current target is closer to the missile than the turning diameter then keep going straight. This avoids the missile orbiting close targets instead of actually getting to them.
2. Otherwise turn towards the target until you are pointing at it.

To calculate the point where the turn ends in 2D:

1. At the point where you want to start turning, the centre of the turning circle is located in a direction perpendicular to the current heading at a distance of your turning radius. Note that there's two of those points - you probably want the one closest to your target. Calculate that position and call it P.
2. You can now construct a right angled triangle with the right angle at the tangent, and two known points - P and your destination. This lets you calculate the distance from the tangent to your target point with Pythagoras. Call it D.
3. Now you need to calculate the intersection of a circle of radius D at your destination with your turning circle. You'll get two solutions which are the two tangent points on that circle where the missile would stop turning (one for each direction of travel round the circle). Pick the point that is in front of the missile - that is your answer.
> 0 votes

---
Tags: projectile-physics
---


# Question
Title: Procedurally generated terrain map. Blend Transitions between terrain types
The question isn't the greatest wording ever sorry.

I have been learning about and prototyping some texture and terrain generation stuff and have run into something perhaps you can help me with.

How it works: I am procedurally generating a terrain height map. It can scroll endlessly in any direction. (image 1) I clamp and mix the colors depending on the value of the height map (image 2)

This is working very well and runs very fast currently, it is after all very simplistic at the moment.

What I need to find is a good way to blur/distort between the terrain transitions. As you can see currently it has very ridged lines and doesn't look all that natural. Given that this is whole thing is procedurally generated I obviously need to find an algo for the blending that can run on the fly. I attempted a bit of pixel jittering and it just looked bad. Also what ever I use has to be able to be seeded so that it maintains consistency (though I doubt that will be a problem since they will most likely all run on randoms).

Any insight would be much appreciated. If I managed to leave out any needed info in my rush to post this just let me know.

# Answer
> 14 votes
When I did this I ended up making a simple gradient file (xml or image based, doesn't matter) that predetermined the color used at the specified distance between the primary height colors (grass vs. sand for instance). This way, there were inbetween states. What is great about this is that you have full control over the transitions.

I suppose that you could also write something that found the mix color based on primary color distance in height via some sort of blending, but, not being a developer beyond hobby, I'm unfamiliar with such technologies (yet).

Here's some gradients I've used. Note that it you can adjust the colors based on the current height:

More grassy/coastal:

Full spectrum:

And here's how it looked. Not bad for fractal at low detail imo...

---
Tags: textures, procedural-generation, terrain
---


# Question
Title: Compiling Ogre3d application using the OgreAppWizard
I have created an ogre application using the ogreappwizard. When I try to compile the solution I get an error saying that `Parameter "basePath" cannot be a relative path.`.

I followed all of the instructions, and have tried reinstalling both the Ogre SDK and the appwizard.

I am losing my head here. What is going on?

# Answer
I have run into this issue myself. There seems to be a bug in the OgreAppWizard.

Until the bug is resolved, the fix is quite simple:

Go to `Project`-\>`Properties`-\>`Configuration Properties`-\>`Debugging`

Then simply remove the leading `"../"` from the path for `Command` and `Working Directory`.
> 1 votes

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


# Question
Title: Faster way to draw dynamic meshes in OpenGL ES
I'm writing a 3D game which is going to inlcude some dynamic meshes.

For now, my code looks like this :

```
private float[] mVertices;
private FloatBuffer mVertexBuffer;

public void onDrawFrame(GL10 gl) {
    // first clear the screen of any previous drawing
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

    // initialize the matrix
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();

    // update the vertex data
    for (int vtx = 0; vtx < mVtxCount; ++vtx){
        // fill in the x, y and z components of the vertex position
        mVertices[vtx * 3] = x;
        mVertices[(vtx * 3) + 1] = y;
        mVertices[(vtx * 3) + 2] = z;
    }

    // update the vertex buffer
    mVertexBuffer.clear();
    mVertexBuffer.put(mVertices);
    mVertexBuffer.position(0);

    // render the vertex buffer
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
    gl.glDrawElements(GL10.GL_LINES, mIndices.length,
                GL10.GL_UNSIGNED_BYTE, mIndexBuffer);
}

```

Here is an easy sample as the index buffer does not change so I only update the vertex position, normal and texture coordinates.

Of course I understand dynamic mesh will always be slower to render than static mesh, but I wonder if the method I use is good or if there is a faster / better way to do this .

# Answer
> 5 votes
I think before you go pointing fingers, you make sure that this is in fact the problem. It might very well be, but before you invest a lot of time an effort in the number solutions below, try profiling your code. You should be looking for large CPU usage areas. If improving that improves performance, then awesome, mission accomplished. Some devices ship without FPUs, so the performance with floats are very poor.

You might try different graphics rendering modes to make sure that you are in fact limited by vertex transfer rates, i.e. using the *same* number of vertices in a static mesh is dramatically faster. If it isn't, then your model(s) are too detailed and filling a buffer faster won't fix anything -- your GPU simply can't handle the geometry + any other stuff you have enabled. You can turn down/off many of the effects like fog/lighting (lighting is especially expensive if your GPU does not have TnL and your CPU does not have a FPU).

As for actual methods of improving performance that take a while to implement, you have a few options:

1. Use GL\_FIXED instead of GL\_FLOAT types. If your CPU does a lot of calculations for the GPU, then fixed point will likely be a fast case for it. GL\_FIXED is the same size as GL\_FLOAT conventionally, so this will not help if data transfer rates are the bottleneck.
2. Use GL\_SHORT instead of GL\_FLOAT types. This will cut transfer bandwidth in half. Since most people don't do integer coordinates for their world's smallest unit, you typically have to constrain the absolute size of your world to a size like 128x128. From there, you can use OpenGL's matrix stack to scale the coordinates. For example, I use GL\_SHORT for texture coordinates where 1024 = 1.0. I then use glScale(1/1024, 1/1024, 1.0) so that when I tell OpenGL the texture coordinates (512, 1024), it will treat them as (0.5, 1.0). It might seem a bit backwards, but generally the GPU can do these transformations for essentially free, and thus all you've done is reduce the amount of data to represent the same position.
3. Check if "vertex buffer objects" extension is supported and use them if they are. There are a lot of tutorials available for a wide variety of languages on how to use them. Essentially, the optimization is that you can have the GPU transfer/draw from one buffer while the CPU writes to another. Because of this "double buffered" approach, less time in spent waiting in the CPU, which can make the graphics appear to render faster. Some implementations have high-speed memory for vertex data and can map these areas into your program. In that way, you can potentially do zero-copy filling of buffers. Consider what OpenGL does normally: You fill an array with floats, you call glDraw\[Arrays/Elements\], then *by the time it returns*, you can delete the whole array. That means either a) the GPU must draw it right there and now, or b) the driver must copy the vertex data for later use. Either way is generally sub-optimal, because you don't have a way of saying to the driver "I'm just going to refill this *same* array with the *same* size next time, and I won't be changing it immediately so you don't need to copy it." Using vertex buffer objects, you can do this.
4. Check platform notes. Some platforms actually have "fast paths", things that their driver specifically or can optimize. Others might prefer vertex data in a certain format, or elements on a certain alignment, or vertices multiples of a certain size, etc.

---
Tags: android, opengl-es, 3d-meshes
---


title: Stencil buffer mask calculation

text:
# Question
Title: Stencil buffer mask calculation
I dont understand how exactly stencil buffer works in openGL. One aspect that confuses me is why do we use a bit operator there in glStencilFunc. Some text say that is is used to achieve multiple stencil planes but I am not sure how that can be done. Can anybody please explain the whole procedure of stencil buffer calculation during the rendering cycle. Thank you.

# Answer
Okay, this does sound like something you can do with stenciling. Stenciling is generally used in conjunction with Multipass Rendering.

## Multipass Rendering

Multipass Rendering basically refers to a rendering loop where multiple renders a performed per frame. Each pass may use a different configuration of OpenGL (e.g. with different stenciling settings) and render the same or different artifacts. The pseudo code would look something like this:

```
initialize the OpenGL configuration for the entire sequence

for each frame
{
    initialize the OpenGL configuration for the frame

    for each rendering pass
    {
        initialize the OpenGL configuration for the rendering pass

        render the artifacts
    }
}

```

In your case, you will need a rendering pass for each layer of rectangles so that you can prepare the stencil buffer before each pass.

## Your Problem

Effectively, you want to restrict the pixels that *can be drawn* in each rendering pass to the set of pixels that *were drawn* in the previous rendering pass. To do this, you are going to need to do three things:

1. Record the pixels you draw.
2. Only draw pixels that were also drawn in the previous rendering pass (except for the first rendering pass, of course).
3. Before each frame, remove the record of which pixels have been drawn.

### Record the pixels you draw

This is where `glStencilOp()` comes in, `glStencilOp()` determines what's going to happen to the **stencil buffer** when a pixel is drawn (and in other situations too, but we won't worry about that). To increment the value in the stencil buffer for each pixel drawn (and hence record that you drew it) include this in the initialization of the entire sequence:

```
glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);

```

The third argument is the important one, it determines what happens when a pixel is drawn (normally), to understand the function better, read the reference docs.

### Only draw pixels that were also drawn in the previous rendering pass

This is a job for `glStencilFunc()`. It determines what's going to happen to the **frame buffer** depending on what the value in the stencil buffer is.

You need to call it before every rendering pass to say 'only draw if the stencil buffer says I drew last time round'. Since the stencil buffer is being incremented each time, the value to test against needs to be incremented too. For example, the first three rendering passes should call `glStencilFunc()` like this:

```
glStencilFunc(GL_EQUAL, 0, 1); // if (stencil_buffer_value == 0) draw;
glStencilFunc(GL_EQUAL, 1, 1); // if (stencil_buffer_value == 1) draw;
glStencilFunc(GL_EQUAL, 2, 1); // if (stencil_buffer_value == 2) draw;

```

Just ignore the third parameter for now, read the reference documentation if want to know what it is.

**EDIT:** The third parameter is used when you want to do bit-wise tests against the stencil buffer value. Most implementations allow 8 bits in the stencil buffer (otherwise known as 8 planes). The third parameter allows you to mask out bits that you do not want to include in the test (by ANDing it with the second parameter before doing the test). Since I have used 1 as the third parameter, ANDing it has no effect. Also, since we are treating the stencil buffer as holding integers in this example, bit-wise tests don't make sense. By using these planes, though, we could potentially hold 8 stencils in the buffer at one time and choose which combination of stencils we want to use in each rendering pass.

### Remove the record of which pixels have been drawn

Each frame you don't want to continue adding to the existing stencil buffer values just like you don't want to leave the previously rendered image in the frame buffer. You clear it in the same way you would clear the frame buffer too:

```
glClear(GL_STENCIL_BUFFER_BIT);

```

Or, do both at once:

```
glClear(GL_FRAME_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

```
> 5 votes

---
Tags: opengl
---


# Question
Title: Do I really have to write my own optimized model format?
So I'm a brand new noob to the world of game dev and I'm starting off by trying to write my own game using C++ and openGL. I'm getting into loading models etc and while searching around for "the best format" I'm finding that most of the common formats are intended for porting between modelling applications and not necessarily for final representation of data when loading into a game environment. I'm being told through various sources that ultimately you want to use formats like collada etc and convert them into a custom binary format optimized for your game. Is this absolutely necessary? I understand the idea, that parsing a large XML or some other ASCII format is going to be slower than reading a binary file type but is it really going to be THAT big of a performance hit if I don't? I can't see it, but before I go and fill the assets directory of my game with dae or fbx files I thought I'd ask.

# Answer
> 5 votes
What I believe these people are saying is that you want to load your COLLADA file into your in-game structure. You can then save the contents of this structure into a binary file ready for loading at runtime.

This can have advantages like the ones you said, but also has disadvantages, typically during the development stage.

Whether the load-time performance gain you get is necessary for your game is for you to decide. If you have a few non-complex models, the difference is probably negligable, and it is up to you to decide what to go with.

If for development purposes you prefer to use COLLADA and parse the XML at load time then go with it! I would recommend you make sure that your loading code is abstract enough so that you can easily replace it with binary files if the loading becomes too long.

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


# Question
Title: What language to use to create a browser-MMO?
I have a game ready to be implemented (Class Diagrams and other UML stuff are good).

Here are some characteristics:

* MMO.
* Browser game **and** download-game.
* Multiplatform.
* With 2D graphics.
* Real time.
* Point-and-click.
* With an online database (duh!).

What language should I use?

# Answer
> 7 votes
Runescape is quite a famous online browser based MMORPG, and they provide an open source project to provide the game as a windows client.

The game itself uses JOGL but any 2D framwork should be good for you, Java is maybe older than Silverlight for example, but is user friendly and well documented.

There is a link here for the windows client and source code.

# Answer
> 6 votes
I want to tell a little story, that is both relevant and educational. I'm currently working at a young company making a browser-and-mobile MMO game. We started work about a year and half ago; and the company founder asked would-be programmers the very same question: "What language should we use? Why? What are the alternatives?". We ultimately convinced him to use C# on both server and client (client in Unity3D). Now, a couple' months back, someone asked the same question on some forum we all read: "What should I use for an MMO?". Our founder read it and laughed: "Yeah, *now* I understand - this question is pointless. All languages are more or less equal; your experience is what really matters."

The moral of the story? Use what you know best, and are comfortable working with.

# Answer
> 2 votes
There's no right answer, and it's not clear if you're talking about on the server (online database) or client (real-time, multiplayform.)

So we can address those separately: 1) Client. Unity has been suggested but the question is how multi-platform are you talking about? iPhone? Android? Xbox360 via XNA? The choice of target platform will to a degree determine the choice of languages. I personally feel that the largest overlap of platform is Flash, followed by a C# logic with custom front-end. Flash is directly available for the browser use, the Air API makes it a desktop application as well, and has implementations for all modern platforms except windows phone 7 and the 360.

C# and different front ends also offer an interesting approach. You could write all of the network and game logic classes in C#, and then implement a specific front-end for the differing platforms. Windows phone 7 and PC could be Silverlight, 360 would be XNA, and iPhone/Android could be MonoTouch/MonoDroid respectively. (However, it's still not clear how prime-time ready the mono products are.)

As pointed out above you can also do Java or Unity, but each of those has less of a multiplatform role then Flash or C#.

2) Server. C++ is the traditional route here, but honestly whatever you feel comfortable with. I've been experimenting with Python based servers for the rapid prototyping. But if you have a java client then a java server is worth looking into for code reuse. Likewise C# to C# gives a great reuse factor. One thing I've been dying to try is a C# server with IronPython embedded in it for AI/ability logic.

However as a last bit of advise given how incredibly complex an MMO is, )See Why is it so hard to develop a MMO? ) the answer really should be "Whatever language you and your team know back and front." You'll be having so many other challenges facing you, your language should be the least of your worries.

# Answer
> 1 votes
Unity would probably fit those. You script it in C#, Boo (sort of a Pythonic language with static typing), or Javascript.

---
Tags: 2d, mmo, browser-based-games
---


# Question
Title: Is a SQLite Database Suitable to Store the Building Blocks for Dynamic Content?
I am trying to make my own game for fun, it is basically a 2d side scrolling shooter, with dynamically generated enemies, levels, loot, and some other things. Currently I have dozens of XML files that define pretty much everything when it comes to the content, along with some constraints to keep things sane. Often times certain things like Weapons or Monsters are composed of several randomized sub components, that get picked out of a pool, according to factors such as rarity, the player level, and the game level.

Currently the way I have it setup, is where during initialization the game creates several factory classes (stuff like WeaponFactory and EnemyFactory), these parse the XML and store the XML's data in a more manageable format. Creation is simply done by invoking a create method, and passing the required parameters (i.e. player level, monster level, etc), these parameters are taken into consideration for what should be generated.

Anyways I was wondering if it would be a better idea to use a SQLite database to store all this information? I have looked around, and it seems to be a mixed response. Does anyone have any sort of insight into this? I am using C++ and OpenGL currently.

*EDIT*

I probably should have been more clear, I was more or less asking is it actually a usable way of doing this kind of stuff. My main concerns lie in the fact of choking the Database with requests. Reality is this game will never see the light, and has technically been done as of a few weeks ago, however I decided to go back retool the engine to use Box2D Physics. This is more a learning process, than anything.

# Answer
> 5 votes
Here's what should **weigh** in on your decision:

XML:

* (+) You **already have** the system implemented - no additional **work** required
* (+) Easy to **mod** the game for people with **minimal technical skills**
* (–) Wasteful with space

SQLite:

* (+) Faster (although it may not matter)
* (+) Uses less space (may not matter)
* You could write a modding UI, or even make it **part of the game**
    + (+) If you do, would be a **great feature** but (–) It would require **considerable work**
    + (–) If you don't you **make modding inaccessible** to almost everyone
* (–) You have to **actually write it and make it work**, and comb through it for bugs (although in my experience with SQLite it's not a big pain, and as with everything, if you've worked with it before you'll anticipate the bugs you've made before).

**Final thought:** In my experience with data SQLite makes **devs happy** and **users slightly defeated** if they are curious enough to actually wonder (where is the data stored) think it's inaccessible to them (stored in the cloud, in an encrypted file, etc etc) and go, "meh, whetever". When all is said and done, I've been much happier with SQLite and other DBs for data, and if your data was in some kind of ugly CSV file or something, I would advise you to go to SQLite, not XML. *The main dilemma for you*, is that with XML you're **done** with that part of the game. With SQLite, you need to put in **work**. I'd say leave it until everything else is at least working, so you have a full prototype. Then you can try to sell/spread your game and roll SQLite **in a patch**.

# Answer
> 0 votes
Do you actually have a problem with your existing system? Or are you just asking, "would it be better if..."?

If you have no problem with the current system, keep it. Don't change technologies during a project unless you need to. Given the simple use case you describe, I can't see any reason why an SQL database would work better than your XML.

Note that SQL is optimised for random access to large amounts of data that are left on disk, whereas XML is optimised for being read in to memory and queried in memory. XML is also much easier for you to edit by hand. Given these factors using a relational database is rarely that beneficial for small games that don't store much data, and is better for games that generate a lot of data as they go along.

# Answer
> 0 votes
Unless for some reason the possible content changes at Runtime, choose whatever format you want for content creation (And since you already have XML up and running, stick with that.) then as part of the game build step pack it down to a binary format that your game can understand. This reduces the time and memory footprint needed to handle text processing, while you can still keep the content mergable in your source code control provider. And of course share the code between the tool writing the binary format and the game reading the binary content if at all possible!

---
Tags: c++, databases
---


# Question
Title: Low traffic client synchronization with server in MMO
I am implementing MMO where player flies in space on his starship controlling it with arrow keys and cooperate with other players.

I want to implement it so that player will be able to dodge his ship from rocket or something else, so I am trying to predict whole game state on client side using the same world simulating algorithm as server use. That game world is written on C# and will be called within client directly (it's written on Unity3D) and through CLR on C++ server (under Linux). Connection through UDP.

Problem is how to maintain, for example, 1000 players within single map (exclusing all other game objects, mobs...): Let's say I will:

* synchronize server with clients 50 times per second
* send to each client states of just that game objects (and players) which he is able to see (within some radius)
* have to send 100 objects to each player within his view radius
* must send averagely 50 bytes per game object (it's id, x,y coords, rotation, state...)

so, it will need to have such network bandwidth: 1000 (clients) * 50 (times per second) * 100 (objects to send to each player) * 50 (bytes per object) = 250 000 000 bytes per second! It's impossible!

Is it possible to reduce this value somehow? For example let clients to fully simulate their game worlds (for a long period of time) and send them just inputs of other clients and synchronize game worlds, let's say, each several seconds but it will cause weird desynchronization issues at leash because of float computations.

Anyway, how such games are programmed in common way? Thank you.

# Answer
You only need about 30 updates (or even less maybe 10 or 20) per second. interpolate the positions of moving objectts client sided. In general you should only send data when it's REALLY needed. In WoW you might receive more updates from the players you are in a group with than from the players that are in the same location. Also, if another player is far away from you, you don't receive as many updates per second about him.

Then, only send one complete snapshot to each player when he connects. After that only send the changes of game objects. If no change occured, don't send it.

Then, make heavy use of BitVectors or howevery you might call them to reduce the amount of unneeded data! Example: You can also try to write a float using only one byte(in a range from 0 to 1 or -1 to 1) so you only have 256 or 128 different values. But the player will not notice any jerky movements thanks to the interpolations.

Look at this for an example with LidgrenLibrary on how to compress data: http://code.google.com/p/lidgren-network-gen3/wiki/Optimization

Next: Try to reduce view radius of players as they move, and only transmit important information in that time. Then when they stop increase their view radius again. You can use a spatial hashing system or a bsp tree to reduce the overhead of looking up objects that are "in range". This is a good read for the topic: http://en.wikipedia.org/wiki/Collision\_detection

Also compress the data **YOURSELF** only YOU know about the data structure and the temporal coherence in the data (which can and should be exploited). A general algorithm such as Bzip2, Deflate, whatever, should be used, but only as the final stage of compression!

Also, for non game-critical information, you could also employ additional P2P techniques. Example: A player plays the "hello" animation.(Just a graphical effect) The player sends this information to the server, but the server doesn't relay the information to the other players. Instead this non-critical effect is send by the player itself to the other clients in range.

EDIT (because of the comment):

Additional methods to decrease the average bit count per second to each player:

1. You wrote that you send "Object did not change". There is no reason to do this. If you worry about packet loss (and getting your simulation out of sync because of this) consider the following: At each fixed timestep (ex. 100, 200, 300, 400...) hash the simulation state and send it to the server. the server confirms or sends a complete snapshot of all data back.
2. For things like rockets or even players you can employ not only interpolation but also extrapolation in order to make the simulation more realistic. Example 'Rocket': Instead of updating with messages like "Is now at position x" just send a message once containing the following: "Rocket Spawned: position(vector), Time(at which simulation step the rocket was spawned), velocity(vector)". So you don't even have to include the rotation because the tip will always be in the "velocity" direction.
3. Combine multiple commands in one message and don't ever send messages smaller than 16-20bytes because the udp header will be bigger than the message itself. Also don't send packages bigger than the MTU of your protocol because fragmentation will slow down the speed of the transmission.
> 20 votes

# Answer
Few questions first.

Are the 'rockets or something else' intelligent or dumb? If they're dumb all you need is the timestamp of fire, the origin, and the vector to simulate their path. If they're intelligent how intelligent are they? Can you compute at the time of fire that they're going to hit or miss? If so you can simulate the entire path on the client. ("At T13 the missile will strike the ship because the play lost the dodge roll / the shooter scored a critical hit.")

In general though there's pretty much no reason to: A) have a clock rate of 50Hz, (Most *shooters* get away with 15-20 and MMOs less than that.) B) send full state every frame. (Does the rotation of a missile in space matter at all? Or can you just assume that it's 'front' is orientated along the vector it's traveling?)

Spend time with prediction and interpolation, and you'll see your bandwidth plummet. A project I worked on had an update rate of 10Hz, and an object state representation of I think 14 bytes. (Compress everything you can! I believe we used 6 bits to define the rotation around the x plane and then another 6 bits for a tilt above/below that plane, it looked indistinguishable from sending an actual rotational matrix / quaternion.)

Another thing you can do is prioritize objects. Show, maybe there's 100 objects in the relevant set, but do you know his view frustum on the server? If something isn't in his view can you drop it's update frequency by an order of magnitude?

The general idea isn't to make a perfect simulation on the client, that's impossible, the idea is to make a fun game where the players won't notice that it's not a perfect simulation.
> 5 votes

# Answer
Here are two approaches:

First:
Switch to deterministic physics, send player commands, ai actions, objects coming into view and whatever can't be determined client-side to clients. This must include non-commands, a confirmation that up to a certain point in time nothing but the commands that has been sent and received apply.

The client must run two or three simultaneous simulations.
1: Halts whenever missing data for the next step.
2: Continue using guess data and provide the state used for rendering. 3: Whenever no 1 comes to a halt this simulation copies the state of no 1, catch up to the current time and take over for no 2, which is then dropped.

If the catch up is fast enough you can leave out differing between no 2 and no 3 and just drop the old data immediately.

Second:
Don't use deterministic physics, do the same as above, but send "full frames" once every few seconds. You can easily completely leave out transferring temporary stuff like bullets.

In both cases you might want to be wary about the client predicting anyone dying, it's kinda silly seeing an opponent unexplode.

And +1 for doing the maths, too many people fail to make simple resource use estimates.
> 5 votes

---
Tags: mmo, client-server, synchronization
---


title: android game saving game state

text:
# Question
Title: android game saving game state
I'm developing a game and i've ran into some questions about saving and resuming the game. Let's say i have 10 animated sprites drawn every frame (which move side to side) and everytime i press the home button or back button and then go back to my game, it starts drawing the sprites at the starting position rather than in the position before the back/home press.

* Do i have to save every sprite and animation position in order to achive resuming the game where i left off (using Bundle, onSaveInstanceState and onRestoreInstanceState())? Or can this be achived some other simpler way.

I'm using the lunarlander example which handles the drawing in a thread and when the user presses the home/back button(onPause) the state is saved and then reloaded on resume.But if i move all the drawing methods to SurfaceView (LunarView) and just call them from a thread(LunarView.draw()), the sprites stay in the exact same position as before the back/home button pressed without saving anything. Can someone explain why this happens? Is it something i should avoid(calling SurfaceView.draw() from a thread) or is this the anwser to my question how to save game state?

Thanks for the reply's.

Regards, J.

# Answer
If I have to guess I think you are calling initialize function every time you try resuming the game. You just have to avoid calling it when the game is resumed. Remember there is a diffrence between launching game and resuming it, and initilize is only used for launching game.
> 1 votes

---
Tags: 2d, android
---


# Question
Title: 3D Ball Physics Theory: collision response on ground and against walls?
I'm really struggling to get a strong grasp on how I should be handling collision response in a game engine I'm building around a 3D ball physics concept. Think Monkey Ball as an example of the type of gameplay.

I am currently using sphere-to-sphere broad phase, then AABB to OBB testing (the final test I am using right now is one that checks if one of the 8 OBB points crosses the planes of the object it is testing against). This seems to work pretty well, and I am getting back:

Plane that object is colliding against (with a point on the plane, the plane's normal, and the exact point of intersection.

I've tried what feels like dozens of different high-level strategies for handling these collisions, without any real success. I think my biggest problem is understanding how to handle collisions against walls in the x-y axes (left/right, front/back), which I want to have elasticity, and the ground (z-axis) where I want an elastic reaction if the ball drops down, but then for it to eventually normalize and be kept "on the ground" (not go into the ground, but also not continue bouncing). Without kluging something together, I'm positive there is a good way to handle this, my theories just aren't getting me all the way there.

For physics modeling and movement, I am trying to use a Euler based setup with each object maintaining a position (and destination position prior to collision detection), a velocity (which is added onto the position to determine the destination position), and an acceleration (which I use to store any player input being put on the ball, as well as gravity in the z coord).

Starting from when I detect a collision, what is a good way to approach the response to get the expected behavior in all cases?

Thanks in advance to anyone taking the time to assist... I am grateful for any pointers, and happy to post any additional info or code if it is useful.

**UPDATE**

Based on Steve H's and eBusiness' responses below, I have adapted my collision response to what makes a lot more sense now. It was close to right before, but I didn't have all the right pieces together at the right time! I have one problem left to solve, and that is what is causing the floor collision to hit every frame. Here's the collision response code I have now for the ball, then I'll describe the last bit I'm still struggling to understand.

```
// if we are moving in the direction of the plane (against the normal)...
if (m_velocity.dot(intersection.plane.normal) <= 0.0f)
{
    float dampeningForce = 1.8f; // eventually create this value based on mass and acceleration

    // Calculate the projection velocity
    PVRTVec3 actingVelocity = m_velocity.project(intersection.plane.normal);

    m_velocity -= actingVelocity * dampeningForce;
}
// Clamp z-velocity to zero if we are within a certain threshold
// -- NOTE: this was an experimental idea I had to solve the "jitter" bug I'll describe below
float diff = 0.2f - abs(m_velocity.z);
if (diff > 0.0f && diff <=  0.2f)
{
    m_velocity.z = 0.0f;
}

// Take this object to its new destination position based on...
// -- our pre-collision position + vector to the collision point + our new velocity after collision * time
// -- remaining after the collision to finish the movement
m_destPosition = m_position + intersection.diff + (m_velocity * intersection.tRemaining * GAMESTATE->dt);

```

The above snippet is run after a collision is detected on the ball (collider) with a collidee (floor in this case). With a dampening force of 1.8f, the ball's reflected "upward" velocity will eventually be overcome by gravity, so the ball will essentially be stuck on the floor. THIS is the problem I have now... the collision code is running every frame (since the ball's z-velocity is constantly pushing it a collision with the floor below it). The ball is not technically stuck, I can move it around still, but the movement is really goofy because the velocity and position keep getting affected adversely by the above snippet.

I was experimenting with an idea to clamp the z-velocity to zero if it was "close to zero", but this didn't do what I think... probably because the very next frame the ball gets a new gravity acceleration applied to its velocity regardless (which I think is good, right?).

Collisions with walls are as they used to be and work very well. It's just this last bit of "stickiness" to deal with. The camera is constantly jittering up and down by extremely small fractions too when the ball is "at rest".

I'll keep playing with it... I like puzzles like this, especially when I think I'm close. Any final ideas on what I could be doing wrong here?

**UPDATE 2**

Good news - I discovered I should be subtracting the intersection.diff from the m\_position (position prior to collision). The intersection.diff is my calculation of the difference in the vector of position to destPosition *from the intersection point to the position*. In this case, adding it was causing my ball to always go "up" just a little bit, causing the jitter. By subtracting it, and moving that clamper for the velocity.z when close to zero to being above the dot product (and changing the test from \<= 0 to \< 0), I now have the following:

```
// Clamp z-velocity to zero if we are within a certain threshold
float diff = 0.2f - abs(m_velocity.z);
if (diff > 0.0f && diff <=  0.2f)
{
    m_velocity.z = 0.0f;
}

// if we are moving in the direction of the plane (against the normal)...
float dotprod = m_velocity.dot(intersection.plane.normal);
if (dotprod < 0.0f)
{
    float dampeningForce = 1.8f; // eventually create this value based on mass and acceleration?

    // Calculate the projection velocity
    PVRTVec3 actingVelocity = m_velocity.project(intersection.plane.normal);

    m_velocity -= actingVelocity * dampeningForce;
}

// Take this object to its new destination position based on...
// -- our pre-collision position + vector to the collision point + our new velocity after collision * time
// -- remaining after the collision to finish the movement
m_destPosition = m_position - intersection.diff + (m_velocity * intersection.tRemaining * GAMESTATE->dt);
UpdateWorldMatrix(m_destWorldMatrix, m_destOBB, m_destPosition, false);

```

This is MUCH better. No jitter, and the ball now "rests" at the floor, while still bouncing off the floor and walls. The ONLY thing left is that the ball is now virtually "stuck". He can move but at a much slower rate, likely because the else of my dot product test is only letting the ball move at a rate multiplied against the tRemaining... I think this is a better solution than I had previously, but still somehow not the right idea. BTW, I'm trying to journal my progress through this problem for anyone else with a similar situation - hopefully it will serve as some help, as many similar posts have for me over the years.

# Answer
> I think my biggest problem is understanding how to handle collisions against walls in the x-y axes (left/right, front/back), which I want to have elasticity, and the ground (z-axis) where I want an elastic reaction if the ball drops down...

I think you should handle the walls exactly the same as the ground. Create a method that takes as parameters the surface normal & the ball's velocity and returns a reflected velocity vector. If you need a short snippet for that, we can show that to. The elastic factor of a ball is the same whether it bounces from the wall or floor. I think you may be needing to factor in gravity so your ball's motion appears more natural.

In a game where you are roughly trying to approximate real life physics, you will most likely have a gravity vector which influences (add to) the ball's velocity vector each frame. The effect of the gravity will appear to influence the ball differently if the ball is bouncing from the floor vs. the walls because the gravity is aligned with the floor and has the most pronounce effect on ball speed changes (magnitude of the velocity vector), so there is where the difference you are expecting may come from.

> Starting from when I detect a collision, what is a good way to approach the response to get the expected behavior in all cases?

1. Determine the ball's position at point of contact. Determine what percentage of the frame's time slice The ball will travel in the reflected direction.
2. Run the surface normal & the ball's velocity vector through the reflection method above. It will return the ball's new velocity vector.
3. Transform the point representing the ball's position at the time of contact by the new velocity vector multiplied by the remainder of the frame's time slice. Factor in the gravity influence on this point.
> 1 votes

# Answer
Sphere colliding against unmovable plane in frictionless physics:

Project the spheres velocity on the planes normal, multiply the projection by 2 and subtract it from the spheres velocity. Done.

Before doing the collision you should check if the sphere is moving towards the plane, if not the collision should not be done, or you risk problems with wall-hugging.

If you want a dampening collision you may multiply by less than 2.

I'm not sure if I answered everything in your question, or if this is advanced enough for you, but I hope you can use it.
> 2 votes

---
Tags: collision-detection, physics
---


# Question
Title: Triangle accuracy picking for animated models in XNA
I can do picking with triangle-accuracy for non-animated models, but I also have *animated* models in my game. How do I do picking on animated models?

I use code based on this project for animation.

My first idea for doing it is:

```
Calculate ray
For each model
    If model bounding sphere collides with ray
         For each meshPart
              Make animation transformation
              Calculate transformed triangles in meshPart
         Test collisions of ray with resulting triangles

```

Have you ever considered how to make something like this?

# Answer
Pardon the brevity as I'm posting from my phone.

1. Unproject to get your ray.
2. Transform the ray by the transpose of your view matrix to get its position in world space.

Now, either: A. For each model, transform the world ray by the transpose of the model's world matrix and test the meshes for intersections, or B. Test the ray against the transformed model mesh.

A is easier, but involves more matrix operations.

The idea is to get the ray and mesh into the same coordinate system before testing.
> 2 votes

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