# Question
Title: What framework provides mouse-interactive components as game sprites?
Background:

I wish to make a really flashy chess game. The squares on the board will be unique terrain. The pieces will be colourful images. The pieces will be animated. The pieces will sometimes be overlaid with each other at times. It will have sound, allow saving, and need keyboard input sometimes.

The basic question (tl;dr):

I am looking for a free framework that will allow me to use interactive GUI components as sprites, that would make such a game easy to develop.

Things I want:

* I need to be able to overlay partially transparent/translucent images on some sort of game canvas.
* The images, or an invisible component holding them, should receive mouse events like clicks, click-and-drag, and mouse-over. Pre-defined checking methods/functions are ok too.
* The framework should allow animation of the images.
* The framework must *not exclude* easy support for music, sound effects, keyboard or file IO. I am happy to use compatible libraries or frameworks top do these things separately, but there's no point saving effort on mouse interaction only to find it has made everything else too difficult.
* The framework and all its dependencies must be free. I want to be able to distribute my game, free or for profit, without ever having to pay money for the tools or frameworks used in development. (Even if you think this is unfair or unrealistic, you won't change my mind.)
* Documentation must be available.
* Cross-platform i.e. should look and behave the same on linux or windows without major tweaking.

Things I **don't** care about:

* Whether what you suggest is technically a framework, a library, an engine, or even a tutorial on how to easily do it.
* I don't need bleeding-edge performance like you need for a fast-paced shooter.
* The precise language or paradigm used.
* Your (correct) belief that flashy graphics won't improve the chess experience. :-)
* Anything relating to chess AI, marketing, or other important but out-of-scope considerations.

I appreciate any suggestions.

# Answer
The things you require, except for sound, are really the bare essentials of any GUI library, so any cross-platform GUI library and an added sound library will do. If you want to go more game-oriented and would like to have the opportunity to add some fancier graphics the first game framework that comes to mind is Unity. But really your requirements are so low/standard that you can use anything that you're comfortable with as long as it is free and cross platform.
> 2 votes

# Answer
Have you looked at Panda3d http://panda3d.org (BSD 2-Clause license http://www.opensource.org/licenses/bsd-license.php ), it's a game/graphics engine, but it can be programmed with Python or C++ (API documentation exists in both languages), has advanced graphics (shader support augmented through Cg), has build in debug tools, state management, mouse support, AI, simple path finding, physics (you could use either ODE or Bullet if needed),and collision detection. With respect to sound FMod or OpenAL can be used. It's been used in commercial applications and hobbyist projects.

Also because it's written in Python/C++ you can create and import content from Blender(open source and free) as \*.obj files(pertaining to 3D models).

The direct link to the manual is:

http://www.panda3d.org/manual/index.php/Main\_Page
> 1 votes

---
Tags: graphics, mouse
---


# Question
Title: XNA 2D - How can I draw a sprite over another?
I'm working on a simple 2D game that is similar to the classic Invader arcade. What I want to know is:

How can I draw a new sprite over the player sprite upon colliding with an enemy/a bullet? Better yet, how can I hide the player so that the hit animation can be shown?

I got the collision detection up and running except for the hit animation. It's being drawn behind the player current position which is awkward.

# Answer
Please investigate the parameters of the spriteBatch.Draw-method. Try not to feel intimidated by the sheer number of parameters of the largest one. The last parameter there is the "layerDepth" which should be a floating point value between 0 and 1. This parameter will be used (only) if you begin your drawing with SpriteSortMode.BackToFront or FrontToBack. If you make use of the layerDepth you don't have to worry to make the Draw()-calls in any particular order.
> 5 votes

---
Tags: xna-4.0
---


title: Moving in an arc using Vector3

text:
# Question
Title: Moving in an arc using Vector3
I'm trying to get this object to move right across the screen until it gets close to the center and arc down smoothly into a straight downward movement. Here's what I've tried:

```
if (position.X < -5000)
   Velocity = Vector3.Right * speed;
else if (position.X < -1000)
{
   Velocity = new Vector3(
   MathHelper.Lerp(Velocity.X, 0, (float)gameTime.ElapsedGameTime.TotalSeconds),
   MathHelper.Lerp(Velocity.Y, -1, (float)gameTime.ElapsedGameTime.TotalSeconds), 0)
   * speed;
}
else
   Velocity = Vector3.Down * speed;

```

However, when it gets to where it should be arcing, it just moves to the right at blinding speed and vanishes before it hits the point where it should be going straight down. If I remove the else if, it does a sharp direction shift no problem. What am I doing wrong in that section?

# Answer
> 2 votes
Your problem is `(float)gameTime.ElapsedGameTime.TotalSeconds`. Those Lerp functions you're using want a value that varies from 0 to 1, while TotalSeconds is going to keep increasing forever.

Maybe instead pass in the amount of time that has passed since the object started turning, and stop lerping after a time of 1?

---
Tags: xna, vector
---


# Question
Title: Loading and using GLEED2D levels into WP7 Game
I've been trying to use this modified version of GLEED2D that includes WP7 support,

The progress so far, is I've been able to load the level XML file to the project and read it successfully thanks to This answer

I got in touch with the author of the modified version, he added the answer to the wiki

The problem now is I cannot implement the following steps, according to the wiki, I now need to:

> "enumerate the levels and then enumerate each item in each level. For each item, add the object/sprite into XNA."

My `initialize()` method now looks like this

```
    protected override void Initialize()
    {

        Stream stream = TitleContainer.OpenStream("Content/leveltest.xml");
        //Stream stream = TitleContainer.OpenStream("Content/level.gleed");
        XElement xml = XElement.Load(stream);
        level = LevelLoader.Load(xml);

        base.Initialize();
    }

```

When I debug I find the level object loaded successfully and has list of layers and list of items inside the layers, but I'm not sure how to continue my way from here to Display the level items on the screen.

Any idea?

--UPDATE--

I added

```
foreach (Layer layer in level.Layers)
{
   foreach (LayerItem item in layer.Items)
   {
      item.Properties.Visible = true;
      //something should be added here to draw
   }
}

```

I am not sure what to add now to draw the item into it's position on screen !?

# Answer
The wiki you linked says the following:

> It is here you can see which variation of ItemProperties you have and then *build your own in-game object*.

And I agree with it. Instead of drawing directly from the Gleed2D classes I think you should be using them as a bridge between the level editor and **your classes**. This gives you more flexibility in deciding exactly what to do with the data from your level. And that's really not hard to do, so I'll give you *an example* that I just wrote from memory (i.e. it's untested). But that's all it is - an example - and you should be writing something *specific to your game*.

**Usage Example**

I'll start at the end and show the interface I aimed for. This is *the only thing* you will need to do on your game for loading and rendering the level after you implement this:

```
MyLevel myLevel; // NEW

// On LoadContent
using(Stream stream = TitleContainer.OpenStream("Content/leveltest.xml"))
{
    XElement xml = XElement.Load(stream);
    Level level = LevelLoader.Load(xml);
    myLevel = MyLevel.FromGleed2D(level, Content); // NEW
}

// On Draw
spriteBatch.Begin();
myLevel.Draw(spriteBatch); // NEW
spriteBatch.End();

```

As you can see, I created a class called `MyLevel` which took care of both loading and rendering of the scene, through the `FromGleed2D` and `Draw` methods respectively. But before going into the implementation of the `MyLevel` class, I'll show another class that is required.

**The Sprite Class**

The first step I did was create a `Sprite` class which stores the texture and all properties that were relevant (in this case I settled for only the sprite's transformation, but you could store other properties too) and which knows how to `Draw` itself using a SpriteBatch. Very straightforward implementation:

```
public class Sprite
{
    public TextureSprite(Texture2D texture)
    {
        Texture = texture;
        Origin = new Vector2(Texture.Width/2f, Texture.Height/2f);
    }

    public Vector2 Position { get; set; }
    public float Rotation { get; set; }
    public Vector2 Scale { get; set; }
    public Vector2 Origin { get; set; }
    public Texture2D Texture { get; set; }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(Texture, Position, null, Color.White, Rotation, Origin, Scale, SpriteEffects.None, 0f);
    }
}

```

**The MyLevel Class**

Here's the class that loads, stores and draws the level. For now, I omitted the implementation of the `FromGleed2D` method purposely, but I'll show it later. For now notice that the `MyLevel` class is basically a wrapper around an array of lists of sprites. Each position in this array is one layer from the level, and the constructor takes how many layers exist in the level. There's a method that lets you add new sprites to a specific layer, and the `Draw` method simply iterates over the sprites in each layer drawing them in order.

```
public class MyLevel
{
    public MyLevel(int count)
    {
        // Create layers array
        _layers = new List<Sprite>[count];

        // Initialize each position in the array
        for(int i=0; i!=count; ++i)
            _layers[i] = new List<Sprite>();
    }

    public static MyLevel FromGleed2D(Gleed2D.InGame.Level level, ContentManager content)
    {
        // Implementation omitted - See below
    }

    public void AddSpriteAt(Sprite sprite, int layer)
    {
        _layers[layer].Add(sprite);
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        foreach(var layer in _layers)
            foreach(var sprite in layer)
                sprite.Draw(spriteBatch);
    }

    private readonly List<Sprite>[] _layers;
}

```

And finally the most important method, `FromGleed2D` which takes care of converting all the relevant data from the Gleed2D level object into our own. First it discovers how many layers there are in the level, and creates the `MyLevel` object. Then it simpy iterates over all `TextureItem`s in the level, creates a `Sprite` from them, and adds the sprite to our level. I've commented the code for clarity:

```
public static MyLevel FromGleed2D(Gleed2D.InGame.Level level, ContentManager content)
{
    // Get layer count and create our level
    int count = level.Layers.Count();
    MyLevel myLevel = new MyLevel(count);

     // Iterate over each layer and item in the Gleed2D level
    int i = 0;
    foreach(var layer in level.Layers)
    {
        foreach(var item in layer.Items)
        {
            // Verify if Item is a TextureItem
            TextureItemProperties properties = item.Properties as TextureItemProperties;
            if(properties != null)
            {
                // Create sprite from TextureItem
                Texture2D texture = content.Load<Texture2D>(properties.TexturePathRelativeToContentRoot);
                Sprite sprite = new Sprite(texture);
                sprite.Position = properties.Position;
                sprite.Rotation = properties.Rotation;
                sprite.Scale = properties.Scale;

                // Add sprite to level at current layer
                myLevel.AddSpriteAt(sprite, i);
            }
        }
        ++i;
    }

    // Finally return the level we created
    return myLevel;
}

```
> 2 votes

# Answer
in the `Draw()` method add the following:

```
spriteBatch.Begin();
foreach (Layer layer in level.Layers)
{
    foreach (LayerItem item in layer.Items)
    {
        TextureItemProperties textureprop = new TextureItemProperties();
        textureprop =(TextureItemProperties) item.Properties;
        string path=textureprop.TexturePathRelativeToContentRoot;
        spriteBatch.Draw(Content.Load<Texture2D>(path), textureprop.Position, Color.White);
    }

}
spriteBatch.End();

```

This will draw the the textures in the places specified, it's a bit amateur but it gets the job done.

---

*Suggestions from David Gouveia (I'm not sure what's the protocol for suggesting a correction when there's so much text that it would be cumbersome to do so in the comments, so I'll add this instead)*

There's a problem with your code. It is possible that not all `ItemProperties` are `TextureItemProperties`, in which case you'd get an `InvalidCastException`. I suggest the following amendment which uses the `as operator` to downcast safely.

Also, you were instantiating a `new TextureItemProperties()` and then assigning on top of it right away. There's no reason to do that so I removed it.

```
spriteBatch.Begin();
foreach (Layer layer in level.Layers)
{
    foreach (LayerItem item in layer.Items)
    {
        TextureItemProperties textureprop = item.Properties as TextureItemProperties;
        if(textureprop != null)
        {
            string path = textureprop.TexturePathRelativeToContentRoot;
            spriteBatch.Draw(Content.Load<Texture2D>(path), textureprop.Position, Color.White);
        }
    }

}
spriteBatch.End();

```
> 1 votes

# Answer
Gleed 2D, by design, makes no attempt to create anything drawable. It's primary purpose is to let the user visually design levels and then work with strongly typed objects to load the level in their game.

So, when you load the level in your game, you end up with a `Level`. A `Level` has `Layer`s, and `Layer`s have objects that derive from `ItemProperties`. So ultimately, you'll want to check what derived type of `ItemProperties` you get when enumerating, and then build your in-game objects from that. Here's an example from a game:

```
public static class GleedConverter
{
  public static void ConvertGleedObjects(LevelScreen levelScreen, Level level)
  {
    var pathConverter = new ConvertToGameObject<PathItemProperties>(
    s => s.GetType(  )==typeof(PathItemProperties) && s.Name.StartsWith( @"path", StringComparison.OrdinalIgnoreCase ),
    ti =>
        {
            return new PathObject(
                levelScreen,
                ti.WorldPoints.ToArray(  ),
                Convert.ToInt32( ti.CustomProperties[ @"speed" ].Value, CultureInfo.InvariantCulture ),
                ti.CustomProperties[ @"followed_by" ].Value as string ) ;
        } ) ;

    var spikeConverter = new ConvertToGameObject<TextureItemProperties>(
    s => s.GetType(  )==typeof(TextureItemProperties) && s.Name.StartsWith( @"Spike",StringComparison.OrdinalIgnoreCase ),
    ti =>
        {
            var spike = new SpikeObject( levelScreen, levelScreen.ScreenManager.Textures[ ti.AssetName ] ) ;

            ti.CopyPropertiseTo( spike, true ) ;

            return spike ;
        } ) ;

   var boundaryConverter = new ConvertToGameObject<TextureItemProperties>(
      s => s.GetType(  )==typeof(TextureItemProperties) && s.Name.StartsWith( @"BoundaryBlock",StringComparison.OrdinalIgnoreCase ),
    ti =>
        {
            var bondaryBlock = new BoundaryBlock( levelScreen,levelScreen.ScreenManager.Textures[ ti.AssetName ] ) ;

            ti.CopyPropertiseTo( bondaryBlock, true ) ;

            return bondaryBlock ;
        } ) ;

    var enemyConverter = new ConvertToGameObject<TextureItemProperties>(
        s => s.GetType(  )==typeof(TextureItemProperties) && s.Name.StartsWith( @"enemy",StringComparison.OrdinalIgnoreCase ), ti =>
                        {
                            var enemyType = (string)ti.CustomProperties[@"type"].Value ;

                            if (enemyType == @"WindMan")
                            {
                                WindMan windMan = WindMan.FromGleed( ti, levelScreen, levelScreen.ScreenManager.Textures[ @"WindMan60x135" ] ) ;

                                return windMan ;
                            }

                            throw new InvalidOperationException(@"Enemy type '{0}' unknown".FormatWith( enemyType ));

                        }) ;

                   [other converters omitted for brevity]

        level.ConvertToGameObjects(
            levelScreen.ScreenLayers,
            new IConvertToGameObject[ ]
                {
                    spikeConverter,
                    boundryConverter,
                    enemyConverter,
                                            [other converters omitted for brevity]
                } ) ;

```

*`LevelScreen`, as passed in the parameters, is a container that contains **my drawable in-game objects**.*

This method creates several objects that **convert different `ItemProperties` into proper *in-game* objects**. In my game, my some of the in-game objects are spikes, enemies, boundary blocks and paths. Note that the converters don't, **at this point**, create the in-game object, they're just converters that are ready to convert to in-game objects. Also note that they're entirely lamda based. If you have more complex converters, you can implement `IConvertToGameObject` yourself, which is simply this:

```
public interface IConvertToGameObject
{
    bool InterestedIn( ItemProperties gleedItem ) ;
    GameObjectBase Convert(  ItemProperties gleedItem ) ;
}

```

At the end of the `ConvertGleedObjects` method above, it makes a call to `ConvertToGameObjects`. This is an extension method that looks like this:

```
public static class GleedExtensions
{
    public static void ConvertToGameObjects(
        this Level level,
        ScreenLayerCollection screenLayers,
        IEnumerable<IConvertToGameObject> converters)
    {
        level.Layers.ForEach( l => screenLayers.AddLayer( l.Properties.Name, l.Properties.ScrollSpeed )  ) ;

        var pairs = from layer in level.Layers where layer.Properties.Visible
                    from item in layer.Items
                    select new
                            {
                                LayerName=layer.Properties.Name,
                                Converter = converters.Single( c => c.InterestedIn( item.Properties ) ),
                                Item = item
                            } ;
        pairs.ForEach(
            p =>
                {
                    GameObjectBase gameObject = p.Converter.Convert( p.Item.Properties ) ;
                    screenLayers.Add( p.LayerName, gameObject ) ;
                } )  ;
    }
}

```

This takes a `Level` (the `Level` you get from Gleed2D). It also takes a `ScreenLayerCollection` (which is a collection of my layers where each layer contains **drawable items**), and a list of `IConvertToGameObject` objects. It then does this:

* Adds layers to the `screenLayers` that were passed
* Creates `pairs`; each pair consists of the visible `Layer` and a list of objects that describe: the layer name, a converter that converts the item (the item from Gleed), and the item itself
* Then for each pair, the converter is called which returns a `GameObjectBase` (each game object in my game derives from this). The new object is then added to the correct layer.

This looks like a lot of work, but when you have dozens/hundreds/thousands of different in-game objects, it's nice to have this separation between the gleed level, the thing that converts the gleed item to your in-game item, and the behaviour of your in-game item.

So, in summary, the flow I use is:

* Load the Gleed level
* Declare the things that convert the Gleed items into in-game items
* Enumerate the Gleed items and ask the converters to convert to in-game items
* Add the in-game items to whatever mechanism is used to store and handle in-game items.
> 0 votes

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


# Question
Title: Orbiting a specific point - Orbiting Camera
How would I create a camera that with the mouse, it allows you to orbit around a specifc position, with the camera always facing that point? I would also like it to be able to always be at a constant distance from the point, and be able to orbit around it in every direction.

Any ideas?

# Answer
> 4 votes
What you're looking for is an ArcBall Camera. I've got a full snippet over here https://roy-t.nl/2010/02/21/xna-simple-arcballcamera but just to explain the general idea:

You set a look-at point in space which you want to orbit. Then you create a vector from that point by rotate around it using the Pitch Yaw and Roll. You then lengthen the vector to your desired distance from the object.

Anyway the most interesting stuff happens in this method:

```
private void ReCreateViewMatrix()
        {
            //Calculate the relative position of the camera
            position = Vector3.Transform(Vector3.Backward, Matrix.CreateFromYawPitchRoll(yaw, pitch, 0));
            //Convert the relative position to the absolute position
            position *= zoom;
            position += lookAt;

            //Calculate a new viewmatrix
            viewMatrix = Matrix.CreateLookAt(position, lookAt, Vector3.Up);
            viewMatrixDirty = false;
        }

```

---
Tags: xna, c#, camera, orbit
---


# Question
Title: Check one side of a rectangle for collision detection?
How can I check to see if only one side of a rectangle is colliding with another?

# Answer
by checking 2 rectangles relative speed, you can tell which sides are colliding. for example if one is going up and the other one is going down, it's obvious that only top edge of the first rectangle can collide with the second rectangle. after that check it's a normal AABB collision detection. you can also check for edges going to collide by checking rectangle position. consider two rectangles, the first one can only collide with top edge of second one only if it's y position is height than others.
> 2 votes

---
Tags: c++, sfml
---


title: Registering collision on particles

text:
# Question
Title: Registering collision on particles
I am using CCParticleSystemQuad to create particle effects. But I want my sprites to be able to collide with particles. Say your character is a dragon, the dragon breath is a particle effect emitting fire. When the breath hits objects (sprites), I should be able to know it collided with some sprites. What are the options to achieve this?

# Answer
> 4 votes
Pixel perfect collision with particles would be very CPU intensive, this would be even worse on a mobile device. You may want to cheat and use a bounding shape to surround the area the particles occupy, and use that bounding shape for collision purposes. This doesn't have to be exact. It's an approximation of the area the particles occupy. I imagine if you actually implemented this and tested it you'd find that it was sufficient for your needs.

# Answer
> 3 votes
The exact answer would be a somewhat Point-In-Polygon algorithm but as mentioned above it will be very (very) time-consuming in real-time and would be more used for simulation purpose.

Most of the time in real-time you can approximate this by using either :

It basically all depends of the average behavior of the shape made by all your particles.

---
Tags: collision-detection, cocos2d-iphone, particles
---


title: 2D Object 'Targeting' / 'Selecting'

text:
# Question
Title: 2D Object 'Targeting' / 'Selecting'
I'm currently working with C# with the XNA framework.

I'm trying to create a list of objects that are individually target-able after they are created and set in a list and displayed on a tile map.

For example, I have a blank tile map and I cycle through the tiles and randomly set objects (we'll say a box) throughout the map. When I set the box object, I add that new iteration of Box to a Box List.

At this point I have a tile map with a series of randomly placed boxes. Within these boxes I also have randomly picked values for their name, size, color etc. And these values are correctly stored within the box object in its respective index in the List.

My question is how do I go about setting up a method for targeting/selecting a box so that when I click on any given box it's respective data values appear? I'm not worried about graphical representation of the selected object but the retrieval of the objects specific data via a mouse click on its position.

I've set up Events to handle the changing of my game states, does this require the same methodology or something all together different?

Thanks for your time.

# Answer
If the boxes have an arbitrary size (meaning that they are not the same size as your tiles) use this method:

```
// Loop through your list of boxes and check to see if the mouse click coordinates is inside the box.

MouseState ms = Mouse.GetState();
Box selectedBox = null;
foreach(Box b in boxList)
{
  if(b.Bounds.Contains(ms.X, ms.Y)
  {
    //box found
    selectedBox = b;
    break;
  }
}

// display information about the 'selectedBox' if it is not equal to null.

```
> 3 votes

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


# Question
Title: Problem playing music and sound effects in Cocos2d-x
I'm new to Cocos2d-x and working on a mac. I'm trying to play music in my demo project but I'm unable to include "SimpleAudioEngine.h" in the default HelloWorld Project. I tried adding CocosDenshion to my project but I got more errors. Anyone who knows how to fix this please help.

# Answer
You need to add CocosDenshion, which is the audio library. Be sure the link is done correctly or copypaste it into your folder and use \<\> import just in case

```
#include <SimpleAudioEngine.h>

```

Once you have it correctly linked the functions used are quite trivial:

```
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("stuff.wav");

```

Be sure to be using the supported formats in each platform
> 3 votes

---
Tags: c++, cocos2d-x
---


# Question
Title: Techniques for benchmarking code running on the Sega Genesis' 68000 CPU?
I'm playing around with writing code for the Sega Genesis, which uses a Motorola 68000. I'm not an assembly code guru by any means so I'm writing in C and using SGDK. As it's slower than assembly, I'd like to be able to benchmark so that I can find slow spots and optimize them as much as I can. But I'm at a loss of how to do that. It doesn't look like the CPU has any timers or ticks that I can use. Any ideas?

One idea I've got is to find the code I want to benchmark and set it to run 1000 or 10,000 times, and have something visible happen when it's done. Because it's looping many, many times, the amount of time it takes is measurable with a stopwatch. Not the most friendly way, but it might be possible to use in some cases.

# Answer
Look at the timer.h include, it has some of the basic timing functions. For reference http://code.google.com/p/sgdk/source/browse/trunk/include/timer.h?r=40

For example this function:

```
// return elapsed ticks from console reset (1/300 second based)
u32  getTick();

```

So, if you wanted to test a piece of code you would do this:

```
u32 start = getTick();
// place code here
u32 dif = getTick() - start;
// 'dif' would be the number ticks that passed.

```
> 4 votes

---
Tags: c
---


title: Render TIny.x bones in Direcx 9

text:
# Question
Title: Render TIny.x bones in Direcx 9
I would like to render the bones of the Tiny.x animated mesh. I know there are 35 bones, and I know their names, but I'm having trouble with each bone's matrix. Do I need to convert the matrix with d3dxvec3transformcoord function, or can I use the .m41,.m42,.m43 on the vertex buffer ?

# Answer
> 1 votes
Each bone transform needs to be combined with it's parent all the way up the hierarchy chain. So a toe bone has to be multiplied to the foot bone which was previously multiplied to the leg bone which was previously multiplied to the hip bone.... etc all the way back to the root bone. Once all that is done, then m41, m42, m43 of the result will represent the position of the toe. The order that you combine bones is opposite for openGL and DirectX.

To render a bone (instead of, say, a toe), it needs geometry in the form of vertices. Typically that geometry is created in a 3d modeling app as a visual aid to see the bone but is not transfered over to the .x file. You would have to create your own.

---
Tags: directx
---


title: Accelerometer to control handstans man?

text:
# Question
Title: Accelerometer to control handstans man?
In my game i have to control handstand man using accelerometer. i used this code:

```
function acc:accelerometer(e)
        if(e.yGravity > 0.1 and e.yGravity < 0.2)then
    boy:applyLinearImpulse(0.1, .5, boy.x, boy.y)

    elseif(e.yGravity > 0.2 and e.yGravity < 0.3)then
    boy:applyLinearImpulse(0.2, .5, boy.x, boy.y)

    elseif(e.yGravity > 0.3 and e.yGravity < 0.4)then
    boy:applyLinearImpulse(0.3, .5, boy.x, boy.y)

    elseif(e.yGravity > 0.4 and e.yGravity < 0.5)then
    boy:applyLinearImpulse(0.4, .5, boy.x, boy.y)

    elseif(e.yGravity > 0.5 and e.yGravity < 0.9)then
    boy:applyLinearImpulse(0.5, .5, boy.x, boy.y)

    elseif(e.yGravity > -0.1 and e.yGravity < 0.1)then
    boy:applyLinearImpulse(-0.1, .5, boy.x, boy.y)

    elseif(e.yGravity > -0.2 and e.yGravity < -0.1)then
    boy:applyLinearImpulse(-0.2, .5, boy.x, boy.y)

    elseif(e.yGravity > -0.3 and e.yGravity < -0.2)then
    boy:applyLinearImpulse(-0.3, .5, boy.x, boy.y)

    elseif(e.yGravity > -0.4 and e.yGravity < -0.3)then
    boy:applyLinearImpulse(-0.4, .5, boy.x, boy.y)

    elseif(e.yGravity > -0.5 and e.yGravity < -0.4)then
    boy:applyLinearImpulse(-0.5, .5, boy.x, boy.y)

    elseif(e.yGravity > -0.9 and e.yGravity < -0.5)then
    boy:applyLinearImpulse(-0.6, .5, boy.x, boy.y)
end

```

please help me how to code.

# Answer
Try this:

```
function acc:accelerometer(e)
    boy:applyLinearImpulse(e.yGravity, .5, 0, 0)
end

```

This huge if statement looks terrible and is definitely the wrong way to be handling your problem, whatever that is. However, you don't describe your problem at all, you don't explain this code (would like to know what exactly are the parameters for applyLinearImpulse), and this website is not a place to submit chunks of code and expect others to do your work for you. If you want a helpful answer, please ask a helpful question. Good luck.
> 1 votes

---
Tags: corona-sdk
---


title: Bukkit saving inventory enchantments

text:
# Question
Title: Bukkit saving inventory enchantments
I am working on a bukkit plugin. One thing I want this plugin to do is teleport you to other worlds on the server. However, I don't want the player's inventory to be saved.

Right now, I have this code:

```
File playerInvConfigFile = new File(plugin.getDataFolder() + File.separator + "players" + File.separator + sender.getName(), "inventory.yml");
FileConfiguration pInv = YamlConfiguration.loadConfiguration(playerInvConfigFile);

        Player user = (Player)sender;
        PlayerInventory inv = user.getInventory();

        String worldName = user.getWorld().getName();
        int i = 0;
        for (ItemStack stack : inv.getContents()){
            i++;
            String start = worldName + "." + Integer.toString(i);

            pInv.set(start + ".amount", stack.getAmount());
            pInv.set(start + ".durability", stack.getDurability());
            pInv.set(start + ".type", stack.getTypeId());
        }
        inv.clear();

```

This works great, but there is a big problem: enchantments are now saved! This is a big problem. I want to know how to both save enchantments to a file, and then read them back in and set them!

Thank you all!

# Answer
There are two methods on ItemStack that you will find of use:

The first is getEnchantments, which returns a Map, which you will need to use an iterator to go through and save off the keys and values.

```
Map<Enchantment,Integer> enchantments = itemStack.getEnchantments();
Iterator<Entry<Enchantment,Integer>> iter = enchantments.entrySet().iterator();
while(iter.hasNext()){
    Entry<Enchantment,Integer> entry = iter.next();
    //do something with the entry
}

```

When you restore the inventory, you need to create a new HashMap, restore the values within the original map, and restore them to the ItemStack, using addEnchantments, which takes as its sole parameter a Map, so you deserialize whatever you serialized before, and then add it to the ItemStack like so:

```
itemStack.addEnchantments(enchantments);

```
> 1 votes

---
Tags: java, minecraft-modding
---


title: Anybody remember this webpage?

text:
# Question
Title: Anybody remember this webpage?
I remember visiting a webpage some time ago (1 year ago maybe)

It contained many java applets, describing how certain mathematical functions like sin, cos, arcsin, exp would make an object move, with an example of animated ball next to it, with its curve and the function name.

It was quite exhaustive, and was quite handy to simulate physical behaviors, like bouncing ball, smoothing cameras...

I can't find it on google, Anybody remembering this page ?

# Answer
> 5 votes
http://sol.gfxile.net/interpolation/

(sorry I forgot it was about interpolation)

---
Tags: mathematics, physics, animation
---


# Question
Title: Game programming in C, where do I get started?
I started programming about 6 months back and have a decent knowledge in how to code in C. I have mainly used it to implement elementary algorithms or solve Project Euler questions (reached 50 now :) ) What I really want to learn since a long time is game programming. Ie make simple 2D games like snake, or pocket tanks. By simple, I no way mean the amount of work or effort it's going to take to make these games

I've tried searching the net but have had no luck with that. Could anyone point me in the right direction?

What exactly will I need to learn? Where do I start?

# Answer
> 2 votes
The question here is what kind of thing is it that you are looking for. You can either go all-in programmer using SDL/Allegro and coding pretty much everything yourself. You can try the intermediate libraries (engines) that give you sprite management and other algorithms much more streamlined and optimized. If you just want to make games because you have one big idea, GameMaker/Construct is the way to go. They give you everything streamlined except the game logic, which is based off a scripting language you can easily learn to make complex stuff and cool effects.

---
Tags: game-design, c
---


# Question
Title: How to make animated buttons in a menu with Cocos2d?
How do I make animated menus with cocos2d, I just want to animate the buttons and not the entire scene. Effects I look for is flipping buttons (like the back of the button is the next menu), buttons that retract once selected and re appear with new button.

Basically what I ask for is cool effects between menu transitions.

# Answer
> 0 votes
Create a FiniteAction from a Sequence and make the sprite asociated to the button play it on touch. Use the different classes available for different effects.

For the back-to-back you need two buttons, one drawn on top of the other with different priorities. Make one do a FlipY while the other does a flipY reverse and change the drawing priority.

Retract is just a Scale or Skew effect.

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


# Question
Title: My game is just about finished! What do I do now?
I have an HTML5/canvas game just about finished and ready to launch. It's a 2d game in which you explore and disrupt a procedurally-generated landscape, crafting items and structures to survive. I have to finalize the 'ending' and fix a few bugs, but the game is pretty much ready for players.

The game will be free to play on the web, and I plan to begin working versions for iOS and the Mac App Store. I will also continue to add content to the game even after it launches.

Can anyone recommend things that I should remember to do before launching the game? Thanks!

# Answer
> 16 votes
Get a couple of friends and make them go through bugs and check all game assets. Think of ways of monetizing it, like implementing the Kongregate API or so.

# Answer
> 16 votes
I agree with Ef Es, get a couple of people, parents/friends whoever, and watch them play through it. It's the worse to launch a game only to find it really hard because you were use to the game mechanics.

I suggest maybe making a blog of the launch of your game, just go over the details, any updates can be listed there as well.

If money isn't a concern, try to get it on as many sites as possible. The first answer to this post has a lot of sites. Make sure to read all the reviews of what people liked and didn't like. Also let your all your friends that you know enjoy gaming know as well.

EDIT: Just realized not all of those sites accept HtML5 games, here are two that accept Html5 games

You can also use PhoneGap and distribute it on iphone/android, which you said you are working on.

---
Tags: html5, html-canvas, marketing
---


# Question
Title: How can I tactfully ask users to help support my free game?
So, I have a game that has a few dedicated users, but very few actual users. It is a free game on the Android marketplace, supported via ads. I've been toying with the idea of periodically popping up a notice to users encouraging them to do stuff like:

1. Look at the ads presented.
2. Write positive reviews in the Android Marketplace.
3. Encourage their friends to play.

Right now, I have it set up in a not released version to do this once every 5 games, once the user has played at least 10 games, unless they are clicking on ads periodically. I am not letting the user know this, I don't want them to click on ads just to get the popups to stop.

Basically, I'm needing a bit more motivation from the users to keep going to the next level, and I'm letting them know what I would like from them.

Is this going to end up helping me out, or am I just going to get myself buried even more? Thanks!

# Answer
> 21 votes
Popups suck, people dislike them. That you've even thought to ask the question should pretty much give you a sense of that.

For the following, I'm assuming that you're making a game which is relatively short, which players play over and over again (Minesweeper, Solitaire, etc). Minor adaptations would be necessary to these comments for long-form games.

My advice would be that if you want to do a popup to prompt the end-user to do things to help you, then do it **only once** for any single user. I wouldn't trigger it by a certain number of games; I'd do it the next time a game ended, after the player had logged a certain total amount of play time (not counting time paused, suspended, in in-game menus, or etc). Fifteen to twenty minutes would be a good period of play time after which the popup would be okay. And then never do the popup again, even for subsequent launches of the game.

Instead of popups (or in addition to the single popup as described above), a better approach would be to integrate text like: *"Help this game: give us a review in the Android Marketplace!"* into a small area on the "game over" or "leaderboard" screen that the player is sent to when a game ends. That way it's visible after *every* game (so it's more frequently in your user's mind), without becoming obtrusive the way that an OS-themed modal dialog box is.

In such a screen, you want to have a large pool of strings to use; don't always use the same one, or users will tune it out. My advice is that you want to have approximately 33% amusing quips, approximately 33% useful gameplay tips, and approximately 33% "things you can do to help me" messages. But those proportions are flexible; new users will prefer the tips, experienced users will prefer the quips, so feel free to bias in either of those directions. And the more strings available, the better; variety keeps the messages fresh, and keeps the users reading them each time they finish a game.

# Answer
> 4 votes
From my experience, yes, do it but you are right to be careful.

If you have just a few dedicated players, TALK TO THEM - setup a forum, a private chat, forum anything like this. give them VIP access, treat them as VIPs (cause they are :))

They will like meeting the developer of the game. Get to know them. People help friends.

Learn what it is that they want. In my experience, people are willing to do a lot for a benefit. We a F2P game and we've tried a number of things in the last 4 years, and almost always a carrot works the best.

I cannot tell you what that carrot is for your game and there are differences between players. For one person, simply a badge "Friend of the game" is enough. Gives them status, and they will work to get it.

For another person, it is a benefit in the game, perhaps money or some in game currency.

If you are asking players for a review, find a place in the game when they get the first high. Find a time/place in the game where they feel great, or when they feel the game is great. ask for a review then. Ideally, offer something for the review (see above - some carrot).

Give you an idea from experience:

In Realm of Empires, when a person captured their second town, they get a big high. Right then, we asked them for a review. We then got some conversion, say 20% of people writing reviews.

Later we tried to offer a carrot - we offered some free credits as a thank you / congratulations. Conversion doubled.

however, we still had a lot of 3/5 or 4/5 reviews. Not because people thought it was a 3 out of 5 game, but we naturally rate games this way.

then we added a added a "5 star reviews are most appreciated and help us grow! :)" at the end of the message, resulting in VAST majority of reviews 5 of out 5 now.

lessons learned : offer a carrot. tell them exactly what you want them to do.

another lesson, learned from different examples is to be direct - tell players directly what you want them to do. Do not make the message convoluted. the more direct the message, the better.

my 2c :)

---
Tags: android, free-to-play
---


# Question
Title: How to move a static Body in Farseer 3.2 using touchpad
I'm developing a 2D game for windows phone using Xna and Farseer library. For now I have two objects/bodies. One is falling from the top and the other one which is static is at the button of the screen and is supposed to be used to catch the object that is falling.

I need to move the static body at the button using mobile phones touch screen only on X axis.

Here is the sample code that I wrote for using the touch pad, note that "tray" is the static body.

```
private void UpdatePlayer(GameTime gameTime)
    {
        // Windows Phone Controls
        while (TouchPanel.IsGestureAvailable)
        {
            GestureSample gesture = TouchPanel.ReadGesture();
            if (gesture.GestureType == GestureType.FreeDrag)
            {
                tray.Position.X += gesture.Delta.X;
            }
        }

        // Make sure that the player does not go out of bounds
        tray.Position.X = MathHelper.Clamp(tray.Position.X, 0, GraphicsDevice.Viewport.Width - trayTexture.Width);
        tray.Position.Y = MathHelper.Clamp(tray.Position.Y, 0, GraphicsDevice.Viewport.Height - trayTexture.Height);
    }

```

and this is the initialization of this Body

```
//Create Floor (tray)
        tray = BodyFactory.CreateRectangle(MyWorld, ConvertUnits.ToSimUnits(143), ConvertUnits.ToSimUnits(12), 10);
        tray.Restitution = 0.2f;        //Bounceability
        tray.Friction = 0.1f;           //Friction
        tray.IsStatic = true;         //Static objects wont move when hit by other objects

        tray.Position = new Vector2(((int)ConvertUnits.ToSimUnits(playerPosition).X),
            ((int)ConvertUnits.ToSimUnits(playerPosition).Y)); //set the position of tray

```

But the problem is I cannot modify the return value of tray.Position because it's not a variable.

So how can I do it?

# Answer
> One is falling from the top and the other one which is static is at the button of the screen and is supposed to be used to catch the object that is falling.

Sounds like you should use a kinematic body instead of a static one and adjust its velocity so that it moves towards the targeted location quickly when its far away and none at all when the x position is the same.

> A kinematic body moves under simulation according to its velocity. Kinematic bodies do not respond to forces. They can be moved manually by the user, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass, however, Box2D stores zero for the mass and the inverse mass. Kinematic bodies do not collide with other static or kinematic bodies.

This prevents the object from teleporting and confusing Box2D and looks better to your users since the object is now chasing around their finger. Also it encourages them to keep their finder on the pad and move the object. The way you have it set up know the best thing to do as a user would to be tapping wherever is under the ball kind of destroying the appeal of a touchscreen which is that you are interacting and physically moving the objects on screen.

I can't really think of a good interpolation function for the velocity off the top of my head unfortunately. Something along the lines of `MathHelper.Lerp(CurrVel, vWeight * dX, iWeight)` might work though.
> 1 votes

# Answer
Probably because it is a property and not a normal member variable. You need to change the entire tray.Position variable like this:

`tray.Position = new Vector2(tray.Position.X + delta.X, tray.Position.Y);`

Note that properties are a C# language feature.

However this is what Farseer considers teleporting an object and this can interfere with the stability of the physics simulation.

> Also note that the SAP algorithm does not like teleporting objects or very high speed objects such as moving from one end of the world to the other or bullets. It may break down from it and cause unreliable collisions. http://www.farseergames.com/storage/farseerphysics/Manual2.1.htm

That's from the old manual but probably still relevant. I suggest you first try just setting the position like you're trying now. If this gives weird behavior try moving the tray using Force and Inertia.
> 2 votes

---
Tags: xna, body
---


title: Directx11 / Tessellation

text:
# Question
Title: Directx11 / Tessellation
What is so special about directx 11's dynamic tessellation? Can't it be implemented by hand, and just render geometry tessellated by your own code using older versions of directx? What are the advantages of using dx11? Thank you!

# Answer
Here are just a few reasons off the top of my head:

* You don't have to store the tessellated mesh in memory at any time, because it's generated on the fly on the GPU and streamed directly into the rasterizer/shader units. This is a huge memory savings versus precomputed tessellation, and can (sometimes) help performance as well due to the reduced memory bandwidth for reading vertices and indices (since on the GPU it will typically stay on-chip rather than being streamed in and out of memory).
* The GPU is massively parallel, so GPU tessellation is also going to be way faster than running the equivalent CPU tessellation each frame (at least if you're tessellating enough stuff).
* You can also make use of the GPU's texture sampling hardware e.g. for applying a displacement map to the tessellated vertices, which would be much trickier and slower if you had to implement the texture sampling yourself on the CPU.
> 9 votes

---
Tags: directx, tessellation
---


# Question
Title: Character jittering with this tile based collision code
I have been trying to get my collision code working for hours now but with every resource I have tried my character still jitters. First I tried using the platformer sample but my character still jittered up and down really quickly, even when standing still. Then I took to these forums and found this post and I used his code and eventually found out that in order for his to work you have to:

1. Move the character's position along the x-axis only.
2. Check if the character collided with something along the x-axis

Then do the same thing for the y axis. In other words, the character could only move one direction at a time and with my game there are a lot of different forces, velocities, accelerations, et cetera. all pulling on the target at once and this kind of solution didn't really work.

I heavily simplified the code in the sample and ended up with this:

```
Rectangle playerBounds = GetPlayerBounds(motion.Position.X, motion.Position.Y, characterWidth, characterHeight);

// Get the player's bounding rectangle and find neighboring tiles.
Rectangle bounds = playerBounds;
int leftTile = (int)Math.Floor((float)bounds.Left / TileSize);
int rightTile = (int)Math.Ceiling(((float)bounds.Right / TileSize)) - 1;
int topTile = (int)Math.Floor((float)bounds.Top / TileSize);
int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / TileSize)) - 1;

for (int y = topTile; y <= bottomTile; ++y) // For each potentially colliding tile,
{
    for (int x = leftTile; x <= rightTile; ++x)
    {
        Tile collision = stage.CustomLayer.GetTile(x, y);

        if (collision.Value == Tile.CollisionTile)
        {
            Vector2 depth = Extensions.GetIntersectionDepth(bounds, collision.Bounds); // Determine collision depth (with direction) and magnitude.

            if (depth != Vector2.Zero)
            {
                if (Math.Abs(depth.Y) < Math.Abs(depth.X)) // Resolve the collision along the shallow axis.
                {
                    motion.Position = new Vector2(motion.Position.X, motion.Position.Y + depth.Y); // Resolve the collision along the Y axis.
                }
                else // Ignore platforms.
                {
                    motion.Position = new Vector2(motion.Position.X + depth.X, motion.Position.Y); // Resolve the collision along the X axis.
                }

                bounds = playerBounds; // Perform further collisions with the new bounds.
            }
        }
    }
}

```

The code produces the jittering effect as well. I have debugged it for hours and I think I found the cause but I do not know how to fix it.

For example, if the character's `Y position is 500` and is found to be colliding with a tile with a depth of `5 pixels`, he will be pushed to `Y position 495`. At this time, though, the loop will continue based off of old `topTile and bottomTile` values and he may still be found to be colliding with those tiles, and will be pushed up to `Y position of 490`. Next time this function is called though when the character has moved back down to `Y position of 495` due to gravity, he won't be colliding because of different initial `topTile and bottomTile` values and will continue moving downwards.

I believe this is what causes the jittering effect but I do not understand why it is happening to me. As far as I know, I am using the same algorithm as everyone else and their code doesn't produce any jittering. All my tiles are of equal size (32x32) and I am using the same `GetIntersectionDepth` method found in the platformer sample.

Thanks to anyone who can help me solve this problem.

# Answer
My solution did not imply that the character can only move in one axis at a time. It can still move in any direction, but you apply forces/accelerations/velocities separately on each axis. But I agree it might not be trivial to add these changes if you already have another system in place. But keep the idea in mind in case you encounter the kinds of problems mentioned in the other post.

As for the jittering problem, I remember I had it too and the solution for me was by doing `Math.Round` on the player position after applying velocity (I did it before handling collisions, but I'm not sure if order matters). You can see that on my example, line 66, and if I remember correctly it was also present in the original sample in the `Update` method or something. From your code snippet I can't see if you're already doing it or not, but I recommend it to prevent jittering at certain speeds.

Other than that suggestion, there's something wrong with your code. In particular, since `Rectangle` is a value type, not a reference type, when you do `bounds=playerBounds` after moving the player, you're not really pointing to the new bounds of the player. It's still the old value. You need to call `GetPlayerBounds()` again to recalculate the new bounds for the player.
> 1 votes

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


# Question
Title: Is SDL conducive to detailed 2D in-Game Animation and intricate particle effects?
Is SDL (when used CORRECTLY) conducive to detailed in-Game animation and displaying interesting high quality particle effects?

If my question seems too vague, at the other end of this link I have an animation reel:

http://zeebashew.squarespace.com/

(30 seconds in a troop of the kinds of characters I will be using run into screen)

I would like to get my games to run at about the level of pixel-detail (if not slightly better as the video is a little bit overcompressed) with 10-15 characters on screen, and 1-4 pre-rendered 2D explosions flying around at the same time.

I just can't help but wonder, is this even possible in SDL?

I can't stress enough though: I absolutely love C++ so far, and SDL has been really cool, but I would really love to feel more certain that I am learning the specifics of the best tool for what I am trying to do.

# Answer
> 3 votes
10-15 characters on screen and a few pre-rendered explosions seems easily doable in SDL - it's just a few sprites to push to screen after all.

However, do note that SDL (1.2, the current non-beta version) is rendered on a software surface if I remember correctly. This means that it isn't accelerated by your graphics hardware (which will happen in SDL 1.3 (Just checked the website, it has been renamed to SDL 2.0 now) which *will* feature hardware acceleration. Just keep that in mind.

---
Tags: c++, sdl
---


# Question
Title: Handling scripted and "native" components in a component-based entity system
I'm currently trying to implement a component-based entity system, where an entity is basically just an ID and some helper methods tying a bunch of components together to form a game object. Some goals of that include:

1. Components only contain state (e.g. position, health, ammo count) =\> logic goes into "systems", which process these components and their state (e.g. PhysicsSystem, RenderSystem, etc.)
2. I want to implement components and systems both in pure C# and through scripting (Lua). Basically I want to be able to define completely new components and systems directly in Lua without having to recompile my C# source.

Now I'm looking for ideas on how to handle this efficiently und consistently, so I don't need to use different syntax to access C# components or Lua components, for example.

My current approach would be to implement C# components using regular, public properties, probably decorated with some attributes telling the editor about default values and stuff. Then I'd have a C# class "ScriptComponent", which just wraps a Lua table internally with this table being created by a script and holding all the state of that particular component type. I don't really want to access that state much from the C# side, as I wouldn't know at compile time, what ScriptComponents with what properties would be available to me. Still, the editor will need to access that, but a simple interface like the following should suffice:

```
public ScriptComponent : IComponent
{
    public T GetProperty<T>(string propertyName) {..}
    public void SetProperty<T>(string propertyName, T value) {..}
}

```

This would simply access the Lua table and set and retrieve those properties from Lua and it could easily be included in the pure C# components as well (but use the regular C# properties then, through reflection or something). This would only be used in the editor, not by regular game code, so performance isn't as important here. It would make it necessary to generate or handwrite some component descriptions documenting what properties a certain component type actually offers, but that wouldn't be a huge issue and could be sufficiently automated.

However, how to access components from the Lua side? If I make a call to something like `getComponentsFromEntity(ENTITY_ID)` I'll probably just get a bunch of native C# components, including "ScriptComponent", as userdata. Accessing the values from the wrapped Lua table would result in me calling the `GetProperty<T>(..)` method instead of accessing the properties directly, like with the other C# components.

Maybe write a special `getComponentsFromEntity()` method only to be called from Lua, which returns all the native C# components as userdata, except for "ScriptComponent", where it'll return the wrapped table instead. But there'll be other component-related methods and I don't really want to duplicate all these methods both for being called from C# code or from Lua script.

The ultimate goal would be to handle all types of components the same, with no special case syntax differentiating between native components and Lua components - especially from the Lua side. E.g. I'd like to be able to write a Lua script like that:

```
entity = getEntity(1);
nativeComponent = getComponent(entity, "SomeNativeComponent")
scriptComponent = getComponent(entity, "SomeScriptComponent")

nativeComponent.NativeProperty = 5
scriptComponent.ScriptedProperty = 3

```

The script shouldn't care what kind of component it actually got and I'd like to use the same methods I'd use from the C# side to retrieve, add or remove components.

Maybe there are some sample implementations of integrating scripting with entity systems like that?

# Answer
> 6 votes
A corollary of FxIII's answer is that you should design everything (that would be moddable) in the scripting language **first** (or at least a very decent portion of it) to ensure that your integration logic actually provisions for modding. When you are certain that your scripting integration is versatile enough rewrite the required bits in C#.

I personally hate the `dynamic` feature in C# 4.0 (I am a static language junkie) - but this is without doubt a scenario where it should be used and is where it really shines. Your C# components would be simply be strong/expando behaviorial objects.

```
public class Villian : ExpandoComponent
{
    public void Sound() { Console.WriteLine("Cackle!"); }
}

//...

dynamic villian = new Villian();
villian.Position = new Vector2(10, 10); // Add a property.
villian.Sound(); // Use a method that was defined in a strong context.

```

Your Lua components would be completely dynamic (the very same article above should give you an idea of how to implement this). For example:

```
// LuaSharp is my weapon of choice.
public class LuaObject : DynamicObject
{
    private LuaTable _table;

    public LuaObject(LuaTable table)
    {
        _table = table;
    }

    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        var methodName = binder.Name;
        var function = (LuaFunction)_table[methodName];
        if (function == null)
        {
            return base.TryInvokeMember(binder, args, out result);
        }
        else
        {
            var resultArray = function.Call(args);
            if (resultArray == null)
                result = null;
            else if (resultArray.Length == 1)
                result = resultArray[0];
            else
                result = resultArray;
            return true;
        }
    }

    // Other methods for properties etc.
}

```

Now because you are using `dynamic` you can use Lua objects as though they were real classes in C#.

```
dynamic cSharpVillian = new Villian();
dynamic luaVillian = new LuaObject(_script["teh", "villian"]);
cSharpVillian.Sound();
luaVillian.Sound(); // This will call into the Lua function.

```

# Answer
> 2 votes
I'd rather do the opposite: write all using a dynamic language and then track down the bottleneks (if any). Once you find one you may selectively reimplement the functionalities involved using a C# or (rather) C/C++.

I tell you this mainly because what are trying to do is to confinate the flexibilities of your system in the C# part; as the system becomes complex your C# "engine" will start to look like a dynamic interpreter, probably not the best one. The question is: are you willing to invest the most of your time into writing a generic C# engine or to extend your game?

If your target is the second one, as I belive, you will probably use your time best focusing on you game mechanics, letting a seasoned interpreter to run the dynamic code.

---
Tags: c#, component-based, entity-system, scripting, lua
---


# Question
Title: How can I create a pack file / archive for game data files, and then load them? (zlib?)
I'm starting to think about how I'm going to go about loading models, images, sounds, etc for my game. I have two competing lines of thought to deal with:

1. If possible, it would be nice to make use of existing libraries to load things like PNGs, etc.
2. I would like to pack all of my game data into a single archive, and it would be great to use an existing library here also.

Is it possible to do this? I've heard that I could use something like zlib for (2), but I've never used it before so I'm not sure how it would work. Is it possible to yank a file out of a zlib archive in memory, and then pass it to some compatible library for the actual loading? How would these two systems interface with each other? Would using zlib slow down the loading process?

I've not had much experience with I/O in my career, so I'm not really sure where to start.

# Answer
> 8 votes
I did pretty much exactly what you describe. Here's a run-down of how my system works:

I maintain a list of all asset files, along with some meta data. This takes the form of a table of contents (TOC) file at the root of a directory tree that will become the archive. Any file in the TOC is included in the archive, along with any metadata about the file.

The TOC is included in the actual archive file at a static offset so it can be very quickly read. It contains offsets for each file, so I know where to seek to grab the compressed data for a given file. Once decompressed, my ResourceManager takes the data from the archive and passes it to the appropriate format handler (ogg, png, etc.) which then produces raw data (PCM data, bitmap, etc.) The raw data is then given to an appropriate loader which will make sure the data is ready for use (on the video card, etc.)

I'd say what you want to do could be a good idea, but it could very well be a lot of unnecessary work. I would suggest you consider whether alternatives would suffice before embarking down this road (especially if you've not done a lot of IO before.) Get ready to spend a good bit of time in a debugger and looking through hex dumps if you go down this route. If you do, I suggest lots of test cases.

# Answer
> 1 votes
For starters you could go with just a folder (it's easy to add and modify 'stuff' in a folder) and later on when your game is up and running nicely, just add a level of zip/unzip (or whatever method you find that suits you) to the loading function and zip the folder up.

For the "Loading .PNG:s and such": This has absolutely nothing to do with the second question and will most probably heavily depend on the platform you are using (XNA, SDL, OpenGL, DirectX, etc.)

# Answer
> 0 votes
After looking into this for a while, it seemed that zlib wasn't going to satisfy my needs. It seems to be focused on compressing and decompressing individual files. I need something that is able to handle archives.

One potential solution I've found would be to use libarchive, which is an archiving library that will handle extracting files from an archive such as a ZIP file. It even allows you to assign the extracted file to a standard FILE pointer, which would make interfacing with any other libraries (PNG, my model loader) potentially more straightforward.

---
Tags: c++, asset-management
---


# Question
Title: How to create life-like sprites from photo or video capture like was done for games like Mortal Kombat 1?
I know they digitized actors but how can I get those same results? How to take a photo or video of someone and digitize it for a 2D game? Digitized sprites were used in several video games through the 90s but fell out of favor when textured 3D graphics became more common. What technology is used today for creating MK1 realism?

# Answer
Here's a link to the Making of Mortál Szombat: http://openmortal.sourceforge.net/making.html
> 6 votes

# Answer
It probably is just a lot of time put into it. Some wild idea:

* Record with a static camera in a green chroma.
* Convert or output the video frames to images.
* Take around 15 frames per every second for each "movement" and discard the rest.
* Photoshop time! Remove the green chroma manually using magic tool, and clean the sprites.
* Prepare and use them for your animations.

I'm not big in video/image edition but maybe there is a filter or program that can automatize transforming the green background into transparent, bitwise is only transforming the uniform chroma color 0x00FF00FF into 0x00000000, or even just remove the alpha bits.
> 7 votes

---
Tags: 2d, graphics, sprites
---


title: Random movement

text:
# Question
Title: Random movement
I am making a game in XNA, and I am trying to make a dog move randomly. The game is platform, so he only moves left and right. I put this code in the Update() method: int random = dog.Next(0, 2);

```
        if (random == 0)
        {
            dogPosition.X -= 20;
        }

        if (random == 1)
        {
            dogPosition.X += 20;
        }

```

I want him to move right or left a little, then stop, then move again like in Terraria or MapleStory. What happens is he changes direction too fast. Is there a way to do this with timers? I couldn't figure the timers out, so I put it in the Draw() method and added a for loop:

```
        for (int dogTimer = 0; dogTimer > 40; dogTimer++)
        {
            int random = dog.Next(0, 2);

            if (random == 0)
            {
                dogPosition.X -= 200;
            }

            if (random == 1)
            {
                dogPosition.X += 200;
            }
        }

```

When I run that code, he does not move at all. Can someone tell me how to use timers to do this, or how to fix the problem in the second code? Any help is appreciated. Thanks is advance :)

# Answer
It seems to me like people missed the XNA tag on the question, so here's an XNA-specific answer.

First of all, you need to add two variables to your `Dog` class (if you don't have a `Dog` class, add them to the class where your `Update` method is located):

```
float elapsedTime = 0; //Time elapsed since the last check
int direction = 1; //Default travel direction

```

Then, you'll want to change your update statement to say this:

```
elapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (elapsedTime > 1) { //Get a new random direction every 1 second
    elapsedTime -= 1; //Subtract the 1 second we've already checked
    direction = dog.Next(0, 2); //Set the direction to a random value (0 or 1)
}

if (direction == 0) {
    dogPosition.X -= 200;
} else {
    dogPosition.X += 200;
}

```

Simply put, it gets a new direction once per second and updates the dog's position.

More in-depth explanation:
This code keeps a count of the elapsed time between each `Update` statement (in seconds). Once that count has reached a certain value (in this case, 1 second), we get a new random direction. It's possible that the dog will continue in the same direction it's going, or it may turn around. It then updates the current X value based on the value of the `direction` variable.

The reason it seemed so random and weird for your previous code, is because `Update` gets run 60 times per second (in theory). This means that you were giving the dog a random direction 60 times per second which would cause it to be jittery. Not only that, but since you put it in a `for` loop, if you had written it correctly, you would have been updating it 60 * 40 = 2400 times per second!
> 3 votes

# Answer
You need to set him targets, and randomize those.

```
update():
    if(position.x = target.x):
        target.x = rand(position.x-range, position.x+range)
    if(position.x < target.x):
        position.x += speed
    else:
        position.x -= speed

```

This should select a destination somewhere within range, walk towards it at speed, and then select a new destination, and walk towards that.

This is pretty simplified, you should be scaling movement against time rather than frames, and there'd usually be some sort of path-finding going on as well.
> 2 votes

# Answer
You can try something like this:

Define a class for a movement event

```
Class MovementEvent
{
    Vector2 startplace;
    Vector2 endplace;
    float currentTime;
    float endTime;
    float idleTime;
}

```

You can create movements like this:

```
dog::CreateMovement()
{
    Movement = new Movement();
    Movement.startPlace = this.Position;
    Movement.endPlace = new Vector2();
    Movement.endPlace.X = this.Position.X + RN; //Guarantee that RN is a random number that will keep the dog in the platform without falling.
    Movement.endPlace.Y = this.Position.Y;
    Movement.currentTime = 0;
    Movement.endTime = (Movement.startPlace - Movement.endPlace).Length() / dogSpeed;
    Movement.idleTime = RID; //Where RID is a random amount of seconds to the dog wait before start walking again. Like MapleStory NPCS do.
}

```

On the dog class, store a MovementEvent. Every frame, check this MovementEvent and do something about it, like this:

```
if(dog.Movement == null)
{
    dog.CreateMovementEvent();
}
if(dog.Movement.currentTime >= dog.Movement.endTime)
{
    dog.Movement.idletime -= gameTime.ElapsedGameTime.TotalSeconds;
    if(dog.Movement.idleTime <= 0) dog.Movement = null;
}
else
{
    Vector2.Lerp(dog.Movement.startPlace, dog.Movement.endPlace, dog.Movement.currentTime / dog.Movement.endTime, dog.position);
}

```

Not sure if this is what you want, but is what I understood about your problem.

If you need any definitions:
Vector2
Vector2.Lerp
Vector2.Length
> 2 votes

# Answer
Or for simplicity just use a 'direction'

```
dx=1; //move right
dx=-1; move left

```

and change that direction sometimes, say every some random seconds, like

```
if(((random() % 500) == 1)

```

in the main loop you'd just move the dog every frame according to dx:

```
dogPosition.X += dx;

```
> 1 votes

---
Tags: xna
---


title: Custom made depth bias (vertex) shader

text:
# Question
Title: Custom made depth bias (vertex) shader
As most of intermediate graphics programmers know, z-fighting can be a problem. That's why most game engines prevent this from happening by using a slope depth bias algorithm.

As there's no direct information on how this is performed, apart from microsoft's reference DirectX page, I wanted to ask whether anyone has any idea on how a vertex shader could be written to implement such a mechanism. I wrote a snippet, but it's not behaving as expected. Here it is (Cg vertex shader code):

```
out_position =  mul(worldviewproj_matrix, in_position);
out_world_position = mul(world_matrix, in_position);

float Dz = camera_position.z - out_world_position.z;
float Dy = camera_position.y - out_world_position.y;
float Dx = camera_position.x - out_world_position.x;
float m = max( abs(Dz / Dy), abs(Dz / Dx));
float Offset = m * main_bias + main2_bias;
out_position.z -= Offset * 0.005;

```

# Answer
The simplest option to get a depth bias is to move the near and far clip planes. See http://tomsdxfaq.blogspot.com/2002\_07\_01\_archive.html#79344425#79344425

You could do that in a vertex shader if you wanted to, but it's easier to do it from the calling code.
> 1 votes

---
Tags: shaders, cg
---


# Question
Title: Using NinePatch in libGDX for Loading Bar
I am trying to create images for a loading bar in libGDX. I came across the `NinePatch` class and I was hoping to use it for this loading bar, since stretching images with a plain `Texture` or `Sprite` looks terrible. Does anyone have any examples on how to use this class? I have done some searching around and I've gotten it to work but the image I use just comes through as slightly transparent and gray. It just doesn't look like the same image. The actual loading bar itself seems to work fine as I just set the width of the foreground loading image. Here is the code I am using so far...

```
// Class vars
private NinePatch loadingBackground;
private NinePatch loadingForeground;

...

// In my constructor
loadingBackground = new NinePatch(new Texture(Gdx.files.internal("loadingback.png")), 8, 8, 8, 8);
loadingForeground = new NinePatch(new Texture(Gdx.files.internal("loadingfore.png")), 8, 8, 8, 8);

...

// Drawing
batch.begin();
loadingBackground.draw(batch, x, y, width, height);
loadingForeground.draw(batch, x, y, loadingWidth, height);
batch.end();

```

I am open to any other suggestions on how I should implement this as well.

# Answer
The left, top, right, bottom arguments are the amount of pixel of the segments. For example in: How to NinePatch

This: turns to this: The left, top, right, bottom are all 8 pixels.
> 5 votes

---
Tags: java, android, graphics, libgdx, loading
---


title: Controlling access to my game

text:
# Question
Title: Controlling access to my game
I'm getting near the point where I'm going to be ready to release an alpha of my game. I'm curious as to how to implement a system where the game is un-launchable if a user name and password haven't been entered and verified. I plan on having an authentication server setup for verifying user credentials. I'm not concerned about making the game pirate proof, because that'll happen. I just want to make it more difficult for the casual user to share. What needs to be in place for such a system to work? My thoughts are to implement a system similar to this:

*The first time the user logs in, have the users computer generate unique value based on their system attributes (not the actual attributes, I'm not collecting that). Logging in to the server sends username/pass and unique value, the server then attributes that username with that unique value and those are checked when the user logs in.*

I don't plan on limiting the amount of computers a user can install on, but I want to be able to disallow obvious abuse of an account, i.e. it's being used on dozens of computers.

Is this system reasonable for a free-time sole developer? Or what kind of system would make sense for my requirements?

**EDIT**

Let me elaborate a little on why I want to use the system unique ID. I think that having a key like that is what would enable me to have an offline mode. I guess I wouldn't need to send the key to the server. But once a user name and password have been authenticated by the server, I can instruct the game to generate that unique ID and pair it with the user name. Then when the user tries to launch the game in offline mode, I can check to see if that computer has been authenticated online before. This would disallow people copying a verified copy of the game to a different computer to use offline mode.

# Answer
Machine specific keys are a backwards step, they always raise customer service costs and only punish legitimate users with lockouts. It's better to suffer 10 pirates for one customer than have 9 pirates and one lost customer, in my opinion.

How about this scenario: your game ships with one missing component; when the customer authenticates his purchase your server encrypts the missing component using the hashed password and installs it. Afterwards, every time the customer plays locally he still has to enter the password and it is used to decrypt the module into memory.

Even better, non-authenticated **future customers** get a phony module that serves up advertisements for your other titles and/or limits their play and recommends that they register.

Your job is to create sales, not punish pirates =)
> 1 votes

# Answer
Why not take the Mojang approach? Once a user has registered either through the game or through your website, have a log-in screen that asks for their username and password. They your game checks the given username/pass with what is registered on your authentication server, and as long as they match then the game starts up. Why do you need to include their system specs as a key? Especially if you aren't going to limit the number of computers it can be installed on?

Of course, you would need an offline mode too. Nothing kills a game's reputation faster than not being able to play it unless you are online.
> 1 votes

---
Tags: java, lwjgl
---


# Question
Title: 3D Translation using only distance and angles
So I'm starting to foray into 3D game programming, but I've hit something of a snag.

I have an object I want to move around. It should always move either forward or backward relative to its local Z axis, and otherwise change directions by changing its local X and Y rotations.

Now doing this in 2D is no problem. When I only consider the X-Z plane, the following code works fine:

```
m_Position.x -= (float)sin(m_Rotation.y * Pi / 180) * Speed;
m_Position.z -= (float)cos(m_Rotation.y * Pi / 180) * Speed;

```

And when only considering the Y-Z plane, the following works fine:

```
m_Position.y += (float)sin(m_Rotation.x * Pi / 180) * Speed;
m_Position.z -= (float)cos(m_Rotation.x * Pi / 180) * Speed;

```

But when combining the two, they don't work. Now I didn't expect them to work just straight up stuck together like that, since the Z value is getting conflicting signals. But I'm not sure where to go from here.

I've read a bit about matrix math, and that seems the way to go, but the tutorials I have found are either difficult to follow, or they focus on rotating a point around the origin (or translating if you already *have* a translation vector, which is the thing I'm looking for). The clearest one I've found is this, but I'm not sure how to adapt the rotate-around-origin matrix math to the move-in-direction-of-angle matrix math.

My *extremely* rudimentary understanding of matrix math would suggest that translations Ta and Tb along angles A and B, if A is a rotation around the Y axis and B around the X axis, would be represented as:

```
Xa = x*sinA + y*0 + z*0 + w*0
Ya = x*0 + y*1 + z*0 + w*0
Za = x*0 + y*0 + z*cosA + w*0
Wa = x*0 + y*0 + z*0 + w*1

Xb = x*1 + y*0 + z*0 + w*0
Yb = x*0 + y*sinB + z*0 + w*0
Zb = x*0 + y*0 + z*cosB + w*0
Wb = x*0 + y*0 + z*0 + w*1

```

But I don't know whether that's right, and what I have to do with them. Multiply them together? Add the resulting vectors? Am I even close?

Can someone point me in the direction of good resources for learning this sort of thing?

EDIT: Just to be clear, I have the object's current (X,Y,Z) and its (Roll, Yaw, Pitch). I want it to move in from the former in the direction defined by the latter. I know I can use OpenGL to do this transformation on a purely visual level by just rotating first and then translating, but I need to have access to the *new* (X,Y,Z) for things like collision detection, indexing, etc.

EDIT 2: I've created the following code after finding this, but I'm not 100% sure if it's correct, since there are also issues with my visual rotations at the moment. It seems to work, at least superficially. Thoughts?

```
float X = (float)sin(m_Rotation.y * Pi / 180) * (float)cos(m_Rotation.x * Pi / 180);
float Y = (float)sin(-m_Rotation.x * Pi / 180);
float Z = (float)cos(m_Rotation.y * Pi / 180) * (float)cos(m_Rotation.x * Pi / 180);

```

# Answer
> 0 votes
Basically you have to:

1. Create a rotation matrix from Yaw/Pitch and Roll
2. Multiply your local direction vector (z-axis) by that matrix and multiply the resulting vector by speed, that is the translation
3. Add that translation vector to your current position

I added a code example. There are 2 convenience classes that do most of the ugly work: vector and matrix. Scroll directly down to main, to see the implementation of 1) 2) and 3)

