# Question
Title: Implementing a wait function in a game script
I have been implementing behavior for enemies in my game and so far I have been doing it sort of like below:

```
public void update()
{
    if (frame > 60 && frame % 30 == 0)
    {
        shootAtPlayer();
    }
    frame++;
}

```

Which is meaning after frame 60 shoot the player every 30 frames. The frame-count is important as the game is fixed frame-rate and everything is relying on this at the moment. There are many small scripts for enemy behavior like above and I currently iterate through each one calling update(). I have realized it will quickly get unweildy dealing in absolute frames and I want to move towards a pattern where I can specify to do X for 60 frames then do Y e.t.c, something that is easily understandable and easy to write. I want to go for something like below:

```
wait(60)
while(true)
{
    shootAtPlayer();
    wait(30);
}

```

I was wondering if there is a design pattern that would easily support such a syntax. My initial thoughts were to create a thread for each script object and have the wait implemented similar to below:

```
wait(int frames)
{
    while(frames > 0)
    {
        frames--;
        suspend();
    }
}

```

with the method running the scripts calling resume in turn on each script. I could potentially have up to 300 scripts running at once which would mean 300 threads to handle. Am I taking the correct approach to solving this problem?

I am programming this in C# XNA.

# Answer
> 3 votes
It would be simpler to create to use events and fibers

Using a fiber means you can `yield` and `return` how many frames to wait until it should be called it again.

Then with a priority queue you can iterate over all events scheduled for the current frame.

```
IEnumerator<int> ai_script()
    yield return 60;
    while(true)
    {
        shootAtPlayer();
        yield return 30;
    }
}

```

and then in the gameloop

```
while(running){

    frame++;
    updateFysics();

    IEnumerator<int> ie;
    while((ie = delayQueue.Pop(frame))!=null){
        if(ie.MoveNext()){//move next then does the call true means there is another wait, false means the task is done
            delayQueue.add(ie,ie.Current+frame);//Current holds the delay requested
        }
    }

}

```

This solution is heavy misuse of C# syntax, but you can use explicit `Fiber`s instead.

---
Tags: xna, c#, software-engineering, ai, scripting
---


# Question
Title: Protecting the integrity of a game state while minimizing amount of data sent
I'm developing a multiplayer game in PHP/jQuery, and naturally have to be wary of any sort of data coming from the client.

At present, I have tables of data representing the map (2D roguelike), monsters, items, and player(s). Initially, my thought was to simply package it all in a JSON object and send it every game tick, however when actually looking at the data I realized that's quite a large packet to be sending.

So, my question is what is a good approach for minimizing data sent to the client? Obviously I would need to figure out some way of validating whatever it sends back. Initially we'd hoped to do some minimal verification on the client-side, but each time we thought of one thing we could do it is immediately invalidated with tools like Firebug.

Kind of an open question I realize, but we want to get this right before we move on with our implementation so we don't have to shoehorn in bugfixes later on.

# Answer
Depends on what information they are already expected to have. For example, if they have the map already on their client, then you only need to send information about non-static things within the map. If they don't have the map then you should try and only send them map data for the area that they're in, and, when sending them information about non-static objects, only send those for the area that they're in as well.

For a 2D game I would have an axis-aligned rectangular/square region (on the server) that represents the area that encompasses everything they would need to know about based on their location. Send them information about objects when they enter the region, and then send them updates on those objects whenever the state of that object changes, then you can send them a small packet when something leaves that area so that they know to delete it from their client. By doing this on the server the server will have a list for each player of the objects that the player cares about and has loaded on their client, and so whenever any object's state changes in a way that a client may care about, have that object call a method on the server that checks if any player currently has that object in range, and if so then you can prepare a packet for that player. I've seen this architecture work on a shipped and successful MMO, I'm sure it could be done for a 2D game as well.
> 3 votes

# Answer
Send the changes, not the data itself. Maps, items, monsters and players should be submitted once while loading, and then only send updates, like "player Z has moved to tile X, Y" or "tile X, Y has become water" or "monster Z shouted"
> 3 votes

# Answer
Consider compression of sending/receiving JSON data blocks between your server and clients.

Here is an article about LZW compression and decompression with JavaScript and PHP.
> 1 votes

# Answer
Regarding your question of data validation it should be performed both on the client and server sides, however it's important to determine which validation to perform where.

Any validation that does not necessarily require communication with the server can be implemented client-side. For example, a player moving to a position outside the boundaries of the map does not necessarily require communication with the server because the map is stored locally on their machine - however, you would still need to perform this validation on the server to handle the case where a malicious user has altered your client side code.

So why not perform all validation on the server? The point is that by having some validation performed on the client you can reduce the number of requests made to the server, providing the player with immediate feedback, saving cpu time and bandwidth. The majority of players are not malicious so it is a 'quick win'.
> 0 votes

---
Tags: html5, client-server, security, anti-cheat
---


# Question
Title: Type of 3D Rotation Animation used in this video
http://youtu.be/IUZqinlhono

I have referred to an application for interactive rotation in 3D space. The same is uploaded on youtube for your reference. I am having difficulty in understanding the rotation of the axis. In the reference app, axis of model moves in bernoulli's lemniscate path. When we swipe horizontal or vertical, it rotates complete 360 degrees however when the angle of swipe is changed (not exactly parallel to X-axis or Y-axis) model's axis moves in lemniscate path and comes back to starting position.

I am not abel to understand the concept and functioning behind this action. I am really stuck and have tried really hard to understand but failed. I will be obliged if anyone helps me understand this.

http://youtu.be/IUZqinlhono

# Answer
Looks to me like the horizontal component of the swipe adjusts camera yaw angle and the vertical component adjusts camera pitch angle. There's no special handling for diagonal swipes; they're just a combination of horizontal and vertical.

Yaw is rotation in the ground plane; an angle offset from North or whatever. Pitch is an angle offset above/below the horizon. The camera is yawing and pitching around a lookat point a foot or so in front of the guy's pelvis. The camera is offset maybe 8 feet from that point and always looks at it.

You can compute a camera transform from the lookat point, offset distance, yaw, and pitch. Just google this. The up vector for the camera transform is calculated from the world-space up vector. (Except when pitch is near +/- 90 degrees; there, you must instead compute your camera up vector from the yaw direction in the ground plane.)
> 1 votes

---
Tags: animation, rotation
---


title: How to motion capture animations?

text:
# Question
Title: How to motion capture animations?
I'm not an animation artist and so I want to create some animations for testing. I want to use a camcorder to record me while I'm running and so I want to know if exists a software that grab the video and translate it in animation frames.

# Answer
First of all, you need to learn about MOCAP - Motion Capture, unless you know how to work with animation rigs etc. you wont have any good from those models.

Proffesional MOCAP studio is **money consuming**, it requires a green screens, special suits, actors, camera operators and huge ammounts of Gigabytes for storing all the date collected, which must be later processed by large workstations.

> http://www.xsens.com/en/general

For my studio, I bought a Xbox Kinect sensor which can be used to create 3d point clouds in real time, which can be later converted into animations or 3d meshes (cheap 3d scanner). It works the way that it sends thousands of small points, not visable to the eyes that are later tracked by the sensor. From these points the camera projects a 3d point cloud which can be later transformed into meshes.

My animator is using this software, to create fast animations.

> http://ipisoft.com/

Before you actually get a Kinect, for these $150, you should try to borrow it from someone, and see how the software works on your pc. It literally eats 30mb of disk space per second + something must process this, a dual core pc wont handle this.

As for the cam recorder, I wouldn't even search for such stuff as it will generate more work than it can save.

**Keep in mind, that even if you get a kinect or any other mocap device you still need to know how to process it, and the process is just the same as creating raw animations... Or get premade animations for *free* http://www.mixamo.com/motions**
> 2 votes

---
Tags: animation
---


