# Question
Title: Problems using easing equations in C# XNA
I'm having some trouble using the easing equations suggested by Robert Penner for ActionScript (http://www.robertpenner.com/easing/, and a Flash demo here) in my C# XNA game. Firstly, what is the definition of the following variables passed in as arguments to each equation?

```
float t, float b, float c, float d

```

I'm currently calculating the new X position of a sprite in the Update() loop, however even for the linear tween equation I'm getting some odd results. I'm using the following values:

```
float t = gameTime.TotalGameTime.TotalMilliseconds;
float d = 8000f;
float b = x.Position.X;
float c = (ScreenManager.Game.GraphicsDevice.Viewport.Width >> 1) - (x.Position.X + x.frameSize.X / 2);

```

And this equation for linear easing:

```
 float val = c*t/d + b;

```

# Answer
> 4 votes
> Firstly, what is the definition of the following variables passed in as arguments to each equation?

The answer was in the link you provided:

* t = current time (starting from 0 and increasing up to the chosen duration)
* d = duration (i.e. total time of the animation)
* b = initial value
* c = change in value (i.e. how much the value should change, or the difference between the final value and the initial value)

Now for your troubles. Let's take a look at the values you chose for `t` and `d`:

```
float t = gameTime.TotalGameTime.TotalMilliseconds;
float d = 8000f;

```

I'm guessing you want your interpolation to take 8 seconds to complete, i.e. 8000 miliseconds. In that case the value of `t` should be starting a 0 on the first frame of the interpolation, and increment a little each frame until it reaches 8000, at which point you should stop updating because the interpolation is complete.

The problem is that you're passing it the value of `gameTime.TotalGameTime` which is the time that has passed **since the game began**, and you're supposed to pass it the time that has passed **since the animation has begun**. Here's the proper solution. First:

```
// Once at the start of the animation
// Note: I'll also use seconds instead of miliseconds
float t = 0f;
float d = 8f;
bool animating = true;

```

And then:

```
// Then once for each frame while the animation is active (i.e. in Update)
if(animating)
{
    t += gameTime.ElapsedGameTime.TotalSeconds;

    // Don't let time exceed the duration
    t = MathHelper.Min(t, d);

    // Calculate your "val" here
    float val = b + t/d * c;

    // Stop animating if we've reached the end
    if(t >= d)
        animating = false;
}

```

As for your other values, the value of `c` looks really cryptic and I'm not really sure what you're trying to do. But basically in this given context, `c` should be the amount of units you want your character to move.

Finally, unless you're trying to do some really fancy easing, I would just use one of the XNA's built in methods for this:

# Answer
> 4 votes
This are the meanings:

```
   t = TimeElapsed => Range[0, Duration]
   b = InitialValue;
   c = FinalValue - InitialValue;
   d = Duration;

```

I have a similar code to this for every easing function:

```
     public static partial class Tweening {
        public static class Quartic {
            public static float EaseIn( float t, float b, float c, float d ) {
                return c * (t /= d) * t * t * t + b;
            }
            public static float EaseOut( float t, float b, float c, float d ) {
                return -c * ((t = t / d - 1) * t * t * t - 1) + b;
            }
            public static float EaseInOut( float t, float b, float c, float d ) {
                if ( (t /= d / 2) < 1 ) {
                    return c / 2 * t * t * t * t + b;
                }
                return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
            }
        }
    }

```

And if you make an Animator class you can use a delegate method like this:

```
   public delegate float TweeningFunction( float timeElapsed,
                                           float start,
                                           float change,
                                           float duration );

```

This way you can change easily the Animator behaviour changing the ease function...

```
   public Movement {
       public TweeningFunction Function;
       ....
   }

   MovementInstance.Function = Tweening.Quartic.EaseIn;

```

In this video I used this approach... you can see it at the code shown at first seconds..

http://www.youtube.com/watch?v=4QDeY15Ox-g

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


# Question
Title: Send regular keyboard samples OR keyboard state changes over network
Building a multi player asteroids game where ships compete with each other. Using UDP. Wanted to minimize traffic sent to server. Which would you do:

1. Send periodic keyboard state samples every from client every to match server physics update rate e.g. 50 times per second. Highly resilient to packet loss and other reliabilty problems. Out of date packets disacarded by server. Generates a lot of unnuecessary traffic.
2. Only send keyboard state when it changes (key up, key down). Radically less traffic sent from client to server. However, UDP can lose packets without you being informed. So the latter method could result in the vital packet never being resent unless I detect and resend this in a timely manner.

# Answer
I'd say 2: as you state, solution 1 would generate too much traffic. There's a chance it works in the beginnings, but then when you'll add other things to send you might have to reduce the input updates frequency and thus you game reactivity. As a rule of thumb, sending deltas instead of complete states is most of the time The Right Thing to do.

You're right in telling that:

> UDP can lose packets without you being informed

But any proper networking subsystem, even built on UDP, will allow you to choose to send your infos with some form of acknowledgement. So you could send critical keyboard inputs reliably, and the rest not-so-reliably.
> 4 votes

# Answer
Send only the state changes, and at relatively longer intervals send a complete status, so that even if a packet got lost after a while you would reset to a correct value.

Furthermore, you can number the udp packets, so that you would know if you are losing too many of them.
> 3 votes

# Answer
Since the server is authoritative on position, this means that you will have significant perceived lag and an extremely poor user experience under many realistically sub-par network conditions.

While your situation is not as complex, I recommend reading older articles about the development of Unreal, Quake, and Counter Strike. I'm having trouble tracking them down now, and I apologize for my lack of Google-Fu, but all three engines had some excellent articles written by the developers back in the day on the precise difficulties they had creating smooth online play and how they resolved them.

Some points that I remember:

* When you take an input event, record the time of the event as related to the timestamp of the world that the player is seeing. So if the player is seeing frame 33271 when they press the shoot button, the event might be `33271:shoot` that is returned to the server. This allows the server to take latency into account, and calculate things like 'at that moment, the player was aiming right at the enemy, even though 0.2 seconds later when I got the event they no longer were'. Without this, the player presses shoot and 0.2 seconds later a missile starts shooting from their ship. **With** this type of prediction, a player presses shoot and 0.2 seconds later the missile appears on their screen, but farther out as if it had already been traveling for 0.2 seconds. This allows for precise and responsive controls regardless of latency.
* Repeat important events until you get an acknowledgement. In the above example, every packet from the player to the server will include `33271:shoot` until the client receives an acknowledgement of that event. If the first and second packet are lost, it will still get there in the third to be acknowledged. In addition, since the event is timestamped the server can still treat the attack as if it happened at the correct time, rather than being delayed due to network packet loss.
* The server should keep a state queue of the last second or so, so that it can determine the proper result of actions that happen in the past... 0.5 seconds ago, was the asteroid lined up with the laser blast? This reduces or eliminates conflicts between the player thinking they hit, but the server thinking they missed. Depends on the first point to work.
* Interpolate values on the client. Client side prediction is hard to get right, and can cause some warping effects, but is essential in creating a smooth experience for the player. Asteroids that are rotating will continue to rotate until disturbed obviously, and the client shouldn't need to get the location of the asteroid every tick. In the same way that client input is repeated until acknowledged, important game state changes should do the same from the server to the client.

I'm sure there are other considerations I've forgotten, and I apologize for not having links to the excellent and informative articles I've read in the past. Some (such as the ones I read about Quake World) are over 15 years old, when online gameplay was a new field. I suspect some of the articles I read were via the old finger protocol on Unix systems, a popular way for developers to interact with fans in the early days.
> 1 votes

---
Tags: networking, keyboard, synchronization, udp
---


# Question
Title: Using a particular font in a commercial game
I'm working on a game I intend to sell, and I want to use this font. The license says:

> "You may NOT copy or distribute the font outside of the licensed household, company, school or institution. Please ask external contacts who want to use the font to purchase their own license at www.CheapProFonts.com."

However, my plans are to use a tool to output a texture using this font to use as a bitmap font in my game. Does this mean I can do so, and sell my game with the font in it?

# Answer
I'm speaking on behalf of CheapProFonts. ;) Obtaining a license for one of our fonts for inclusion in a software is easy and inexpensive: Just let us know that the font you purchase IS for that purpose, and then purchase two licenses for the font.

So for $20 you will be allowed to include the font in your game and distribute as many copies of that game as you want to. No limit. If you make a demo of the game (=another binary/program so to speak) you should also purchase a $20 license for that. And if you make a sequel, another license @ $20 for that. And so on. One double license per font per software. And a credit would be nice ;)

I hope you find our licensing scheme easy and affordable.

Kind regards

Roger
> 14 votes

# Answer
(Disclaimer: I am not a lawyer)

**In the United States** a font *face* is not copyrightable (Eltra Corp. v. Ringer, 579 F.2d 294 (4th Cir. 1978)). But font *software* is copyrightable. A TrueType font (such as one you might download from cheapprofonts.com) contains instructions for how to render that font and is therefore a copyright piece of software.

A bitmap font that you create based on such a font is also font software (instructions for how to render that font) - and it is a derivative work of the original font software. To distribute it requires that you have a licence for creating and distributing derivative works of the original font.

(**EDIT**: This was the prevailing wisdom at the time this answer was written. It may not actually be true. See comments and this link for details.)

A way around this is to pre-render all your text. This way you are not distributing software instructions for rendering that font, you have merely *used* those software instructions to create an image.

Outside the United States? Ask a real lawyer :)
> 13 votes

# Answer
If the output bitmap matches the look of the font (the typeface) then it essentially IS the font, and yes you would be violating the license.

> You may embed the font in electronic documents, but you may NOT include the font in a software product - this requires a special license.

Even though it's just an image it would still be the exact font, which is the point. And this would obviously be a software product.

My best suggestion to you is to examine what you like about the font. What characters cause it to stand out to you or cause it to look good, what features (i.e. the roundedness, the thickness, the "bubble" shape, etc.) and then use a font creator package to create your own font which has these same features, so that it looks similar but is obviously not the same and was created from scratch. In the process you might find one or two characters which don't quite look good to you in the original font, but by creating them yourself you can fix them and make it even better.

Alternatively, you could ask them exactly what that "special license" is that they mentioned in the section I quoted above. Perhaps you can spend a bit more money and buy a special commercial software license for the font. Depending on how much you consider your time worth, this could be the better option over taking the time to create an imitation font.
> 6 votes

# Answer
Using it that way would not be allowed. You're not allowed to use or copy fonts in any way, up to and including in printed material, without a license to do so.