```
#include <cmath>
#include <cassert>
#include <cstdio>

#define NEARLY_EQUAL_EPS_F( a, b, eps )     (fabsf( (a)-(b) ) < (eps))
#define ASSERT_VECTOR( v )                  (assert( NEARLY_EQUAL_EPS_F(0.0f, (v)[3], 1.e-7)))
#define FLOAT_FORMATOR                      "%10.6f"

namespace demo
{
    class vector
    {
    public:
        vector() {}
        explicit vector( const float _v[4] )                    { v[0]=_v[0]; v[1]=_v[1]; v[2]=_v[2]; v[3]=_v[3]; }
        vector( const vector &_v )                              { v[0]=_v[0]; v[1]=_v[1]; v[2]=_v[2]; v[3]=_v[3]; }
        vector( float _x, float _y, float _z, float _w )        { v[0]=_x; v[1]=_y; v[2]=_z; v[3]=_w; }

        float           &operator[]( int i )                    { return v[i]; }
        const float     &operator[]( int i ) const              { return v[i]; }

        // useful for glVertex3fv, glNormal3fv
        const float*    data_ptr() const                        { return v; }
        // add vector s
        vector          operator+(const vector &b ) const       { ASSERT_VECTOR( b ); return vector( v[0]+b[0], v[1]+b[1], v[2]+b[2], v[3]+b[3] ); }
        // scale vector
        vector          operator*( float scale ) const          { return vector( v[0]*scale, v[1]*scale, v[2]*scale, v[3]*scale ); }

    private:
        float v[4];
    };

    class matrix
    {
    public:
        matrix() {}

        vector&                 operator[]( int i )             { return cols[i]; }
        const vector&           operator[]( int i ) const       { return cols[i]; }

        // useful for glMultMatrixf, glLoadMatrixf
        const float*            data_ptr() const                { return cols[0].data_ptr(); }
        matrix&                 rotateY( float a );
        matrix&                 rotateX( float a );
        matrix&                 rotateZ( float a );

        // return an identity matrix
        static matrix           identity();
        // create a rotation matrix around y-axis
        static matrix           rotate_y( float a )             { return matrix::identity().rotateY( a ); }
        // create a rotation matrix around y-axis
        static matrix           rotate_x( float a )             { return matrix::identity().rotateX( a ); }
        // create a rotation matrix around y-axis
        static matrix           rotate_z( float a )             { return matrix::identity().rotateZ( a ); }

    private:
        vector cols[4];
    };

    inline
    matrix
    matrix::identity()
    {
        matrix m;
        m[0] = vector( 1.0f, 0.0f, 0.0f, 0.0f );
        m[1] = vector( 0.0f, 1.0f, 0.0f, 0.0f );
        m[2] = vector( 0.0f, 0.0f, 1.0f, 0.0f );
        m[3] = vector( 0.0f, 0.0f, 0.0f, 1.0f );
        return m;
    }

    inline
    matrix&
    matrix::rotateY( float a )
    {
        cols[0][0] = cos(a);    cols[0][1] = 0.0f;  cols[0][2] = -sin(a);   cols[0][3] = 0.0f;
        cols[1][0] = 0.0f;      cols[1][1] = 1.0f;  cols[1][2] = 0.0f;      cols[1][3] = 0.0f;
        cols[2][0] = sin(a);    cols[2][1] = 0.0f;  cols[2][2] = cos(a);    cols[2][3] = 0.0f;
        cols[3][0] =            cols[3][1] =        cols[3][2] = 0.0f;      cols[3][3] = 1.0f;
        return *this;
    }

    inline
    matrix&
    matrix::rotateX( float a )
    {
        cols[0][0] = 1.0f;      cols[0][1] = 0.0f;      cols[0][2] = 0.0f;     cols[0][3] = 0.0f;
        cols[1][0] = 0.0f;      cols[1][1] = cos(a);    cols[1][2] = sin(a);   cols[1][3] = 0.0f;
        cols[2][0] = 0.0f;      cols[2][1] = -sin(a);   cols[2][2] = cos(a);   cols[2][3] = 0.0f;
        cols[3][0] =            cols[3][1] =            cols[3][2] = 0.0f;     cols[3][3] = 1.0f;
        return *this;
    }

    inline
    matrix&
    matrix::rotateZ( float a )
    {
        cols[0][0] = cos(a);    cols[0][1] = sin(a);    cols[0][2] = 0.0f;      cols[0][3] = 0.0f;
        cols[1][0] = -sin(a);   cols[1][1] = cos(a);    cols[1][2] = 0.0f;      cols[1][3] = 0.0f;
        cols[2][0] = 0.0f;      cols[2][1] = 0.0f;      cols[2][2] = 1.0f;      cols[2][3] = 0.0f;
        cols[3][0] =            cols[3][1] =            cols[3][2] = 0.0f;      cols[3][3] = 1.0f;
        return *this;
    }
    // matrix-matrix multiplication
    inline
    matrix operator*( const matrix &a, const matrix &b )
    {
        matrix result;

        register unsigned int r;
        register unsigned int c;

        for( r = 0; r < 4; ++r )
        {
            for( c = 0; c < 4; ++c )
            {
                result[c][r] = a[0][r] * b[c][0] +
                    a[1][r] * b[c][1] +
                    a[2][r] * b[c][2] +
                    a[3][r] * b[c][3];
            }
        }
        return result;
    }

    // matrix-vector multiplication
    inline
    vector operator*( const matrix &m, const vector &v )
    {
        vector ret;
        ret[0] = v[0] * m[0][0] + v[1] * m[1][0] + v[2] * m[2][0] + v[3] * m[3][0];
        ret[1] = v[0] * m[0][1] + v[1] * m[1][1] + v[2] * m[2][1] + v[3] * m[3][1];
        ret[2] = v[0] * m[0][2] + v[1] * m[1][2] + v[2] * m[2][2] + v[3] * m[3][2];
        ret[3] = v[0] * m[0][3] + v[1] * m[1][3] + v[2] * m[2][3] + v[3] * m[3][3];
        return ret;
    }

    inline void DumpVectorf( FILE *file, const char *msg, const vector &p )  { fprintf( file, "%-15s: "FLOAT_FORMATOR" "FLOAT_FORMATOR" "FLOAT_FORMATOR" "FLOAT_FORMATOR"\n", msg, p[0], p[1], p[2], p[3] ); fflush( file ); }

    inline void DumpMatrixf( FILE *file, const char *msg, const matrix &m )
    {
        fprintf( file, "%-15s:\n", msg );
        fprintf( file, "  row0: "FLOAT_FORMATOR" "FLOAT_FORMATOR" "FLOAT_FORMATOR" "FLOAT_FORMATOR"\n", m[0][0], m[1][0], m[2][0], m[3][0] );
        fprintf( file, "  row1: "FLOAT_FORMATOR" "FLOAT_FORMATOR" "FLOAT_FORMATOR" "FLOAT_FORMATOR"\n", m[0][1], m[1][1], m[2][1], m[3][1] );
        fprintf( file, "  row2: "FLOAT_FORMATOR" "FLOAT_FORMATOR" "FLOAT_FORMATOR" "FLOAT_FORMATOR"\n", m[0][2], m[1][2], m[2][2], m[3][2] );
        fprintf( file, "  row3: "FLOAT_FORMATOR" "FLOAT_FORMATOR" "FLOAT_FORMATOR" "FLOAT_FORMATOR"\n", m[0][3], m[1][3], m[2][3], m[3][3] );
        fflush( file );
    }
}

using namespace demo;

int main()
{
    vector m_Rotation(1.0f, 0.5f, 0.0f, 0.0f);
    vector m_Position(2.0f, 3.0f, 0.0f, 1.0f);
    float speed = 3.0f;

    // 1) first calculate the rotation matrix from m_Rotation
    // !Mind the rotation order, here we use X, Y, Z, if you use a different one, reshuffle this
    // We create 3 matrices, each one for a rotation around 1 of the axes,
    // then we multiply them to find the final rotation matrix
    matrix rot = matrix::rotate_x(m_Rotation[0]) * matrix::rotate_y(m_Rotation[1]) * matrix::rotate_z(m_Rotation[2]);
    DumpMatrixf(stdout, "matrix rot", rot);

    DumpVectorf(stdout, "position start", m_Position);

    // 2) now calculate the translation vector by multiplying the local-space walking direction with that matrix to find the world-space walking direction
    // I assume here your nomal walking direction in object space is {0, 0, -1} change it if you use a different one
    vector translation = rot * vector(0.0f, 0.0f, -1.0f, 0.0f);
    // multiply it with the "Speed"
    translation = translation * speed;
    DumpVectorf(stdout, "translation", translation);

    // 3) add the final translation to the position
    m_Position = m_Position + translation;
    DumpVectorf(stdout, "position final", m_Position);

    return 0;
}

```