# Question
Title: Best way to gain C++ working experience for a job in games (coming from C#)
I am a software developer, experienced with C# (5 years experience) alongside a few other languages.

My "dream job" is working in video games as a developer.

Most jobs require knowledge of C++, which i currently don't have (except for some of the basics).

I've looked around, and most big game companies require something along 3-5 years of previous experience with C++.

My question is -- what would be a good route to get myself up to this required experience level, coming from C# ?

I've thought of some possible ways to do it:

Get more knowledge about C++ from books. Participate in open-source projects that are written in C++. What would be the best way to learn C++ and have working-level experience with it, in particular for the game industry?

# Answer
> 29 votes
As a game developer, my main concern hiring a C# guy would be a lack of low-level knowledge.

So, consider a project where your work entails low-level optimization like re-arranging the data layout of classes or rewriting code to take advantage of SIMD instructions. Take a C++ open-source game, optimize it, and post the framerate increase on your resume.

If I were interviewing you, I'd care less about the C++ on your resume and more about whether you can answer my C/C++/low-level interview questions. I'll take a stab at some standard interview questions you might have trouble with (warning: I'm no C# expert):

* How are C++ classes laid out in memory? Draw a diagram of bytes. Include vtable pointers and padding/alignment of member variables. What about a derived class? What about a multiply-derived class?
* How does a virtual function call happen, at a low level? Talk about assembly operations like reading a value in memory and jumping to an address.
* Know about C-style cast, static\_cast, and dynamic\_cast between pointers to types with various inheritance relationships. For example, classes B and C both derive from class A. What happens when you try to cast from A\* to B\* (or B\* to C\*) using these various casts? (I mention because I don't think C# would even allow these specific casts.)
* Why is it terrible to pass an stl vector by value, instead of by reference? (I mention because most types in C# are reference types and thus it is basically impossible to make this kind of mistake in C#.)
* What does it mean for a structure or function to be cache-friendly? Why might a structure-of-arrays perform better than an array-of-structures?
* Understand heap, stack, and static memory. If an object was allocated with new, where does it live in the process's memory? What about a local variable? A global variable?
* What's a memory leak? What are some best practices for avoiding them? (I mention because there's no *delete* in C#!)
* How would you debug a memory access violation crash? What about if the crash happened in some middleware library for which you don't have source code?

# Answer
> 1 votes
What Eric said. I would also add to avoid "new" where it's not neccesarly. It's very common in C# but considered as bad practice in C++11 and also slower than stack allocation and more dangerous because you have to manually deallocate it.

I would be also careful with old books, they teach old practices. I personally prefer reliable forums/websites, stackoverflow/isocpp.

---
Tags: c++, c#, software-engineering, jobs
---


title: How to get into video game writing?

text:
# Question
Title: How to get into video game writing?
I'm an excellent writer with a talent for crafting characters, worlds, and plotlines of a unique and appealing nature. For some reason I'm studying computer science, but I know fiction writing is my true calling.

How can I find an entry-level job or internship developing the stories, characters, and dialogue for a video game? That would be my dream job, and I know I could make a superb showing.

Any tips on where I can find opportunities? Google searches turned up a ton of game design jobs, but I think that's different. I couldn't find anything related to writing.

Thanks!

# Answer
I do not have personal experience doing this so my suggestions are just speculation. (this is just how I would do it)

Firstly, you'll need a portfolio for your writing, developed characters, manifested environment/world descriptions ect...

You'll need to showcase your abilities in this way to allow people to explore the possibility of you being a good fit as a writer for their project.

I would research small and indie companies to see what sort of projects they are working on and find a few you would like to contact and pursue. If and after you've written successfully for a few games (or one game if you are plenty happy with the results) then you can start to broaden your horizons and look towards bigger and better projects/companies.

Best of luck to you!
> 10 votes

# Answer
I would recommend attending any game and/or mobile development meetups you can.
There you will find more than a few folks that have the opposite situation...they understand the programming end of things, but can't wrap a story around their pixels. Talk with them (and listen!). In the meantime, develop a storyboard for a game. Start with your favorite genre (tower defense, 1st person shooter, whatever) and write a concise description of the world/environment, the characters and objects, and the game play. Think of this as your "elevator pitch", something that you can use to quickly show a developer in a 5 minute read what you are able to do.
> 7 votes

# Answer
Game design is different, but related. The couple guys I know who work as narrative designers (ie. they craft the stories for RPGs) started in the industry as level designers, and from there demonstrated to their boss that they were really passionate about the storyline.
> 2 votes

# Answer
+1 for your confidence... I would simply suggest sending résumés to multiple game companies. Attach a few pages with on each a chapter or two describing or telling bits of stories about individual characters. This should attract attention.

If you are as good as you say, with your Computer Science background you will land a job in the industry at some point.

But don't **stop at small companies**. Larger structures have more budget for background stories and narrative work.
> 2 votes

# Answer
Like anything else you want to excel at: practice it. So in other words start writing. And writing and writing and writing. And keep reading and developing your appreciation for the craft.

Participate in nanowrimo. Try and get a book deal, or to publish short stories somewhere. I think the way that works is you shop your *finished story* around to try to get it published. When you have some stories out that people can read, they can more easily select/recruit.
> 2 votes

---
Tags: jobs
---


# Question
Title: joystick movement for Geometry Wars clone
I am kinda new in game programming, but I've got a semestral work to make a game, so I decided to do a clone of Geometry Wars. Despite that the game is really simple (in principle), I have ran into a problem I can not solve. I use SDL, OpenGL in C (vanilla C, so no C++/C# and stuff, only procedural ANSI (I think ANSI) C). When I get input from joystick, it is fine in the console (if I flush it to the output, it will make immediate action) but when I draw a simple dot (it shouldn't be that time consuming to draw a dot on screen) it have a slight to severe input lag (up to 3 sec.). But that's only the first part of my problem, because it not only renders slow, the movement is totally different from that I make with joystick. Here is the code:

```
void pollInput()
{
    SDL_JoystickUpdate ();
    SDL_PollEvent(&event);
    double XYValue;
    if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) )
    {
        if( event.jaxis.axis == 0)
        {
            XYValue = event.jaxis.value / 2500.0;
            XYValue = floor(XYValue);
            player.playerX += (XYValue);
            printf("X: %.0lf\n", XYValue);
        }
        if( event.jaxis.axis == 1)
        {
            XYValue = event.jaxis.value / 2500.0;
            XYValue = floor(XYValue);
            player.playerY += (-XYValue);
            printf("Y: %.0lf\n", XYValue);
        }
    }
}

```

I am really stuck here. And another question came to my mind, is it a good idea to add the input from joystick to the XY coords of the player? Shouldn't I make it like acceleration? If yes, would you kindly write a pseudocode for that? Thank you for your replies guys!

# Answer
Your problem is with how you're using `SDL_PollEvent`.

You want to do this:

```
while( SDL_PollEvent(&event) )
{
    // event-handling code goes here
}

```

The problem is that SDL generates many events per rendered frame, but your code is only processing one of those events, and leaves the others still pending. This is going to be where your lag is coming from -- any unprocessed events are left in the event queue, so when your code runs, it's picking up not-yet-processed events from the past, instead of current ones.

`SDL_PollEvent()` returns `1` to indicate that it has given you an event, or `0` if there was no event for you to process. So by putting it inside a while loop, you'll continue to process events each frame until there are no more left to process. This means that each frame, you will only process events which were generated for that frame, and you'll process all of them, instead of only one.
> 1 votes

# Answer
I assume `player.playerX` is the position of X. I am not sure how large `event.jaxis.value` can go, but

```
XYValue = event.jaxis.value / 2500.0;
XYValue = floor(XYValue);
player.playerX += (XYValue);

```

means the player will move at a speed proportionally to how far you move the joystick, I guess (I have no experience about joysticks.)

~~Apparently you seem you don't like the movement.~~

If you want to make it acceleration, you will need a `velocity` (for X and Y axis) variable for your player.

```
// I recommend you put the dividend it higher or the character may accelerate too fast.
XYValue = event.jaxis.value / 8000.0;
XYValue = floor(XYValue);
player.velocityX += (XYValue);
if (sqrt(player.velocityX * player.velocityX + player.velocityY * player.velocityY) > 20)
    player.velocityX = 20; // implement max speed
// same goes for Y axis, not repeating.

```

then, in your game loop,

```
player.playerX += player.velocityX;
// same goes for Y axis, not repeating.

```

Max speed would be necessary such that

* your player won't move too fast that the player cannot follow.
* prevent problems in collision detection (when player, in one frame, goes through an enemy without two shapes overlapping at all.)

---

**EDIT** about the input lag, I would suggest you look into

1. ~~Is the joystick input already laggy? Try write up a very simple code that just reads the joystick input and print some plain text output, presumably with `printf`, and do not do any other things.~~
2. Look into FPS of your game - though it should be unlikely according to your description, but who knows. See how long, in wall clock time, it takes to complete an iteration of your game loop for your game.
> 0 votes

---
Tags: movement, sdl, c
---


title: Unity3d Transform.position float range

text:
# Question
Title: Unity3d Transform.position float range
I thought floating point has a very large range, for example up to 3.4\*10^38. However today I tried to set my player's Transform.position.x to 1000000 in the GUI and it gave me a warning:

> "Due to floating-point precision limitations, it is recommended to bring the world coordinates of the GameObject within a smaller range."

Does that mean that my single scene has to be smaller than 1000000\*1000000\*1000000. Is this considered big enough? I will need multiple scenes if I want a larger world? When a new scene gets loaded, will my player's position be reseted? How do I manage the position data so that it doesn't go out of range?

I'm using Unity3D Pro.

# Answer
Floating point precision is all relative. The further away from the origin, the less absolute precision you have.

In unity's case, general best practices are to use 1 unit = 1 meter. Do you need your entities to be a million meters away from each other?

A common practice for games with huge worl'ds is to occasionally reset the player's and worlds position to the origin.

As for your other questions it really depends. We can't answer "is it big enough".

Have you tried making a prototype to scale and run into specific issues or are you just trying to make the error go away?
> 4 votes

---
Tags: unity, floating-point
---


# Question
Title: Is it clever to use some engine to start game developing?
I started C# programming, in order to later develop games with XNA. I read a good game development book for C#. Since I already knew other languages, I could quickly learn C# features and syntax code. I then stepped over into XNA. Since the book I was reading was a bit old, I put it aside, and started to look at game development tutorials about XNA over the Internet. I could accomplish and understand most of them, using 2D graphics. I created animated sprites, made my characters move in any direction, scrolled my background together with my characters movement, and so on. Everything was done with "raw" XNA.

I found some of those things hard to understand, and I found that some things wee already be built into the framework. I found other game engines, which I could clearly understand at least the simple line codes, such as *"FlatRedBall"*, *"Axiom"* and *"Quick Start Engine"*. I already knew of the famous ones, like *"OGRE"*, *"Unreal"* and *"Unity"*. At the same time, I was tempted to throw it all away, and start learning some famous game engine programming. I wanted to stay with XNA, as it took me time to learn; time I wouldn't like to waste it.

This time, I leave it up to the experienced ones. Can I go through some game engine, and use what it has to offer, even if I'm starting with game development? Some people could think that it is good to get use to the boring routines of a naked framework. If so, what would be the recommended one to start off with? I heard that it varies from market to market. We could perhaps consider that I want an RPG-specific.

# Answer
It depends on what you want to learn. If you want to "just create a game" you can be good with an engine. I personally do not recommend this.

If you want to really understand how computer graphics works you must go deeper and learn all the stuff. From refreshing your linear algebra (at least matrices, vectors and linear spaces) to understanding how graphics pipelines work. XNA is the best framework to start with. My first game was in it (I mean real game, first 3D app was battle tanks in openGL). If you want to start 3D programming, don't have such ambitious plans, you can't do an RPG now. You should try to make some game where you are flying in space full of cubes and trying to shoot the red ones, to learn the basics. It will probably take you more time than you think :). But it will teach you lots.

And go for it! 3D graphics programming is the best thing you can do for living. It is hard, fun, and creative in one package.
> 11 votes

# Answer
There is nothing wrong with using an existing engine, it all comes down to your goals.

If you are most interested in just building some games or game design, the faster you get to the gameplay code the better. Something like Unity is great here, as you can use your C# knowledge and start attaching scripts to objects and have something running immediately.

If you want to become a game programmer, then you need to understand things at a lower level. A framework like XNA is a good starting place. You can rely on the framework to get things up and running and then start replacing parts of the framework with your own code as you learn how to build each component of your game.
> 17 votes

# Answer
---

## ADVICE FROM AN AMATEUR

## //From Zero to Amateur over Years of Learning

---

I would definitely stay away from high level engines like Unity or Torque2D MIT. They are great for small prototypes, but I would never take them seriously to develop my own video game. Why would I? What is the point unless it was nothing more than a simple SideScroller or Arcade remake?

Most game engines, libraries, or frameworks do nothing more than the simplest of tasks with a whole lot of bloated code with functions and features you'll never use.

---

When I was new in game development years ago, I started at the top. Very high level engines. Not anything too high like RPG MAKER, but definitely high up there like Unity and Torque. Then I went lower, to XNA and C#, because it had so many resources and tutorials. My primary project needed the performance, or perhaps I'm just obsessive-compulsive about wanting incredible performance in my software, even if it is not a large project. XNA simply did not cut it, and I had a lot of problems with the engine that I read required a headache to fix. What is the point of using something "higher level" like XNA/C# when you're doing the same work (fixing XNA bugs & problems) as you would rolling your own engine in C++?

After quite awhile of learning, I eventually learned about how game engines are designed and began looking into the code of the engines themselves. Reading what most professionals have to say and the complaints of the critics of game engines made me realize, 'Why even use an engine?"

Brushing up on my C++ and really getting into some philosophies used in that language helped me a lot. However, I had spent so much time learning about so much I just wanted to start making a game.

So I ended up with something with quite a lot of praise, was C++, and very low level: SDL. Unfortunately, this was a headache. It is so low level, I see next to no reason why to even use this library. I'd rather simply learn OpenGL and do it myself from scratch. Honestly, it was mostly the fact I needed to implement my own code to do something as basic as flip an image (and other's implementation wasn't working because of how I handled sprites) which drove me to trash SDL permanently. It's great if you want a software renderer, but IMO I'd rather trash it to go lower with hardware (OpenGL) or higher (SFML).

Not wanting to buy another book on amazon and learn yet another API, I went higher. SFML is simply wonderful, not to mention highly praised all over the internet. I have read almost an endless number of positive reviews, with next to no negatives. I cannot say the same for SDL. It handles all of the extreme basics, but leaves the rest up to me and other libraries of my choosing. I've stuck with it ever since.

---

IMO, a game engine is just silly. Low level libraries are much better choices for both expert and beginner programmers.

Also to note, I have learned more about programming concepts and have sharpened my software development skills when forced to handle things at a lower level than I have ever learned with high level WYSIWYG game engines.

What does something like Unity give you over XNA? Visual editing and a crutch. Newbies will eventually learn you'll still have to code pretty much the entire game just as you would if you had bare C++, and the visual editors are inefficient to something you could create yourself.

What does something like XNA give you over SFML or your own implementation of OpenGL and other useful libraries? IMO, absolutley nothing good. Worse performance, C# instead of C++, a plethora of newbie tutorials but significantly less professionalism, and some headache savers that IMO are once more just a crutch for what you should just learn with C++. I was initially intimidated with C++ and loved C#, mostly because of hear-say and rumors of the opinions of fools who had the same troubles I had initially with C++: I just wanted a good enough programmer. I realized I needed to learn more fundamentals and sharpen my weaknesses in order to overcome the troubles I had with C++, which C# "made easy." Do I ever miss the simplicity of some things in C#? Not even! I know how to do it in C++ without a hassle.

---

**If low level libraries or learning DirectX/OpenGL intimidates you, then just wait until you start getting into the complexity of creating a full video game.**

My philosophy on game engines can be summed up in two examples explaining the redundancy and uselessness of engines, except in isolated circumstances.

Newbies who are intimidated with low level libraries, will have a seizure when they discover that even with a high level engine like Unity, (besides graphics rendering, audio playing, content loading; real basic stuff) it will be almost identical to making a game from scratch. **The complexity is in engineering a game, not understanding the API or developing the classes to render to the display.**

Experts who aren't intimidated by the complexity of creating a full game in something like Unity, have no use for Unity because the time in which it would take to confidently learn the API and requirements of a specific engine is probably more of a headache and more time than it would take to code the few classes required to do the basics.

So engines are useless to newbies, because newbies can't make anything with them because they lack the engineering skills. Likewise, engines are useless to veterans, because they already have the engineering skills to do it without an engine, and might as well roll their own more efficient, specific 'engine' than to go through the headache of learning both the game engine's API, functions, and performance quirks. Not to mention the massive nightmare of working with engines that you sometimes can't touch because they're not open source (or even if they are, reading other's code can be a nightmare at times).

Heck, even some "low level" "game frameworks" are nothing more than a few classes to create a window, render to the display, and play audio. This is something a professional could do themselves from scratch using other libraries like SDL/SFML or their own implementation of OpenGL/DirectX/OpenAL, in a fraction of the time it takes to actually complete a full video game.

---

**TLDR;**

1. If you want to program, **learn to be a programmer**.
2. **Avoid using engines**, but do not be a fool and ignore incredibly useful libraries.
3. If you want to be a **Game Designer**, try an WYSIWYG engine and pump those games out!
4. If you want to be a **Game Programmer**, avoid engines like the crutch that they are.
5. **For ME**, using higher level game engines crippled my ability to become a programmer. The moment I started using lower level libraries instead or not using any library at all, I began to learn so much that I quickly went from a total newbie to someone that can now create video games without any reference, tutorials, or book alongside me. Just my compiler and a lot of engineering and practice.

The amount of learning I gained from low level libraries in a SHORT amount of time was much greater than the amount I gained in a VERY LONG amount of time with higher level ENGINES.\**
> 1 votes

---
Tags: c#, xna, 3d
---


# Question
Title: Texture mapping issue in my Wavefront *.obj parser
I wrote a simple `*.obj` parser reading read vertices, texcoords and normals. But when I draw a model the texture isn't mapped correctly.

I have already tried `uv.y = 1.0f - uv.y` to get inverted Y axis coordinates as suggested by a few people but my textures are still displayed skewed.

I know that both texture file and rendering code are correct. Because when I render a plane and use hand written and hard coded texture coordinates and vertices it renders fine. I can render a textured cube by hand fine, too.

I use an index buffer to store vertex elements and I use the face elements provided by the `*.obj` file to fill texture coordinate buffer and normal buffer.

```
Model::Model(const string &givenName, const string &filePath){
    name = givenName;

    std::ifstream in(MODEL_PATH+filePath, std::ios::in);
    if(!in){
        error("Model \"" + filePath + "\" does not exist");
        return;
    }

    ModelMeshIndex tempindex;

    vector<vec3> normals;
    vector<vec2> uvs;

    string line;
    while(getline(in, line)){
        if(line.substr(0,2) == "v "){
                    std::istringstream s(line.substr(2));
                    vec3 v(0.0f);
                    s >> v.x >> v.y >> v.z;
                    data.vertices.push_back(v);
        }
        else if(line.substr(0,2) == "vt"){
                    std::istringstream s(line.substr(2));
                    vec2 v(0.0f);
                    s >> v.x >> v.y;
                    //v.y = 1.0f-v.y;
                    uvs.push_back(v);
        }
        else if(line.substr(0,2) == "vn"){
                    std::istringstream s(line.substr(2));
                    vec3 v(0.0f);
                    s >> v.x >> v.y >> v.z;
                    normals.push_back(v);
        }
        else if(line.substr(0,2) == "f "){
                    std::istringstream s(line.substr(1));
                    char tmp; // For the slashes between elements
                    unsigned short a,b,c, d,e,f, g,h,i;
                    s >> a >> tmp >> d >> tmp >>g;
                    s >> b >> tmp >> e >> tmp >>h;
                    s >> c >> tmp >> f >> tmp >>i;
                    a--; b--; c--; d--; e--; f--; g--; h--; i--;
                    data.index.vertexElements.push_back(a);
                    data.index.vertexElements.push_back(b);
                    data.index.vertexElements.push_back(c);

                    data.index.uvElements.push_back(d);
                    data.index.uvElements.push_back(e);
                    data.index.uvElements.push_back(f);

                    data.index.normalElements.push_back(g);
                data.index.normalElements.push_back(h);
                    data.index.normalElements.push_back(i);
        }
        else if(line[0] == '#') continue;
        else continue;
    }

    for(unsigned int i = 0; i < data.index.normalElements.size(); ++i)
        data.normals.push_back(normals[data.index.normalElements[i]]);

    for(unsigned int i = 0; i < data.index.uvElements.size(); ++i)
        data.uvs.push_back(uvs[data.index.uvElements[i]]);

    //data.uvs.push_back(vec2( 0.0f, 0.0f)); // bottom left
    //data.uvs.push_back(vec2( 0.0f, 1.0f)); // top left
    //data.uvs.push_back(vec2( 1.0f, 0.0f)); // bottom right
    //data.uvs.push_back(vec2( 1.0f, 1.0f)); // top right

    good = true;
}

```

What is wrong with my parser?

# Answer
> 0 votes
I have found my issue. When reading from an index, which I was, it seems that OpenGL reads textures from the same element of the vector that the index buffer points to for each vertex. I have fixed this issue by loading all of the vertices, textures and normals into seperate buffers and setting buffers to point to the data then drawing with glDrawArrays()

Thank you for the help!

# Answer
> 7 votes
This may be a winding issue. Are you sure that the texture coordinates are parsed in the right sense of rotation?

However, this how you should debug you program.

* Draw in wire frame mode to find out how the rectangle is composed out of two triangles. The OpenGL command for this is `glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);`.
* Use a texture with a gradient fading between four different colors located at the corners. This way you can exactly check how the texture is mapped.

You already know that texture mapping is wrong, but you don't know in which way. Therefore you should perform the two steps above. I have a good day, so I made you such a gradient texture. Click to enlarge.

It is very likely that you can fix the issue by your self then. Otherwise please update your question with screenshots of those debugging steps so that we can provide further help.

---
Tags: c++, opengl, uv-mapping, glm, obj
---


title: Reverting the view SDL

text:
# Question
Title: Reverting the view SDL
So in my SDL application, which I setup for OpenGL, if I were to do the following code:

```
glBegin(GL_QUADS);
glVertex2i(0, 0);
glVertex2i(50, 0);
glVertex2i(50, 50);
glVertex2i(0, 50);
glEnd();

```

The quad shows up on my right hand side of my screen. I tried to use *glOrtho* but that didn't work for some reason. What happend?

# Answer
The problem seems to be because you are treating (0, 0) as the bottom left; in OpenGL (0, 0) is the center of the screen.

To say this is counter-intuitive is silly, it is fully your opinion to say so.

I presume you have a 50x50 window you are trying to fill?

**To get your desired behaviour you would need the following:**

```
glBegin(GL_QUADS);
glVertex2i(-1, -1); // bottom left
glVertex2i( 1, -1); // bottom right
glVertex2i( 1,  1); // top right
glVertex2i(-1,  1); // top left
glEnd();

```

**and a diagram**

*(-1, 1)--------------------------(1, 1)*

*----------------------------------------*

*-----------------(0,0)-----------------*

*----------------------------------------*

*(-1,-1)------------------------(1, -1)*
> 3 votes

---
Tags: opengl, game-mechanics, sdl, graphics-programming
---


title: Designing a flexible tile-based engine

text:
# Question
Title: Designing a flexible tile-based engine
I'm trying to create a flexible tile-based game engine to make all sorts of non-realtime puzzle games, just as Bejeweled, Civilization, Sokoban, and so on.

The first approach I had was to have a 2D array of Tile objects, and then have classes inheriting from Tile that represented the game objects. Unfortunately that way I couldn't stack more game elements on the same Tile without having a 3D array.

Then I did something different: I still had the 2D array of Tile objects, but every Tile object contained a List where I put and different entities. This worked fine until 20 minutes ago, when I realized that it's too expensive to do many things, look at this example:

I have a Wall entity. Every update I have to check the 8 adjacent Tiles, then check all of the entities in the Tile's List, check if any of those entities is a Wall, then finally draw the correct sprite. (This is done to draw walls that are next to each other seamlessly)

The only solution I see now is having a 3D array, with many layers, that could suit every situation. But that way I can't stack two entities that share the same layer on the same tile. Whenever I want to do that I have to create a new layer.

Is there a better solution? What would you do?

# Answer
Did you actually *see* this problem, or have you just thought it up? Because I fail to see how iterating over objects list has any noticeable effect on performance. You'd have to have hundreds of objects per tile for this to matter. Most games I can think of have 10, tops.

If you *really* have a problem, the best idea is to cache data, not change representation. In your example, wall configuration probably doesn't change every frame. Just cache correct sprite type, don't recalculate it constantly.

If you want to make some crazy game that has lots of objects, and they change all the time, you can create different layers with different semantics. For example, wall layer contains only walls, no more than 1 per tile, and, say, decoration layer contains lists of objects that never change.

Finally, if you want to have ultra-flexible architecture that ideally supports every possible game - tough luck, there's no such thing.
> 2 votes

# Answer
Two suggestions. First, you should resolve the sprite that each tile will be drawn with during the load of your tile map/level. It should be easy enough to traverse the 2D array one your level is loaded and decide that a certian wall needs to be a **L** shape and another needs to be a **|** shape.

Second, I would store static data related to a tile in a different place than active data. So a tile object may have a list of objects which come and go from the tile but there is no need to traverse this to see if, e.g. we just want to know if the tile is walkable or not.

This psudo code is more or less how I have approached a tile based system.

```
Tile {
  Texture tex;
  //...other static data...
  List currentObjects;
}

Tile t = Tiles[x][y];

```

This assumes that there is static tiles in your game but that is a pretty good assumption in many tile based games where you are dealing with walls and the like.
> 2 votes

# Answer
You said:

> I had was to have a 2D array of Tile objects, and then have classes inheriting from Tile that represented the game objects. Unfortunately that way I couldn't stack more game elements on the same Tile without having a 3D array.
>
> Then I did something different: I still had the 2D array of Tile objects, but every Tile object contained a List where I put and different entities. This worked fine until 20 minutes ago, when I realized that it's too expensive to do many things

This is exactly the situation that you want to solve using the MVC (model view controller) pattern to separate out your model from your view. MVC makes this problem two parts:

* How to model a stack of tiles
* How do display a stack of tiles

Instead of having a 2D array of tiles, or a 2D array of a list of tiles, your model would store a 2D array of game objects. Then your 2D array of tile classes will look at the corresponding game objects and decide how to render them.

Instead of having a single Tile instance render a single game object, you can have a single Tile instance render something that looks like *a stack of objects.* This would be more efficient, and would give you clean separation of your core code logic, and how it looks.

Just like walls. The logic is very trivial, but the rendering is more complex.
> 1 votes

# Answer
I agree with @Omnion. Use the list approach, but keep it sorted if performance is a problem. That is to say use a hybrid approach. Use the list as your third dimension , but only identify the first 5 items as a specific type, and anything after that is an ink own type, or a type that won't require checking multiple times per frame.
> 0 votes

# Answer
You should "never" make separate classes for things like tiles. You should make a struct from bytes, shorts and ints that refer to the type of tile and objects on it. Performance wise ints are the best to go with or even long on 64 bit systems. But if you ever want to save your map you should go with bytes or shorts wherever you can, especially for huge maps.

In my games i have a map class that has just fields like: byte tileType; 256 different terrain types is enough for this game. Takes 1 byte. ushort tileObject; 65,536 different objects is plenty to go with. Takes 2 bytes etc.

If i take the example above each tile takes only 3 bytes in memory. So a 10000x10000 would be 300mb in memory and should not be a problem. Whenever you need to look for something you determine where on the map you want to look and what you are looking for and iterate the arrays accordingly.

If you have dynamic stuff all over the map ask yourself if the player really notices that stuff far out of it's viewport.
> 0 votes

---
Tags: c#, 2d, performance, tiles
---


title: How to draw only visible tiles?

text:
# Question
Title: How to draw only visible tiles?
I have a big map with isometric tiles(3d camera), how can i draw only visible tiles ?

Whats the best way to do that ? space partitionning (octrees etc...)?

# Answer
If all the tiles are approximately the same size, lie roughly on a flat plane, and the camera is always a set distance from the plane, simply calculate the tile that the camera is looking directly at and then cull any tile whose `distanceSquared()` from the looked at tile is greater than a value that would place it outside the FOV.

When considering the 'value', consider the obliqueness of the vertical component of the FOV when using an isometric perspective.

Further optimization can be had by doing the same with small groups of tiles rather than each tile individually.

This method will usually give a number of false positives but will cull the vast majority in a big map situation and is relatively cheap.
> 2 votes

# Answer
Figure Out a visible rectangle of tiles. Only draw that. Isometric vies complicate things, but only slightly. Simply start at the leftmost, topmost tile and draw that row. Then the next. You should be able to convert between screen and world space, so converting and visible spot on the screen aligned visible rect to tile coords should be straightforward. It depends on your internal representation of the game world, so it's hard to give more specific math.

Spatial partitioning will help more with very very worlds. A simple fixed-scale quad tree is fine. Or even fixed size chunks.
> 2 votes

# Answer
This approach works for diamond shaped isometric maps.

1) Find out what the top left tile on the screen is.

2) Depending on how you draw the map offset this by 2 tiles in both directions off the screen. So now you chosen a tile outside the viewport area.

3) Calculate how many horizontal rows and how many vertical rows need to be drawn so you end up on the opposite site of the viewport.

