title: Legal Lego game

text:
# Question
Title: Legal Lego game
As Lego (the old blocks not the 'new' hi-teck stuff) are now in the public domain, can I make a game where the graphics are made out of lego blocks?

Well, I can, but is it legal?

# Answer
> 15 votes
First, I am not a lawyer, this is not legal advice, if you follow my advice and get sued and lose your house then it's your fault not mine.

Unfortunately, as simple as that question is, it really needs to be broken down into two questions.

1) If I get sued for copyright infringement, will I win?

Maybe! Assuming those pieces are in fact public domain now, then it seems like a rather clear victory. Now, for the sake of this entry, I'm going to assume you win, unquestionably. I don't know that for certain, but we're just going to make that assumption.

2) Will I get sued?

Maybe.

Unless you have a nice big legal war chest to rely on, getting sued is almost as bad as losing. You can't hope to match Lego's legal funds. It will not happen. You'll go to court, and you'll probably blow thousands of dollars *just on prep work*. And then, even if you win, there's no way you're getting that money back without a second court case - more money, and you're not even guaranteed to win that one.

You may want to read this story. For posterity, here's the important bits:

> As a film student in early 2001, I was a juggernaut. I was making a lot of short films that were garnering moderate acclaim, and I was always pushing ahead, making bigger and bigger projects. For my senior thesis, I wanted to base it on a short story by Isaac Asimov, which was part of the compilation that made up the book “I, Robot”.
>
> I called, I got permission, and they faxed the form to my professor’s office.
>
> In our last week of shooting, 3 months after I received written consent to use the short story, one of the crew brought in a copy of Variety, which mentioned that a major studio purchased the book rights to I, Robot, and planned to make a film. Initially, I thought, “Awesome – free promotion!” Alas, that’s not what was looming on the horizon.
>
> Somehow the legal team from the studio found out about a student project, in a small private college in the Midwest, with no budget, being shot in a warehouse basement, and decided to issue a cease and desist order. Basically, what that means, is that the studio’s lawyers said to us, “You’re using our property. Stop, or we’ll sue you into the stone age.” I responded by sending them the consent form from the Asimov estate, and explained that it was a student project, not a commercial venture worth litigating.
>
> Instead of the letter recognizing our valiant efforts as students that I expected, I found myself on the tail end of a phone call that changed my life. I was contacted directly by the lead of the studio’s legal team, who explained my situation to me very clearly. He told me that I was technically in my legal right to use Isaac Asimov’s material. However, if I chose to proceed, they would file multiple lawsuits totaling over 2 million dollars against me. In the end, I might win, but it would take hundreds of thousands of dollars in legal fees just to fight it, but would cost them nothing more than the salaries they already pay their lawyers. It would be 10 years before any type of verdict could be levied, and by then it wouldn’t matter what the outcome was, since their film would be long since released.

So, when you say "Well, I can, but is it legal?", that's really the wrong question to ask. The right question is whether or not Lego will permit you to do so, and whether you have the money to defend yourself if Lego decides they won't let you do so.

I'll let you decide, for yourself, how likely Lego is to object.

Again, not a lawyer, not legal advice, get a lawyer.

(Disclaimer: segments of this were copied from a similar reply I made to a similar question.)

# Answer
> 4 votes
This kind of questions are usually answered by lawyers after a good amount of money, and not even them will tell you for sure. To be sure you'll have to meet a judge in a courtroom, which I guess is what you're trying to avoid :)

If Lego is actually public domain you'll probably have no problems as long as you don't use the Lego trademark/logo or anything else that isn't public domain.

# Answer
> 1 votes
Be careful.

Just because the basic LEGO patent has expired, that doesn't mean that all their other intellectual property is in the public domain, nor that the laws are the same everywhere you want to market your own product. If your game represents itself as being in any way remotely related to LEGO toys, the LEGO company or trademarks, you could face trouble.

1. A game that has blocks that have the LEGO logo on them will definitely be a problem.
2. A game that uses bricks that look a *lot* like LEGO could be a problem.
3. A game that uses interlocking bricks with a vague resemblance to LEGO will probably be fine.
4. A game that uses interlocking bricks that don't look like LEGO bricks will almost certainly be fine.
5. A game with a generic construction theme would be fine.

If in doubt, come up with your own slant on the construction idea, or pay for proper legal advice.

---
Tags: legal, copyright
---


title: Aggro with Images

text:
# Question
Title: Aggro with Images
I have three UIImageViews. enemy1, enemy1AggroBox and mainSprite. What I want to do is when mainSprite and enemy1AggroBox interect, I want enemy1 to start moving towards mainSprite. Basically creating aggro for a game.

```
if(CGRectIntersectsRect(mainSprite.frame, enemy1AggroBox.frame)){
//Code here//
}

```

My plan would be to call this method in viewDidLoad. I'm not using any sort of framework like cocos2d or OpenGLES. If you need to see any more code just ask.

# Answer
> 1 votes
I'm not familiar with the particular platform you're working on, but I would imagine that a simple rectangle intersection function would solve this.

```
if ( intersects(mainSprite.frame, enemy1AggroBox.frame ) {
    MoveTowardPlayer(Player1, Enemy1);
}

bool intersects(const Rect& first, const Rect& second) const {
    if (first.Max.X < second.Min.X )
        return false;

    if (first.Max.Y < second.Min.Y )
        return false;

    if (second.Max.X < first.Min.X )
        return false;

    return (second.Max.Y >= first.Min.Y )
}

```