The output of the example:

```
matrix rot     :
  row0:   0.877583   0.000000   0.479426   0.000000
  row1:   0.403423   0.540302  -0.738460   0.000000
  row2:  -0.259035   0.841471   0.474160   0.000000
  row3:   0.000000   0.000000   0.000000   1.000000
position start :   2.000000   3.000000   0.000000   1.000000
translation    :  -1.438277   2.215381  -1.422480   0.000000
position final :   0.561723   5.215381  -1.422480   1.000000

```

# Answer
> 0 votes
> Basically, it should move in whatever direction the camera is looking.

Assuming you have a view matrix representing the inverted position/orientation of the camera, You already have this direction without needing to calculate it.

```
Matrix myNewMatrix = view.Invert();

float3 directionToMovePlayer = new float3(-myNewMatrix.m31, -myNewMatrix.m32, -myNewMatrix.m33);

```

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


# Question
Title: SAT, How Do I Find The Penetration Vector?
I've just successfully implemented Separating Axis Theorem (SAT) in my game but I was wondering how do I find the penetration vector? I heard it can be useful for collision response. e.g. The harder they collide the harder the response.

I want the penetration vector so I apply it to the position of an object when it is current penetrating an other so I can move it back outside of the other object's bounds.

Here is my code so far.

Any help would be much appreciated,