4) Now draw your map row by row.

```
for (int row = 0; row < rowCount; row++)
{
for (int col = 0;col < colCount; col++)
{
tileXtoDraw = topLeftTile.x + col + (row / 2) + (row%2) //modulus there for each other row
tileYtoDraw = topLeftTile.y - col + (row / 2);
//check if this tile is within the map region(no -10 or more then length)
//
//Draw your map as you normally do. tileXtoDraw and tileYtoDraw are
//just the [x,y] in the array, you just iterate them differently.
}
}

```

Hope this helps!
> 1 votes

---
Tags: opengl, tiles, isometric, octree
---


# Question
Title: How much memory usage is too much in a Flash game?
I'm developing a Flash game, and I can appreciate that the memory usage is a little high for a Flash game (I think). Let's say 100+ MB.

So how much is too much when talking about memory usage in Flash games?

# Answer
> 6 votes
I've been wondering about this as well, so I decided to check out some popular games and watch Firefox's plugin container memory consumption.

Memory starts and defaults back to around 5-10MB on my setup. With that in mind, here are the peak memory usages in the first 3-5 minutes of gameplay for some popular games:

Notes:

Smeet is a Facebook Social Game, it ran at around 100 MB, and peaked at 200 when I entered an area with lots of characters and assets. Chibi Knight has fairly simple assets, but an extremely large multi-screen background image (non-tiled), which explains it's high memory usage. The two lowest memory games are both non-scrolling and single-screen (at least in the first couple minutes), explaining their low usage.