Something like this would work provided your rectangles are Axis-Aligned (which you've indicated they are in your comment (below your question).

And to make one move towards the other (using pseudo-code, I don't know what engine you're using so I can't write exactly what you'll need to compile):

```
void MoveTowardPlayer(const Unit& player, const Unit& enemy) {
    // Get the difference in positions between player and enemy
    Vector2 direction = player.position - enemy.position;

    // Normalize the difference to get a direction vector
    direction.Normalize(); // Also sometimes called Unitize

    // Move the enemy in the direction of the player, based of the amount of
    // time has elapsed, and the enemy's movement speed, in units per second.
    enemy.position += (direction * enemy.movementSpeed * timeDelta);
}

```

I'm just giving a generic example on how to move your enemy toward a player. That question alone is pretty broad.

# Answer
> 0 votes
To make a UIView (or any subclass like UIImageView) move to a given point, in a given amount of time, do this.

```
NSTimeInterval totalDuration = 3.0; // three seconds

// if you change any view property inside this block
// it will be smoothly interpolated over a duration
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:totalDuration];

enemy1.center = mainSprite.center;

[UIView commitAnimations];

```

---
Tags: iphone, objective-c
---


# Question
Title: Separation of world state and animation in a turn based game
How do you handle the separation of animation from the world state within a turn based game? I'm working on a 2D grid based game currently. The below code is simplified to better explain.

When an actor moves, I want to pause the flow of turns while the creature animates and moves to the new position. Otherwise, the screen could lag significantly behind the world state, which would cause weird visual appearance. I also want to have animations that don't block the flow of the game - a particle effect could unfold over multiple turns without affecting gameplay.

What I've done is introduce two types of animations, which I call blocking animations and non-blocking animations. When the player wants to move, the code that gets executed is

```
class Actor {
    void move(PositionInfo oldPosition, PositionInfo newPosition) {
        if(isValidMove(oldPosition, newPosition) {
             getGame().pushBlockingAnimation(new MoveAnimation(this, oldPosition, newPosition, ....));
             player.setPosition(newPosition);
        }
    }
}

```

Then the main update loop does:

```
class Game {
    void update(float dt) {
        updateNonBlockingAnimations(dt); //Effects like particle explosions, damage numbers, etc. Things that don't block the flow of turns.
        if(!mBlockingAnimations.empty()) {
            mBlockingAnimations.get(0).update(dt);
        } else {
             //.. handle the next turn. This is where new animations will be enqueued..//
        }
        cleanUpAnimations(); // remove finished animations
    }
}

```

...where the animation updates the screen position of the Actor.

One other idea I am implementing is to have a concurrent blocking animation, where multiple blocking animations would be updated simultaneously, but the next turn wouldn't happen until all of them were done.

Does this seem like a sane way to do things? Does anyone have any suggestions, or even references to how other similar games do such a thing.

# Answer
If your system works for you, I don't see any reason not to do so.

Well, one reason: It might get messy when you don't easily can judge the consequences of "player.setPosition(newPosition);" anymore.

Example (just making things up): Imagine you move the player with your setPosition on top of some trap. The call to "player.setPosition" itself will trigger some other call to .. say a trap listener code which in turn will push a blocking animation by itself that displays a "hurting splash" on top of itself.

You see the problem: the splash gets displayed simultanously with the *move* of the player towards the trap. (Lets assume here that you don't want this, but want the trap animation to be played right after the move finished ;)).

So as long as you are able to keep all the consequences of your actions in mind that you do *after* those "pushBlockingAnimation" calls, everything is fine.

You may need to start to wrap game logic into "blocking something" - classes so they can be queued to execute after the animation finishes. Or you pass a callback "callThisAfterAnimationFinishes" to the pushBlockingAnimation and move the setPosition into the callback function.

Another approach would be scripting languages. For example Lua has "coroutine.yield" which returns the function with a special state so it can be called later to continue at the next statement. This way you can easily wait for the end of the animation to execute game logic without cluttering the "normal" program flow look of your code. (means your code would still look a bit like "playAnimation(); setPosition();" instead of passing callbacks around and cluttering game logic over multiple functions).

Unity3D (and at least one other game system I know) features the C# "yield return" statement to simulate this directly in C# code.

```
// instead of simple call to move(), you have to "iterate" it in a foreach-like loop
IEnumerable<Updatable> move(...) {
    // playAnimation returns an object that contain an update() and finished() method.
    // the caller will not iterate over move() again until the object is "finished"
    yield return getGame().playAnimation(...)
    // the next statement will be executed *after* the animation finished
    player.setPosition(newPosition);
}

```

Of course, in this scheme the call to move() gets all the dirty work now. You would probably apply this technique only for specific functions where you know exactly who call them from where. So take this only as a basic idea how other engines are organized - its probably way too complicated for your current specific problem.

I recommend you stick to your pushBlockingAnimation idea until you having real-world trouble. Then modify it. ;)
> 2 votes

---
Tags: java, animation, turn-based
---


# Question
Title: Resource loader for an HTML5 and Javascript game
I have made a type to shoot game using HTML5, Javascript and Ruby on Rails.
Here is the link for the game Tweetraitor

I wanted to make a loader for resources (sounds, images) when the game starts. Currently when the game starts the background image takes time to load and it does not look good. This loader should load all the assets those are used later in the game.

Code for the game is here: Tweetraitor on GitHub

In the current version, all the images are loaded using js in an erb file which controls the game logic. Is there a better way to do this?

# Answer
I have to admit I have no idea of Ruby and how it's used together with js, but here is how I'd do it with js:

```
window.onload = function() {
        var sources = {
            resource1: "img/sprite1.png",
            resource2: "img/sprite2.png",
            resource3: "img/sprite3.png"
        };
        loadImages(sources, initGame);  // calls initGame after *all* images have finished loading
    };

    function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        for (var src in sources) {
            numImages++;
        }
        for (var src in sources) {
            images[src] = new Image();
            images[src].onload = function(){
                if (++loadedImages >= numImages) {
                    callback(images);
                }
            };
            images[src].src = sources[src];
        }
    }

    function initGame(images) {
        // some code here...
    }

```
> 3 votes

---
Tags: javascript, html5
---


# Question
Title: High school-level geometry book focusing on game dev for struggling student?
Here's the situation. My brother, a freshman in high school, isn't doing too well in geometry. Partially because he doesn't do half the work, but partially because he seems to have genuine difficulty with the material. So then I thought, since geometry is so useful in game dev, why not get him a book that presents geometry concepts in that light so that he can better grasp them?

Note that he doesn't actually want to make video games, so coding is not important, only an understanding of geometry that'll get him through the rest of the year. He does like video games, however. A book in game-focused geometry would serve as supplementary to his schoolwork, not as a substitute. To be concise, this is exactly what I need;

* 2D only! 3D is not relevant here!
* Not much focus on programming (or it can at least be bypassed).
* Good for high school freshmen who are just trying to get a B and get out.
* Direct applications are important, but if the explanations are super clear then this can be forgiven. For instance, http://tinyurl.com/83e9wsu I've skimmed this book and can safely say that it'll be great for his required Algebra II and Trig course next year, even though its relation to game development is pretty much in name only.

# Answer
A book on video game geometry is probably not going to help your brother much. It will talk about mathematics topics used in *video games*, not necessarily those covered in his curriculum, and may entirely skip over certain things he needs to know to pass his subjects.

Plus, just because it's related to video games doesn't mean it's going to be fun - it's a maths book either way.

### Have you tried pointing your brother to Khan Academy?

It's a free (as in Wikipedia) library of lectures which cover, among other things, almost every topic in the American curriculum including geometry. They're short and explained in a way that's quite easy to understand. If your brother is struggling because he doesn't quite understand how to do things, rest assured he'll be able to learn from Khan Academy.
> 3 votes

---
Tags: mathematics, geometry, books
---


title: Octree division

text:
# Question
Title: Octree division
I have an octree, with a high poly rabbit inside it, and a 12 polygon platform.

The deal is this. You're shooting a ray at the rabbit. He of course dodges (or you miss).

The yellow beam is your death laser.

The "candidate" triangles that are selected due to the parts of the octree you hit are shown in purple.

So clearly you have this striping that occurs, because the root node was hit, you ended up testing any polys in the root node. And the polys that are on the *borders* of the octree subdivision end up in the root node, with the subdivision algorithm I'm using.

**So I want to reduce the number of polys in the root node.**

If I just move the bunny to the corner,

With the bunny in the corner raytracing the entire scene takes 1/3 the time (35s vs 95s if the bunny is in the middle). I believe this is because less of the bunny's triangles are in the root, and octree root-only hits check fewer polygons.

I'm surveying ways to improve performance. Basically to push the tris as far down the tree as possible, so that the objects are mostly in the leaves.

I tried doing this naively, and used this subdivision algorithm which I made up:

```
split root into 8 CANDIDATE CHILDREN
foreach TRI in root:
  foreach of the 8 CANDIDATE CHILDREN
    if the CANDIDATE CHILD partially contains TRI (at least one vertex of TRI)
      add TRI to CANDIDATE CHILD
CLEAR tris in root

```

This pushes triangles down the hierarchy into leaf nodes. But I get holes from certain angles, with weird miss patterns:

(expected)

holes from one angle:

same scene, different angle:

I think it's because I'm clearing the root. (Because when I don't clear the root, raytracing works correctly, all angles)

Have I "pushed" the polygons down the tree correctly? Can any one guess why I have holes?

How do you improve the performance of your octree?

Do I have to split the triangles? I'm trying to avoid that, so I don't get thinner and thinner triangles/multiply the scene geometry any more than I need to.

I'm also aware that KD trees and that they should outperform octrees, but they also require poly splitting, I'm really looking for ways to improve my octree here.

# Answer
I understand now why I get holes. I'm using a bad AABB-triangle partial containment scheme: an AABB "partially contained" a triangle iff the AABB contained **at least one a vertex** of the triangle.

E's are "empty", according to the bad "Triangle partially in AABB" detection scheme.

I guess this means that if you want to push everything down to leaf nodes, you *must* split the triangles.
> 2 votes

---
Tags: octree
---


title: How to setup JBox2D?

text:
# Question
Title: How to setup JBox2D?
I recently downloaded the JBox2D but how do I set this up?

It's *jbox2d-2.1.2.2*. All I can see is a bunch of code and folders.

# Answer
> 1 votes
Assuming you are not using Maven or Ant; extract the jbox2d-2.1.2.2.zip file and then open up the jbox2d-2.1.2.2\jbox2d-testbed\target directory. Find the below file and then add it to you class path.

```
jbox2d-testbed-2.1.2.2-jar-with-dependencies.jar

```

If you are using Maven see the Getting Started Quide

---
Tags: java, android, box2d
---


title: Multidimensional Pathfinding Algorithms

text:
# Question
Title: Multidimensional Pathfinding Algorithms
When trying to program hostile AI units for a war strategy game using pathfinder methods, do programmers ever have one algorithm for the unit to move and a separate algorithm for the unit to actively listen for nearby objectives (e.g. opposing warriors, power ups, opposing team's fortress, treasure, etc)?

Any insights as to how these methods function would make me happy.

# Answer
> 0 votes
You can use the same algorithms as normal, for example this is my version of A\* in 3D: http://roy-t.nl/index.php/2011/09/24/another-faster-version-of-a-2d3d-in-c/

All you have to do is to make the 'is adjacent' function fetch 3 dimensions.

---
Tags: ai, path-finding, actionscript-3
---


title: Cinematic in 2D games

text:
# Question
Title: Cinematic in 2D games
I am searching for a way to create and integrate cinematic in a simple 2D game with XNA for Windows Phone. I don't know if the best way is to create an animation with sprite and commonly process to animate them... or Is it possible to create the animation with an external tool and read it from the code.

Thanks for your help

# Answer
> 5 votes
I'm going to look at how some pre-existing implementations work (that I have actually used) - and hopefully that will give you some ideas on how to integrate it with your game engine.

# Operation Flashpoint

Operation Flashpoint (original release) has a command and control system for entities. This is essentially a list of commands that entities had to perform - the AI system would be responsible for carrying out the commands. Entities could be anything: an enemy, the camera, the player, etc. All the entities had to exist 'before the fact' (but there is nothing stopping you from making a 'create entity' command). Let's take the example of two people meeting, having a conversation, getting into a car and driving off.

* Entity1: ignore player
* Entity2: ignore player
* Camera: Track Entity1
* Entity1: move to Alpha
* Entity2: run to Alpha
* Entity1: start talking, play 'sound1.ogg' when: Entity1 at Alpha when: Entity2 at Alpha
* Entity1: move to and enter Car1 (driver) when: 'sound1.ogg' complete
* Entity2: move to and enter Car1 (passenger) when: 'sound1.ogg' complete
* Entity1: move to Charlie when: Entity1 in Car1 when: Entity2 in Car1
* Camera: restore, Entity1: restore player aggression, Entity2: restore player aggression when: Car1 enters Area1

This system did have some bugs (very rarely cut-scenes that never ended because of border cases like where the AI didn't choose a predictable route) - but resulted in very 'natural' looking sequences because people were not following straight paths etc.

# XAML

XAML uses a story-board system. This is basically a list of animations that need to play - it is essentially the same as the Operation Flashpoint example except the timings are used instead of 'waiting on things' and entities move along predetermined paths. Again, using the above example:

* Entity1: move from Alpha to Charlie at 0s taking 5s *this will be a straight line*
* Entity2: move from Bravo to Charlie at 0s taking 5s
* Camera1: move to Delta at 0s taking 1s
* Camera1: move target from (Start) to Charlie at 0s taking 5s
* Entity1: start talking animation at 5s
* Sound: play 'sound1.ogg' at 5s originating from Charlie
* Entity1: move to Echo at 10s taking 5s
* Entity2: move to Echo at 10s taking 5s
* Entity1: get in Car1 (driver) at 15s
* Entity2: get in Car1 (driver) at 15s
* Car1: move to Foxtrot at 16s taking 30s
* Camera: restore at 19s

There are two problems with this (I prefer it less):

* Things could move unnaturally fast or slow
* If you want to change the cut-scene you will need to go and adjust all the timings.

# How to do it in XNA

After you have chosen a way to describe cut-scenes you will likely have an some form a file from your editor (possibly an XML file). You would then create a content processor and add your cut-scene to your content project. At runtime you would then call something along the lines of `CutSceneComponent.Execute(Content.Load<CutScene>("CutScenes\\Level3"))`.

---
Tags: xna, 2d, windows-phone-7
---


# Question
Title: Keep running CGRectIntersect Method - Objective C
I have two UIImageViews. mainSprite, and enemy1. And I have a method that makes enemy1 start moving towards mainSprite. So here's that method.

```
-(void)enemy1Aggro{
if (CGRectIntersectsRect(mainSprite.frame, enemy1Aggro.frame)) {
    if (mainSprite.center.x > enemy1.center.x) {
        enemy1.center = CGPointMake(enemy1.center.x+2, enemy1.center.y);
    }
    if (mainSprite.center.x < enemy1.center.x) {
        enemy1.center = CGPointMake(enemy1.center.x-2, enemy1.center.y);
    }
    if (mainSprite.center.y > enemy1.center.y) {
        enemy1.center = CGPointMake(enemy1.center.x, enemy1.center.y+2);
    }
    if (mainSprite.center.y < enemy1.center.y) {
        enemy1.center = CGPointMake(enemy1.center.x, enemy1.center.y-2);
    }
}

```

} This works because I'm calling it on an IBAction that is a button that gets held down. But the problem is that when that button stops being pressed, this method stops running. So what I need is a way to have this method keep on running. Maybe a for loop? I'm not using anything like cocos2d, and I'm not using CoreGraphics. If you need to see any more of my code just ask.

Thanks :)

# Answer
You can use NSTimer to setup something like gameloop which calls ur method again and again

Your code should look somethings like this:

```
- (void)viewDidLoad
{
    [super viewDidLoad];
    [NSTimer scheduledTimerWithTimeInterval:1/30.0 target:self selector:@selector(enemy1Aggro) userInfo:nil repeats:YES];
}

```

The above code will invoke the `enemy1Aggro` 30 times per second.
> 1 votes

---
Tags: collision-detection, objective-c, image
---


# Question
Title: Common ways to keep up with character state in a 2D game?
I am currently developing a 2D Blockdude clone for learning purposes and am wondering about storing character state in the game. For example, the character can be facing either right or left. What are some common ways of handling character state? Unfortunately, the question is so broad none of my searches have come up with anything (or maybe I'm searching for the wrong terms). Should I be using a state machine?

How I'm doing it now using the "character facing" example (code is Java):

```
enum CharacterFacing {
    RIGHT, LEFT
}

class Character {
    CharacterFacing facing;

    Character() {
        // start with the character facing right
        facing = CharacterFacing.RIGHT;
    }

    // called when the player hits the left arrow
    void moveLeft() {
        facing = CharacterFacing.LEFT;
    }

    // called when the player hits the right arrow
    void moveRight() {
        facing = CharacterFacing.RIGHT;
    }
}

```

Because the "facing" state is so simple, I've also thought about just a boolean:

```
class Character {
    boolean facingRight;

    Character() {
        // start with the character facing right
        facingRight = true;
    }

    // called when the player hits the left arrow
    void moveLeft() {
        facingRight = false;
    }

    // called when the player hits the right arrow
    void moveRight() {
        facingRight = true;
    }
}

```

# Answer
*Because the "facing" state is so simple, I've also thought about just a boolean:*

I like to answer by listing how I would approach problems of this type:

1. Start with the solution that need the least amount of "new stuff" (new classes, new functions, new variables, new constants etc..)
2. Once you need more, add it (in its "least amount of new stuff" - form).
3. Always be ready to change your classes. Most changes will involve the *removal* of features as well as addition. That's good. Be *never* afraid of changes. If you start to "not want to change this stuff anymore - it might break", this is a first sign that you need to think of simpler solutions.
4. Learn your refactoring tools of your IDE to make less errors when changing.
5. Most important: **This is not a dogma. Its a guidance.** You *will* break this rule. Often.

So for your specific question: Since the boolean is one less type to declare and 3 lines less code, go for it (as a rule of thumb - not an dogma ;)).

Until you like to have more than two possible values or you start to get confused by the code and always have to look up what exactly the boolean was. In either case refactor the code *then* to use an enum, the state-object pattern, split the class into a hierarchy or whatever seems the easiest solution with your new requirements then.

PS: yea.. its not *my* idea.. Other were first. ;)
> 4 votes

# Answer
*Should I be using a state machine?*

I won't really call it a state machine personally. Its more like a clean method of knowing which way the player is facing rather than having say magic numbers for example i.e.

```
if (direction == 15) // what is 15?

```

15 means nothing to me, whereas

```
if (direction == CharacterFacing.Right)

```

Is so much more clear and leaves no room for interpretation, i can easily see that this code will come into play when the character is facing right. So i'd say yes, there's nothing wrong with using a 'state machine' even in this most basic of ways. It just keeps things clean and nice to read.

P.s - I don't think there's a difference between using enums & bools, i mean they both do exactly the same job, i suppose the only difference with boolean's is that like you have done, there's more work involved in making sure the "facingLeft" bool would have to be set to false & vice versa in the opposite movement functions. Its all about personal preference really.
> 3 votes

# Answer
Looks sensible.

In this case, it might sometimes be useful to store it as an `int` instead, but only use values of `-1` (left) and `1` (right). Then, when the character starts walking, you don't need to check direction, but you can simply do:

```
float dt = /* amount of time elapsed since last frame */;
float speed = /* character walking speed */;
position.x += dt * speed * facing;

```
> 1 votes

---
Tags: java, state
---


# Question
Title: What is the most effective way to work with a friend on the same game?
We need something where we can check files out, edit them, check them back in and then build from the them.

Something like Google Docs where we can edit the same code at the same time would be a ideal.

We are both using Visual Studio 2010.

# Answer
> 19 votes
As I stated in a comment to your question, I'm very curious for **true collaborative editing**. I did research some time ago but most solutions just didn't meet the standards: either they were plain text editors with syntax highlight, had insane costs or were unavailable cross-platform (like SubEthaEdit...)

Until I stumbled into Saros! It's a neat Eclipse plugin, so it might be easy to integrate with your current workflow. You can watch their demo video, it's quite impressive. It's very well thought for a true collaborative editing environment and has some very well-though key features. It supports an arbitrary number of participants, full project synchronization, real-time editing with markers and highlighting (ala Google Docs), following your partner's view, several participant-awareness methods and much more (you can even share your screen using this plugin.) And apparently it integrates with many other Eclipse plugins!

I have yet to test it myself, but it's one of the few projects still maintained and looks very promising. Give it a shot and let me know (read these guidelines before.) I promise I'll come back here and post my impressions as a comment when I try it myself.

**EDIT:** Also, as Gustavo pointed in a comment, Cacoo might be useful too. It's an online collaborative tool for drawing UMLs (actually, any kind of diagram.) Saros supports a whiteboard, but there's nothing like a diagram tool if you want to avoid clumsiness.

# Answer
> 36 votes
"we just need something where we can check files out edit them and then check them back in and build from the same set of files"

Use version control; a version control system (VCS) is exactly what you described, with the added bonus that it stores a history of every change anyone has made. There are lots of popular version control systems out there:

http://subversion.apache.org/

http://mercurial.selenic.com/

http://git-scm.com/

I don't use Visual Studio personally, but I am completely certain that Visual Studio has support for all of these version control systems.

# Answer
> 9 votes
For my team, we use three programs depending on what we need to work on:

* **TortoiseSVN** for code (try to have programmers use the same IDE, standardize conventions and encourage good commenting)
* **Dropbox** for multimedia (for models/sprites/audio files, allows devs to work locally until artists/composers/modelers are ready to deliver)
* **GoogleDocs** for documentation (for design documents/mockups/pitches usually for designers, managers and producers)

To coordinate the efforts of different members (who work at different times) we use **Assembla's** ticketing system. This way everyone is updated on the status of the entire project or a particular avenue of their choice. Also use **Skype/Google Hangout/Face-to-face** communication to make sure everyone's on the same page on at least a weekly basis.

This method typically works when a team consists of 3-5 people who have established roles (programmer, artist, modeler, designer etc.). If this doesn't work, try other methods or combine working aspects to make one of your own. Good luck!

# Answer
> 7 votes
Sounds like you want either drop box, a version control system, or both.

Dropbox is the most convenient. Just make your changes and save and Dropbox will sync over the changes on your friends machine. Don't think 2 people can work on the file at the same time though without overwriting each others work.

However, I recommend you use a version control system Subversion, GIT, and Mercurial are currently the big 3. There are a lot of advantages to using a VCS: including the ability to automate backups, rollback changes, and checkout your code on any computer that has access to your server.

Having used the 3 I mentioned I found Subversion the easiest to get started with and Assembla allows for *free private* SVN or GIT repositories.

# Answer
> 5 votes
As mentioned in other answers, a VCS is the way to go. Git is my favourite, but that could just be because it was the first one I used.

I found this online book very helpful for learning Git. http://progit.org/book/ Whatever VCS you go with, it's worth it to dedicate a few hours figuring out how to use it.

Another thing worth mentioning - VCS are great for source code (or any text files), but storing images and sound files can bloat your repository unnecessarily. Some people recommend a separate repository for this, but I find Dropbox works well for these kinds of resources.

For a school project, we used a public Dropbox folder, and used this script to keep our resources up-to-date https://github.com/dc2011/td/blob/master/tools/extrafiles.sh

It checks the md5 hash of the file in Dropbox against the hash of the file already on disk (if it exists) so that only new or changed files are downloaded.

# Answer
> 4 votes
As many have mentioned, you need version control. There is a nice free offering from FogCreek software (you have them to thank for providing stackexchange which makes this site possible). It is called Kiln (built on top of Mercurial) and it integrates with a nice bug/feature/time tracking software product they have built called FogBugz. For a team of 2 developers they provide free versions of these products (and host them for you). I use this setup for my own projects and the paid versions for all the software products I work on for my employer (we have a much larger team of developers, so must use the paid versions). Worth a look for sure.

If you do decide to use these, here are some good tutorials or useful links to get you started:

# Answer
> 1 votes
I would suggest Bazaar version control. It's small, practical, very good for small / one2few men projects. Git and SVN are used more often for larger projects/teams. Bazaar has in development VS plugin, but for you it doesn't make much of a difference using it outside VS. It's really easy to use it once you get to know it and initially set it up. It has few more plugins that get handy.

# Answer
> 1 votes
Tools that my team uses for smooth collaboration:

•GitHub, which if you have a little bit of money is an extremely cheap and easy way to host all your source. This is the version control platform that most people on here have been talking about. Think of it as a Pastebin account that exists on your local hard drive and is updated whenever any of your team members makes changes. Hosted projects are called depositories. There are loads of free Git clients, some of them integrate right into Windows to make keeping your depositories clean and up to date.

•Google docs for game design documents, ideas, concepts art.

•Occasional use of DropBox if one of us needs a specific asset or script...this is however rare and we prefer to work through GitHub.

# Answer
> 1 votes
If you ara using Visual Studio, the best option is Team Foundation, is from Microsoft and is the best Version Control that I know, the negative thing is that you need a server, sql server, and the team foundation server to run in the server (the client is already with visual studio), if you have the chance, try it.

# Answer
> 1 votes
For virtual pair programming, I use this setup(coordinating everything over Skype):

1. Install an SSH server on one of your machines.
2. Install tmux
3. The other person ssh's into your computer.
4. Have the host start a tmux session
5. Have your partner run 'tmux at' in his SSH connection

Now you and your friend will see the exact same terminal screen. But you probably want the ability to work together outside of your computer, right?

1. Make a Bitbucket.org account, create a project(I prefer Git), and follow their instructions on making an empty repository.
2. Copy your project's files over with "git add . && git commit -m 'Initial commit.'"
3. Push to Bitbucket with "git push origin master"

Now you and your friend can work on changes independently, and push them to Bitbucket when you're ready.

This won't let the both of you edit together in Visual Studio in any nice way, but you'll be able to edit the source code itself if you're pairing on some new feature or debugging a problem. As long as you push your changes afterward, your friend can open it up in VS.

# Answer
> -2 votes
Lots of good suggestions already but if you want to go for a low-tech and simple solution, this works for me when I collaborate:

1. Use comments at then head of each script to keep track of when it was edited, who by and when ie:

```
Vers      Date      Author   Note

1.0.1     12/10/11  Paul     Added a new boss to level 12
1.0.2     22/11/11  Frank    Fixed the bug introduced by Paul

```
2. A private forum or better still a Wiki is a good way to communicate ideas and keep everyone up to date with progress.

The ideas given already are better than this solution but this is very easy to implement with minimal time investment, for a small project with just a couple of people working together it might be sufficient for your needs.

Having worked for a large global organisation I can honestly say the amount of time lost due to red-tape surrounding their version control software (MKS) is a real pain!

---
Tags: tools, version-control
---


# Question
Title: Should the camera's rotation value be clamped?
I noticed that when writing a camera for my 2D game that the camera rotational value of -6 and 6 is equivalent to 0.

That is, -6 = -12 = -18 = -24 = 6 = 12 = 18 = 24.

I was wondering if it was considered good practice to always keep the rotational value between -6 and 6, like so:

```
    public float Rotation
    {
        get
        {
            return rotation;
        }
        set
        {
            rotation = value;

            if (rotation <= -6 || rotation >= 6) rotation = 0;
        }
    }

```

Does it matter either way?

# Answer
In XNA, the easiest way to do this is to just have MathHelper do the angle wrap-around for you all by itself, using code like this:

```
rotation = MathHelper.WrapAngle( rotation );

```

Here's what's going on, and how it works under the hood:

Your rotation value is expressed in radians. (Radians are like degrees, but instead of being in a range of \[0 .. 360\], they exist in a range of \[0 .. 2\*PI\] or \[-PI .. PI\], where PI is an irrational numerical constant approximately equal to 3.1415927.

To answer your question: Yes, it's usually considered good practice to keep angle values within your selected bounds. As you'd expect, an angle of 0 is identical to an angle of 2 * PI which is equal to an angle of 200,000 * Pi; they all represent exactly the same angle. But because of how floating point numbers are represented in a computer, very large numbers become less precise, so it's usually considered a good practice to keep them close to zero when it's practical to do so.

In XNA, PI is provided to you in `MathHelper.Pi`, and 2.0 * PI is provided in `MathHelper.TwoPi`. So a straight-forward way to unwind your angle into the \[-PI .. PI\] range would be:

```
while ( rotation < -MathHelper.Pi )
{
  rotation += MathHelper.TwoPi;
}
while ( rotation > MathHelper.Pi )
{
  rotation -= MathHelper.TwoPi;
}

```

If you prefer the \[0 .. 2.0 * PI\] range, then you could adjust the parameters in the 'while' loops above, to use those ranges instead.

In practice, of course, you actually want to use the MathHelper.WrapAngle function that I showed at the start of this answer. But this is the basic idea of what that function does internally.
> 6 votes

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


# Question
Title: SpriteBatch Draw Using Floats with the Destination Rectangle
So I created a nice little isometric tile engine and I have it so that when you scroll with the mouse it changes a variable called scale. Scale is a float and gets passed through the spritebatch.draw() function. I apply scale to all of the math I do when generating the positions of the tiles.

The problem I am having is Rectangle will not accept float numbers so when I make my Dest Rectangle for the spritebatch.draw() I can not use the numbers I need to because they are now floats.

I tried using vector4 instead of rectangle but the spritebatch.draw was throwing an exception saying it was expecting Rectangle not Vector4.

Is it possible to draw the dest rect using floats instead of ints?

Btw the scale is all working properly however since I am casting the floats to ints any scale that should have a decimal gets truncated and I end up with spaces between my tiles.

# Answer
Rather than drawing out through the destination rectangle, you could draw from a position and apply a scale.

```
Spritebatch.Draw(myTexture, // Texture
    myPosition,             // Position
    sourceRect,             // Source rectangle
    Color.White, // If you don't want to add tinting use white
    0,                      // Rotation
    null,                   // Origin
    Scale,                  // You guessed it
    SpriteEffects.None,     // Mirroring effects
    depth);                 // Layer depth

```
> 4 votes

---
Tags: xna, c#, xna-4.0, sprites, xna-content-pipeline
---


# Question
Title: How do 2D art assets (eg. sprites) work?
I have an idea on a game and planning on developing a 2D game using XNA for Windows Phone 7.

I've started off today by free hand drawing some concept art of what I want some of the characters to looks like. Now the problem is taking those concepts and putting them in digital form.

The first thing I realized I really don't know the different parts of game art. I know there are sprites, textures and animation but that is about it. I think textures are sprites on a 3D object but not sure if that is correct? Here are some general questions about game art I have:

* Do you use textures in 2D games?
* Where do you apply the different parts of game art? For example when you use sprites vs animation.
* What are the difference between sprites, textures animation and other art?
* Are sprites, textures and animation the only art elements to a game?
* Is all 2D art in games considered sprites? Characters, background, etc.
* What size do you make your sprite sheets and each character in a sprite sheet?
* Any good books or tutorials on teaching to draw art from a digital prospective? I was thinking about getting "GIMP Bible", however most books like this teach more photo editing than digital drawing.

My objective is learn how to take my concept art(backgrounds and characters) and put them into digital form using Gimp and learning about the different parts of game art.

Anyway, thanks to anyone that can help.

# Answer
> 11 votes
> I think textures are sprites on a 3D object but not sure if that is correct?

No.

Strictly speaking, a texture is a term for one or more images that are bundled together in an object called a "texture", within the context of a GPU-based rendering system. A texture can be used when rendering a 3D object. Or it can be used when rendering a 2D object, because 2D objects are just special cases of 3D objects.

A sprite is the term for an image, or part of an image, that is used to represent an entity (or part of an entity) in a game rendered with sprite/tile-based graphics.

You can put sprites *inside* textures. XNA does this internally, as it uses your 3D rendering system to render your stuff.

> Do you use textures in 2D games?

XNA does. And generally most people who make games with 2D graphics do. It's the fastest way. But ultimately, this is an implementation detail that you should leave up to XNA.

> Where do you apply the different parts of game art? For example when you use sprites vs animation.

This question is confused. Animations are *composed* of sprites. They're not separate things; one is a superset of the other. Typically you have a big image that holds multiple sprites that, when you flip between them, form animations.

> What are the difference between sprites, textures animation and other art?

Again, this question is confused.

> Is all 2D art in games considered sprites? Characters, background, etc.

Historically, "sprite" was used for things that move, while "tile" was used for things that don't move. However, you're using XNA, where "sprite" is used for both fixed and mobile things.

The historical reason was hardware-based. On 2D consoles, the hardware actually governed how sprites and tiles were rendered. It had hardware based tilemaps, scrolling, and sprite maps and animations. In modern graphics renderers, there's no need to make a distinction at the rendering level. Conceptually, you can make that distinction. But XNA makes you define your concepts.

> What size do you make your sprite sheets and each character in a sprite sheet?

Within the hardware limitations for your platform of choice, however you see fit. That's up to you.

However, if performance is a concern (and in 2D games it often isn't a big one), you will want to pack as many sprites as possible into as few images as possible. You generally want all the terrain for your level in one sheet, and common enemies to share the same sheet. Things like that.

But you don't have to go crazy with it. The biggest thing is getting your terrain in a sheet. If you have to use different sheets for the at most 40 other characters you might be drawing on the screen, that's not going to be a major performance issue.

---
Tags: xna, graphics, textures, graphics-design
---


# Question
Title: What is the ideal way to separate presentation and logic, and when is it OK to combine them?
I'm still somewhat new to "proper" design, but I'm trying to keep with it as much as possible. I thought I was OK but I've run across a slight dilemma: how should I be implementing the actual drawing and updating of entities?

For example, in my project I have a `TextBox` class. The 'easy' way, and the way that I usually see in tutorials across the Internet, are to give this class its own `Update()` and `Draw()` methods. But I don't think my textbox class should have to know anything about how it's being drawn, so I thought it might be good to make it implement some kind of `Drawable` interface, but even that still involves implementing drawing code.

So I thought of adding all my `TextBox`es to a `List<TextBox>` that a drawing class would load to handle the drawing, but then I realized that my `TextBox` class itself doesn't (and shouldn't?) have a `Draw()` method within the class, so I would have to write a sister method in the graphics implementation somewhere as a `DrawTextBox()` or something like that. I guess this COULD work, but I can't shake the feeling that having to have this kind of coupling of classes is bad practice.

So where should I ultimately be placing the code to draw, and where should I have the logic behind it? A `TextBox`, for example, involves drawing multiple elements, and it's timed because it's a typewriter-style output, and I eventually want to add in-text commands for delays and sound. Should I include some of this stuff in the main class? Have a Draw method in some graphics class somewhere else? And then later dealing with timing and sound, how should I be separating all of it?

# Answer
> 2 votes
The way I've always done it is to have each object draw themselves. It keeps everything in one place, you don't need to open up the internals for someone else to draw you, and therefore can increase encapsulation. This also allows you override the draw method to do something special in derived classes.

# Answer
> 1 votes
I think which way you chose to organize code depends on the scale of the game and how far you are willing to go out of your way to make the program beautiful and efficient.

That said I would have a Drawing class that implements every type of object that can draw to the screen in your game. Then have an interface implement these behaviors and pass that interface to the classes that need to make draw calls on objects.

```
class Sprite {}
class Player {}
class Enemy {}
class Terrain {}

public class DrawingManager : IDraw {}

public interface IDraw
{
    void DrawSprite(Sprite sprite);
    void DrawPlayer(Player player);
    void DrawEnemy(Enemy enemy);
    void DrawTerrain(Terrain terrain);
}

```

Since your using XNA you can pass the `IDraw` interface using `Game.Services` or you can write your own helper class for that. Either way if you want to achieve a typewrite type output (display a certain amount of text per frame I assume), this would work. Just keep a copy of the object in the `DrawingManager` (passed through by the interface), and once it reaches the end have some to clear it from the DrawingManager's list when its done.

# Answer
> 1 votes
I sometimes like to have the entity keep a reference to the object that will represent it on screen, and return that to the renderer object when it's time to draw everything.

Another way would be to have separate EntityRenderer objects in a list, each holding a reference to the entity in question, and deciding how to render it based on the entity's properties. This is close to a pure separation of responsibilities but can be a lot of work for little benefit.

---
Tags: xna, design-patterns
---


# Question
Title: How legal would it be to use some elements of the Half Life universe in my non comercial, indie game?
I'm planning to make a simple, HTML5 game, that would use some elements of the Half Life universe. Basically, it would be a 2D Portal clone, but it would have it's own story, and portals would be different, along with the mechanics of making and using them. Also, how far can I go with this? If possible, I'd like to have Gman, a character from Half Life, walk by a few times, and maybe even use some of the sounds from Half Life or Portal. It's also important to note that I wouldn't be making any kind of profit.

# Answer
> 6 votes
Using characters, ideas or other assets from another game is illegal if you do not have permission. As @Kylotan said: whether or not the game is non-profit does not change anything, either way you would be breaking laws around copyright and possibly patents too. That being said, there are games and other media based around Valve titles that have been created for which Valve have taken no action against. Doing what you described in your question would probably be OK with them too. However, I am not a lawyer and am in no way legally responsible if you do get a knock on the door about the game you intend to create. It's up to you if you want to take the chance.

# Answer
> 2 votes
Using their characters is not legal at all, nor is using their sounds (or graphics, or unique names). Your game being non profit makes no difference (except to the amount of damages you'd pay).

Copying gameplay is allowed, however. They don't own the concept of portals, but they are likely to own a trademark on the name 'Portal' in the context of computer games.

---
Tags: javascript, html5, legal, browser-based-games
---


# Question
Title: Is it possible to export a simulation (animation) from Blender to Unity?
I created an explosion animation within Blender, something as shown in this video. To achieve this I used a particle-system, together with the "Explode" modifier.

This kind of animation (simulation) doesn't get exported to other file-formats though and I'd like to export the animation as FBX, so that I can use it in Unity. So I basically need some way to "bake" the animation to keyframes. I wonder if there's a way to achieve this?

After some testing I found out, that the only way the simulation gets exported is by writing a sequence of `obj` files. So an answer on how to integrate/animate such a sequence of `obj` files in Unity would also be welcome.

*Side note:* I also tried to get an answer to this over at the blender community.

# Answer
> 5 votes
After countless tests (and some coding) I was able to find two valid approaches to the problem. Both aren't optimal solutions, but apparently there is none (exporting a simulation from Blender to Unity simply doesn't work).

### Approach 1: Export as obj sequence and swap meshes in Unity

Pretty straight-forward. Exporting a simulation using the `obj` exporter generates a separate file for every frame of the animation (if the "Animation" option has been toggled in the export options). Drag all these files into your Unity project (eg. into `Assets/Models/MyAnimation`). Then write a simple script to swap the mesh of the GameObject at runtime.

**Pros:**

* Animation is the same as in Blender

**Cons:**

* I haven't tested this with hi-poly meshes or multiple concurrently playing animations, but most likely it's going to have an impact on performance.
* It's really cumbersome to drag each mesh file separately onto the script component. Not really feasible for an animation with lots of frames. See image below (each `Element` in the `Meshes` array is a file with the mesh for that frame):

### Approach 2: Create the explosion procedurally within Unity

This approach is a mixture of the approach proposed by Jonathan Dickinson and the way the explode-modifier works in Blender. In Blender, the explode-modifier uses a particle-system to determine the movement of shards/shrapnels caused by the explosion.

I wrote a script that splits the mesh into triangles and uses a `ParticleSystem` to animate the triangles.

**Pros:**

* Works with any mesh.
* Behavior/animation can easily be tweaked by modifying the particle-system. For best results, the simulation has to be in world-space and the particle-renderer should be turned off (see screenshot below).

**Cons:**

* Explodes into plain old triangles, which doesn't look very natural.
* With hi-poly meshes it hits the CPU hard when the mesh is being split into triangles. This could be optimized though.

### Comparison

Here's a video that shows both types of animation in effect. The used scripts (both written in C#) can be found here:

### Update: MetaMorph

Thanks to the Blender Community (especially the users *chipmasque* and *enzyme69*) I was pointed towards a third possible solution, which is MetaMorph. It's a Unity script and a Blender export addon which allows you to export shape-keys from Blender and play them in Unity. While there seems to be some issues with getting a shape-key animation from an explosion, it should work fine for other types of simulations and other shape-key driven animations (eg. facial animations/morphs etc.).

# Answer
> 3 votes
*I'm going to go ahead and answer this with the procedural approach. I'll assume you have a workable knowledge of linear algebra. I am going to hash over this quite quickly so feel free to ask me to expand on any point of the answer.*

Consider this overhead:

* Storing each model in memory (and disk) using a vertex buffer (or whatever your graphical platform uses).
* Having to render this buffer each frame; this includes swapping buffers in and out of GPU memory.

This isn't too different from this:

* Having to determine the 'broken' parts of the mesh (this can be pre-calculated during your build).
* Having to fill a buffer each frame (set up with discard-on-write).
* Having to render this single buffer each frame.

I would strongly recommend at least ***experimenting*** with a procedural approach to this.

Essentially what you need to do is find the normal of each triangle face, and choose a extrusion distance (just a constant that you can tweak, most likely). Following that create a new set of vertices for each triangle offset by `Extrusion * -Normal` (they can likely inherit the UV coord of their original vertex). Finally wire them up in the index buffer - which you can keep as static data (so long as you retain the order of the triangles). This can be done when you load meshes that can explode; or as part of your build phase. Remember that shared vertices (arising due to index buffers or such) need to be duplicated. I would essentially store the data in something like the following structure:

```
ExtrudedTriangle
{
   Vector3 A, B, C, D, E, F
   Vector3 TA, TB, TC // Texture coords, D, E, F are same as A, B, C
   Vector3 Translation
   Quaternion Rotation
   Single Scale // Possibly
}

```

Now when you need to fill the buffer all you need to do is go over each triangle (in order) and append it to your vertex buffer. You don't need to worry about the indicies as those are constant. *This is very similar to how sprite particle system works (except the indicies are not constant).*

You can also skip filling the vertex buffer each frame by additionally passing in the `offsetToCenterOfExtrudedTriangle`, `originalCenterOfExtrudedTriangle` and `extrudedTriangleNormal` into the vertex buffer. You can then have your vertex shader animate each individual vertex.

---
Tags: animation, unity, blender
---


# Question
Title: Why are changes in one object applied to all objects in a list?
I've got two List:

1. **BasicModels**: As Content has to be loaded at the start of the game I instanciate and load all models into this list.
2. **ModelsOnScreen**: Every time when a Model is added to the screen I take the corresponding object out of **BasicModels** and put it into **ModelsOnScreen**. At the same time I write the ID of the Model at it's location in ModelsOnScreen.

So the problem is though I change the Id at a specific place in the list, changes are applied to all models in **ModelsOnScreen**.

```
 for (int i = 0; i < _game.Models.Length; i++)
        {
            if (assetName == _game.Models[i].name.ToString())
            {
                _game.modelsOnScreen.Add(_game.Models[i]);
                _game.modelsOnScreen[_game.modelsOnScreen.Count - 1].ID = nameCounter;
            }
        }

```

What could be the problem? My theory is that the Models I put into ModelsOnScreen are only references, no separate instances. If that is so, how could I solve this problem?

Any advice is welcome,

greets BC++

# Answer
Yes, your suspicion is correct — the `.Add()` method does not make a copy of the model, so when you change `_game.modelsOnScreen[_game.modelsOnScreen.Count - 1]` you are also changing `_game.Models[i]` — they refer to the same object. It's rare for a function to make a copy of an object.

If you want many different IDs associated with the same Model, then make a new class/struct that stores an ID and a model, and create a new instance of that for each ID.
> 1 votes

# Answer
As far as I can tell, nameCounter is being assigned to the ID property of every single model added to modelOnScreen. Look closely at the loop and you'll see that your code is equivalent to:

```
for (int i = 0; i < _game.Models.Length; i++)
{
    var model = _game.Models[i];
    if (assetName == model.name.ToString())
    {
        _game.modelsOnScreen.Add(model);
        model.ID = nameCounter;
    }
}

```

If you only want to modify the last model added (I presume that's your intention?) move that assignment out of the loop and only do it once every model has been loaded. And yes, models are probably references, if you are using classes for them. Value types in C# are structs, enumerations and primitive types.
> 0 votes

---
Tags: xna, objects
---


# Question
Title: SFML Segmentation Fault when using VBOs?
I'm trying to follow along with the gltut tutorials and for some reason when I call GLDrawArrays my program segmentation faults. I've been looking at the state of my application with the Mac OpenGL Profiler and Googling and I can't seem to figure out why it isn't working. I may have missed setting some OpenGL state somewhere.

My code is here, it segfaults on line 32. If I don't call `glEnableClientState(GL_VERTEX_ARRAY);` and the respective `glDisableClientState(GL_VERTEX_ARRAY);` it compiles and runs, but I get no rendering, which is what I would expect given my limited OpenGL knowledge.

# Answer
Well, there are a couple of things that are... odd about this code.

### First:

```
glDrawArrays(GL_TRIANGLES, 0, 2);

```

That will never actually draw anything. Triangles are made of 3 vertices and you told it to read 2.

I doubt that's causing the seg-fault, but it might be. Just change the 2 to 3.

### Next:

```
const float vertexPositions[] = {
  0.75f, 0.75f, 0.0f, 0.2f,
  0.75f, -0.75f, 0.0f, 0.2f,
  -0.75f, -0.75f, 0.0f, 0.2f,
};

```

Again I'm not sure how you copied that wrong, but the "0.2f" for the W component should be "1.0f".

### The source of your segfault:

```
glEnableClientState(GL_VERTEX_ARRAY);

```

Why do you call this? OK, I know why you're calling it. You've somehow taken a tutorial that's supposed to be showing you how to do modern, shader-based OpenGL, and are adapting it to fixed-function stuff.

If you are, then you need to adapt it *properly*.

`glVertexAttribPointer` is for setting up generic vertex attributes. You *cannot* use generic vertex attributes with fixed-function rendering. If you're going to do things in fixed-function, you need to actually do them in fixed function:

```
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(4, GL_FLOAT, 0, 0);

glDrawArrays(GL_TRIANGLES, 0, 3);

glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);

```
> 4 votes

# Answer
My guess: You have 12 floats for your positions. You are telling to OpenGL that each vertex should be 4 floats by second parameter in here: `glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);`, so you have 3 vertices for these.

Then you tell OpenGL to draw 2 triangles in glDrawArrays command. But this would need 6 vertices - 3 vertices per triangle. So this could cause segmentation fault. Try to draw just one triangle or add more vertices.
> 0 votes

---
Tags: opengl, rendering
---


# Question
Title: What are some of the more commonly used projectile rendering techniques?
couldn't find a duplicate question (bit surprising to me) but anywho I'm starting to get near implementing the rendering of projectiles for my game.

My question is what are some good techniques for efficiently rendering projectiles? I would like emphasis on techniques that leave room for the projectiles to be "rich" and dynamic (Cool to look at!)

I'm also using DX11 for my rendering engine so bleeding edge techniques that can make use of that would be much appreciated too.

Thanks!

# Answer
(I'm going to assume you are talking about a 3D game; if you mean a 2D game then you should specify that in your question.)

Different kinds of projectiles necessitate different approaches to visualizing them, with the three main kinds being: use a 3D model to represent the projectile (eg. a missile in an FPS), use a billboard sprite to represent the projectile (eg. a laser in a space sim), or use a particle emitter to represent the projectile (eg. a magic blast in an RPG).

Using a model for the projectile is pretty straightforward. Simply make a 3D model of the missile or whatever and move that model through the air when the weapon is fired. Often you actually combine this with a particle emitter to do, say, the flame exhaust of a missile, although shots like arrows from a bow would be just a 3D model with no particle system.

Using a billboard sprite is similar to using a model, but instead of a full 3D mesh the projectile is only a single quad. Apply a picture of the projectile as the texture on that quad. Sometimes the quad is stretched from gun to target (eg. a laser). If the projectile is something like an energy ball then the sprite is usually set to face the camera completely, but if the projectile is a laser then you want to set the sprite to rotate toward the camera around its long axis and not on either of the other axes.

Using a particle emitter for the projectile requires you to first implement a particle system in your game. With the particle system in place, spawn an emitter (ie. the point the particles emit from) at the weapon and move the emitter through the air to the target.
> 2 votes

---
Tags: rendering, particles
---


# Question
Title: general routine of creating real video games?
i'm new to game developement and i want to fill the missing spots in the proccess of creating games for PC. my intentions are for first person action games like "return to castle wolfenstein", "hitman" or "call of duty" series. i've done some interior designs in autodesk 3ds max and also wrote web/windows programs in c#. so now i like to know how games works. here is what i came up with:

first: create models and export them in whatever format your rendering engine prefers. so any object has to be modeled seperatly no mater what kind of object it is.

second: tell the engine where and when to render which object.

Q1) what about object behaviors?do you use the 3d software built in scripting like maxscript? or is there some other way to create behaviors in advanced levels?

Q2) how do you create clipping for objects? since by default graphical shapes don't have such a feauture.

Q3) most of those games played in a virtual world. so do you have to create the world at once? or is it actually seperate pieces that will be assembled by rendering engine?

i know these are very deep questions that can't be simply answered in a few lines. so if there is any book that is not too detailed and not too general, i'll be really appreciate knowing about it. in any case i really appreciate your answers.

# Answer
> 4 votes
This is a bit of the "how does the world work?" question, but I'll try and give you a summary, since I don't know of any book that answers this succinctly without walking you through each step in turn.

The objects that get rendered are usually made with 3DS Max or Maya, and then exported in a format that your engine can read. Most existing engines have custom exporters, or can read one of the existing model formats (eg. FBX, Collada).

The positioning, movement, and behaviour of the objects once the game is running is all dictated by the game code. In most commercial games, this is written either in C++, or in a language specific to the engine (eg. Unrealscript for Unreal, C# or Unityscript for Unity, etc), or some combination of the two. Some of the functionality will come from the engine, some is made specifically for each game. This is basically what the programmers are spending years doing when each game gets made.

I don't know what you mean by 'clipping' for each object, but if you mean detection of collisions then there are algorithms that measure a model and determine its shape and size, and can compare those dimensions against those of other objects (eg. the floor, walls, projectiles, other characters). What happens when a collision is detected is decided by the game code.

Each engine has a different way of dealing with a virtual world. Some will load it in as basically one large piece of geometry made in a level editor or 3D package. (Indoor settings are often done in a way similar to this.) Others might store it as a height map plus a variety of decorations such as rocks, trees, etc. (Outdoor games are like this.) In each case it might be possible that one single model or terrain is not big enough, so you create several and work out some way of stitching them together at run time - again, this is handled by the engine and the game code.

---
Tags: 3d
---


# Question
Title: Building different game objects (EG Spells, Items,) for an rpg game
I believe the best way to manage item data would be to use xml?

For spells would the best option be to create a class (EG Fireball) and define all of the parameters inside of that class? Like Initilize Update and Draw? Then have a class called ParticleEngine and define Inside of fireball the type of particles to use?

Something like ParticleEngine Effects = new ParticleEngine(texture1,texture2,texture3,amountofparticles,offset,delay,life)

Or is there a better way to handle all of this?

What are some different stuctures and or what is the most efficient way of handling all of that data?

# Answer
> 5 votes
The choices you make in code depend upon what your expectations are for the game.

* How many different skills/items are in your game?
* How much code do they share in common?
* Do they interact with each other?
* How does the player obtain new skills/items?
* How often will you release new skills/items?
* Can users create their own?

Let's say you're creating a single-player game where you expect the player to go through 10 levels and get a new skill at the end of every level. In that case, you don't need a complicated system for managing skills. You could simply create a new class for each skill and hard code specific methods for each skill (e.g. `Shoot()`, `Summon()`, `SetOnFire()`).

On the other hand, let's say you're creating a multiplayer game with a release cycle of a new skill every week, and you expect to have hundreds of skills. In that case, you need an easy way to deliver new skill definitions to players, so XML or some binary format makes sense. Additionally, skills will likely share a lot of features, so a component-based entity system makes sense.

The same logic applies for your question about the fireball skill and particle system. Is the fireball skill the only class that will be using particles? In that case, just hard code the relationship. If many skills will be using particles, then you may want to use a message passing system, so that any entity can request a particle to be created without needing a reference to the actual particle system object. You could use dependency injection if you expect to have multiple types of particle systems.

There's no correct answer to code architecture, just a bunch of tradeoffs that you decide upon that best fits your game and development team.

---
Tags: xna, c#, game-design, game-mechanics, xml
---


# Question
Title: How to prevent 2D camera rotation if it would violate the bounds of the camera?
I'm working on a `Camera` class and I have a rectangle field named `Bounds` that determines the bounds of the camera. I have it working for zooming and moving the camera so that the camera cannot exit its bounds.

However, I'm a bit confused on how to do the same for rotation. Currently I allow rotating of the camera's Z-axis. However, if sufficiently zoomed out, upon rotating the camera, areas of the screen outside the camera's bounds can be shown.

I'd like to deny the rotation assuming it meant that the newly rotated camera would expose areas outside the camera's bounds, but I'm not quite sure how. I'm still new to Matrix and Vector math and I'm not quite sure how to model `if the newly rotated camera sees outside of its bounds, undo the rotation`. Here's an image showing the problem:

https://i.stack.imgur.com/NqprC.png

The red is out of bounds and as a result, the camera should never be allowed to rotate itself like this. This seems like it would be a problem with all rotated values, but this is not the case when the camera is zoomed in enough.

Here are the current member variables for the `Camera` class:

```
private Vector2 _position = Vector2.Zero;
private Vector2 _origin = Vector2.Zero;
private Rectangle? _bounds = Rectangle.Empty;

private float _rotation = 0.0f;
private float _zoom = 1.0f;

```

Is this possible to do? If so, could someone give me some guidance on how to accomplish this? Thanks.

**EDIT**: I forgot to mention I am using a transformation matrix style camera that I input in to `SpriteBatch.Begin`. I am using the same transformation matrix from this tutorial.

# Answer
I've written an article before called Limiting 2D Camera Movement with Zoom which shows you how to translate and zoom the camera freely without never letting it show beyond some predefined bounds. Whenever you move or zoom the camera, its position and zoom are automatically validated. Unfortunately, I did not cover rotation in that article because the math required would be a lot trickier.

**However**, that's only because instead of *simply undoing* the movement to the latest known valid orientation, I was actually taking care of clamping it back to the *closest valid orientation* instead, and I haven't figured out how to do that for rotation.

But in your case, **if you only care about undoing the rotation** whenever the camera sees outside its bounds, then it's actually *pretty easy* to do! Here's a step by step guide on how to implement that.

---

**Step 1**

Assign the new camera rotation but keep track of the old rotation value too. If you cache your view matrix, be sure to update it because it will be needed for the next step. Example:

```
float previousRotation = _rotation;
_rotation = value;

```

**Step 2**

Calculate the *positions of the four corners of the camera in world space*. In order to do that you only need to transform each of the viewport's corners (i.e. in view space) by the inverse view matrix. Example:

```
// Calculate the inverse of the view matrix
Matrix inverseView = Matrix.Invert(ViewMatrix);

// Storing viewport size just to make code below smaller
float vh = viewport.Height;
float vw = viewport.Width;

// Calculate four corners in world space
Vector2 tl = Vector2.Transform(new Vector2(0, 0), inverseView);
Vector2 tr = Vector2.Transform(new Vector2(vw, 0), inverseView);
Vector2 bl = Vector2.Transform(new Vector2(0, vh), inverseView);
Vector2 br = Vector2.Transform(new Vector2(vw, vh), inverseView);

```

**Step 3**

Revert back to the old rotation if *any of the corners lies outside of the camera's bounds*. Example:

```
if(!bounds.Contains(tl) || !bounds.Contains(tr) || !bounds.Contains(bl) || !bounds.Contains(br))
{
    _rotation = previousRotation;
}

```

*Note:* XNA's `Rectangle` stores ints, not floats, so you'll have to convert between `Vector2` and `Point` (and cast the vector components to ints) to use `Contains` **or** use a `RectangleF` structure such as this instead.
> 2 votes

---
Tags: xna, c#, camera, matrix, vector
---


# Question
Title: What's the right/standard way of achieving separation of concerns?
Some background:

I want to start developing games, and taking some of the advice given in this site, I've started with something simple and familiar, such as pong, tetris, etc. I want to take as much time as needed to make sure that I have the basics right before moving on to something bigger. I have medium programming experience but I realize making games is a different thing.

I find myself wondering many things like should this be in a separate class? Should this module handle this stuff or is it better to let other modules have that kind of functionality? For example, the bouncing of a ball in pong, right now is handled in the ball module, but maybe it's better that some other module did it.

Right now I have different modules: one for the graphics, one for the game logic, and others for the objects (depending on the kind of movement required, not all the objects are alike). I know I am asking a lot, any tips you have will be very much appreciated.

Short question:

What's the right or standard way of separating the modules? What have you found most effective? Is it enough to just keep the drawing (graphics) and the logic separate? Is it necessary to have a lot of classes? (for example for the objects in the game, to handle the movement, etc)

# Answer
The way I generally have learned any aspect of programming including game engine design is by reading books then making something crappy and realizing it was crappy because I ignored the patterns in the books. So I read the books again.

The books I have on this topic have been very helpful:

* Applying UML and Patterns (Craig Larman)
* Software Engineering for Game Developers (John Flynt)
* Game Engine Architecture (Jason Gregory)

The patterns as suggested in the comments, are very similar or exactly the same across all types of applications including games. **Before you start worrying about game engine specific patterns, I would look into the more general design patterns. Pick a language you like and find a book called "design patterns in \[language name\]". Since the patterns are so similar, once you know them, apply them to a game like tetris as you've suggested and you'll start to see their benefits.**
> 2 votes

---
Tags: architecture, software-engineering
---


title: How should I manage multiple entities?

text:
# Question
Title: How should I manage multiple entities?
Before I start making a game, I'm trying to figure out how I will manage things. One of the first things I'm not sure about is how to manage entities (enemy, player, projectile...)

I'm going to be using either C, C++, Java, or C#

One of the ideas I have is to use one array for projectiles and one for enemies. Each time I have a new entity, I grow my array. Here is the problem: If player/enemy is firing, that creates a new entity which means the projectile array is growing.

Suppose its projectile #2053, when it hit something, I free it, then in my loop to check which projectiles are to do something, like getting closer to there target, I check if every # of my array to see if its null, if not, check is trajectory. But the problem is that the array will grow each time a new projectile is fired, and I will get a memory problem at the end.

So how should I manage my entities?

I need an awnser that covers both object oriented and procedural, since I mainly do things in C.

# Answer
In general, you want to avoid `free`ing objects in your game. Generally, games are designed in such a way that when you load a level, the maximum number of objects are created while loading and only destroyed when exiting the level (sometimes, even that is not done so that the next level, which uses the same player/enemy classes loads even faster without an increase in the amount of memory used). Most games have pre-determined limits which the programmers can then work with (e.g. decal limits, maximum enemies, maximum bullet shells, maximum particle count) and sometimes this can be adjusted by the player.

Of course, this done not work for bigger games, such as Mass Effect, in which case complex memory pools are setup specifically for the purpose of avoiding memory fragmentation, lowering load times or eliminating them altogether (e.g. God of War).

I would recommend to start off by marking your projectiles as *active* or *inactive* instead of destroying them. The simplest memory pool will be a `vector` array where you reserve, let's say, 3000 projectiles\[\*\]. Each projectile has a variable which lets you know when to update (alternatively, you can have your `vector` store `std::pair<bool, projectile>` where the `first` variable of the `pair` will let you know if an update is required).

In your update loop, simply iterate over the projectiles and update only the ones that require updating. You may think this is slow, but it is very very fast. I myself initially thought this sort of thing would be very slow and though a list would be better. Problem with `list` is that you lose cache coherency and you end up taking a hit by all the cache misses (no idea what I am talking about? Don't worry! :).

**EDIT:** I just saw your tag, which is `C` and not `C++` in which case you will not be able to use `vector` containers. That is not a show stopper. See the answers to this question for libraries that simplify management of arrays (among other things).

<sub>\[\*\] Use `resize()` to create the projectiles as well. If you are using pointers to projectiles, then `reserve()` and `push_back` 3000 `new` projectiles. If your projectiles are big objects, I would store pointers rather in the `vector`.</sub>
> 3 votes

---
Tags: software-engineering, c
---


# Question
Title: How to generate random points on the surface of a quadrilateral
Alright, I'm sure there has to be a simple way to do this but it eludes me at the moment.

I want to be able to generate random points on the surface of a quadrilateral in 3D space. (Defined simply as four points) What is the best way to go about doing this?

If the quad is a rectangle, this is trivial to do with random interpolation between points. However, this won't work for me since my quads aren't guaranteed to have rectangular properties.

# Answer
Cut the quad into two trianles, get their area size, then first random-pick one of the triangles (based on their areas) and finally pick a random point in the triangle using your favourite standard algorithm for triangles.
> 6 votes

# Answer
You can easily do this with a variant of bilinear interpolation. For example

```
Point randomInQuad(Point a, b, c, d) {
  double s = random(0.0,1.0);  // uniform in [0,1]
  Point e = s*a + (1-s)*b;
  Point f = s*c + (1-s)*d;
  double t = random(0.0,1.0);
  return t*e + (1-t)*f;
}

```

You can interpret this as putting each of the vertices of your quad at a corner of a unit square. Then, you randomly pick a point in the unit square. Finally, you use bilinear interpolation (which is a series of affine combinations) to interpolate a vertex at that point.
> 2 votes

---
Tags: mathematics, random
---


# Question
Title: How do you implement 2D collision detection?
I would like to know the best or most efficient way to test for 2D collision.

I am currently using AABBs, but the problem with this, is that your objects will be hitting things when they shouldn't. On top of this, AABBs cannot be rotated.

I was considering using per pixel collision, but I feel that it would lag on large bitmaps, since there would be a lot of pixels to check.

What I would like to know, is how I can allow my bounding boxes to be rotated, and use any polygon instead of just rectangles for collision. Also, is there a way of creating circular collision bounds that aren't just approximations of circles?

# Answer
> 6 votes
So it depends on what you are trying to do.

If you want something simple, I recommend stick with axis aligned AABBs for most things - they make collision detection really easy.

Generally when you're writing collision code you'll have to write specialized cases for all pairs of shapes (ie. line-line, line-circle, line-box, circle-line, circle-box, circle-circle, box-box).

For 2D, the main principle is called the Separating Axis Theorem. This is an excellent guide to it.

Typically another trick that people use is to have multiple layers of collision detection to speed things up. Circle-Circle collision might be expensive, but if you check whether the two circles AABBs are overlapping first, you can potentially save a lot of time.

If you are really wanting to have more advanced physics and response, I would recommend that you go with an already made physics engine. JBox2D is a port of the popular Box2D engine, and is generally quite good. That said, I would still recommend reading through those two articles so that you have an understanding of what is going on behind the scenes with collision detection and response.

---
Tags: 2d, collision-detection
---


# Question
Title: How to refactor and improve this XNA mouse input code?
Currently I have something like this:

```
public bool IsLeftMouseButtonDown()
{
    return currentMouseState.LeftButton == ButtonState.Pressed && previousMouseSate.LeftButton == ButtonState.Pressed;
}

public bool IsLeftMouseButtonPressed()
{
    return currentMouseState.LeftButton == ButtonState.Pressed && previousMouseSate.LeftButton == ButtonState.Released;
}

public bool IsLeftMouseButtonUp()
{
    return currentMouseState.LeftButton == ButtonState.Released && previousMouseSate.LeftButton == ButtonState.Released;
}

public bool IsLeftMouseButtonReleased()
{
    return currentMouseState.LeftButton == ButtonState.Released && previousMouseSate.LeftButton == ButtonState.Pressed;
}

```

This is fine. In fact, I kind of like it. However, I'd hate to have to repeat this same code five times (for right, middle, X1, X2). Is there any way to pass in the button I want to the function so I could have something like this?

```
public bool IsMouseButtonDown(MouseButton button)
{
    return currentMouseState.IsPressed(button) &&  previousMouseState.IsPressed(button);
}

public bool IsMouseButtonPressed(MouseButton button)
{
    return currentMouseState.IsPressed(button) &&  !previousMouseState.IsPressed(button);
}

public bool IsMouseButtonUp(MouseButton button)
{
    return !currentMouseState.IsPressed(button) &&  previousMouseState.IsPressed(button);
}

public bool IsMouseButtonReleased(MouseButton button)
{
    return !currentMouseState.IsPressed(button) &&  previousMouseState.IsPressed(button);
}

```

I suppose I could create some custom enumeration and switch through it in each function, but I'd like to first see if there is a built-in solution or a better way..

Thanks!

# Answer
> 7 votes
The naming of your functions is hard to determine, and looks like you've just covered the 4 boolean cases. For example, what is the purpose of `IsMouseButtonsDown(MouseButton button)`? The only case I can think of is where you want to keep a flag for a player holding down a key to charge something up. But you'd probably want to keep that flag stored elsewhere.

For checking inputs, I like to do something like this:

```
[Flags]
public enum MouseButton
{
    Left   = 0x01, // equiv 0b0001
    Middle = 0x02, // equiv 0b0010
    Right  = 0x04, // equiv 0b0100
    None   = 0x00  // equiv 0b0000
}

public class MouseInput
{
    private MouseButton mouseButtonsThisFrame;
    private MouseButton mouseButtonsLastFrame;
    private MouseState currentMouseState;

    public void update()
    {
        mouseButtonsLastFrame = mouseButtonsThisFrame;
        mouseButtonsThisFrame = MouseButton.None;

        currentMouseState = GetMouseState();
        mouseButtonsThisFrame |=  currentMouseState.LeftButton == ButtonState.Pressed ? MouseButton.Left : MouseButton.None;
        mouseButtonsThisFrame |=  currentMouseState.MiddleButton == ButtonState.Pressed ? MouseButton.Left : MouseButton.None
        mouseButtonsThisFrame |=  currentMouseState.RightButton == ButtonState.Pressed ? MouseButton.Right : MouseButton.None;
    }

    public bool wasPressed(MouseButton button)
    {
        // Not quite clear and correct as noted by Cypher
        //return (mouseButtonsLastFrame & button) == button && (mouseButtonsThisFrame & button) == button;

        // This is a little better
        return (mouseButtonsLastFrame & button) == button && (mouseButtonsThisFrame & button) != button;
    }

    public bool isDown(MouseButton button)
    {
        return (mouseButtonsThisFrame & button) == button;
    }

    public bool isUp(MouseButon button)
    {
        return ((mouseButtonsThisFrame ^ button) & button) == button;
    }
}

```

That way you can check for something in your update loop like so:

```
public void update()
{
    if (mouseInput.wasPressed(MouseButton.Left | MouseButton.Right) {
        ExecuteDoubleMouseButtonComboAttack();
    } else if (mouseInput.wasPressed(MouseButton.Left)) {
        ExecutePitifulSingleMouseButtonAttack();
    }
}

```

Of course you'd want to introduce some timing compensation for the double button stuff, but this style of managing input has proven to be nice and flexible for me. Like ClassicThunder says, you're kind of stuck in a polling model with XNA. The system event work around works but only if you don't want to deploy to Xbox.

# Answer
> 2 votes
In the example that you wanted to achieve, you used a `MouseButton` enumeration, but unfortunately there's no such type in XNA.

Nonetheless, I would actually recommend you to go ahead with your idea, create that enumeration yourself and branch on it. It's what I do on my projects and it's also useful when I want to store which mouse buttons were pressed inside an event. And if you mark it as `Flags` you can even store and check for multiple buttons at once:

```
[Flags]
public enum MouseButtons
{
    None = 0x0,
    Left = 0x1,
    Middle = 0x2,
    Right = 0x4,
    X1 = 0x8,
    X2 = 0x10
}

```

But since you asked if it was possible to write something like `currentMouseState.IsPressed(button)` here's an extra trick. If instead of passing it an enumeration you don't mind passing it the *name* of the button, then **it is possible** using a little bit of reflection and an extension method. Just add this class to your project and you're good to go:

```
public static class MouseStateExtension
{
    public static bool IsPressed(this MouseState state, string buttonName)
    {
        return (ButtonState)(typeof(MouseState).GetProperty(buttonName).GetValue(state, null)) == ButtonState.Pressed;
    }
}

```

The result would be that you could then call it by writing `currentMouseState.IsPressed("LeftButton")` or any other valid button name.

Not that I would really recommend going this route, but it's good to be aware of the alternatives. And of course it only works if you pass it a valid property name of type `ButtonState`, otherwise it will crash.

# Answer
> 0 votes
> Is there any way to pass in the button I want to the function so I could have something like this?

Nope. Such functionality is built in for the keyboard but not the mouse.

Personally I hate how XNA handles mouse input. If you want an alternative take a look at this. It has a delegate that translates messages sent to the window your game is embedded in then fires events specific to the type of input.

Most useful of these for you are the below.

```
/// <summary>Event raised when a mouse button is pressed.</summary>
public static event MouseEventHandler MouseDown;

/// <summary>Event raised when a mouse button is released.</summary>
public static event MouseEventHandler MouseUp;

```

Which allow for event driven input.

```
InputSystem.Initialize(Game.Window);

InputSystem.MouseUp += delegate(Object o, MouseEventArgs e) {

    switch (e.Button) {
        case MouseButton.Left:
        case MouseButton.Middle:
        case MouseButton.Right:
        case MouseButton.X1:
        case MouseButton.X2:
        break;
    }
}

```

---
Tags: xna, c#, input, design-patterns
---


# Question
Title: What would be the most efficient mechanism to implement branching choices?
I am developing a Windows game engine that will let you create games styled like *"Phoenix Wright: Ace Attorney"*. I have finished developing the data entry parts (evidence, profiles, animations, etc.), and now I am going to create the scene editor. With this editor, you can create courtroom scenes.

I am having a particular game-flow design problem with "choice branches", where the player can select an option from many, and something will happen depending on the choice. How should I design such thing? I have no problems creating a linear flow (action, action, action, etc.), but I am confused by things like cross-examination or chatting involve branching choices (action; if did something, do this; if did something else, do that; etc.).

What would be the most efficient mechanism to organize such branches for my design, in the simplest way for the user to understand? I don't want to make it too complex for the user to make a game with the engine.

# Answer
> 3 votes
A Finite State Machine would seem to fit this type of flow. Users can easily understand a FSM with very little explanation. You might organize individual states such that they have entry and exit events. For instance when you enter the state, graphics/text xyz are displayed.

The exit conditions for each state are simply the choices that the user can choose from. Based on the choice made, you enter a new state or possibly loop back to the existing state.

---
Tags: game-design
---