Thanks in advance.

# Answer
The classic way to do this is the GJK algorithm. It's a fairly complicated algorithm with a lot of moving parts, so might be tricky to implement. However, there are many implementations out there on the Web that you might be able to adapt.

A simpler way to get an approximate penetration vector might be to leverage the SAT itself; when you iterate over all the possible separating axes and check for overlap on each, keep track of which axis has the *shortest* overlap and use that as the penetration vector.
> 4 votes

# Answer
You should be already calculating it, atleast kind of. When projecting shapes onto a normal you're checking if two projections are overlapping. To make this information more usefull, you should store that value, that value is the distance the two shapes need to be moved in a given direction to avoid collision. Now to calculate the actual penetration vector all you have to do is check which value was the smallest and that's your penetration vector. That's all.
> 1 votes

---
Tags: c++, opengl, collision-detection, separating-axis-theorem
---


title: How to generate closed curve?

text:
# Question
Title: How to generate closed curve?
How can I do that? I can generate simple beziers, but how can I generate a closed curve like this:

http://www.youtube.com/watch?feature=endscreen&NR=1&v=hlDYJNEiYvU

# Answer
> 6 votes
Just Google `closed bezier curve`, there are plenty of useful results, including one that has a code example It's just like a open bezier curve, but for the "next" point on your last point, you use the first point.