# Answer
> 5 votes
According to your tags it says "browser-based-games" depending on the game and its complexity, I would say 100mb most likely too much, unless you are creating a large mmo style flash game(even that is very large!)

There is a bunch of compression options you have for flash as well, which may shrink your game down

---

tiny: 0 - 200 KB;

small: 200 - 700 KB

Medium: 800 - 1400 KB

Large: 1500 - 4000 KB

too Large: 4000 - 9000 KB

---

# Answer
> 4 votes
The answer depends on your target audience. Do you want people to play your flash game on their Netbook and/or their flash supporting Playbook or Android tablet? If so, then memory usage over and beyond 50 MB is likely going to be an issue. If you only expect your game to be played on tricked out gaming rigs, then taking up 100-400 MB memory is likely not going to be a problem.

The issue, may be Flash's ability to address this much memory quickly. I'm not a flash developer so I don't really know, but if your game needs this much memory it probably has a lot of supporting code, which is where, even on "gods-own-machine," you may run into issues.

# Answer
> 4 votes
FWIW, I was helping out a family member complaining of a slow PC. She plays CafeWorld on facebook. Investigation lead to Firefox/the flash plugin taking up almost a gigabyte of memory usage. I thought this might have been a fluke, having experienced many browser-based memory leaks over the years, closed everything and tried it with another browser. I watched the memory usage as it slowly crawled back up to the 970~ mb mark as all the game's various assets loaded.