Luckily, there are many sources of free and free-to-license fonts out there. Chances are very good you can find an acceptable alternative.
> 3 votes

# Answer
> "may NOT copy or distribute the font outside of the licensed household, company, school or institution. Please ask external contacts who want to use the font to purchase their own license at www.CheapProFonts.com."

If you plan to sell the game with their font in it (whether you transfer it to a bitmap or not doesn't matter), then you are distributing it outside of the scope of the license so you will need to contact CheapProFonts (whom I presume are the owners of the font) for a commercial license.
> 2 votes

# Answer
Font makers cannot rewrite copyright law. If it is just an image of the font they hav no legal grounds. It it is an outline then they do.
> -4 votes

---
Tags: legal, distribution, commercial, fonts
---


# Question
Title: Anyone can suggest some Game Frameworks for GNU/Linux?
So I've been developing a little bit with XNA + C# in Windows, not really much: just some 2D stuff, but I've found that XNA is a really good framework.

I'm a GNU/Linux user, and I'm definitely migrating my desktop to Gentoo Linux (I've been using Arch in my laptop for a while now).

But, of course, I need a C# + XNA alternative... I'm not really an expert in any language, so I can really pick up anything (except, maybe, Functional ones), I prefer C-Like languages like Java or Ruby, I tried Python but found the Whitespace syntax confusing.

I would like to hear some of you'r suggestions, I'm not asking for "the best", but for "some suggestions", so I think this is objective enough.

Probably you're going to suggest C++ + SDL, but I would prefer something more "High Level" like XNA, but I'm open to discuss anything.

So... any ideas ?

**Note:** I think this questions meets the guidelines for this site, if it doesn't: please not only downvote this question, but comment on what can I do to improve it. Thanks.

**PS: 2D Games, not 3D**

# Answer
> 1 votes
> But, of course, I need a C# + XNA alternative...

Not necessarily try MonoGame. Otherwise I hear good things about Love.

# Answer
> 0 votes
If you like XNA and C#, try MonoGame, and continue working with the tools you already know.

PyGame is a popular choice for Python programmers, and fairly popular in general I'd say.

You can also go the browser/HTML5 route and use something like Crafty, and hit multiple platforms (including mobile, and of course Linux) very easily.

# Answer
> 0 votes
If you want to code in Ruby, Gosu is a lightweight framework that gives you a basic game loop and and 2D drawing support (quads, images and fonts). There is also Chingu which builds on top of Gosu and adds alot off extra stuff like animations, a basic game object, etc.

For Java, there is Slick2D but i haven't used that in ages, so no idea if it is still developed/supported

---
Tags: xna, linux
---


# Question
Title: How much server bandwidth does an average RTS game require per month?
My friend and I are going to write a multiplayer, multiplatform RTS game and are currently analyzing the costs of going with a client-server architecture.

The game will have a small map with mostly characters, not buildings (think of DotA or League of Legends). The authoritative game logic will run on the server and message packet sizes will be highly optimized.

We'd like to know *approximately* how much server bandwidth our proposed RTS game would use on a monthly basis, considering these theoretical constants:

1. 100 concurrent users maximum
2. 8 players maximum per game
3. 10 ticks per second

Bonus: If you can tell us approximately how much server RAM this kind of game would use that would also help a great deal.

Thanks in advance.

# Answer
> 3 votes
As @royT suggested the best solution would be letting players to host their own games. although you will end up developing a match-making server, but the costs for that one is much more cheaper than a dedicated game server.

But other than that Option let's do some multiplications. first of all you need to check how much data you need to send per game-state. for example let's say there each player can own at most 100 units in the game, and each one can have a position in a plane with 16k\*16k resolution. which will result in roughly 28 bits of data for just position. let's say there are some extended data for these units. for example their type, hitpoint, experience and so on. for these extended data I guess reserving 20 bits is reasonable. so far we have computer 48 bits unit, multiply that by number of units and you'll get to 4800 bits for one play units in a game. for each player there are some other variable you need to send, for example how much money they own, or if they are chatting to other player. I guess assuming 200 bits average is more than enough, which will result in 5000 bits per player, knowing that each game consist of at most 8 players we will need 40Kbits or 5KB for just player data in each game-state. of course every player only needs to send his own data, but needs to receive game-states from all other players, so in total server needs to send 4375Bytes to each player and receive 625B from him. meaning exactly 5KB bandwidth for each player connected to server per tick. multiply that by number of ticks per second and you'll get to the 50KBps and multiply that number of seconds in a month (2592000) and you'll get to ~129GB bandwidth usage per month per player. so your server needs ~13TB bandwidth to handle all the traffic! I know these numbers seems a bit too much crazy but that's what you'll get by the values you provided.

but that's not how big RTS titles were implemented! I'm not sure how they did handle their transactions but they usually use less bandwidth for example:

* WarcraftIII : 3KBps down and 1KBps up.
* BattleForge : 5KBps down and 1KBps up.
* DotA2 : 10KBps down and 3KBps up.
* StrongHold crusader : 5KBps down and 3-4KBps up.

(note that all these numbers are what I can remember from the time I was/am playing those games)

putting these numbers as a base you can see there still is a huge bandwidth usage server needs to handle (maybe around 1TB per month).

# Answer
> 1 votes
You've got some of the numbers you need for your estimate, but not all. The main thing you don't have is what data packets are going to be sent, and how big they are.

For example, if you know you have 100 players and 10 ticks per second, and you're assuming each tick means a data packet being sent from the server to every game to say, "Here is the current game state", that translates to 100 players * 10 packets/sec * DATA\_PACKET\_SIZE bytes per second. Item in caps is something you don't have yet.

Another one you need is how big a command packet is from the client to server. That is, if a player makes a move or hits a key or takes an action, that's a packet sent from client to server. So 100 players * ESTIMATED\_COMMANDS\_PER\_SECOND\_MAX * COMMAND\_PACKET\_SIZE = estimated data per second for players.

---
Tags: client-server, rts
---


title: On screen controller for libgdx games?

text:
# Question
Title: On screen controller for libgdx games?
Does anyone know a better controller for 2D Games than a virtual on screen joystick? The pros of the joystick are:

* Easy to implement for developers
* Familiar interface for users

But there is a huge con:

* The screen is obscured by thumbs.

And also, is there any library for a quick implementation of virtual joysticks for Libgdx?

# Answer
> 4 votes
Personally, I've found most "on screen joysticks" pretty lame, no matter how slickly they're implemented. Its a pretty clear case of taking a solution from a different technology (consoles/arcades) and trying to apply it to a new and rather different technology (multi-touch screens), and resulting in a mess. So, I'd add some more "cons" to your list that the joysticks give no natural feedback (e.g., for resting at neutral, or reaching a limit of the joystick on any axis, or knowing if your thumb is "on" the button or not).

On one of the recent Google Android Developer Hangouts (Mar 30, 2012), the Google folks reviewed 'Overkill' and I remember them commenting on how they liked they way it improved on the virtual "joystick".

'Neil Rajah' is a new (libGDX-based) game with a nice twist on the standard joystick. Its like Canabalt in that your character auto-runs, but left and right thumbs control jumping and attack respectively. I thought it was reasonably well done, and a compromise that worked well enough with the limits of multi-touch. (On second thought, it hardly qualifies as a joystick ... but maybe that's my point.)

I suggest you edit the question to be less libgdx specific and more about generic multi-touch (unless I'm mis-reading your intention). There may be games on other multi-touch platforms that do innovative things with virtual input controllers that would be worth"borrowing".

# Answer
> 0 votes
From my experience with Libgdx, you will more than likely need to write up your own system. While it may be a solid learning experience, it will not be the fastest route. I suggest you hop on the LIBGDX IRC and ask around. That always helped me. :)

Libgdx is pretty simple to override, however, because it uses the Table-Layout system it may be tricky to handle the positioning of UI elements dynamically.

Good luck!

---
Tags: libgdx, touch, controllers, multitouch
---


title: Duplicating Images in SFML

text:
# Question
Title: Duplicating Images in SFML
I was wondering how one would go about duplicating the same sprite in SFML, instead of having to create new sprites every time I would want have another sprite of the same image. Just some basic thought process or pseudo-code is what I'm looking for.

Thanks.

# Answer
> 3 votes
Well,

The whole idea of SFML sprites is to share a heavyweight object (texture) between all lightweight(sprite) that requires it. That is already the arguably best way.

Of course, there is one alternative, you can reuse the same sprite by just sharing it across your entities, and each one sets a new tranform before re-rendering the sprite. Im not even sure if that is anyway better than the first method, but seems to be what you want.

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


# Question
Title: How to chain actions/animations together and delay their execution?
I'm trying to build a simple game with a number of screens - 'TitleScreen', 'LoadingScreen', 'PlayScreen', 'HighScoreScreen' - each of which has it's own draw & update logic methods, sprites, other useful fields, etc. This works well for me as a game dev beginner, and it runs.

However, on my 'PlayScreen' I want to run some animations before the player gets control - dropping in some artwork, playing some sound effects, generally prettifying things a little. However, I'm not sure **what the best way to chain animations / sound effects / other timed general events is**.

I could make an intermediary screen, 'PrePlayScreen', which simply has all of this hardcoded like so:

```
Update(){
     Animation anim1 = new Animation(.....);
     Animation anim2 = new Animation(.....);
     anim1.Run();
     if(anim1.State == AnimationState.Complete)
          anim2.Run();
     if(anim2.State == AnimationState.Complete)
          // Load 'PlayScreen' screen
}

```

But this doesn't seem so great - surely their must be a better way? I then thought, 'Hey - an AnimationManager! That'd be awesome!'. But then that creeping OOP panic set in as I thought about it some more.

If I create the Animation in my Screen, then add it to the AnimationManager (which may or may not be a GameComponent hooked up to Update/Draw), how can I get 'back' to it? To signal commands like start / end / repeat? I'd still need to keep a reference to the object in my Screen so that I could still communicate with it once it's buried in the bosom of a List in my AnimationManager. This seems bad.

I've also tried using events - call 'Update' on all the animations in the PlayScreen update loop, but crucially all of the animations have a bool flag ('Active') which determines whether they should begin. The first animation has this set to 'true', all others 'false'. On completion the first animation raises an event, which sets animation 2's bool flag to true (and so it then runs). Once animation 2 is complete another 'anim complete' event is raised, and the screen state changes.

Considering the game I'm making is basically as simple as it gets I know I'm overthinking this... it's just the paradigm shift from web -\> game development is making me break out in a serious case of the *stupids*.

# Answer
**The Basic Framework**

Here's my solution to this common problem. First let's choose a name for an *action that spans several frames*, such as an animation. I'll call it a `Process` which is the terminlogy I found in this book, but *don't* mistake it with the processes on your OS, it's a different concept. In this context, a process is *anything* that needs to be updated, possibly several times, before it completes.

I'll start by defining a base class for our process. Something as simple as this is enough (I kept the name as Process for consistency with the discussion above, but since .NET already has a class named like that, you might want to give it another name):

```
public abstract class Process
{
    public abstract void Update(float elapsed);
    public bool Finished { get; set; }
}

```

Now let's create a class that serves as a process queue. You add processes to this queue, and they get executed in turn. This is where my implementation differs from the one in the book above. In the book every process is updated every frame, but in this case I'll make them *sequential* instead, so that the second process only starts when the first one ends. Once again it's a simple class:

```
public class ProcessQueue
{
    public void Add(Process process)
    {
        _processQueue.Add(process);
    }

    public void Update(float elapsed)
    {
        if (_processQueue.Count > 0)
        {
            _processQueue[0].Update(elapsed);
            if(_processQueue[0].Finished)
            {
               _processQueue.RemoveAt(0);
            }
        }
    }

    private readonly List<Process> _processQueue = new List<Process>();
}

```

And that's it, although you're free to add more methods, for example to clear the queue or to know how many processes are currently queued. Now just make your `Animation` class inherit from `Process` and chain them like:

```
// On startup
var processQueue = new ProcessQueue();

// Chain a few animations
processQueue.Add(new Animation(...));
processQueue.Add(new Animation(...));
processQueue.Add(new Animation(...));

// On Update
processQueue.Update(elapsed);

```

Note that you can create and chain all the processes you want before the game starts, because they only really start being executed when you call update for the first time on the queue.

When implementing the `Animation` class inheriting from `Process` make sure to set the `Finished` property to true when the animation ends, so that it will get removed from the queue.

*I think that probably already answers your question, but if you're interested in the subject, keep reading.*

---

**Bonus - Some Useful Processes!**

I might as well drop some useful types of processes for pretty much any type of game! Hopefully these will inspire you to make your own processes too.

First we have the `SleepProcess` which as the name implies, does nothing for a certain duration of time:

```
public class SleepProcess : Process
{
    public SleepProcess(float duration)
    {
        _duration = duration;
    }

    public override void Update(float elapsed)
    {
        _timer += elapsed;
        if(_timer >= _duration)
            Finished = true;
    }

    private float _timer;
    private readonly float _duration;
}

```

And sometimes you don't need a process that spans several frames - a single frame is enough. The following `GenericProcess` makes that easy:

```
public class GenericProcess : Process
{
    public GenericProcess(Action action)
    {
        _action = action;
    }

    public override void Update(float elapsed)
    {
        _action();
        Finished = true;
    }

    private readonly Action _action;
}

```

**Mixing Everything Together - An Example**

Here's how you can use these processes. Let's say for instance that you would like to play animation A, wait 2 seconds, play animation B, and finally write a message to the debugger. By using the processes above you can implement this entire sequence as four lines of code:

```
processQueue.Add(new AnimationProcess(...));
processQueue.Add(new SleepProcess(2));
processQueue.Add(new AnimationProcess(...));
processQueue.Add(new GenericProcess(() => Diagnostics.Debug("Message")));

```

And the only thing you need to do is remember to call `Update` on the process queue. Can you see how powerful this concept can be when properly used? Pretty much *everything* in your game can be considered as a process!

**What About Looping?**

What if I wanted to take the example above and *make it loop* infinitely? Well, this too, is extremely simple to implement with this framework, using a sort of "delayed recursive" call. Just put the processes you want to loop inside a function, and then add a `GenericProcess` at the end that adds that calls that function once more:

```
void LoopProcesses()
{
    processQueue.Add(new AnimationProcess(...));
    processQueue.Add(new SleepProcess(2));
    processQueue.Add(new AnimationProcess(...));
    processQueue.Add(new GenericProcess(() => Diagnostics.Debug("Message")));

    // Call LoopProcesses again after all of the above are finished
    processQueue.Add(new GenericProcess(LoopProcesses));
}

// Call once to start looping
LoopProcesses();

```
> 7 votes

---
Tags: xna, c#, game-loop
---


# Question
Title: Switching songs - MediaPlayer lags the game
When the player encounters a boss in the game I'm working on, I want to have the music change. It seems simple enough with the MediaPlayer class to fade out the current song, switch to another, and then fade the new song in. However, at the point where the second song starts, the game freezes for a split second. The songs in question aren't particularly large either - the first song is 1.7mb and the second song is 3.1mb, both mp3 format. This is the code I'm using to do it:

```
protected void switchSong(GameTime gameTime)
{
   if (!bossSongPlaying)
   {
      MediaPlayer.Volume -= ((float)gameTime.ElapsedGameTime.TotalSeconds/10);
      if (MediaPlayer.Volume < 0.05f)
      {
         MediaPlayer.Play(bossSong);
         MediaPlayer.Volume = 1.0f;
         bossSongPlaying = true;
      }
   }
}

```

What can I do to eliminate that momentary hang?

# Answer
I ended up using WMPlib, which seems to work a whole lot faster.
> 2 votes

# Answer
It looks like you have roughly the same problem as described here: http://forums.create.msdn.com/forums/p/44169/419462.aspx

The solution there seems to be the following.

In the loading screen of your level do the following for all the songs you would like to play in the level:

```
MediaPlayer.Play(backgroundSong);
MediaPlayer.Pause();

```

This way your songs are preloaded and should not cause a stutter.

Are more solid approach would be to switch to XACT, which ables you to use more advanced features of the XNA sound engine and doesn't seem to cause problems. Other people have noted that WAV files also don't cause problems, but this could make your game very large.
> 4 votes

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


# Question
Title: Is there a (family of) monotonically non-decreasing noise function(s)?
I'd like a function to animate an object moving from point A to point B over time, such that it reaches B at some fixed time, but its position at any time is randomly perturbed in a continuous fashion, but never goes backwards. The objects move along straight lines, so I only need one dimension.

Mathematically, that means I'm looking for some continuous f(x), x ∈ \[0,1\], such that:

* f(0) = 0
* f(1) = 1
* x \< y → f(x) ≤ f(y)
* At "most" points f(x + d) - f(x) bears no obvious relation to d. (The function is not uniformly increasing or otherwise predictable; I think that's also equivalent to saying no degree of derivative is a constant.)

Ideally, I would actually like some way to have a family of these functions, providing some seed state. I'd need at least 4 bits of seed (16 possible functions), for my current use, but since that's not much feel free to provide even more.

To avoid various issues with accumulation errors, I'd prefer the function *not* require any kind of internal state. That is, I want it to be a real function, not a programming "function".

# Answer
> 4 votes
For this post, y = f(t) where t is the parameter you vary (time/progress) and y is distance to target. So I will speak in terms of points on 2D plots where the horizontal axis is time/progress and the vertical is distance.

I think you can make a cubic Bezier curve with first point at (0, 1) and fourth (last) point at (1, 0). The two middle points can be randomly placed (x = rand, y = rand) within this 1-by-1 rectangle. I am unable to verify this analytically, but just from playing around with an applet (yeah, go ahead and laugh) it seems that the Bezier curve will never decrease with such a constraint.

This will be your elementary function b(p1, p2) which provides a non-decreasing path from point p1 to point p2.

Now you can generate a b(p(1) = (0, 1), p(n) = (1, 0)) and pick a number of p(i)'s along this curve such that 1

Essentially, you are generating one "general" path, and then breaking it up into segments and regenerating each segment.

Since you want a mathematical function: Suppose the above procedure is packaged into one function y = f(t, s) which gives you the distance at t for the function of seed s. You will need:

* 4 random numbers for placing the 2 middle points of the main Bezier spline (from (0, 1) to (1, 0))
* n-1 numbers for the bounds of each segment if you have n segments (the first segment always starts at (0, 1) ie t=0 and the last ends at (1,0) ie t=1)
* 1 number if you want to randomize the number of segments
* 4 more numbers for placing the middle points of the spline of the segment your t lands at

So each seed must supply one of the following:

* 7+n real numbers between 0 and 1 (if you want to control the number of segments)
* 7 real numbers and one integer greater than 1 (for a random number of segments)

I imagine you can accomplish either of these by simply supplying an array of numbers as the seed s. Alternatively, you could do something like supply one number s as seed, and then call the built-in random number generator with rand(s), rand(s+1), rand(s+2) and so on (or initialize with s and then keep calling rand.NextNumber).

Note that even though the whole function f(t, s) is made up of many segments, you are only evaluating one segment for each t. You *will* need to repeatedly calculate the boundaries of segments with this method, because you will have to sort them to make sure no two segments overlap. You can probably optimize and get rid of this extra work and only find the endpoints of one segment for each call, but it is not obvious to me right now.

Also, Bezier curves are not necessary, any suitably behaving spline will do.

I created a sample Matlab implementation.

The Bezier function (vectorized):

```
function p = bezier(t, points)
% p = bezier(t, points) takes 4 2-dimensional points defined by 2-by-4 matrix
% points and gives the value of the Bezier curve between these points at t.
%
% t can be a number or 1-by-n vector. p will be an n-by-2 matrix.
    coeffs = [
        (1-t').^3, ...
        3*(1-t').^2.*t', ...
        3*(1-t').*t'.^2, ...
        t'.^3
    ];

    p = coeffs * points;
end

```

The compound Bezier function described above (deliberately left unvectorized to make it clear how much evaluation is needed for each call):

```
function p = bezier_compound(t, ends, s)
% p = bezier(t, points) takes 2 2-dimensional endpoints defined by a 2-by-2
% matrix ends and gives the value of a "compound" Bezier curve between
% these points at t.
%
% t can be a number or 1-by-n vector. s must be a 1-by-7+m vector of random
% numbers from 0 to 1. p will be an n-by-2 matrix.
    %% Generate a list of segment boundaries
    seg_bounds = [0, sort(s(9:end)), 1];

    %% Find which segment t falls on
    seg = find(seg_bounds(1:end-1)<=t, 1, 'last');

    %% Find the points that segment boundaries evaluate to
    points(1, :) = ends(1, :);
    points(2, :) = [s(1), s(2)];
    points(3, :) = [s(3), s(4)];
    points(4, :) = ends(2, :);

    p1 = bezier(seg_bounds(seg), points);
    p4 = bezier(seg_bounds(seg+1), points);

    %% Random middle points
    p2 = [s(5), s(6)] .* (p4-p1) + p1;
    p3 = [s(7), s(8)] .* (p4-p1) + p1;

    %% Gather together these points
    p_seg = [p1; p2; p3; p4];

    %% Find what part of this segment t falls on
    t_seg = (t-seg_bounds(seg))/(seg_bounds(seg+1)-seg_bounds(seg));

    %% Evaluate
    p = bezier(t_seg, p_seg);
end

```

The script which plots the function for a random seed (note that this is the only place where a random function is called, the random variables to all other code are propagated from this one random array):

```
clear
clc

% How many samples of the function to plot (higher = higher resolution)
points = 1000;

ends = [
    0, 0;
    1, 1;
    ];

% a row vector of 12 random points
r = rand(1, 12);

p = zeros(points, 2);

for i=0:points-1
    t = i/points;
    p(i+1, :) = bezier_compound(t, ends, r);
end

% We take a 1-p to invert along y-axis here because it was easier to
% implement a function for slowly moving away from a point towards another.
scatter(p(:, 1), 1-p(:, 2), '.');
xlabel('Time');
ylabel('Distance to target');

```

Here's a sample output:

It seems to meet most of your criteria. However:

* There are "corners". This may be amenable by using Bezier curves more appropriately.
* It "obviously" looks like splines, although you can't really guess what it will do after a non-trivial period of time unless you know the seed.
* It very rarely deviates too much towards the corner (can be fixed by playing with the distribution of the seed generator).
* The cubic Bezier function cannot reach an area near the corner given these constraints.

# Answer
> 1 votes
I guess that instead of blending a bunch of transformed cosines (like the dot products in perlin noise give you), you could blend several monotonic functions that start at f(0)=0, like f(x) = x, or 2x, or x^2, etc. In fact since your domain is limited to 0=\>1 you could also blend in trig functions that fit the bill within that domain like cos(90\*x+270). To normalize your methods to end at 1, you can simply divide the weighted sum of these monotonic methods starting at f(0)=0 by f(1). Something like this should be fairly easy to invert as well (which I gather you want from the bit about stateless real functions versus programming functions).

Hope this helps.

# Answer
> 1 votes
One can analyze this crude picture You can end up with a function that performs your animation on the fly, by making use of an uniform rand function. I know this isn't the exact mathematical formula, but there's actually no mathematical formula for a random function, and even if there were one, you'd be coding a lot to achieve this. Considering you didn't specify any smoothness conditions, the speed profile is $C^0$ continuous (but since you're not dealing with robots, no need to worry about discontinuous acceleration profiles).

# Answer
> 1 votes
The usual way of generating an increasing sequence of N random numbers from \[0,1\] is to generate N random numbers in any range, then divide them all by their total sum, then sum them one-at-a-time to get the sequence.

```
Generate the sequence 2, 2, 5, 8, 6.
Their sum is 23, so our numbers to sum are 2/23, 2/23, 5/23, 8/23, and 6/23.
Our final sequence is 2/23, 4/23, 9/23, 17/23, 23/23

```

This can be extended to 2D by generating these values for both X and Y. You can increase N to get any granularity you want.

---

In @teodron's similar answer, you cited efficiency concerns with large time-scales. Without knowing the actual problem you're facing, I can't tell if that concern is valid; but another option would be to generate for *small* N, and simply smooth the result. Depending on the application, this may actually give *better* results.

*N=100, no smoothing*

*N=15, with smoothing*

# Answer
> 1 votes
I suggest this implementation inspired by the summation of octaves found in fractal noise, with a bit of cheap ass shuffling here and there. I believe it is reasonably fast and can be tuned by asking for fewer octaves than stored in the parameters with a loss of precision of about `1/2^octave`.

You could see it as a piecewise implementation that only requires *O(log(pieces))* time. The parameter array is used both for the divide-and-conquer pivot position, and for the distance traveled when reaching the pivot.

```
template<int N> struct Trajectory
{
    Trajectory(int seed = 0)
    {
        /* The behaviour can be tuned by changing 0.2 and 0.6 below. */
        if (seed)
            srand(seed);
        for (int i = 0; i < N; i++)
            m_params[i] = 0.2 + 0.6 * (double)(rand() % 4096) / 4096;
    }

    double Get(double t, int depth = N)
    {
        double min = 0.0, max = 1.0;
        for (int i = 0, dir = 0; i < N && i < depth; i++)
        {
            int j = (dir + 1 + i) % N;
            double mid = min + (max - min) * m_params[j];
            if (t < m_params[i])
            {
                dir += 1;
                t = t / m_params[i];
                max = mid;
            }
            else
            {
                dir ^= i;
                t = (t - m_params[i]) / (1.0 - m_params[i]);
                min = mid;
            }
        }
        t = (3.0 - 2.0 * t) * t * t; // Optional smoothing
        return min + (max - min) * t;
    }

    double m_params[N];
};

```

It could be made faster by pre-computing the floating point divisions, at the cost of storing three times as much information.

This is a quick example:

The example was obtained with the following code:

```
for (int run = 0; run < 5; run++)
{
    /* Create a new shuffled trajectory */
    Trajectory<12> traj;

    /* Print dots */
    for (double t = 0; t <= 1.0; t += 0.0001)
        printf("%g %g\n", t, traj.Get(t));
}

```

# Answer
> 0 votes
Thinking out loud, and admitting calculus is not my strong point... is this perhaps not possible? To avoid any obvious pattern, the average of the noise function over any change in x must be close to zero, and to guarantee monotonicity the amplitude of noise over that change in x must be smaller than the change in x, as any larger amplitude could result in a lower value at x' relative to x. But that would mean that as you reduce dx towards 0, such a function must also reduce dA (where A is amplitude) towards zero, meaning you get no contribution from any compliant noise function.

I can imagine it being possible to formulate a function that gradually decreases the noise contribution as x approaches 1, but that will give you a curved function that decelerates as x approaches 1, which is not what I think you want.

---
Tags: mathematics, animation, random
---


title: Crash when using datablocks

text:
# Question
Title: Crash when using datablocks
I have really throughly searched the net and could not find any solution for this so I ask for help here.

Anyway, I have this datablock in datablocks.cs:

```
    datablock t2dSceneObjectDatablock(EnemyShipConfig)
{
   canSaveDynamicFields = "1";
   Layer = "3";
   size = "64 64";
   CollisionActiveSend = "1";
   CollisionActiveReceive = "1";
   CollisionCallback = true;
   CollisionLayers = "3";
   CollisionDetectionMode = "POLYGON";
   CollisionPolyList = "0.00 -0.791 0.756 0.751 -0.746 0.732";
   UsesPhysics = "0";
   Rotation = "-90";
   WorldLimitMode = "KILL";
   WorldLimitMax = "880 360";
   WorldLimitMin = "-765 -436";

   minFireRate = "2000";
   maxFireRate = "1200";
   laserSpeed  = "800";
   minSpeed    = "100";
   maxSpeed    = "150";
};

```

This is an exact reproduction of an object that I have manually edited in the editor. So far, I just used clone() to get as many enemies as I need, while it was out of sight. It is a r-type style shooter, so I need a variable amount of enemies. Since clone() spams my log, I decided to use datablocks, since it is also more flexible.

That's what I get when I use clone():

> Con::execute - 0 has no namespace: onRemoveFromScene

However, once spawning begins, my game freezes and crashes:

```
    function SpawnEnemy()
{
    //%spawnedEnemy = EnemyShipMaster.clone(true);
    %spawnedEnemy = new t2dStaticSprite()
    {
       class         = "EnemyShip";
       sceneGraph    = $global_sceneGraph;
       datablock     = "EnemyShipConfig";
       imageMap      = "starshipImageMap";
       layer = 3;
    };

    %speed  = getRandom(%spawnedEnemy.minSpeed, %spawnedEnemy.maxSpeed);
    %y      = getRandom(-320, 320);

    // Set Properties
    %spawnedEnemy.setPositionX(700);
    %spawnedEnemy.setPositionY(%y);
    %spawnedEnemy.setVisible(true);
    %spawnedEnemy.setLinearVelocityX( -%speed );
    %spawnedEnemy.setTimerOn( getRandom( %spawnedEnemy.maxFireRate, %spawnedEnemy.minFireRate ) );
}

// Definition of $global_sceneGraph from game.cs:
$global_sceneGraph = sceneWindow2D.loadLevel(%level);

```

As I said, it works fine when I use clone() (which is commented out here), but my log gets spammed. I really hope someone can shed some light for me, this is driving me crazy.

# Answer
I found out what caused it:

First of all, in the documentation it says that you need the datablock with the Keyword "datablock". In a different place on the same page in the documentation it says you need to use "dataBlock".

The real and correct keyword is "config".

The following changed code works:

```
datablock t2dSceneObjectDatablock(EnemyShipConfig)
{
   canSaveDynamicFields = "1";
   Layer = "3";
   size = "64 64";
   CollisionActiveSend = "1";
   CollisionActiveReceive = "1";
   CollisionPhysicsReceive = "0";
   CollisionPhysicsSend = "0";
   CollisionCallback = true;
   CollisionLayers = "3";
   CollisionDetectionMode = "POLYGON";
   CollisionPolyList = "0.00 -0.791 0.756 0.751 -0.746 0.732";
   UsesPhysics = "0";
   Mass = "0";
   Rotation = "-90";
   WorldLimitMode = "KILL";
   WorldLimitMax = "880 360";
   WorldLimitMin = "-765 -436";

   minFireRate = "2000";
   maxFireRate = "1200";
   laserSpeed  = "800";
   minSpeed    = "100";
   maxSpeed    = "150";
};

function SpawnEnemy()
{
    %spawnedEnemy = new t2dStaticSprite(EnemyShip)
    {
       sceneGraph    = $global_sceneGraph;
       config        = "EnemyShipConfig";
       imageMap      = "starshipImageMap";
    };
    %speed  = getRandom(%spawnedEnemy.minSpeed, %spawnedEnemy.maxSpeed);
    %y      = getRandom(-320, 320);

    // Set Properties
    %spawnedEnemy.setPositionX(700);
    %spawnedEnemy.setPositionY(%y);
    %spawnedEnemy.setVisible(true);
    %spawnedEnemy.setLinearVelocityX( -%speed );
    %spawnedEnemy.setTimerOn( getRandom( %spawnedEnemy.maxFireRate, %spawnedEnemy.minFireRate ) );
}

```
> 0 votes

---
Tags: pc, torque
---


title: Using Nifty GUI with Slick2D

text:
# Question
Title: Using Nifty GUI with Slick2D
As seen here NiftyGUI has it's own GameState classes, I want to know if for adding UI to one state of my game I need to make that state `NiftyOverlayGameState` or still a `BasicGameState` but to add a `NiftyOverlayGameState` as well.

# Answer
From the documentation you linked, here are the different implementions you will have to use based on the functionality you desire:

> * **NiftyGame, NiftyBasicGame** \- Implementing the Game or the BasicGame, this classes are supposed to display only the Nifty-GUI over the entire game.
> * **NiftyGameState, NiftyBasicGameState** \- Implementing the GameState or the BasicGameState, this classes are supposed to display only the Nifty-GUI over the entire state of the game. This can be useful in for GUI-only states such as a login state.
> * **NiftyOverlayGame, NiftyOverlayBasicGame** \- Implementing the Game or the BasicGame, this classes are supposed to display the Nifty-GUI on top of something else. For example on top of the actual game graphics.
> * **NiftyOverlayGameState, NiftyOverlayBasicGameState** \- Implementing the GameState or the BasicGameState, this classes are supposed to display the Nifty-GUI on top of something else, such as the game graphics.
>
> This means if you want to add the NiftyGUI to just one state of your game, you should probably use the **NiftyGameState** or **NiftyBasicGameState**.

Then depending on your requirements you'll extend the Slick2D game state with this:

`protected void initGameAndGUI(GameContainer container, StateBasedGame game) throws SlickException;`

Then inside that you'll call this:

`protected final void initNifty(GameContainer container, StateBasedGame game, ...);`

For more details, read up on the Preparation and Slick2D-Game Implementations manual.
> 4 votes

---
Tags: java, gui, slick
---


title: How to handle circle penetration

text:
# Question
Title: How to handle circle penetration
I've been working on circle to circle collision and have gotten the intersection method working correctly, but I'm having problems using the returned values to actually separate the circles from one another.

This is the method which calculates the depth of the circle collision

```
public static Vector2 GetIntersectionDepth(Circle a, Circle b)
{
    float xValue = a.Center.X - b.Center.X;
    float yValue = a.Center.Y - b.Center.Y;

    Vector2 depth = Vector2.Zero;

    float distance = Vector2.Distance(a.Center, b.Center);

    if (a.Radius + b.Radius > distance)
    {
        float result = (a.Radius + b.Radius) - distance;
        depth.X = (float)Math.Cos(result);
        depth.Y = (float)Math.Sin(result);
    }

    return depth;
}

```

This is where I'm trying to apply the values to actually seperate the circles.

```
Vector2 depth = Vector2.Zero;
for (int i = 0; i < circlePositions.Count; i++)
{
    for (int j = 0; j < circlePositions.Count; j++)
    {
        Circle bounds1 = new Circle(circlePositions[i], circle.Width / 2);
        Circle bounds2 = new Circle(circlePositions[j], circle.Width / 2);

        if(i != j)
            depth = CircleToCircleIntersection.GetIntersectionDepth(bounds1, bounds2);

        if (depth != Vector2.Zero)
        {
            circlePositions[i] = new Vector2(circlePositions[i].X + depth.X, circlePositions[i].Y + depth.Y);
        }
    }
}

```

# Answer
> 6 votes
I think the way that makes more sense is to have each circle move back half of the depth, instead of moving only one of the circles.

That should be as easy as adding half of the penetration depth to each circle but in opposite directions:

```
circlePositions[i] -= depth / 2f;
circlePositions[j] += depth / 2f;

```

But that's assuming you're calculating the intersection depth correctly. Your method looks a bit shady though. For instance you're calculating those `xValue`and `yValue` variables but you're never using them. Either way, here's a simpler implementation:

```
public static Vector2 GetIntersectionDepth(Circle a, Circle b)
{
    Vector2 direction = b.Center - a.Center;
    float distance = direction.Length();
    direction.Normalize();
    float depth = (a.Radius + b.Radius) - distance;
    return depth > 0 ? depth * direction : Vector2.Zero;
}

```

There's also a bigger problem at hand which is that when separating the circles you could be creating new intersections between circles that you already handled earlier in the loop.

And to close it off, here's a simplified and optimized version of your loop above (although it still doesn't solve the problem I just mentioned above):

```
float radius = circle.Width / 2f;
int count = circlePositions.Count;
for (int i = 0; i < count; ++i)
{
    for (int j = i + 1; j < count; ++j)
    {
        Circle bounds1 = new Circle(circlePositions[i], radius);
        Circle bounds2 = new Circle(circlePositions[j], radius);
        Vector2 depth = GetIntersectionDepth(bounds1, bounds2);
        if (depth != Vector2.Zero)
        {
            Vector2 halfDepth = depth / 2f;
            circlePositions[i] -= halfDepth;
            circlePositions[j] += halfDepth;
        }
    }
}

```

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


title: Android frame by frame PNG animation

text:
# Question
Title: Android frame by frame PNG animation
I am new at Android game development. I have done some apps before, but none of them are games :)

So, I wanted to do a frame-by-frame animation of PNGs. I tried with AnimationDrawable, but OutOfMemory error comes quickly (I have a lot of PNGs). So I came upon SurfaceView. But I am stuck, because I really don't find any useful tutoirals/examples.

What is the best way to make an animation like this?

Here there already is a great answer to almost the same question, but all the links there don't work anymore.

I would really like to here suggestions how to make an animation frame-by-frame with PNGs in Android and if you have any tutorials or examples, I will be really happy :)

**EDIT**

I thought wrong about sprites, I think... Sorry, but I am a noob at game developing :) I have 60 PNG pictures (40kb, 427\*420px each - on disk) which I would like to put in a animation. Is this even possible to do it with frame by frame animation?

The most similar and famous game that is close to mine is Talking Tom (but I don't know if they have frame-by-frame or any other method for animation).

# Answer
> 1 votes
The Android APIs (like SurfaceView) are only really helpful for the simplest style of games like a simple puzzle game with no animations. If you are looking to create a game with a number of animated characters and any kind of complex gameplay, you're going to want to go another route. I suggest using OpenGL ES for the graphics and either a physics library like Box2D or build off of an existing engine like AndEngine. It really depends on what kind of game you want to make.

---
Tags: java, android, animation
---


# Question
Title: Best Tutorials for Learning XNA (VB 2010)
> **Possible Duplicate:**
> XNA development tutorials

I'm looking for some good tutorials for XNA 4.0 (with VS 2010) using VB. I've been looking on google and can't find much that's useful. So does anyone know some good sites or videos I can watch to teach me the basics. I know how to write in VB so just the basics and tips for XNA. I am hoping to make a 2D game.

# Answer
I strongly recommend you to use C# for programming XNA since is the primary language for it.
> 0 votes

---
Tags: xna-4.0
---


# Question
Title: Can J2EE be used to implement games ? Is there any connection between J2EE and games?
Making an game using applets, but have to implement project using J2EE. Is there any sense in making a game with using J2EE for implementation ?

Our teacher said that we can make games for the java project, now she has put in the requirement that we have to use J2EE, and expects us to make the game. Where does J2EE comes in the picture ?

# Answer
J2EE is the superset for Java SE and Java ME, meaning that you have as many libraries available as you would for those two.

Now, it does not make much sense choosing EE, because most of the additions are oriented to big servers and databases.
> 2 votes

# Answer
As Ef Es said J2EE is the superset for J2SE. Your teacher may have wanted you to use either a database or a server for your game to communicate with.
> 0 votes

---
Tags: java
---


# Question
Title: How to avoid game objects accidentally deleting themselves in C++
Let's say my game has a monster that can kamikaze explode on the player. Let's pick a name for this monster at random: a Creeper. So, the `Creeper` class has a method that looks something like this:

```
void Creeper::kamikaze() {
    EventSystem::postEvent(ENTITY_DEATH, this);

    Explosion* e = new Explosion;
    e->setLocation(this->location());
    this->world->addEntity(e);
}

```

The events are not queued, they get dispatched immediately. This causes the `Creeper` object to get deleted somewhere inside the call to `postEvent`. Something like this:

```
void World::handleEvent(int type, void* context) {
    if(type == ENTITY_DEATH){
        Entity* ent = dynamic_cast<Entity*>(context);
        removeEntity(ent);
        delete ent;
    }
}

```

Because the `Creeper` object gets deleted while the `kamikaze` method is still running, it will crash when it tries to access `this->location()`.

One solution is to queue the events into a buffer and dispatch them later. Is that the common solution in C++ games? It feels like a bit of a hack, but that might just be because of my experience with other languages with different memory management practices.

In C++, is there a better general solution to this problem where an object accidentally deletes itself from inside one of its methods?

# Answer
**Don't delete `this`**

**Even implicitly.**

***\- Ever -***

Deleting an object while one of its member functions is still on the stack is begging for trouble. Any code architecture which results in that happening ("accidentally" or not) is **objectively bad**, is **dangerous**, and should be **refactored immediately**. In this case, if your monster is going to be allowed to call 'World::handleEvent', **do not, under any circumstances, delete the monster inside that function!**

(In this specific situation, my usual approach is to have the monster set a 'dead' flag on itself, and have the World object -- or something like it -- test for that 'dead' flag once per frame, removing those objects from its list of objects in the world, and either deleting it or returning it to a monster pool or whatever is appropriate. At this time, the world also sends out notifications about the deletion, so other objects in the world know that the monster has stopped existing, and can drop any pointers to it that they might be holding. The world does this at a safe time, when it knows that no objects are currently processing, so you don't have to worry about the stack unwinding to a point where the 'this' pointer points at freed memory.)
> 39 votes

# Answer
Instead of queuing events in a buffer, queue up *deletions* in a buffer. Delayed-deletion has the potential to massively simplify the logic; you can actually free up memory at the end or beginning of a frame when you know nothing interesting is happening to your objects, and delete from absolutely anywhere.
> 21 votes

# Answer
Instead of letting the world to handle the deletion you could let another class's instance to serve as a bucket to store all deleted entities. This particular instance should listen to `ENTITY_DEATH` events and handle them such that it queues them up. The `World` can then iterate over these instances and perform post-death operations after the frame has been rendered and 'clear' this bucket, which in turn would perform the actual deletion of entities instances.

An example of such a class would be like this: http://ideone.com/7Upza
> 4 votes

# Answer
You can implement managed-memory in C++ yourself, so that when `ENTITY_DEATH` is called, all that happens is the number of its references is reduced by one.

Later as @John suggested at the begging of every frame you can check which entities are useless (those with zero references) and delete them. For example you can use `boost::shared_ptr<T>` (documented here) or if you are using C++11(VC2010) `std::tr1::shared_ptr<T>`
> 2 votes

# Answer
Use pooling and don't actually delete objects. Instead, change the data structure they are registered to. For example for rendering objects there is a scene object and all the entities somehow registered to it for rendering, collision detection etc. Instead of deleting the object, detach it from the scene and insert into a dead objects pool. This method will not only prevent memory problems (such as an object deleting itself) but also may speed up your game if you use the pool correctly.
> 2 votes

# Answer
I would suggest implementing a factory that's used for all game object allocations in the game. So instead of calling new yourself, you would tell the factory to create something for you.

For example

```
Object* o = gFactory->Create("Explosion");

```

Whenever you want to delete an object, the factory pushes the object in a buffer that is cleared the next frame. Delayed destruction is very important in most scenarios.

Also consider sending all messages with a delay of one frame. There is only a couple of exceptions where you need to send immediately, that vast majority of cases however just
> 2 votes

# Answer
What we did in a game was use placement new

```
SomeEvent* obj = new(eventPool.alloc()) new SomeEvent();

```

the eventPool was just a big array of memory which was carved up, and the pointer to each segment was stored. So alloc() would return the address of a free block of memory. In our eventPool the memory was treated as a stack, so after all the events had been sent we'd just reset the stack pointer back to the start of the array.

Because of the way our event system worked we didn't need to call the destructors on the evetns. So the pool would simply register the block of memory as free, and would allocate it.

This gave us a huge speed up.

Also ... We actually used memory pools for all dynamically allocated objected in development, as it was a great way of finding memory leaks, if there was any objects left in the pools when the game exited (normally) then it was likely there was a mem leak.
> 1 votes

---
Tags: c++, scene-graph
---


# Question
Title: When should one use the Abstract, Implements, or extends keywords?
I'm just now moving from a beginner to intermediate level android programmer in the java language. i can successfully write a game framework of classes that work together to accomplish a task beyond basic things, like hello world. but i'm having issues with some pretty basic OOP concepts; When should i derive from an abstract class? When is it more efficient to use an Interface instead of simply sub classing a parent?

Basically, between extends, implements, and the abstract keywords, which keywords should be used instead of the others? i'm not looking for a basic definition, as i know them. i need to no when and why i should apply them to my code? what advantages does one have over the other? which is best for game development?

---

Ok specifically what i'm talking about is that i have a game framework that looks like this:

Graphics interface

class screen implements graphics

Throughput interface

class keyreader implements throughput

GameThread extends thread

abstract character

class player extends character

class npc extends character

... are these good ways to write a game framework or should i stick to one type of OOP inheritance?

# Answer
> 4 votes
I'll try to approach this from a simplified and informal point of view. You should still turn to the bibliography and take some time to study object oriented concepts correctly. These are also only the most common uses, although there's other situations for them.

**Abstract Classes**

Should be used when it *doesn't make sense for an instance of the base class to be created*. Just take a look at the common begginer's example that presents a shape hierarchy:

You can find a way to describe any of the subclasses in very concrete terms (e.g. an ellipse has a center and two radius, a polygon is a collection of vertices, the others are specializations of the previous cases). On the other hand, a shape is an abstract concept in the sense that it can refer to any of the other cases, but you can't find a concrete definition for it. In sum, ask yourself the question:

> Is there enough information to create a meaningful instance of this class?

And if the answer is no, make it abstract.

**Interfaces**

Should be used when you have a *set of operations that you would like to see supported by several classes*, but you want those classes to *still be able to inherit (i.e. extend) from other classes*. Classes in java *can't inherit from multiple classes, but they can implement multiple interfaces*.

So let's say you had this interface and these two classes (sorry if the syntax is wrong, I'm a bit rusty on Java):

```
interface ITalk { void Talk(); }
class A extends ParentA implements ITalk {}
class B extends ParentB implements ITalk {}

```

Notice how they have completely different parents but still implement the same interface? Now you could make a method that *only cares if the object knows how to talk regardless of its parent*:

```
void SomeMethod(ITalk talkingObject) { talkingObject.Talk(); }

```

And call it with instances of either type:

```
A a = new A();
B b = new B();
SomeMethod(a);
SomeMethod(b);

```

Basically it's a *looser* kind of inheritance, that only concerns itself with *what the class has or can do* but not *how it does* \- which is why interfaces don't have implementations for their members.

---
Tags: java, architecture, interface
---


title: JBox2D applyLinearImpulse doesn't work

text:
# Question
Title: JBox2D applyLinearImpulse doesn't work
So i have this line of code:

```
if(input.isKeyDown(Input.KEY_W)&&canJump())
    {
        body.applyLinearImpulse(new Vec2(0, 30), cam.screenToWorld(body.getPosition()));
        System.out.println("I can jump!");
    }

```

My problem is that the console display `I can jump!` but the body doesn't do that. Can you explain to me if i do something wrong?

Some more code. This function creates my 'hero' the one supposed to jump.

```
private Body setDynamic(float width, float height, float x, float y)
{
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(width/2, height/2);

    BodyDef bd = new BodyDef();
    bd.allowSleep = true;
    bd.position = new Vec2(cam.screenToWorld(new Vec2(x + width / 2, y + height / 2)));
    bd.type = BodyType.DYNAMIC;
    bd.userData = new BodyInfo(width, height);

    Body body = world.createBody(bd);
    body.createFixture(shape, 10);

    return body;
}

```

And this is the main update loop:

```
if(input.isKeyDown(Input.KEY_A))
    {
        body.setLinearVelocity(new Vec2(-10*delta, body.getLinearVelocity().y));
    }
    else if (input.isKeyDown(Input.KEY_D))
    {
        body.setLinearVelocity(new Vec2(10*delta, body.getLinearVelocity().y));
    }
    else
    {
        body.setLinearVelocity(new Vec2(0, body.getLinearVelocity().y));
    }

    if(input.isKeyDown(Input.KEY_W)&&canJump())
    {
        body.applyLinearImpulse(new Vec2(0, 30), body.getPosition());
        System.out.println("I can jump!");
    }
    world.step(delta * 0.001f, 10, 5);

}

```

# Answer
Adding your update loop was useful :D

The problem is that you are overwriting the linear velocity each step.To move the player, apply forces. And do not set the speed, never.

Try something like this:

```
if(input.isKeyDown(Input.KEY_A))
{
    body.applyLinearForce(new Vec2(-3000, 0), body.getPosition());
}
else if (input.isKeyDown(Input.KEY_D))
{
    body.applyLinearForce(new Vec2(3000, 0), body.getPosition());
}

if (input.isKeyDown(Input.KEY_W) && canJump())
{
    body.applyLinearImpulse(new Vec2(0, 30), body.getPosition());
    System.out.println("I can jump!");
}

world.step(delta, 10, 5);
world.clearForces();

```
> 0 votes

---
Tags: java, box2d, physics
---


# Question
Title: How to keep a data structure synchronized over a network?
**Context**

In the game I'm working on (a sort of a point and click graphic adventure), pretty much everything that happens in the game world is controlled by an action manager that is structured a bit like:

So for instance if the result of examining an object should make the character say hello, walk a bit and then sit down, I simply spawn the following code:

```
var actionGroup = actionManager.CreateGroup();
actionGroup.Add(new TalkAction("Guybrush", "Hello there!");
actionGroup.Add(new WalkAction("Guybrush", new Vector2(300, 300));
actionGroup.Add(new SetAnimationAction("Guybrush", "Sit"));

```

This creates a new action group (an entire line in the image above) and adds it to the manager. All of the groups are executed in parallel, but actions *within* each group are chained together so that the second one only starts after the first one finishes. When the last action in a group finishes, the group is destroyed.

**Problem**

Now I need to replicate this information across a network, so that in a multiplayer session, all players see the same thing. Serializing the individual actions is not the problem. But I'm an absolute beginner when it comes to networking and I have a few questions. I think for the sake of simplicity in this discussion we can abstract the action manager component to being simply:

```
var actionManager = new List<List<string>>();

```

*How should I proceed to keep the contents of the above data structure syncronized between all players?*

Besides the core question, I'm also having a few other concerns related to it (i.e. all possible implications of the same problem above):

* If I use a server/client architecture (with one of the players acting as both a server and a client), and one of the *clients* has spawned a group of actions, *should he add them directly to the manager, or only send a request to the server, which in turn will order every client to add that group*?
* What about packet losses and the like? The game is deterministic, but I'm thinking that any discrepancy in the sequence of actions executed in a client could lead to inconsistent states of the world. *How do I safeguard against that sort of problem*?
* What if I add too many actions at once, won't that cause problems for the connection? Any way to alleviate that?

# Answer
**If I use a server/client architecture (with one of the players acting as both a server and a client), and one of the clients has spawned a group of actions, should he add them directly to the manager, or only send a request to the server, which in turn will order every client to add that group?**

You have three options in this case, two of which you have already mentioned. The choice of which option you take depends on a variety of factors that only you can be the best judge of:

**1:** Client spawns group of actions adds them directly and then sends them to the server. The server accepts it without any checks

\*Benefits of this approach are that as far as the client is concerned, their own actions gives them an instant feedback independent of the network delay. The disadvantage is that the client's *messages* are accepted by server as fact (which they may not be)\*

**2:** Client sends a request to the server, which in turn broadcasts the request to everyone, including the client that originated the request.

*Benefits of this approach are that the server is now is in control of everything that happens in the game which alleviates most issues with illegal activity (here illegal can range from the client clipping a wall to performing a move that is now illegal because the server has more information that the client did not have when the client made a particular move)*

**3:** Client spawns group of actions, adds them directly and then sends them to the server. The server processes the request, runs its own checks on the actions to make sure they are not illegal, and then broadcasts the move to all players including the client.

*This takes the best of both 1 and 2 at the cost of slightly more bandwidth requirements. The benefits are instant feedback to the client for their own moves and if the moves the client makes are illegal, the server takes appropriate actions (forcefully corrects the client).*

**What about packet losses and the like? The game is deterministic, but I'm thinking that any discrepancy in the sequence of actions executed in a client could lead to inconsistent states of the world. How do I safeguard against that sort of problem?**

Packet loss and extreme lag is a hard problem to fix. Different solutions (none of them perfect) are employed to deal with the problem depending on the type of the game (e.g. dead-reckoning). I will assume you game does not have to synchronize physics.

One of the first things you should be doing is time-stamping all your moves. Your system should then take these into account and *play* the moves accordingly (perhaps the server has this responsibility and then deny illegal moves). When implementing this system, assume 0 latency (test locally).

0 latency is of course, not a good assumption, even on local networks, so now that all moves respect time, which time do you trust? That's where the issue of time synchronization comes into play. Many articles/papers online will guide you to solving this proiblem.

**What if I add too many actions at once, won't that cause problems for the connection? Any way to alleviate that?**

First the obvious stuff. Never send strings or serialized objects. Don't send messages as fast as the game itself is updating. Send them in chunks (e.g. 10 times a second). There will be error (especially rounding error) that the server/client will need to fix the errors once in a while (so every second, the server sends everything \[everything = all data that is important to keep things in your game in the correct state\] which the client then *snaps* to and/or takes into account to correct its state). ***EDIT: One of my colleagues mentioned that if you are using UDP \[which you should, if you have lots of data\] then there is no network ordering. Sending more than 10 packets a second increases the changes of the packets arriving out of order. I'll see if I can cite that claim. As for out of order packets themselves, you can either discard them or add it to your system's message/move queue which is designed to handle changes in the past to correct the present state***

You should have a messaging system that relies on something that takes up very little space. If you have to send something that can only have two values, then send only one bit. If you know you can only have 256 moves, then send an unsigned char. There are various bit twiddling tricks to pack messages as tightly as possible.

Your messaging system will most likely make use of lots of enums to allow you to easily extract moves from an incoming message (I would suggest to take a look at RakNet and examples therein if you do not understand what I mean here).

I am sure you already know that you cannot *fix* issues that arise with hight latency and packet loss but you can make its effects less pronounced. Good luck!

***EDIT: Patrick Hughes's comment above with the link renders this answer incomplete and specific to OP's question at best. I would highly suggest reading the linked topics instead***
> 9 votes

---
Tags: architecture, networking
---


# Question
Title: Calculating the 2D edge normals of a triangle
What's a reliable way to calculate a 2D normal vector for each edge of a triangle, so that each normal is pointing outwards from the triangle?

To clarify, given any triangle - for each edge (e.g p2-p1), I need to calculate a 2D normal vector pointing away from the triangle at right angles to the edge (for simplicity we can assume that the points are being specified in an anti-clockwise direction).

I've coded a couple of hacky attempts, but I'm sure I'm overlooking some simple method and Google isn't being that helpful today - that and I haven't had my daily caffeine yet!

# Answer
This answer is for when the winding is unknown. As the question is now phrased, simply calculating the edge normal directly is entirely sufficient and trivial.

So, say you are trying to find the normal for edge AB. Take the normal (AB.y, -AB.x). Now dot this normal with the vector AC. If the result is positive, then the normal is facing towards the "inner" half-space, so invert the normal.

ex:

```
A = (3,4)
B = (2,1)
C = (1,3)

AB = (2,1) - (3,4) = (-1,-3)
AC = (1,3) - (3,4) = (-2,-1)
N = n(AB) = (-3,1)
D = dot(N,AC) = 6 + -1 = 5

since D > 0:
  N = -N = (3,-1)

```

You could also use the "2D cross product" (treat each vector as if it were a 3D vector with a Z component of zero) between AB and AC, test if the resulting Z component were positive or negative, and then take the RHS or LHS normal respectively of AB. I find the dot product approach to be simpler.
> 5 votes

# Answer
Here is a method that works:

* get a vector normal to the triangle, for instance `p1p2 ^ p1p3`
* for each edge, take the result of its cross product with that vector
* normalize

If your triangles are in a 2D space, you can use `(0 0 1)` as the normal vector and the results are (assuming `p1` has coordinates `(x1 y1)` etc.):

```
edgenormal(p1p2) = normalize(vec2(y2 - y1, x1 - x2))
edgenormal(p2p3) = normalize(vec2(y3 - y2, x2 - x3))
edgenormal(p3p1) = normalize(vec2(y1 - y3, x3 - x1))

```

This is assuming `p1p2p3` is anticlockwise.
> 2 votes

---
Tags: 2d, vector, normals
---


# Question
Title: How much to bake user input in a client-server?
Assume a client-server game where there server manages all state and the clients are simply rendering / input.

How much should I bake user input from the client before sending it off to the server?

Does it make sense to send *"jump"* or *"space keydown"*?

I'm inclined to bake the input as much as possible. Am I setting myself up for pain later?

# Answer
> 4 votes
I'd send "jump", reason being that it applies to each keyboard, gamepad, and AI. "space keydown" might be useful in some cases, but I can't think of any right now.

# Answer
> 1 votes
Speaking from MVC perspective, the client would be the View and the Controller, and the server would run the Model. One of the job of the Controller is to translate raw user input into model-appropriate input (i.e. Spacebar to Jump). Doing it this way will allow the client/controller to easily do key remapping, write alternative controller, and write alternative client (e.g. you might want a mobile-version and a desktop-version playing in the same server; with the controller translating them to mode-appropriate input, you woouldn't need to modify the server to add them).

---
Tags: networking, input, client-server
---


# Question
Title: What freeware frameworks and tools to choose if I want to build a game like Farmville or Club Penguin?
Say I like to experiment with multiplayer games and I do not want to reinvent the wheel and build yet another game server. I don’t mind configuring and writing wrappers and adapters (both in c++ and java) for the server.
What server does Farmville use? Is it Java or C based? What isometric flash engine do they use? What other examples can I look into to learn the subject?
Thanks.

# Answer
> 3 votes
One of your best bets is to look at SmartFoxServer Lite. It's free, but better packages cost money. It's basically a socket server that uses JSON for all its communication and works well with various clients.

(I haven't used it myself, but heard it recommended in the past.)

# Answer
> 2 votes
For your database needs, I'd highly recommend looking into Membase.

> Membase is the primary database for the popular FarmVille and Café World applications at Zynga; and it provides a shared data management platform for NHN, Korea’s largest web application operator with nearly 70 million unique users. - Membase Website

The engine Zynga uses to build FarmVille is highly custom, but this website links to various isometric flash engines and frameworks you may want to look in to.

# Answer
> 2 votes
Maybe this is a useful link which gives some insights: How FarmVille Scales to Harvest 75 Million Players a Month (also mind the related articles)

---
Tags: multiplayer, open-source, server
---


title: How does flocking algorithm work?

text:
# Question
Title: How does flocking algorithm work?
I read and understand the basic of flocking algorithm. Basically, we need to have 3 behaviors:
1. Cohesion
2. Separation
3. Alignment

From my understanding, it's like a state machine. Every time we do an update (then draw), we check all the constraints on both three behaviors. And each behavior returns a `Vector3` which is the "correct" orientation that an object should transform to. So my initial idea was

```
        /// <summary>
        /// Objects stick together
        /// </summary>
        /// <returns></returns>
        private Vector3 Cohesion() {
            Vector3 result = new Vector3(0.0f, 0.0f, 0.0f);
            return result;
        }

        /// <summary>
        /// Object align
        /// </summary>
        /// <returns></returns>
        private Vector3 Align() {
            Vector3 result = new Vector3(0.0f, 0.0f, 0.0f);
            return result;
        }

        /// <summary>
        /// Object separates from each others
        /// </summary>
        /// <returns></returns>
        private Vector3 Separate() {
            Vector3 result = new Vector3(0.0f, 0.0f, 0.0f);
            return result;
        }

```

Then I search online for pseudocode but many of them involve velocity and acceleration plus other stuffs. This part confused me. In my game, all objects move at constant speed, and they have one leader. So can anyone share me an idea how to start on implement this flocking algorithm? Also, did I understand it correctly? (I'm using XNA 4.0)

# Answer
> 5 votes
You really don't want constant velocity. Flocking is going to work and look better if the boids can speed up or slow down while flocking. Otherwise a separated boid may never be able to catch up to the flock.

This article has some very easy to read code (CoffeeScript), a decent explanation, and a pretty demo you can tweak:

http://harry.me/2011/02/17/neat-algorithms---flocking/

# Answer
> 3 votes
I would tend to assume you have already read through Reynold's (the guy who invented boids) page about flocking, but since you didn't directly mention it I'm going to link it here:

http://www.red3d.com/cwr/boids/

He gives great explanations of how several aspects of his flocking algorithms work, including Cohesion, Separation, and Alignment.

---
Tags: xna, algorithm, xna-4.0, ai
---


# Question
Title: Box2D platformer movement. Are joints a good idea?
So i smashed my brains trying to make my character move. As i wanted later in the game to add explosions and bullets it wasn't a good idea to mess with the velocity and the forces/impulses didn't work as i expected so something stuck in my mind: Is it a good idea to put at his bottom a wheel(circle) which is invisible to the player that will do the movement by rotation? I will attach this to my main body with a revolute joint but i don't really know how to make the main body and wheel body to don't collide one with each other since funny things can happen. What is your oppinion?

# Answer
> : Is it a good idea to put at his bottom a wheel(circle) which is invisible to the player that will do the movement by rotation?

That is exactly what you should. I once wrote a tutorial on it for C#/XNA and Farseer, but you should be able to adopt it easily to Java and Box2D (Farseer is based on Box2D).

Here's the tutorial:

http://www.sgtconker.com/2010/09/article-xna-farseer-platform-physics-tutorial/

The end result should be something like this:

And a video: http://www.youtube.com/watch?v=iC\_Y9Tq5JeU&feature=player\_embedded
> 4 votes

---
Tags: java, box2d, physics
---


# Question
Title: How to create a "retro" pixel shader for transformed 2D sprites that maintains pixel fidelity?
The image below shows two sprites rendered with point sampling on top of a background:

* The left skull has no rotation/scaling applied to it, so every pixel matches perfectly with the background.
* The right skull is rotated/scaled, and this results in *larger pixels* that are no longer *axis aligned*.

**How could I develop a pixel shader that would render the transformed sprite on the right with axis aligned pixels of the same size as the rest of the scene?**

This might be related to how sprite scaling was implemented in old games such as Monkey Island, because that's the effect I'm trying to achieve, but with rotation added.

---

**Edit**

As per kaoD's suggestions, I tried to address the problem as a post-process. The easiest approach was to render to a separate render target first (downsampled to match the desired pixel size) and then upscale it when rendering a second time. It did address my requirements above.

First I tried doing it `Linear -> Point` and the result was this:

There's no distortion but the result looks blurred and it loses most of the highlights colors. In my opinion it breaks the retro look I needed.

The second time I tried `Point -> Point` and the result was this:

Despite the distortion, I think that might be good enough for my needs, although it does look better as a still image than in motion.

To demonstrate, here's a video of the effect, although YouTube filtered the pixels out of it:

http://youtu.be/hqokk58KFmI

However, I'll leave the question open for a few more days in case someone comes up with a better sampling solution that maintains the crisp look while decreasing the amount of distortion when moving.

# Answer
You should apply your shader AFTER your sprite has been rotated.

If the whole scene has not been shaded yet and your sprites are actually pixelated, what you need is some kind of post-FX filter for your whole scene. Averaging regions of pixels will work ok. It's not exactly what you intend (it'll look kinda dithered when moving/rotating) but it might do the trick.

The only way to keep that retro look truthful to what you want is to actually draw your sprite rotations yourself. It has nothing to do with how scaling was implemented: the resolution was actually poor, speaking of which, did you try with extremely low resolutions? It might also do the trick and will look more natural since, well, it's actually what caused the effect you're looking after. And it's cheap! VERY cheap! In fact it'll be cheaper than what you already have (less fragment shader executions.)

The effect is ruined in your sample image because your resolution is high compared to your sprites, so it lets you see the real pixels on the scene.
> 3 votes

---
Tags: 2d, graphics, fragment-shader
---


# Question
Title: xml file save/read error (making a highscore system for XNA game)
i get an error after i write player name to the file for second or third time (An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll

Additional information: There is an error in XML document (18, 17).) (in highscores load method In data = (HighScoreData)serializer.Deserialize(stream); it stops)

the problem is that some how it adds additional "\>" at the end of my .dat file could anyone tell me how to fix this?

the file before save looks:

```
<?xml version="1.0"?>
<HighScoreData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PlayerName>
    <string>neil</string>
    <string>shawn</string>
    <string>mark</string>
    <string>cindy</string>
    <string>sam</string>
  </PlayerName>
  <Score>
    <int>200</int>
    <int>180</int>
    <int>150</int>
    <int>100</int>
    <int>50</int>
  </Score>
  <Count>5</Count>
</HighScoreData>

```

the file after save looks:

```
<?xml version="1.0"?>
<HighScoreData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PlayerName>
    <string>Nick</string>
    <string>Nick</string>
    <string>neil</string>
    <string>shawn</string>
    <string>mark</string>
  </PlayerName>
  <Score>
    <int>210</int>
    <int>210</int>
    <int>200</int>
    <int>180</int>
    <int>150</int>
  </Score>
  <Count>5</Count>
</HighScoreData>>

```

the part of my code that does all of save load to xml is: DECLARATIONS PART

```
  [Serializable]
    public struct HighScoreData
    {
        public string[] PlayerName;
        public int[] Score;

        public int Count;

        public HighScoreData(int count)
        {
            PlayerName = new string[count];
            Score = new int[count];

            Count = count;
        }
    }

    IAsyncResult result = null;
 bool inputName;
    HighScoreData data;
int Score = 0;
    public string NAME;

    public string HighScoresFilename = "highscores.dat";

```

Game1 constructor

```
 public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        Width = graphics.PreferredBackBufferWidth = 960;
        Height = graphics.PreferredBackBufferHeight =640;
        GamerServicesComponent GSC = new GamerServicesComponent(this);
        Components.Add(GSC);
    }

```

Inicialize function (end of it)

```
  protected override void Initialize()
    {

```

//other game code base.Initialize();

```
        string fullpath =Path.Combine(HighScoresFilename);

        if (!File.Exists(fullpath))
        {
            //If the file doesn't exist, make a fake one...
            // Create the data to save
            data = new HighScoreData(5);
            data.PlayerName[0] = "neil";
            data.Score[0] = 200;

            data.PlayerName[1] = "shawn";
            data.Score[1] = 180;

            data.PlayerName[2] = "mark";
            data.Score[2] = 150;

            data.PlayerName[3] = "cindy";
            data.Score[3] = 100;

            data.PlayerName[4] = "sam";
            data.Score[4] = 50;

            SaveHighScores(data, HighScoresFilename);
        }

```

}

all methods for loading saving and output

```
 public static void SaveHighScores(HighScoreData data, string filename)
{
// Get the path of the save game
    string fullpath = Path.Combine("highscores.dat");

// Open the file, creating it if necessary
FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate);
try
{
// Convert the object to XML data and put it in the stream
    XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
serializer.Serialize(stream, data);
}
finally
{
// Close the file
stream.Close();
}
        }

    /* Load highscores */
    public static HighScoreData LoadHighScores(string filename)
    {
    HighScoreData data;

    // Get the path of the save game
    string fullpath = Path.Combine("highscores.dat");

    // Open the file
    FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate, FileAccess.Read);
    try
    {
    // Read the data from the file
        XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
    data = (HighScoreData)serializer.Deserialize(stream);//this is the line
    // where program gives an error
    }
    finally
    {
    // Close the file
    stream.Close();
    }

    return (data);

    }

    /* Save player highscore when game ends */
    private void SaveHighScore()
    {
    // Create the data to saved
    HighScoreData data = LoadHighScores(HighScoresFilename);

    int scoreIndex = -1;
    for (int i = 0; i < data.Count ; i++)
    {
    if (Score > data.Score[i])
    {
    scoreIndex = i;
    break;
    }
    }

    if (scoreIndex > -1)
    {
    //New high score found ... do swaps
    for (int i = data.Count - 1; i > scoreIndex; i--)
    {
    data.PlayerName[i] = data.PlayerName[i - 1];
    data.Score[i] = data.Score[i - 1];
    }

    data.PlayerName[scoreIndex] = NAME; //Retrieve User Name Here
    data.Score[scoreIndex] = Score; // Retrieve score here

    SaveHighScores(data, HighScoresFilename);
    }
    }

    /* Iterate through data if highscore is called and make the string to be saved*/
    public string makeHighScoreString()
    {
    // Create the data to save
    HighScoreData data2 = LoadHighScores(HighScoresFilename);

    // Create scoreBoardString
    string scoreBoardString = "Highscores:\n\n";

for (int i = 0; i<5;i++)
{
scoreBoardString = scoreBoardString + data2.PlayerName[i] + "-" + data2.Score[i] + "\n";
}
return scoreBoardString;
}

```

when ill make this work i will start this code when i call game over (now i start it when i press some buttons, so i could test it faster)

```
   public void InputYourName()
   {
                     if (result == null && !Guide.IsVisible)
                     {

                          string title = "Name";
                          string description = "Write your name in order to save your Score";
                          string defaultText = "Nick";
                          PlayerIndex playerIndex = new PlayerIndex();
                          result= Guide.BeginShowKeyboardInput(playerIndex, title, description, defaultText, null, null);
                        // NAME = result.ToString();

                     }

                if (result != null && result.IsCompleted)
                     {
                         NAME = Guide.EndShowKeyboardInput(result);
                         result = null;
                         inputName = false;
                         SaveHighScore();
                     }

  }

```

this where i call output to the screen (ill call this in highscores meniu section when i am done with debugging)

```
spriteBatch.DrawString(Font1, "" + makeHighScoreString(),new Vector2(500,200), Color.White);

  }

```

# Answer
Please have a look at FileMode.OpenOrCreate or FileMode.Create

> ? Because the former (OpenOrCreate) will have the effect, that if the file already exists, it will simply be opened (without deleting the existing content). Then if the data that you write is shorter than the data that was written before, the additional bytes of the old data will still be part of the new file (at the end). Which will break the XML syntax during loading, as there are additional characters at the end.
> 2 votes

---
Tags: xna, xml, debugging, leaderboards, file
---


title: Drawing Shape in DebugView

text:
# Question
Title: Drawing Shape in DebugView
As the title says, I need to draw a shape/polygon in Farseer using debugview. I have this piece of code which converts a Texture to polygon:

```
//load texture that will represent the tray
        trayTexture = Content.Load<Texture2D>("tray");

        //Create an array to hold the data from the texture
        uint[] data = new uint[trayTexture.Width * trayTexture.Height];

        //Transfer the texture data to the array
        trayTexture.GetData(data);

        //Find the vertices that makes up the outline of the shape in the texture
        Vertices verts = PolygonTools.CreatePolygon(data, trayTexture.Width, false);

        //Since it is a concave polygon, we need to partition it into several smaller convex polygons
        _list = BayazitDecomposer.ConvexPartition(verts);
        Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1));
        foreach (Vertices verti in _list)
        {
            verti.Scale(ref vertScale);
        }

        tray = BodyFactory.CreateCompoundPolygon(MyWorld, _list, 10);

```

Now in DebugView I guess I have to use "DrawShape" method which requires:

```
DrawShape(Fixture fixture, Transform xf, Color color)

```

**My question is how can I get the variables needed for this method, namely Fixture and Transform?**

# Answer
Have you tried the official documentation?

The getting started section shows how to create a fixture:

http://farseerphysics.codeplex.com/documentation

> Fixture A fixture attaches (fix) the shape to the body so that the centroid of the shape becomes the body’s position. Whenever you move the body, you also move the shape. Once a collision occur to the shape, the force is calculated and applied to the body.
>
> Her is the code to create a World with a single body:

```
   1:  //Create a World object with zero gravity
   2:  World world = new World(Vector2.Zero);
   3:

   4:  //We create a body object and make it dynamic (movable)
   5:  Body myBody = world.CreateBody();
   6:  myBody.BodyType = BodyType.Dynamic;
   7:
   8:  //We create a circle shape with a radius of 0.5 meters
   9:  CircleShape circleShape = new CircleShape(0.5f);
  10:
  11:  //We fix the body and shape together using a Fixture object
  12:  Fixture fixture = myBody.CreateFixture(circleShape);

```

You can also use the fixture factory

```
  Fixture fixture = FixtureFactory.CreateCircle(_world, 0.5f, 5, new Vector2(10, 0));

```

You can probably create a default transform (that doesn't transform anything) using:

```
Transfrom transform;
transform.SetIdentity();

```

Note that you can also use the Box2D manuals, since Farseer offers the same features.
> 0 votes

---
Tags: xna, box2d, farseer-physics-engine
---