---
Tags: beziers, curves
---


# Question
Title: (XNA) What's a Good Database Program for a Turn-Based RPG?
I'll begin by saying that I feel my level of expertise matters here, and so I have about a year worth of experience as a programmer in the C# language and most of the .NET framework as a whole, but have scarcely worked with databases at all throughout my career so far. Can't exactly say why. Either way, I'm a bit of a beginner, although SQL/LINQ I am capable of working with once I have this question resolved. Moving on...

At home, I am developing a single-player (so only one person needs to access it) turn-based RPG in XNA. I have a lot of the logic done and the time has come for me to begin building a database for it.

**THE REQUIREMENTS:** There will be both dynamically written data not included with the program (such as the location in the world at which a player saved his game, that he may load in the same place) and read data that needs to be capable of being distributed easily with the program (such as a table containing stats of every monster).

**THE DESIRED BUT OPTIONAL PERKS:** Beyond these absolute requirements, ease of use is a second priority I want to focus on. My amatuer nature doesn't want me digging around on ground I am too unfamiliar with.

**MY ATTEMPTS AT RESEARCH:** I understand Access to be a simple-to-use (though oft frowned upon) choice that could work based on needing only one user to access the database at a time. SQL Server could also work, but I understand it to be more difficult to use based on my needs. And in both cases, I am not sure if there are complications associated with the distrubution of pre-loaded data with the programs. In this case, I think I should use an XML file to hold the data I want the game to come with, but I am not sure. Amidst all of this, I have also considered creating the .dbml right there in Visual Studio because it seems the simplest, but same issue: I don't know the limitations of capability and distribution.