Absurd, but I'm sure you can point at the game and say it has millions of users. (yup, just checked, 14 million monthly users, blah)

# Answer
> 0 votes
I would differentiate between download size and memory size, some assets are large, other game related data structures bloat the client's memory but require little bandwidth to download.

That was the strategy behind FLV, to compress the video code for download, and then decompress it assuming fast CPU and lots of memory in the client.

# Answer
> 0 votes
128 Megabytes is the Default maximum, so I would say above 128 Megabytes is too much.

---
Tags: software-engineering, flash, browser-based-games, memory-efficiency
---


# Question
Title: Is it possible to let the mouse control hand animation?
I want to let the player control hand motion with the mouse is that possible?

# Answer
> 1 votes
It is certainly possible.

What are you using?

I don't have much experience in 3D at all, but I imagine it would be as simple (at least to start) as attaching the mouse input to the center of the hand, imposing limits, smoothing input, etc.

With something like Unity I imagine you could do it in a matter of minutes, albeit a rough implementation.

As long as the hand has at least one joint in it, I can't imagine it would be very difficulty to at least begin prototyping.

Wouldn't it be identical to using the WASD keys for movement? Just instead of a central point on the entire entity, it would just be a central point on the hand joint, or an object you created within the hand which moves the mesh around with the hand as a lead.

The same as dynamically animating a skeleton in any way outside of precanned animations.

---
Tags: animation, skeletal-animation
---


# Question
Title: Do you actually use diagrams to model games?
I mean mostly UML but any method that works is viable. So - do you actually model your games with UML/other diagrams or different methods? I had a subject at my university about modelling with UML and it seemed like more effort than actual benefit but I realise that might be only because I've never created a huge complex IT system. So is it worth the while and what types of diagrams/methods are usually\* the best?

\*Of course, many times concrete tools need be chosen to concrete problems but maybe there are some patterns.

**Edit:** I forgot one important thing - do you create diagrams **before** or **after** implementing stuff? What I mean is - when one designs and implements something one usually changes mind or something unexpected comes up and one has to make changes, sometimes major ones - and doing them in already complex diagrams seems equally hopeless as in the code itself.

# Answer
> 21 votes
I like to think that everything around us can be represented, one way or another, through a diagram. Even if it is just a linear diagram representing the transition between the states of a particular object throughout time (like a living being, going through a number of states from birth to death). I use diagrams to lay down my thoughts and ideas for the actual implementation. I improvise quite a lot.

Therefore, my diagrams are most of the time at a very high level, and feel like *mind maps*.