I have tried to outline what I know and what I need to accomplish, as well as some of the options I have attempted to research, but ultimately, my knowledge has holes in it I can't find the answers to and I can't form a conclusive answer. Thus, I ask you kind people, based on the above, what is my best option for how to start building my game's database?

# Answer
> 6 votes
You don't need a database for a turn-based RPG, just store your save game data in an object and serialize it to disk. You can serialize binary or serialize to something readable like XML which you can then later import easily via the content pipeline importer.

Requiring users to have Access, or any other non-integrated database, installed next to your game is going to be quite the hassle. If you really really really need a relational database you should look at something that you can integrate so that users don't need to install a fully fledged database. An example is SQL server compact http://msdn.microsoft.com/en-us/library/aa983326.aspx.

# Answer
> 4 votes
Here is a link to a similar question

Basically any flat file (XML, JSON to name two) will do, you can also use SQLite with XNA 4.0. Or like Roy T stated, you can save game data in an object (Lists, custom class, dictionary list can provide very fast lookup)

Here are some samples from microsoft

---
Tags: xna, rpg, databases
---


# Question
Title: Can I use the default depth buffer when drawing to FBO?
How to attach default depth buffer to FBO? How to use depth renderbuffer buffer attached to FBO (after drawing to it) as a default depth buffer?

Basically I want to use the same depth buffer for both the FBO and backbuffer rendering.

# Answer
> 4 votes
You can't.

This is by design. OpenGL (and older versions of DirectX) were designed back in the days when windowed apps literally shared the same frame buffer. That meant that if you had two overlapped windows, the windows would be trying to use the exact same pixels from the color, depth, and stencil buffers. The windowing systems dealt with this via a hard-coded masking operation.

In other words, you do not own the default depth buffer, cannot change the default depth buffer, and cannot reliably read from the default depth buffer in the OpenGL API.

Your best bet is to just do all of your rendering in an FBO and then use a texture blit to get the final image into the default FBO.

---
Tags: opengl, shaders, glsl, depth-buffer
---