To throw some examples in, this is actually a class inheritance map (one that's been cut) in my game where Interactive Object is the base type.

This is an FSM (Finite-state machine) diagram for a spikes trap (those awesome traps on which you step and *woosh* spikes show up from the ground).

This is a *handbook* diagram (named this way because it's intended to be a *come back to it often* diagram) that I drew recently. It outlines the components of a game, and also helps with gathering the required assets, as you can see immediately what's needed and what isn't. I recommend these on small projects, as they get pretty huge on big ones. They can be broadened further though, so that may fix things.

When I go to a lower level, it's usually because I need to plan the most intricate aspects of my architecture, and I usually deal with UML there. I never concentrate on outputting absolutely clean and correct UML though. I've adopted what I liked the most about the UML convention, and turned it into a nice mindmap-ish UML. It's simple and does the job for me, but I wouldn't go with it in an environment where actual UML is expected, for obvious reasons.

Another situation when I have to go to a lower level is when I have to describe actual algorithms. I use what I call *flow diagrams*. It is a format inspired by the diagrams used in *white box testing*.

A sample for the spike trap that I drew right now would look like this:

This is normally the final layer between diagrams and actual algorithm implementations. If the need arises, I detail the flow diagrams further (with extra executed instructions), and deduce or estimate complexity, and build accurate test cases. I also prefer diagrams over pseudocode.

Not that related to game development, I also have a nice format to describe the screens in a multi-screen app, the functionality that the user can trigger on each screen, and the relationship between screens. I normally build these before starting the actual development, and they act like a map throughout the development process. If it's for a client, the screen diagram is even more useful! It helps me go through all of the project, from start to beginning, and take into consideration all of the functionality that it's going to need. Therefore, it's invaluable to providing an accurate cost and time estimate.

So yeah, I definitely diagram everything and anything. If I have an idea, I can and will definitely draw a diagram for it. If I somehow start a project without at least a very broad diagram to back me up, I feel crippled.

# Answer
> 15 votes
I certainly do - both structural and behavioral - my rule of thumb is that I make diagrams when the cost of making the diagram is less than trying to remember what the hell I was thinking a month later - or when I need to clearly explain myself to some other developer

Class diagrams when the inheritance hierarchy becomes sufficiently complex

Object diagrams when things like instantiation of objects becomes something bordering on the creation of a Frankenstein monster from disparate parts - especially useful in kitchen sink vertex and pixel shader users, to make sure all of the requisite bits are pushed through the pipe

Sequence diagrams when the detailed interactions between a set of objects become complex - this is extremely useful in modeling complex render flows where previously computed information is needed at barely related downstream locations

# Answer
> 8 votes
**Diagrams are a great way to communicate, document and aid your design**, and design is the most significant part of software development. UML has a lot of features but you are not meant to use them all at the same time, only the ones that are useful.

When navigating in a new city, do you actually stop and look at a map, rather than just continue and follow signs? That's what design vs coding is about. When things are unfamiliar, when the problem is complex, when you feel lost, that's when thinking about design is most helpful, and it's better to do it earlier than later. It's much easier to change your design before you've implemented anything.

Diagrams are a great way to visualise the problem and help your design, especially for visual thinkers (which is most of us on gamedev I'd imagine). A lot of problems become trivial, defects become obvious, when it's clearly mapped on a diagram. Some issues you may find in a diagram:

* Too many connections to a single component? You may have a god object that is hard to maintain
* Too many interconnections? Maybe the modularity can be improved, to make the architecture less fragile
* Too many pathways between two components? Perhaps you have tight coupling
* For high-performance applications such as games, are there too many components involved in the hot path or inner loop? This may impact your performance
* Most of the time however, the diagram will show inconsistencies between the design you envisioned, and the actual implementation

Furthermore, diagrams are great for communicating and documenting your design, either to non-technical people or people who are new to your project - and remember, in 6-months time you are practically new to the project too!

How you use UML should be driven from these considerations. Diagramming for your own sake? Use whatever notation you are most comfortable with. Collaborating with other developers? Try to include the details of API calls, message types, directions of dependencies. Discussing architecture? Black boxes and simple connections will suffice. No-one uses the full set of UML features anyway, plus it is very useful as a set of standardised notation that many people understand - whereas my napkin doodles may be incomprehensible to you and vice versa.

As for myself, I use diagrams all the time - simple notepad drawings for personal projects, simple UML diagrams at work. This UML diagram is what I'd consider too complex, and one that I'd never make because the cost of producing and maintaining it outweighs its benefit, but of course YMMV.

# Answer
> 8 votes
I'd say there are two types of diagrams. Formal diagrams and scribbles.

Regarding formal diagrams, I do them when I'm working with other programmers, but I rarely do so when I'm programming alone.

However, that doesn't mean I sit and code whatever comes to mind. In my opinion, the most important thing when programming (or actually anything in life) is to *think first and do later*.

Coding is a very mechanical task. You type and words appear on the screen. The idea is that by the time you start coding, you should have already solved the problem at hand. Making scribbles is a great way to sort your thoughts, and even force yourself to do the thinking that you need to do the coding part correctly. Scribbles are not meant to be saved for future reference, just so you can understand your thought processes easily.

Don't worry if you take too much time thinking. I think that a good balance happens when you dedicate 90% of your time thinking and 10% coding. I've met several "senior" programmers who live by "we don't have time to think, just to do". But even if they call their code "done" earlier than those who do take the time to think about what they're doing, they (or the unlucky souls left afterwards) then spend countless hours fixing and patching something that should have been built correctly from the beginning.

The best thing is that thinking is free! you don't have to be sitting on your computer to think. You can think about the code while you're eating, commuting, exercising... In fact, the best ideas come when you least expect them, so keep your mind open at all times, and only start coding when you really know what you're going to code.

Here's a related article that I happen to agree with.

**Edit**: Regarding the actual format and type of diagrams, I'd recommend you go freestyle, and actually handwritten instead of using prepackaged tools. Remember that the point is to help you in your thought process, so feel free to draw whatever you like. Semantics are whatever you like them to be, and they may be different between diagrams, and even between different parts of the diagram.

There are three main benefits with freestyle/handwritten diagrams over prepackaged tools:

1. You're not forced to abide to the type of diagram supported by whatever tool you choose. Sometimes mapminds will work, sometimes something more like UML will be fine, while other times a logic diagram will do. Other times a completely custom diagram is what works, and no tool can give you all the flexibility of freestyle diagrams (try punching a hole through the paper and continuing on the reverse side of the paper, in your favorite package, and see what happens)
2. You will spend more time actually diagramming instead of using the tool. Regardless of the tool, pen and paper is always faster at diagramming than keyboarding and mousing through menus to find the specific elements you're looking for.
3. You don't need a computer to handwrite. Most of the time I'm doing complex designs, I do them in a library, a cafe, or even inside an airplane. Also, good ideas always pop up in the least appropriate moment, so be sure to always carry something to write with, and something to write on.

# Answer
> 0 votes
It may be worth pointing out a few design diagram talks from the Game Developers Conference 2013. These are some very practical and road-tested examples -- and it seems they've been presented at many conferences across the years.

*(The other answers have done an admirable job of demonstrating why and how design-focused diagrams can be tremendously helpful in planning, building, growing, and maintaining a codebase, so I'll leave that aspect alone, and trust these resources might be useful to anyone visiting the question.)*

Joris Dormans and Ernest Adams discussed the Machinations game design/balance diagramming system. (Here's a paywalled GDC Vault video from GDC EU 2012; samples from GDC 2013 on Dormans' wiki.) Rather than attempt to paraphrase, here's how the wiki describes the system:

> Machinations is a theoretical framework and an interactive, dynamic, graphical representation that describes games as dynamic systems and focuses on closed feedback loops within them. The intention is to find a way to express and investigate (recurrent) game structures methodologically. Machinations offers a new lens on the intuitive and delicate practice of game design and balancing.

Noah Falstein gave a talk called "The Arcane Art of Puzzle Dependency Diagrams" (paywalled GDC Vault video). I can't find any non-paywalled link here, but various folks have discussed or posted their notes on-line.

Both talks discussed when they created and how they maintained these diagrams, to one extent or another.

# Answer
> 0 votes
You should probably check this article about using a simple abstract grammar to describe your gameplay loop, how it can help you identify design problems, and how easy it is to iterate at that level.

http://www.gamasutra.com/blogs/JoshuaStarner/20130205/186060/Applying\_Abstract\_Models\_to\_Game\_Design.php

I can also point you toward my own work on the subject, more based on the economics of the gameplay loop, using abstract resources to track things like opportunities, luck or preparation:

http://www.stephanebura.com/diagrams/

If you find this approach useful, you should have a look at Joris Dormans' Machinations, a tool for making such diagrams and running their simulations:

http://www.jorisdormans.nl/machinations/

His whole process is explained in his book:

http://www.amazon.com/Game-Mechanics-Advanced-Design-Voices/dp/0321820274/

---
Tags: architecture
---


# Question
Title: How do I make a button that can only be pressed once / you can't hold it
I've created a button by checking if the left mouse button is being pressed and the cursor x/y are in the boundaries of the button but the issue is that if you even hold it down for longer than a second it receives way to much input. Is the way I'm checking if the button is pressed bad or how can I make it so this won't happen.

# Answer
> 0 votes
You need to check for a mouse state *change*. Only trigger a mouse down event IF the mouse was up during the last frame, and mouse is down during this frame. In some frameworks, you may need to hold on to two mouse states, one for last frame and one for this frame. The same goes for keyboard states.

---
Tags: java, libgdx
---


title: Strange rendering in XNA/Monogame

text:
# Question
Title: Strange rendering in XNA/Monogame
I am trying to render G-Code generated for a 3d-printer as the printed product by reading the file as line segments and the drawing cylinders with the diameter of the filament around the segment. I think I have managed to do this part right because the vertex I am sending to the graphics device appear to have been processed correctly. My problem I think lies somewhere in the rendering. What basically happens is that when I start rotating my model in the X or Y axis then it renders perfectly for half of the rotation but then for the other half it has this weird effect where you start seeing through the outer filament into some of the shapes inside. This effect is the strongest with X rotations though.

Here is a picture of the part of the rotation that looks correct:

And here is one that looks horrible:

I am still quite new to XNA and/Monogame and 3d programming as a whole. I have no idea what could possibly be causing this and even less of an idea of what this type of behavior is called. I am guessing this has something to do with rendering so have added the code for that part:

```
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        basicEffect.World = world;
        basicEffect.View = view;
        basicEffect.Projection = projection;
        basicEffect.VertexColorEnabled = true;
        basicEffect.EnableDefaultLighting();

        GraphicsDevice.SetVertexBuffer(vertexBuffer);

        RasterizerState rasterizerState = new RasterizerState();
        rasterizerState.CullMode = CullMode.CullClockwiseFace;
        rasterizerState.ScissorTestEnable = true;
        GraphicsDevice.RasterizerState = rasterizerState;

        foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, vertexBuffer.VertexCount);
        }

        base.Draw(gameTime);
    }

```

I don't know if it could be because I am shading something that does not really have a texture. I am using this custom vertex declaration I found on some tutorial that allows me to store a vertex with a position, color and normal:

```
    public struct VertexPositionColorNormal
    {
        public Vector3 Position;
        public Color Color;
        public Vector3 Normal;

        public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration
        (
            new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
            new VertexElement(sizeof(float) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0),
            new VertexElement(sizeof(float) * 3 + 4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0)
        );
    }

```

If any of you have ever seen this type of thing please help. Also, if you think that the problem might lay somewhere else in my code then please just request what part you would like to see in the comments section.

# Answer
> 1 votes
Looks to me like a lack of a depth buffer, so that the cylinders are being drawn on top of each other in the order you supply them, rather than according to their depth on screen.

I don't know XNA so I can't advise you as to specific programming, but make sure that when you create/request your context (`GraphicsDevice`?) you request that it has a depth buffer.

---
Tags: xna, c#, monogame, windows-phone-8, shading
---


# Question
Title: How to create a projection matrix in OpenGL ES 2.0
So I have the following...

```
float s = 0.5f;

void renderFrameLine() {
  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  GLfloat vVertices[] = { s, s, 0.0f, s, -s, 0.0f, -s, s,
    0.0f};
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices);
  glEnableVertexAttribArray(0);
  glDrawArrays(GL_TRIANGLES, 0, 3);
}

```

This works great so now I want to add depth so I get ready by changing my vertex shader as following...

```
GLbyte vShaderStr[] =
"attribute vec4 vPosition;   \n"
"uniform mat4 Projection;   \n"
"void main()                 \n"
"{                           \n"
"     gl_Position = Projection * vPosition; \n"
"}                           \n";

```

And based on this code in GLM...

```
template <typename valType>
    GLM_FUNC_QUALIFIER detail::tmat4x4<valType> perspectiveFov
    (
            valType const & fov,
            valType const & width,
            valType const & height,
            valType const & zNear,
            valType const & zFar
    )
    {
#ifdef GLM_FORCE_RADIANS
            valType rad = fov;
#else
            valType rad = glm::radians(fov);
#endif
            valType h = glm::cos(valType(0.5) * rad) / glm::sin(valType(0.5) * rad);
            valType w = h * height / width; ///todo max(width , Height) / min(width , Height)?

            detail::tmat4x4<valType> Result(valType(0));
            Result[0][0] = w;
            Result[1][1] = h;
            Result[2][2] = - (zFar + zNear) / (zFar - zNear);
            Result[2][3] = - valType(1);
            Result[3][2] = - (valType(2) * zFar * zNear) / (zFar - zNear);
            return Result;
    }

```

I create the following function to create a perspective matrix...

```
void glFrustumf(float near, float far){
        float aspectRatio = .5;
        float DEG2RAD = 3.14159f / 180.0f;
        float fov = 90*DEG2RAD;
        float h = cosf(0.5f*fov)/sinf(0.5f*fov);
        float w = h * aspectRatio;
        float a =  - (near+far)/(near - far);
        float b = - ((2*far*near)/(far-near));

        float proj[16] = {
                        w, 0, 0, 0,
                        0, h, 0, 0,
                        0, 0, a, 1,
                        0, 0, b, 0
                    };
        GLint projectionUniform = glGetUniformLocation(programObject, "Projection");
        glUniformMatrix4fv(projectionUniform, 1, 0, &proj[0]);
}

```

This doesn't seem to work and instead returns a blank screen. Can anyone tell me what I am doing wrong?

**Update**

I also tried

```
void glFrustumf(float near, float far, float left, float right, float bottom, float top){
        float deltaX = right - left;
        float deltaY = top - bottom;
        float deltaZ = far - near;

        float a = 2.0f * near / deltaX;
        float b = 2.0f * near / deltaY;
        float c = (right + left) / deltaX;
        float d = (top + bottom) / deltaY;
        float e = -(near + far) / deltaZ;
        float f = -2.0f * near * far / deltaZ;

        float proj[16] = {
                        a, 0, 0, 0,
                        0, b, 0, 0,
                        c, d, e, -1.0f,
                        0, 0, f, 0
                    };
        GLint projectionUniform = glGetUniformLocation(programObject, "Projection");
        glUniformMatrix4fv(projectionUniform, 1, GL_FALSE, &proj[0]);
}

```

but no dice...

**Per previous comment**

Based on this line...

> 2  nearVal right - left 0 A 0 0 2  nearVal top - bottom B 0 0 0 C D 0 0 -1 0
>
> A = right + left right - left
>
> B = top + bottom top - bottom
>
> C = - farVal + nearVal farVal - nearVal
>
> D = - 2  farVal  nearVal farVal - nearVal

I changed to this...

```
float proj[16] = {
                        a, 0, c, 0,
                        0, b, d, 0,
                        0, 0, e, f,
                        0, 0, -1, 0
};

```

But still just black...

Also tried...

```
void glFrustumf(float near, float far){
    float aspectRatio = .5;
    float DEG2RAD = 3.14159f / 180.0f;
    float fov = 90*DEG2RAD;
    float w = fov/aspectRatio;
    float a =  - (near+far)/(near - far);
    float b = - ((2*far*near)/(near - far));

    float proj[16] = {
                    w, 0, 0, 0,
                    0, fov, 0, 0,
                    0, 0, a, b,
                    0, 0, -1, 0
                };
    GLint projectionUniform = glGetUniformLocation(programObject, "Projection");
    glUniformMatrix4fv(projectionUniform, 1, 0, &proj[0]);
}

```

Also tried ...

```
void glFrustumf(float near, float far){
    float aspectRatio = .5;
    float DEG2RAD = 3.14159f / 180.0f;
    float fov = 90*DEG2RAD;
    float cot = (1 / (tanf(fov)/2));
    float cota = cot /aspectRatio;
    float a =  - (far+near)/(near - far);
    float b = - ((2*far*near)/(near-far));

    float proj[16] = {
                    cota, 0, 0, 0,
                    0, cot, 0, 0,
                    0, 0, a, b,
                    0, 0, -1, 0
                };
    GLint projectionUniform = glGetUniformLocation(programObject, "Projection");
    glUniformMatrix4fv(projectionUniform, 1, 0, &proj[0]);
}

```

# Answer
> 1 votes
Per previous this works...

```
void glFrustumf(float near, float far){
  float aspectRatio = .5;
  float DEG2RAD = 3.14159f / 180.0f;
  float fov = 90*DEG2RAD;
  float h = cosf(0.5f*fov)/sinf(0.5f*fov);
  float w = h * aspectRatio;
  float a =  - (near+far)/(near - far);
  float b = - ((2*far*near)/(far-near));

  float proj[16] = {
    w, 0, 0, 0,
    0, h, 0, 0,
    0, 0, a, 1,
    0, 0, b, 0
  };
  GLint projectionUniform = glGetUniformLocation(programObject, "Projection");
  glUniformMatrix4fv(projectionUniform, 1, 0, &proj[0]);
}
...
glFrustumf(0.1f, nf);

```

This now seems to work, I think Wolfgang's advice about the book is pretty solid. It helped a lot.

more info...

https://github.com/jrgleason/CrossGLESMobile

# Answer
> 3 votes
I have had this exact problem. https://stackoverflow.com/questions/14713343/projection-theory-implimented-in-glsl

First thing I suggjest is getting a book called "3D Math Primer for Graphics and Game Development", which goes into detail on the clip matrix derives the whole formula for both OpenGL and DirectX projections. (There is a slight difference, oddly enough.)

Your matrix, in the first attempt, is actually correct. The error, or reason your screen is blank, is because your passing it to the Vertex Shader with `glUniformMatrix4fv(projectUniform, 1, GL_FALSE, &proj[0]);` That GL\_FALSE, should be GL\_TRUE. Giving `glUniformMatrix4fv(projectUniform, 1, GL_TRUE, &proj[0]);`

The projection matrices are as fallows (Row Major Format):

OpenGL:

```
| zoomX   0        0      0 |
|   0   zoomY      0      0 |
|   0     0   (f+n)/(f-n) 1 |
|   0     0   (2nf)/(n-f) 0 |

```

DirectX:

```
| zoomX   0        0      0 |
|   0   zoomY      0      0 |
|   0     0   (f+n)/(f-n) 1 |
|   0     0   (nf)/(n-f)  0 |

```

I'm also posting my implimentation. My implimentation automatically adjust's the row major format to column major format. So to pass a matrix in this format, you specify `GL_FALSE`. As opposed to your implimentation where you should specify `GL_TRUE`. Make shure you understand how to identify when to use `GL_FALSE` or `GL_TRUE`.

```
template <class type> struct mat4_t
{
    type m00, m10, m20, m30;
    type m01, m11, m21, m31;
    type m02, m12, m22, m32;
    type m03, m13, m23, m33;

    mat4_t();
    mat4_t(type, type, type, type,
           type, type, type, type,
           type, type, type, type,
           type, type, type, type);
};

template <class type> mat4_t<type>::mat4_t()
{
    m00 = 0; m01 = 0; m02 = 0; m03 = 0;
    m10 = 0; m11 = 0; m12 = 0; m13 = 0;
    m20 = 0; m21 = 0; m22 = 0; m23 = 0;
    m30 = 0; m31 = 0; m32 = 0; m33 = 0;
}

template <class type> mat4_t<type>::mat4_t(type n00, type n01, type n02, type n03,
                                           type n10, type n11, type n12, type n13,
                                           type n20, type n21, type n22, type n23,
                                           type n30, type n31, type n32, type n33)
{
    m00 = n00; m01 = n01; m02 = n02; m03 = n03;
    m10 = n10; m11 = n11; m12 = n12; m13 = n13;
    m20 = n20; m21 = n21; m22 = n22; m23 = n23;
    m30 = n30; m31 = n31; m32 = n32; m33 = n33;
}

typedef mat4_t<float> mat4;

mat4 ProjectionMatrix(float aspect, float fovy, float near, float far)
{
    float h = near * tan(radians(fovy));

    float fmn = far - near;
    return mat4(h * aspect, 0.0, 0.0,                0.0,
                0.0,        h,   0.0,                0.0,
                0.0,        0.0, (far + near) / fmn, 1.0,
                0.0,        0.0, (2*near*far) / fmn, 0.0);
}

```

---
Tags: opengl-es
---


# Question
Title: Error returning a value from a function?
It tells me the error is on this line: this.srcX = ShipSrcXPicker(type);

However I cannot see it? I am returning the values from these methods that are being called? Is there something I am missing? I am making a Object and drawing the image to the screen?

```
function Player()  //Object
{

this.PlayerHullMax = 1000;
this.PlayerHull = 1000;
 this.PlayerShieldMax = 1000;
this.PlayerShield = 347;
this.Experience = 2684;

//where on canvas memory
this.type = "Cruiser";
this.srcX = ShipSrcXPicker(type);
this.srcY = ShipSrcYPicker(type);
this.drawX = ShipdrawXPicker(type);
this.drawY = ShipdrawYPicker(type);
this.playerWidth = ShipWidthPicker(type);
this.playerHeight = ShipHeightPicker(type);
}

Player.prototype.draw = function()
{
ClearShipsCanvas();
ctxShips.globalAlpha=1;
 ctxShips.drawImage(spriteImage,this.srcX,this.srcY,this.playerWidth,this.playerHeight,this. drawX,this.drawY,this.playerWidth,this.playerHeight);
 };

function ShipSrcXPicker(type)
{
if (type == "Cruiser")

 {
    return 0;
 }
 }

function ShipSrcYPicker(type)
{
if (type == "Cruiser")

 {
    return 1385;
 }
}

function ShipdrawXPicker(type)
{
 if (type == "Cruiser")

 {
    return 100;
 }
}

function ShipdrawYPicker(type)
{
if (type== "Cruiser")

 {
    return 400;
 }
}

function ShipWidthPicker(type)
{
if (type == "Cruiser")

 {
    return 150;
 }
}

function ShipHeightPicker(type)
{
if (type == "Cruiser")

 {
    return 90;
 }
}

```

# Answer
Next time you post, write what the error is.

> ReferenceError: type is not defined

This means that the variable `type` is not defined. However, `this.type` is defined. So the line you point out should be changed to:

```
this.srcX = ShipSrcXPicker(this.type);

```

And all the subsequent lines should be changed similarly.
> 2 votes

---
Tags: javascript, html-canvas
---


title: Physics for space game

text:
# Question
Title: Physics for space game
I am making a space game where you fly a ship.

I am trying to work out the physics for such a game and so far came up with:

```
var thrust; //between 1 & 100 how much the engines are pushing
var mass; // the mass of the spaceship
var speed; //the speed at which the spaceship is moving

```

Now big ships will have more mass to therefore take longer to speed up and longer to slow down once the thrust is off. Big ships will be slow because of the mass.

Small ships will speed up faster and slow down faster but also go faster.

How will I implement this into a game? I can do the keyevents, if up is pressed for 5 frames for example will I make the thrust raise to by 10 each frame(example) and then increase the speed of the ship based on some formula of the mass & thrust?

This is the game: Only UI and menus made but wan to get an idea of my physics before I implement the movement http://www.taffatech.com/DarkOrbit.html

# Answer
First of all, you need to learn the basics of vectors. Just find a good tutorial. It will not take long. Try this.

For simulating a physical object:

**Newton's first law of motion:** *"An object at rest remains at rest unless acted upon by a force. An object in motion remains in motion, and at a constant velocity, unless acted upon by a force."*

What this means is that it takes no energy for an object to remain at its current velocity (linear and angular). It only takes energy to *change* the velocity. (Note: *speed* is the magnitude of velocity and is a scalar). This energy can come from thrusters, gravity, explosions, collisions, and even light falling on it.

**Newton's second law of motion:** *"The acceleration of a body is directly proportional to, and in the same direction as, the net force acting on the body, and inversely proportional to its mass. Thus, F = ma, where F is the net force acting on the object, m is the mass of the object and a is the acceleration of the object."*

This means that we can calculate the acceleration on a body if we know the total force acting upon it, and its mass.

**Newton's third law of motion:** *"When one body exerts a force on a second body, the second body simultaneously exerts a force equal in magnitude and opposite in direction to that of the first body."*

I won't deal with collisions here, but this means that in a collision both bodies receive the exact same collision force in the same position, but in opposite directions.

Once you can calculate acceleration, you can integrate it to find velocity, and integrate velocity to find position.

If your object looks like this:

```
struct PhysicalObject
{
    vec3 _position;
    vec3 _velocity;
    vec3 _total_force;
    float _mass;
}

```

Your update function should look something like this:

```
void update(float _DeltaTime)
{
    this._velocity += this._total_force * (_DeltaTime / this._mass); // a = F/m
    this._position += this._velocity * _DeltaTime; // simplectic Euler integration
    this._total_force = vec3(0.0,0.0,0.0); // clear force accumulator
}

```

As you can see, if there is no external force, then the velocity will not change, but it is still added to position every frame, thus fulfilling first law. In space, there is no friction slowing the ship down so it would continue along its path forever (unless you want to go through a nebula or something).

This update function uses Euler integration, which is the simplest, but also the most inaccurate. Presumably this will be no problem, but if you need more accuracy, you can either decrease the timestep and do more update iterations per frame, or else look into a better integrator, such as Runge-Kutta.

You will also need analogous data and calculations to deal with rotational stuff, but I leave that as an exercise for the reader. It's a bit more complicated however. For example, the rotational equivalent for mass is a matrix rather than a scalar. :-/
> 2 votes

# Answer
So, there is no gravity? If you give some speed to object, it moves forever? What about this:

```
// values can be vectors
var speed = 1;
var mass = 1;
var position = 0;
function speedUp(d) { speed += d/mass; }  // change speed by d
function move() { position += speed; }

```
> 1 votes

---
Tags: physics, javascript, html-canvas
---


# Question
Title: What libraries and tools does LISP have that's usefull for games?
LISP is my favorite language and i don't wanna use c++ or any other language, but i don't know if there are much support for tools for game making, and i cant find much on the internet, anyone care to help?

# Answer
> 1 votes
http://3bb.cc/tutorials/cl-opengl/index.html

Here's a link to a few tutorials that show how to use OpenGL in LISP. Beyond that, so long as you are practicing, you should be able to structure some samples and eventually some games once you learn how to use OpenGL properly.

Also, though they are old, the old NeHe tutorials at http://nehe.gamedev.net have some LISP translation of at least their earliest tutorials.

# Answer
> 2 votes
Another idea is to use one of the .net lisp variants around, in which case you gain access to all that .net has to offer for gamedev.

---
Tags: software-engineering
---


title: Libgdx: setting windows's icon

text:
# Question
Title: Libgdx: setting windows's icon
When I export my game as runnable .jar file with custom window's icon - it doesn't run. It runs only in debug mode and when I try to launch .jar with the console it says that it cannot load icon file.

Picture of my problem:

# Answer
> 3 votes
You probably did not include the icon in your jar file, or you did include it, but not in the right location. From the console, run

```
jar tf Trace.jar

```

to get a list of all files that are actually included in your .jar file. Check if there is an entry for the given path, namely

```
src/trace/game/core/game.jpg

```

If it is absent you'll have to configure your IDE to include it properly. If the image file is there, but not under the above path, you'll either have to configure your IDE to put it in the correct place inside the jar, or adapt your code to look for the file in a different place.

---
Tags: java, libgdx
---


# Question
Title: When should I hard-code data versus load external data?
I'm a thousand or so lines of code into making my own 2D space-based game, which creates networks of randomly generated star systems and populates them with a random selection of planets, stations, ships and weapons.

There will potentially be hundreds of different stations/ships/etc that the game will need to use - so here's what I was wondering. Should I spend the time to create a 'softcoded' data-loader, which would store all of this information in (for example) XML files, and would therefore be somewhat easier to modify later, or should I simply go with what I've been doing right now - hardcoding all of the objects into the main engine of the game.

I'm the only person on the project, and as I said, it's only a hobbyist thing I'm doing in spare time away from university. But would the community recommend investing in creating an entire extra system of storing data in additional files?

What are the benefits of softcoding data in a way like this, versus simply hardcoding it all via constructors? Is there a long-term benefit to having external files that can be modified - if I'm not looking for the game to have 'mods', is it necessary to have external files? If it's just a hobbyist thing that I might give up on in a few weeks or months, should I waste time on this?

# Answer
# Yes. You should implement a system to load content outside your main engine.

Headers for succinct answers.

## No. It does not consume too much time.

I think the question of whether it is a valid allocation of your limited time is moot; even if only for the fact that it will be a small portion of total project time.

You will spend hundreds (thousands) of hours on a game project that you take to completion. Perhaps not on an Pong clone, but surely so for your complex space game. Compare that to a config file reader. Implementing a system to pipe XML into your main constructor, and subsequently restart to game process, will take *maybe* 10 or 20 hours. Even if it takes you 50 or 100, it will be a tiny fraction of total project time.

## It will save time

It's not a time expense; it's a time investment. And it will pay off.

Workflow matters, and having a config loader will make your workflow better. By creating a system that allows you edit configurations on the fly, you will save countless rebuilds. You can look at the game while it's running, tweak XML, and recheck in seconds. Or you can look at code, find a line of code (among thousands), edit its values extremely carefully (you're in your main engine, afterall), rebuild, execute, get the game back to the testing state, try hard to remember what it looked like before the change, and see if your change had the effect that you intended. Assuming nothing breaks in your engine, your train of though is surely disrupted.

From a more fundamental comp-sci perspective, try to remember that the most time-consuming part of writing software is not having a few extra keystrokes or whitespace. It's bug-hunting. And if you spend a little extra time to make things clearer by writing more verbose code, you save yourself much more time later. In your case, writing a content importer results in cleaner code that will be easier to read. Instead of miles and miles of hardcoded values, your source will feature a simple file load. Likewise, you can read the config file without wading through game engine code. Both parts become more maintainable and easier to debug.

## One-member teams benefit the most

If you hired an artist to generate some of that content, you would need to make tools for them to work with. They need to make pixel edits, and see the effects rapidly. You would not dare force them to rebuild code in order to see every change. Their time is expensive, and you don't want to waste it.

Now imagine that artist is very unskilled and slow (programmer artist), and has lots of other stuff to worry about because they are also the main programmer and musician. You definitely don't want to waste that time, or the project will never finish. And, that crappy artist will hate training to be a better artist, because they spend all their time renaming asset strings in code.

Don't do that to yourself. Make the tools, and you will have more time to make a game.
> 63 votes

# Answer
This is a good question and the best answer I can give is that only experience can really tell you when it's a good idea to take the path that is more difficult/time-consuming. If anyone tells you you should ALWAYS do it the 'proper' way, then they are simply wrong.

You already understand that it is a tradoff. On one hand, hardcoding is so tempting because it is quick and easy to get going, but in the long run adding features and debugging will become nightmarish. On the other hand, writing a great, flexible, expandable system requires a large initial investment, but makes life a hell of a lot easier in the long run.

The goal is to get something finished, and if you get bogged down in making a great system, the goal will recede further and you will lose motivation. Hard-coding stuff is fine in some circumstances but you must understand the ramifications of doing it. Here are some reasons why hardcoding is a bad idea:

* You may think your project is small, but it is possible that it grows as you decide to add more features. If you start off hardcoding, there is going to come a time when the energy required to maintain it (updaating it with new stuff and fixing the myriad of inevitable bugs) will start to seriously outweigh the initial gains.
* Hard-coding stuff is by definition specific to the current project. For the next project, you will have to start from scratch again, possibly hardcoding stuff again (because that's what you will be comfortable with). If you had put the time into a decent loading system, you could skip that work and headaches for all future projects.
* You may be working alone at the moment, but there may come a time when you wish to bring someone else onto the project. Are you going to take the time to explain your disgusting parochial system and write documentation for it?
* Hard-coding often involves having to know what certain magic numbers mean, or complicated class dependencies. You may be able to keep it all in your mind now, but just wait until you've been away from the code for a while. Even with extensive comments, a badly designed structure is hell to go back to.

I would say you should feel free to hard code stuff on only the smallest details. If you have even the slightest notion of the element you are working on being used by someone else, growing much larger, or being used in another project, then take the time to do it right, now.

On the other hand, I prototype like a madman and hard-coding certain things is quick and easy and leaves you free to concentrate on experimenting. It kind of depends on your style of working.
> 10 votes

# Answer
What you're talking about is data-driven programming.

For small projects, it may not be worth the time investment, as there are often much more important features that you could improve.

However, data driven programming can be VERY easy to implement. If you're serious about it, you should probably use XML, JSON, or YAML, but you can also use plain text files.

# Data-driven Programming

**Pros**

1. Allows designers to access and modify game data without programming knowledge
2. You can make modifications to the game **without needing to recompile**. This should not be underestimated, as you can develop a game much more rapidly this way. Good games come after many iterations.

**Cons**

1. It takes time and effort to implement.
2. It may increase the complexity of the program.
> 8 votes

---
Tags: game-design, data-structure, data-driven
---