# Question
Title: Does C# have a future in games development?
I recently learned that the MMO Minecraft is powered by Java from a recent interview on CVG.co.uk on a possible collaboration between two former and now competing colleagues. In the interview he bluntly said that the founder of Minecraft is a Java coder and he is a C or C++ coder so they are incompatible with each other. So collaborating on future projects will be difficult.

This got me thinking, If Java could do that? What does the future hold for MS very popular C# language and .Net platform as far as games or mainstream games development is concerned?

# Answer
> 22 votes
You should check out XNA. A platform for building games for Windows, Xbox 360 and Windows Mobile 7. All in C# and .NET.

# Answer
> 11 votes
I've been working in professional game development for over 5 years. Most of this time, I used C# almost exclusively.

C# and .NET stack in general is really great for server-side tech. I've worked on no less than 4 MMO games with server written in C#. Also, with Unity3D gaining popularity, many browser AND mobile games require C#. Don't forget XNA framework: it's not the engine of choice for AAA console titles, but there are many great games made with it, and many more currently in the making.

Overall, C# definitely has a future in game development.

# Answer
> 10 votes
As has been mentioned, Mono brings C# to multiple platforms. In that same area, you'll find Tao, a multiplatform library for Mono and .NET that allows access to Cg, DevIL, FreeGLUT, GLFW, GLU, ODE, OpenAl, OpenGL, PhysicsFS, SDL, and WGL. It's obviously not as robust when it comes to features as XNA (which provides fundamental engine components directly to the developer); but, it's plenty powerful.

So, cross platform beyond Microsoft controlled OS's and hardware is definitely possible. Just, not as many popular indie games have utilized this ability, yet.

As has also been mentioned, XNA coupled with C# allows independent developers to publish to the 360, PC, and Windows Phone 7.

Overall, C# is alive and well in game development as an engine/game language.

As a tools language, it's in use everywhere. I've built tools for EA, THQ, and now Arkadium all using C#.

# Answer
> 5 votes
Not only does C# have a future in games development, it has a present - Check out Magicka, a game recently released (and selling well) that was developed using XNA. Also take a look at the winning Dream.Build.Play entries. C# is a viable way to make games (although right now I don't believe it's the right choice for *all* games).

As time goes by we'll see it becoming more popular in the computer gaming industry, however I don't expect a sudden shift to C# at any point.

# Answer
> 4 votes
Java has always been a very versatile language and there's always been the ability for people to code games in it, from simple web based games (Java applets / GWT with the canvas plugin) to full 3D beasts (checkout JMonkey). So I wouldn't say the fact Java can do that sort of thing is a C# killer, because most people know Java can do that already.

C# will still remain popular though since it inevitably ties in with Windows, Windows mobile and the Xbox much better than Java (which, really, is all game developers really care about targeting so the cross platform advantage that Java has is mostly lost.) It's also got XNA which has really taken off in terms of game development.

So yes, Java is a perfectly good platform for games development if anyone wishes to go down that route, but it's certainly no C# or .NET killer.

# Answer
> 4 votes
Check out Unity 3D; C# (and JavaScript, and Boo) scripting in a high-performance 3D engine.

Add XNA to the mix and you're looking at a couple of great platforms for using C# for game development.

# Answer
> 1 votes
Yes, C# has a future, with the XNA framework. Most prefer C++ because of speed, but C# is not **that** slow anymore...

# Answer
> 1 votes
Also - MonoDroid may be an option for C#.

# Answer
> 1 votes
What he did with Java in this instance was create an applet so that you could just log on to the site and play with a very common plugin, completely transparent to which operating system was being used. I imagine his thinking was that Java was quite transparent when used this way and it would make it easy for the quick iterative development / testing he was getting fans to do. I don't believe you can just do this with XNA because usually the tester has to have everything installed as well as the game and some general knowledge about how to compile and run this.

So I would say that there is no paradigm shift from this, it just suited what he needed at the time and obviously worked out well.

# Answer
> 1 votes
Sure, lots of programming languages have a future in games development. It is an often used false dilemma used in the computing press that there can be only one tool of type X and that everybody wants this to occur.

Nothing could be farther from the truth.

C# and Java have been used in games for a long time. C and C++ have for even longer, and still are. Lua is used as the scripting language for some incredibly popular games, with the engine written in C/C++.

So clearly, no programming language is blowing other programming languages out of the water as The Game Programming Language. In fact, we see a tendency for leading games to be composed of a high performance compiled programming language for developing the engine(s) in. and then a higher level dynamic programming language for scripting how the UI and stuff behaves.

The key at the moment is performance. If any of the programming languages/libraries used cause unpredictable/uncontrollable pauses in the application then in an action game, that will fall flat on its face. In a text-based adventure game, that might be okay however.

---
Tags: c#, software-engineering, game-industry, .net
---


# Question
Title: Making a 2D Platformer in C++/SDL. Looking for tutorials/examples/resources
I have a lot of experience with C++, but I have no experience with game programming. This summer I plan to create a 2D platformer from scratch using C++/SDL for the learning experience. I am looking for as many resources as possible to help me get started. Good source code, tutorials, anything.

One of the best tutorials I've found are the inactive jump 'n' run dev tutorials by the late Florian Hufsky. Any similar tutorials?

# Answer
> 4 votes
If you're a C++/object-oriented kinda guy, you might find SFML easier to work with. It's very similar to SDL, except that is has an OO interface. It's not as widespread as SDL, but still has quite a large following.

As for tutorials, since you're experienced with C++ you can probably get away with reading tutorials aimed at other engines and languages and apply the high level concepts, referencing your API and its help forums for specific issues you encounter along the way.

* Flash Game Dojo is aimed at Flixel & Flashpunk users, but has a lot of "beginning game programming" type of material.
* GameDev.net is another huge resource (look at their articles and wiki)
* Also look at the FlipCode archives. These generally cover more advanced topics, but you may find them useful in the future.

# Answer
> 3 votes
Airstrike is a small and simple game to start from. The source code is **short and simple**. It's not a platformer, but that may be a good thing, since you may not want your architecture to have outside influence. Every **low-level action** you may want is implemented - there aren't many (load resources, play sounds, display sprites...)

---
Tags: c++, 2d, sdl, platformer
---


title: Level Design Tips

text:
# Question
Title: Level Design Tips
What are some pitfalls or pieces of good advice when designing levels or maps for a (presumeably 3D but not necessarily) game?

# Answer
> 55 votes
* Make use of "arenas"--confined spaces where the player must solve some puzzle, fight some enemy, etc to move on. This is often referred to as "gating" the player, ie barring their progress until they have completed their task. This helps to create a sense of accomplishment when the player is allowed to continue, and makes for easy save/retry loops. The "arena" does not have to be an "arena" in the classical sense, it simply refers to any confined space where the player has to complete a task--it could be a courtyard that has no exit until an enemy bashes through a wall, for example.
* Block the area behind the player as much as possible (within reason). Playtesting has demonstrated that players are more confident about moving forward in a level if the amount of backtracking available to them is limited. This also plays nicely with the "arena" concept--an explosion in the tunnel a player just exited confines them to the next area of the map, creating a new "arena".
* Following along the same lines as the second point, carefully limit the number of paths available to a player. While it is common these days to advertise that there are multiple paths through the game, this is frustrating to players who want to ensure that they are seeing everything the game has to offer. Some branching, however, can make the game more interesting and is more practical as it provides multiple path options to AI, etc, and gives the player some freedom of choice.

# Answer
> 45 votes
* Players never look up -- Avoid putting enemies or solutions to problems above the top of the screen when player is looking straight out. Unless, of course, you've taught the player that it's necessary to do so (i.e. Portal).
* Use lighting to highlight important features or the way to go. Players are very receptive to going down a path if there's a light in it. You can use this to help players not get lost in seemingly complicated areas.
* Don't spawn/place enemies behind the player. That's just frustrating.
* Add quick saves often (assuming your game has that feature).

# Answer
> 31 votes
**Don't make a bunch of "jump" puzzles.**

There is nothing more frustrating than having to do the same jump about ten times until you get it perfectly right (or you have to redo previous jumps because you missed the Xth jump and have to start over).

# Answer
> 24 votes
**No water levels please.**

You can generalize this to a few good tips:

* Don't make the levels frustrating -- Don't make the player needlessly backtrack around the level. Don't make the level dependent on some split second timing to get right (and screwed if you don't). Play through the level a few times. Get others to play through it as well. Make sure that you all find it fun. If you don't, chances are not good that the majority of people will either.
* Don't make all the typical levels -- Underwater, on ice or snow, surrounded by fire, moving platforms with bottomless pits, etc. It's okay to have some to provide familiarity, but of course you want your game to stand out. For that, you're gonna have to come up with some sort of setting and mechanic that is unique and interesting (while keeping point#1 in mind).
* When introducing a new mechanic (player moves differently, player gets a new tool, etc.), don't make the level hard. Keep it simple. Allow the player time to adjust and learn what you have just thrown into the game. You can then reuse the mechanic in a later level and ramp up difficulty then.
* Make levels meaningful and have purpose that fits in with the overall game or story. Don't make the player go in the water just because you can. And definitely don't make any items suddenly not work just for the sake of "making the level harder". Find some other way, or don't do the level. People don't like levels that suddenly make everything they've been using up to that point useless. It makes the whole level seem like torture.

There are other things you can learn about how (not) to design levels if you just do research (by which I mean Google) on "why water levels suck".

# Answer
> 21 votes
* Build your art in modular pieces that can be reused throughout the level (or multiple levels)
* Create "Hero" or detail pieces that really stand out and can act as a point of reference for the player.
* Use dirtmaps/detail maps that can overlay your modular pieces to break up any tiling effects.
* Be conscious of your far plane and draw distance.
* Find ways to create depth in your level. Juxtapose near and far objects to show distance
* Think of your level like a movie-set; are you ever going to go behind something? No? Then don't model it!
* S-Curves are your friend. They help with occlusion and with streaming.

# Answer
> 17 votes
Valve's games with developer commentary (particularly: Half Life 2: Lost Coast, Episode 1 and Episode 2, Team Fortress 2 and Portal) are well worth checking out for some good tips on level design.

(L4D also has commentry, but I can't remember if it had much about level design in it.)

# Answer
> 10 votes
Somethings to add to already great advice given.

* Set physics parameters (minimum and maximums) first before starting to design level. (I.e. Jump height, run speed, etc.)
* Make sure enemy placements are not impossibly in favor to the enemy, conversely make sure the AI scripts/tools allot for the enemy to take advantage of their placement.

# Answer
> 10 votes
**When everything is special, nothing is special.**

Make sure that your level/game has a 'comfortable average' that is fun, but that the attention-grabbing moments can rise above.

# Answer
> 9 votes
**Use silence to you advantage!**

If your game is going to be scary in anyway silence is key! With a long duration of silence the player gets stressed and scared wondering when something is going to happen. So right in the middle of the level make some guard "Hey! Get back here!" or make some explosion out of no where happen near the players character.

Be careful though. Because where you place the sound is very important. It is entirely an art. I can only give one piece of advice that is essential for the silence to pay off:

**Make sure the player cannot see right away where the sound is coming from. Otherwise the scariness will be less intense.**

# Answer
> 8 votes
Give the player the information they need to succeed. If the solution to a level relies on something obscure or some new ability then teach the player about it. There doesn't have to be some specific tutorial where you spell it out, rather you can teach the player using cut scenes or making small puzzles at the start of the level that introduce new concepts at a basic but explicit level.

# Answer
> 7 votes
In a linear context, provide the player with challenge, but also rest. Gradually increase the difficulty in an upward wave, something like

```
Very easy (1) -> Normal (3) -> Easy (2) -> Hard (4) -> Normal (3) -> Very Hard (5) -> Hard (4) -> Extreme (6) -> ...

```

# Answer
> 6 votes
Just a few that just came to my mind while i came across this...

* Think about how you balance **challenges and rewards.**
* Think about how you can provide **variation and contrast**
* Think about **which order and what time during the learning curve to introduce which game element**

Some more thoughts...

* **Have recognizable locations** or objects at places you want the player to be able to recognize easier so he can navigate easier is less likely to get lost or confused
* You may also think of **levels having similar qualities to a song**. What i mean by this is that a typical song has **a start, a build-up, a breakdown, etc, etc...** So there are elements which are used most of the time, there are intense and chilling moments and of course surprises and single events (like that cool break in a track that you wish would plax more than only once per song ;)

Wish i'd have time to write more - i love this subject ;) Need to do some work now... Maybe later...

# Answer
> 5 votes
Auntie Pixelante has some excellent posts on level design where she deconstructs classic game levels

Check out:

# Answer
> 4 votes
**Make user stories for the type of play styles the game is supposed to appeal to**

If the focus is on exploration, try to avoid penalizing the player for it, both in terms of deaths that send the player back, as well as in time spent backtracking.

If the game is to appeal to players who like speed runs, consider different ways that the player can optimize their path - have some weapons kill enemies faster than others (Megaman), have some paths with fewer obstacles or further away from bottomless pits (Sonic 3&K).

If the game is intended to appeal toward players who try to make perfect runs, make sure that "game over" isn't a significant penalty (Ikaruga, Megaman). Also, keep in mind that difficulty is combinatorial: If an obstacle has a 10% chance of being beaten on a given try, 3 of those obstacles in a row gives a chance of 0.1% - sure, players get better with practice, but they make mistakes, too, so make sure to add checkpoints in between, or lower levels for the player to fall onto.

If narrative is a significant part of the game, keep the pace slow to ensure the player becomes attached to the scenery. Vary scenery intentionally - not just to keep the player engaged with the narrative, but as a visual cue for change in game mechanics (ice, water) or difficulty. ColourLovers is your friend.

Consider whether randomly generated levels would benefit or detract from your design:

* Can be a plus for multiplayer arenas, tactical RPGs, RTS, arcade shooters, and casual games
* Usually a minus for games with a focus on speed/perfect runs or heavy narrative, where the player has a strong relationship with the level design.

# Answer
> 4 votes
Design your first level to teach players how to play. The original Mario Bros. games are good examples of this:

http://us.wii.com/iwata\_asks/nsmb/vol1\_page4.jsp

http://www.significant-bits.com/super-mario-bros-3-level-design-lessons

# Answer
> 3 votes
**Keep rewarding me**

I like being rewarded for my actions. So loads of small bonus items, small upgrades, gold/points something that immidiately gives me pleasure so I want to continue grabbing more and more.

**Dont punish me with time-limits**

What I dont like in a game is when the developers finds it too easy and uses TIME as the only thing keeping me from completing a level. That is bad level design. You could use time as a "bonus", but never as a punishment. Sometimes the phone rings, the dinner is ready or even a toilet has to be visited. A pause is not enough here. If I am close to the goal and the level ends just because I was 5 seconds short, there is not much reason for me to try once more for 7 minutes.

My approach is to keep the player happy and occupied even in stressed situations.

So, none or a minimum of "Whoops dead, replay the last 5 minutes to get right back here"... instead, make it attractice to try again, not a punishment.

# Answer
> 2 votes
Avoid slippery-slidey ice levels.

Or at least keep the ice to a minimum.

# Answer
> 1 votes
*@Sean James* is for linear games, fine. I somewhat disagree.

if your game *is* linear, for god's sake don't pretend it's not. A linear game that fakes being non-linear should burn in hell (hello, Metroid Fusion).

non-linear is fine and much fun, as long as:

* there is a good map, where it is crystal clear which areas you have already visited which doors you still have to open, which items you didn't grab for whatever reason and in general which area of the map corresponds to which area of the game
* the player can mark and comment arbitrary map locations
* you try as much as possible to avoid dead ends: if I go back to an earlier section to explore a door I missed, I'll be pissed off if there is a single useless room
* there are nice means of transportation between different areas of the map (i.e. don't do like Aquaria - which is a great game apart from that)

To sum it up, the ideal is doing like Castlevania, but better.

# Answer
> 0 votes
Here are a few links about game design and level design collected on my webpage: http://www.newarteest.com/game\_dev.html

Especially take note of the link "evaluating game mechanics for depth" because that is a really informative article about level designers.

---
Tags: game-design, maps, level-design, levels
---


title: Level Design V.S. Modeler

text:
# Question
Title: Level Design V.S. Modeler
From what I understand being a level designer and a character/environment/object/etc Modeler are two different jobs, yet sometimes it feels like a Modeler can also do the job of the level designer. I know this also depends on the scale of the game. For small games maybe they are one and the same, but for bigger games they become two different jobs.

I understand a background in some modeling could not hurt when it comes to level design, but the question I have is: Do jobs prefer people who can model for level designing? This way they can kill two birds with one stone and have someone to create the assets and design the level.

What is your opinion of the training? Does level design contain skill sets that make them completely different from what a modeler can do, or is this an easy transition for a modeler to become a level designer? Can you be a bad level designer but a good modeler and vice versa?

# Answer
It depends on how the levels are created. Sometimes level designers wont even touch a single vert during the entire level creation process. Usually they have tools that allow the level designer to make the level without having to deal with polygons (Hammer for Source engine games, Unreal Editor for unreal). But as far as your question goes, I'm sure being able to also create 3d assets as well as design levels would increase your chances of getting a job but it doesn't necessarily make you a better level designer.
> 4 votes

# Answer
Level design is not really about visual design, although in many studios level designers do end up doing a lot of visual design work (eg. applying textures to the level.) Level design is really about planning the flow of the level, making decisions about gameplay, and laying out challenges for the player to overcome. Level design as a discipline starts with written plans and drawn schematics before firing up a level editing tool.

"Pure" level design is embodied by a workflow called "white-boxing" where the level designer places blank (not necessarily white, anymore than blueprints have to be blue) geometry in the scene to establish scale and structure, places all the dynamic items and enemies around the scene, and then environment artists go through and replace all the stand-in geometry with polished assets.

Here are a few links about game design and level design collected on my webpage: http://www.newarteest.com/game\_dev.html

Especially take note of the link "evaluating game mechanics for depth" because that is a really informative article about level designers.
> 4 votes

---
Tags: animation, art, level-design, jobs
---


# Question
Title: What is the difference between a level designer and an environment artist?
What are a level designer's roles in the development of a game, what are an environment artist's, and how do they compare? Are they overlapping roles? Does a game development team typically have both roles?

# Answer
It depends on the studio. There are two fundamental camps. The terms are ones I've used, but probably aren't common elsewhere.

"Dallas-style" level designers typically do everything, typically using some kind of engine that has heavy brush editing (i.e. quake based). Usually from layout, texturing, placing props, lighting, NPC placement, scripting, etc. "Environment artist" isn't really a position that exists. Usually the art department are involved with making textures, ancillary props, skyboxes, and occasionally some integrated hero props (that are usually first roughed out with brushes and then exported into a format where the artist can make something over top of it in something like Max). You'll occasionally do things like paintovers from concept artists to give the LDs some artistic inspiration for the final art passes. The LD is primarily the one responsible for maintaining performance. A lot time this is with older engines that require a bit more care and technical knowledge because these engines are portal based.

"California-style" level designers mostly do layout and scripting only. This is more common with engines that are based around art tools (i.e. the LDs are also using Max). After gameplay is proved out, the environment artists go in and do the rest. Texturing, props, particles, sometimes lighting, and pretty much anything that isn't gameplay specific is done by the artists. They usually work pretty close with the concept artists. The artists have a good amount of responsibility with performance in this mode as well, usually in the form of "keep this number in the green" for a given scene.

Fortunately, "Dallas style" level designing seems to be going away. Splitting up responsibilities means that you aren't putting as much on the shoulders of the LDs. Plus you have a higher theoretical artistic bar if your artists are the ones doing the "arting up".

Why is "Dallas style" still popular at all? Mainly due to the engines being used. Artists generally are averse to learning LD tools. They can be very comfortable with Max/Maya, but trying to get a not-very-technical artist to use something like Radiant can be a bit of a disaster. Some studios have solved this as a culture issue.
> 18 votes

# Answer
An environment artist would focus on building the ambient nature of the world, ideally intended to immerse the player. This would probably range from the colours of the sunset, to the placement of non-gameplay oriented objects. A level designer would be implementing the placement of Ai, vehicles and necessary game objects.

If you think of a game such as Crysis, an environment artist would likely design the world in an artistic sense, then revise it based on changes made by the level designer after.

Contrary to what CommunistDuck mentioned, world objects such as doors and plants would probably be done by a 3d artist.
> 4 votes

# Answer
Level design is not really about visual design, although in many studios level designers do end up doing a lot of visual design work (eg. applying textures to the level.) Level design is really about planning the flow of the level, making decisions about gameplay, and laying out challenges for the player to overcome. Level design as a discipline starts with written plans and drawn schematics before firing up a level editing tool.

"Pure" level design is embodied by a workflow called "white-boxing" where the level designer places blank (not necessarily white, anymore than blueprints have to be blue) geometry in the scene to establish scale and structure, places all the dynamic items and enemies around the scene, and then environment artists go through and replace all the stand-in geometry with polished assets.

Here are a few links about game design and level design collected on my webpage: http://www.newarteest.com/game\_dev.html

Especially take note of the link "evaluating game mechanics for depth" because that is a really informative article about level designers.
> 3 votes

---
Tags: jobs
---


# Question
Title: connecting multiple anti-aliased lines together
I implemented/copied the wu line algorithm from pseudo-code on wiki-pedia and other places.

When drawing a sine wave it breaks down at the point where the line changes from y dominant to x dominant (or vice versa). (I did not copy the endpoint code because it looks terrible and I do not need them for my purposes. )

Does anyone know a solution for this issue? If not I will modify the algorithm myself to get it to work. I am just curious if someone else has run into this and knows exactly how to fix it. Is it possible to implement without the lines being globally aware of each other? Or is this why drawing API's implement moveto and lineto functions?

The pseudo code

# Answer
> 1 votes
Are your pixel pairs really covering the line points? You appear to have an off-by-one error in your algorithm implementation.

I suggest plotting the aliased version of your curve and superposing the two images, maybe using two separate colour channels. You will probably see where the error lies. Or you could post some code for double checking.

---
Tags: software-engineering, graphics, graphics-programming, c
---


title: Fbx mesh animation opacity export

text:
# Question
Title: Fbx mesh animation opacity export
3d Max does export Opacity value of an material to Fbx, which in Xna (when importet/processed) can be easily found in BasicEffect of a mesh instance Alpha property (and used in draw method).

My question is:

1. Can opacity values on animated mesh be exported (specific opacity states/values over time/keyframes) ??

From what I gathered it seems that only Opacity value of the First frame of animated mesh is exported (and found in BasicEffect of mesh). So if in Max there are keyframes with different opacity values and Max animation preview clearly show these transparency transitions when moving scroll, then do not get exported to Fbx.

Are there knows techniques/hacks to inject opacity from animated meshed (values over time/keyframes) to Fbx?

# Answer
So, you want to animate the material transparency setting. You might want to use a different format if FBX does not support that, at least for this specific effect, maybe detach to a different mesh, and export as collada file instead for that effect. I don't know if collada is supported in XNA, nor if would support material opacity animation. But is by far a more complete format, allowing a lot more stuff to be ported from a scenery.

I haven't really searched, but some stuff that pops, in case collada is not already supported by default (if not, they should add it) : link 1, link 2

Edit: Collada plugin for Max, info. You can try also with this other one.
> 1 votes

---
Tags: xna, models
---


# Question
Title: Getting OpenGL hardware acceleration with SDL on Linux
I'm trying to use SDL + OpenGL but I don't believe hardware acceleration is working because the framerate for around 18000 polys is about 24fps on a quad core machine but is a hopeless 1-2fps on an Intel Atom. Even the quad core starts to struggle when the poly count rises above this.

I've checked my code over but I'm clearly missing something obvious. I've changed my SDL initialisation code to use the same code as in the SDL OpenGL test. It reports that SDL\_GL\_ACCELERATED\_VISUAL is 1 but that hw\_available in SDL\_VideoInfo is 0

Also the vendor is reported correctly as Nvidia on both machines and accelerated apps such as Compiz and glxgears work fine.

Any ideas of what to try?

Thanks

# Answer
If you are using glBegin()/glEnd() in your code, especially if setting textures and states redundantly between frames (i.e., draw with texture 1, then 2, then 1, then 2, as opposed to 1,1,2,2), you probably are incurring driver overhead. Especially this is the case if you are noticing that a slow processor is chugging while it still has a good card. Using glDrawArrays or similar usually has *much* better performance.

Without a full code listing, though, there really isn't a way to know for sure. SDL is a pretty thin wrapper, so unless you are doing something really weird I wouldn't expect an error. Also, what cards are being used?
> 6 votes

---
Tags: opengl, c++, sdl, linux
---


title: Unity Deactivating a gameObject

text:
# Question
Title: Unity Deactivating a gameObject
I'm trying to deactivate an GameObject when a certain variable reaches a certain value. It is an imported FBX and doesnt have a MeshRenderer. I'm trying to stop it now with `TheGameObject.gameObject.activate = false;` then nothing happens.

Is there any other way to do this or fix this?

# Answer
> 5 votes
The property is `active`, not `activate`. And you can try using `SetActiveRecursively` if your game object has multiple child objects. Just setting the active flag doesn't set the active flags of child objects.

---
Tags: unity, javascript
---


# Question
Title: Should I use GL_GENERATE_MIPMAP_SGIS or GL_GENERATE_MIPMAP?
I'm using Windows 7 and most people in the group of this specific OpenGL project is too, there's only one member on Windows XP. We are all using Visual Studio 2010 though. I don't know if the OpenGL headers come with VS or with Windows but I would assume it's VS. And since we are all using the same VS version, albeit not the same SKU, I'm also assuming we all have the same OpenGL headers and version running on our systems.

That said, the version installed on my system (note that I haven't installed anything OpenGL related) is 2.1 and it does support `GL_GENERATE_MIPMAP`, I don't need to resort ot the SGIS extension.

However, the Windows headers only support version 1.1. To work around that, I'm using GLEW. I also noticed that both `GL_GENERATE_MIPMAP_SGIS` and `GL_GENERATE_MIPMAP` have the same exact values defined.

So my question is, should I do the following on my texture loading routine:

```
if(GLEW_SGIS_generate_mipmap) {
    glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
    glTexImage2D(GL_TEXTURE_2D, 0, glFormat, texWidth, texHeight, 0, glFormat,
        GL_UNSIGNED_BYTE, texPixels);
} else {
    gluBuild2DMipmaps(GL_TEXTURE_2D, glFormat, texWidth, texHeight, glFormat,
        GL_UNSIGNED_BYTE, texPixels);
}

```

...or can I just assume everything will work and just do this:

```
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
glTexImage2D(GL_TEXTURE_2D, 0, glFormat, texWidth, texHeight, 0, glFormat,
    GL_UNSIGNED_BYTE, texPixels);

```

?

I would think that this code would fail (and the game wouldn't probably run) if the OpenGL version doesn't support mipmapping generation like that, but nowadays, most people probably have OpenGL 2.1 on their systems right, probably in Windows XP too (without any development tools installed)?

Also, another small question...

My laptop has 2 graphics card, one integrated (Intel) and the other dedicated (NVIDIA), with NVIDIA Optimus technology. Mipmapping using the dedicated GPU seems to have better quality. I mean, the integrated card mipmapping seems more pixelized in near planes (I'm talking about a plane terrain texture) than the dedicated one. And when I move the camera, the near pixels "blink" a little (with the integrated card) and it's distracting, while the far pixels look nicely linear. Yes, I'm using `GL_LINEAR_MIPMAP_LINEAR` for the minifying filter. Anyway to fix this?

# Answer
Available OpenGL functionality is determined by the graphics hardware/driver revision; it is independent of installed developer tools.

If you want to be super-safe, use your first version and test for GLEW\_VERSION\_1\_4 too:

if(GLEW\_VERSION\_1\_4 || GLEW\_SGIS\_generate\_mipmap)

That will take care of the cases where either 1) the SGIS extension is reported by a driver/card that reports a GL version before the extension became part of the core, 2) where the GL version is sufficient but the SGIS extension is not reported (which I haven't seen in the wild, but I suppose it could happen) or 3) neither condition is met and you fall back to GLU. GL\_GENERATE\_MIPMAP\_SGIS and GL\_GENERATE\_MIPMAP are the same, so it doesn't matter which one you use in your code (assuming one is available, so is the other; it all looks the same to the runtime).

As to your other question: a difference in the setting for anisotropic filtering or anti-aliasing would be my guess.
> 1 votes

# Answer
Here's a link which has good information about automatic mipmap generation: http://www.opengl.org/wiki/Common\_Mistakes#Automatic\_mipmap\_generation

In short:

```
if OpenGL >= 3.0, use glGenerateMipmap

else if OpenGL >= 1.4, use glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);

else video card is pretty old at this point, fall back to gluBuild2DMipmaps?

else cut off support

```
> 2 votes

---
Tags: opengl, extension
---


# Question
Title: Simple Update loop to show questions one at a time
I have two lists which work with an XML file which holds questions and answers. At the moment the project displays all the questions at the same time so they "flicker" on the screen and iterate between each item in the list.

Whats the easiest way (coding) to pause the random generated list on any particular questions?

Question class:

```
class question
{
    public string questionString;
    public string apple;
    public string pear;
    public string orange;

    //the ? indicate the int can be nullable so it can accept the string item
    int? correctAnswer;

    public question(string newquestionString)
    {
        parseQuestion(newquestionString);
    }

    public void parseQuestion(string newquestionString)
    {
        List<string> questionComponents = newquestionString.Split('|').ToList<string>();

        questionString = questionComponents[0];
        apple = questionComponents[1];
        pear = questionComponents[2];
        orange = questionComponents[3];

        correctAnswer = Int32.Parse(questionComponents[4]);

    }

```

In Game1:

```
    Random q = new Random();
    int i = q.Next(questions.Count);

    spriteBatch.Begin();
    spriteBatch.DrawString(myfont, questions[i], new Vector2(100 + 100 *i, 100), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].questionString, new Vector2(100 + 100, 100), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].apple, new Vector2(100 + 100, 200), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].orange, new Vector2(100 + 100, 300), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].pear, new Vector2(100 + 100, 400), Color.Black);
    spriteBatch.End();

```

# Answer
> 3 votes
Does the code labeled "Game1" occur in the `Draw(GameTime gameTime)` method? If so, the problem looks as though you draw a different question each frame not that you need to draw slower. If you draw the same thing every frame, there should be no flicker; I would adjust the code like this:

```
// private class level variable
int currentQuestion = 0;

// in the Update(GameTime gameTime) method
if(userChoseAnswer) // check input and see if you should advance to the next question
{
    Random q = new Random();
    // might want to add code here to avoid showing
    // questions already shown? unless that wont help your game
    currentQuestion = q.Next(questions.Count);
}

// in the Draw(GameTime gameTime) method
spriteBatch.Begin();
spriteBatch.DrawString(myfont, questions[currentQuestion], new Vector2(100 + 100 *i, 100), Color.Black);
spriteBatch.DrawString(myfont, myQuestions[currentQuestion].questionString, new Vector2(100 + 100, 100), Color.Black);
spriteBatch.DrawString(myfont, myQuestions[currentQuestion].apple, new Vector2(100 + 100, 200), Color.Black);
spriteBatch.DrawString(myfont, myQuestions[currentQuestion].orange, new Vector2(100 + 100, 300), Color.Black);
spriteBatch.DrawString(myfont, myQuestions[currentQuestion].pear, new Vector2(100 + 100, 400), Color.Black);
spriteBatch.End();

```

# Answer
> 4 votes
The update and draw loops run roughly 60 times per second (30 on WPF, and it also depends on how much your computer is doing in each loop and how fast the computer is). To update the questions slower you need to keep track of the time passed. You can do that as following

```
float elapsedSeconds = 0;
public void Update(GameTime gameTime){
     elapsedSeconds += (float)gameTime.ElapsedGameTime.TotalSeconds;
     if(elapsedSeconds > TimeIWantAQuestionToDisplay)
     {
       elapsedSeconds = 0;
       question = q.Next(questions.Count);
     }
}

```

---
Tags: xna, xml
---


# Question
Title: Instancing with empty data, or varying vertex counts?
I am new to game development, having only developed a few games before, in 2D space, but with 3D rendering.

I have implemented instancing before, but this is only my 2nd time doing it. I have a question regarding instancing.

To do instancing, I have a geometry buffer having a vertex declaration (for instance) 32 VertexPositionColor elements. This is because I have a few elements with 32 vertices in them.

I am rendering all elements as linelists. However, there are some elements in the list that doesn't have 32 vertices. I would like to include these in the instancing render process too.

So my final question is, what happens if I (for instance) fill out 8 of the vertices with their indexes, but then still send all the 32 vertices into the instancing shader? Is it possible?

Is there a better approach to be able to instance all kinds of elements, with various vertex counts?

# Answer
> 2 votes
Resizing or creating a buffer is a costly operation, don't do it at draw-time.

There is no processing cost for having unused vertices in your vertex buffer (or unused indices in your index buffer, for that matter). They just take up a small amount of memory.

---
Tags: xna, c#, directx, hlsl
---


title: gl_PointCoord always zero

text:
# Question
Title: gl_PointCoord always zero
I am trying to draw point sprites in OpenGL with a shader but gl\_PointCoord is always zero.

Here is my code

Setup:

```
//Shader creation..(includes glBindAttribLocation(program, ATTRIB_P, "p");)
glEnableVertexAttribArray(ATTRIB_P);

```

In the rendering loop:

```
glUseProgram(shader_particles);
float vertices[]={0.0f,0.0f,0.0f};
glEnable(GL_TEXTURE_2D);
glEnable(GL_POINT_SPRITE);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
//glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);(tried with this on/off, doesn't work)
glVertexAttribPointer(ATTRIB_P, 3, GL_FLOAT, GL_FALSE, 0, vertices);
glDrawArrays(GL_POINTS, 0, 1);

```

Vertex Shader:

```
attribute highp vec4 p;
void main() {
  gl_PointSize = 40.0f;
  gl_Position = p;
}

```

Fragment Shader:

```
void main() {
 gl_FragColor = vec4(gl_PointCoord.st, 0, 1);//if the coords range from 0-1, this should draw a square with black,red,green,yellow corners
}

```

But this only draws a black square with a size of 40. What am I doing wrong?

Edit: Point sprites work when i use the fixed function, but I need to use shaders because in the end the code will be for opengl es 2.0

```
glUseProgram(0);
glEnable(GL_TEXTURE_2D);
glEnable(GL_POINT_SPRITE);
glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
glPointSize(40);
glBegin(GL_POINTS);
glVertex3f(0.0f,0.0f,0.0f);
glEnd();

```

Is anyone able to get point sprites working with shader? If so, please share some code.

# Answer
> 1 votes
Curious. It's working exactly as it should for me. The only real difference is that I'm using an OpenGL 3.2 Core Profile.

Vertex shader:

```
#version 150

uniform mat4 ProjectionMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ModelMatrix;

in vec3 Position;

void main(void)
{
   gl_PointSize = 40.0;
   gl_Position = ProjectionMatrix * ViewMatrix * ModelMatrix * vec4(Position, 1);
}

```

Fragment shader:

```
#version 150

out vec4 FragmentColour;

void main(void)
{
   FragmentColour = vec4(gl_PointCoord.st, 0, 1);
}

```

---
Tags: opengl, shaders
---


# Question
Title: Rendering everything with a shader when only squares are needed?
I am building a game that is tile-based (filled with glowy vector squares). Right now, I am considering using instancing for drawing these, but I would like to know if there is a faster approach.

The squares are all of the same size. They should be rendered in a rectangular grid, and I know exactly how many of them I should render. The squares are also made with linelists (so 8 vertices for a single rectangle).

Knowing all this, is instancing still the best approach? Or can I utilize the GPU more here? (in my game, I only utilize 1% of the GPU, but 100% of the CPU).

# Answer
> 6 votes
You are probably hitting 100% CPU because you are at the batch limit. You get a few thousand batches per frame. A batch is basically equivalent to a call to one of the `GraphicsDevice.Draw*` functions.

You probably want to read this answer.

While you can reduce the number of batches with instancing, because your geometry is so simple you are probably better off using `DynamicVertexBuffer` or `DrawUserPrimatives` to put all your geometry into a single batch. (This is the technique that `SpriteBatch` uses.)

For such a small amount of geometry, the cost of calculating and sending the vertex data to the GPU will be comparable to, and quite possibly better than, the cost of transmitting the instancing data.

Additionally, if your data doesn't change every frame, you should use `DynamicVertexBuffer` and instead of refreshing it every frame, add a `ContentLost` handler and then only refresh it when you need to or if the device is lost.

Obviously, if your data never changes at all you should simply build it into a single, static `VertexBuffer`. If what you are drawing is terrain, and it is not deformable, just have one (or more) huge (thousands of vertices) vertex buffer that you can scroll around, and let the GPU handle culling for you.

# Answer
> 1 votes
You can use geometry shader and send just one point and normal for each rectangle. In geometry shader produce for example triangle strip. But if you need texture coordinates, it could be problem.

// Deleted some Opengl info (now I have taken note that you are talking about XNA :) )

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


# Question
Title: Does it make sense to include an index for linelists?
Does it make sense to include an index by using DrawIndexedPrimitives, when using linelists performance wise? I could imagine it would be easy for the GPU to generate such indexes anyway.

# Answer
Indexing provides two major benefits:

1. Speed. Vertices are only transformed once. If you have two connected lines (consisting of a total of three vertices), an indexed draw will only call the vertex shader three times. Without indexing, you'll pass in four vertices (even though two of them will have the same coordinates), and the vertex shader will be called four times. Multiple this by a few million primitives...
2. Memory. In the above example, your vertex buffer will only have to hold three vertices, and your index buffer will have four indices. You're trading the space required to store one of the vertices for the index list. If you're using a large vertex type (`VertexPositionNormalTexture`, for instance), this makes sense.

If you use a 16-bit index buffer or non-trivial vertex types, your savings with indexing will most likely outweight the memory cost of the extra vertices (ie - a good thing).

Also, there is a small bit of GPU overhead with indexing, but it can be very small compared the running the vertex shader many more times than is necessary.

**Edit**

I thought of an example where you'd need to use non-indexed vertices. If you want to implement something like horizontal window blinds (picture for clarity), you may start with a model that has them closed (ie, all the blind surfaces are coplanar). To open them you'd apply different rotation matrices to each of the faces. Vertices that overlapped when closed would now be separate in world space. (When closed, the bottom edge of one slat will sit on top of the top edge of the next one down, and when open, they don't touch at all).

(Incidentally, that would be a perfect application of instancing \[which can be thought of as yet another layer of indexing\] if you had many sets of blinds.)
> 4 votes

# Answer
If you draw a line where the end point of the first line is the start point of the second line then you can use LineStrip to 'automatically' get indices.

If you draw lines where vertices are never shared between lines then indices will get you no benefit at all (might even slow it down).

If some part of your vertices are shared then it can indeed be smart to use an index buffer.
> 1 votes

---
Tags: xna, c#, directx, hlsl
---


# Question
Title: In Ren'Py, how do I show a different image depending on variables?
At the start of my RenPy game, the player chooses a male or female character. The game plays out the same for both, save for some details.

The problem is that I want to write:

```
show hero normal

```

and get the image of the correct sex of the character chosen at the start.

I started to write a python function to do this, but it looks wrong because there seems to be enough ATL language to do this, even if I can't find a way.

Any idea?

# Answer
ATL doesn't have an if statement at the moment. You can use DynamicDisplayable for this - the code looks like:

```
image hero normal = ConditionSwitch(
    "male", "male_normal.png",
    "True", "female_normal.png")

```

I've added an ATL if statement to the list of things I'll add to Ren'Py in the future, since it really should be there.
> 5 votes

# Answer
Someone on this forum showed me that I could use choice in ATL :

```
image hero normal:
    choice( hero_sex == "man" ):
        "hero_man_normal.png"
    choice( hero_sex == "woman" ):
        "hero_woman_normal.png"

```

Not perfect solution but simple enough to solve my problem.
> 2 votes

---
Tags: sprites, python, scripting, visual-novel, renpy
---


# Question
Title: How do I find artists to work on my game?
I ask "how" rather than "where" because there are undoubtedly lots of artists that are just plain lousy or unreliable.

Let's assume both paying and non-paying (mods, free games/open-source) positions.

# Answer
One tip I've heard is to **build as much of the game as possible before looking for artists**. Build the game with placeholder art before you post about the game so that artists can get a feel for the game, its play style and environment, etc before building assets for it. They can also use the prototype to decide if it's a project they'd actually like to work on.

Another tip I've heard is to avoid asking for people to "join your team" as this seems "noobish". Instead post the prototype and say that you need an artist or artists to finish it. If you post at the right communities someone will almost always come along that is interested.

You can, of course, pay an artist per asset, etc from a more "professional" site. This is really a personal choice. Modelers, musicians, voice actors, etc can all be hired from sites that can be found with some quick googling. However keep in mind that you should still provide these people with as much of a game as possible so they can create something that "fits". You can also easily determine if a model will deform properly, light well, etc before accepting the asset if you have build as much of the game as possible beforehand.

One final note, if you are building any artist tools: be sure to have them rock solid and well documented before sending them to an artist, or you will waste time and money sending them revised versions of the tool or having them rebuild assets.
> 41 votes

# Answer
Artists are generally as lousy and unreliable as the client is, so the answer is to be professional and to look for professionals.

I second a lot of things David said in his post about Networking - this is the only way you will find reliable artists to work on your game for little to no money. But I will add some tips as well:

1. Never, never promise 'payments once we've made a profit'. This is a red flag to artists. It means we're never going to get paid. No matter how good you think your game is, promising profits is a really bad idea, and will scare away professional artists.
2. If you want us to be reliable, we need the same thing from you. On a non-paid game, this means: getting all the info from you that we need for each asset, not having a ton of arbitrary revisions (as this is a lot of extra work), a reasonable deadline (if we're doing it for free, we can't do it fast - we need to work, too), and timely communication (don't leave us hanging for weeks). For a paid project, make sure you pay on time. I can speak from experience when I say that promises left unkept will halt all art production in the meantime. In the end, a non-paying gig is only going to hold us so far, as we need to eat and pay rent too. If you really want an artist to stick with you for a while without pay, you have to find someone really invested in both the game, and their partnership with you.
3. Budget Negotiations. If you have a really tight budget, tell the artist! Many professional artists can be willing to dip their fees if the project is something they really believe in. If you can only afford $XXX to go toward art assets, tell them what the budget is upfront, and ask them to tell you how many assets/how much work that your budget can afford you. A good artist should be able to bring up an estimate, and as long as you're both reasonable, even if you can't work out a deal immediately, you can leave a good impression on each other and leave open the possibility of working together in the future.
4. Find an artist who's work you love and that you think will fit the project. You're much more likely to find a good fit if you find them, rather than them replying to a job ad. A good idea is to maybe find 20 artists that you like, and contact them. Even better if you can find the common thread that you liked about their work - because then even if you get negative replies to your first batch, you have the vocabulary to tell other artists exactly what you want.
5. Check out art forums. Some good ones: www.conceptart.org , www.cghub.com , www.cgsociety.org . There is also deviantart.com, but I would stay wary - the general population of artists there are in the amateur category, and while they may be really enthusiastic, they probably don't have a lot of experience and will therefore be more unreliable.
6. Ask for a resume, portfolio, list of references. Just like any other job! Follow up on the references, and if they have published titles, look at the titles! Someone with published work under their belt is much more likely to follow the game through - they've done it already!

Hope this helps!
> 17 votes

# Answer
I find it very difficult to randomly jump on a project with a random individual for free.

You may find someone willing to join your project for free but they will likely have little to no experience and there is no promise they'll stick around.

My single, biggest piece of advice to find artist's (or programmers, or audio guys, or ... :

**Network**
Have you ever been to the Game Developers Conference? You'll meet some amazing independents there and you don't have to fork out the money to get the top tier pass to meet them (scout events, meet-ups, etc). But if you do pay for a good pass, you might be inclined to jump in an art session to network. ;)

GDC isn't in everyone's bag-o-tricks so I'd be on the look-out for any game development related events around you.

If you're in school you can try to put together a meet-up on your campus to bring people out.

Get yourself out on the web and abuse the forums around you. If you've seen an artist's work send them a message and say hi. They might not be available but they may know a few artists that are.

While you're developing, thing about starting a development journal on gamedev.net or blog. My dev journal was what led me to join an independent team from a friendship that sparked.

**Help Wanted Forums**
tigsource.com and gamedev.net have some pretty friendly help wanted areas. I posted on tigsource for some artistic help and I received a couple of responses.

**Contract Work**
If you don't put in the time to network, you're flat out going to pay for your artwork on freelance websites like odesk, guru, craigslist, or others.
> 11 votes

# Answer
The answer depends on exactly your intention. The more control you want to have, the more you have to be bringing to the table. For example, you could build the game using placeholder art and then try to find a talented artist to polish all the graphics. Similarly, if you pay them (up-front cash, not a percentage of future profits) then by definition you are bringing money to the table.

If however you want to recruit an artist from the beginning then don't expect to direct everything. They will want and rightly expect a lot of creative control; after all, the project is as much a speculative venture for them as it is for you.

It is simply impossible to know with 100% certainty how well someone will work out until you work with them on something, so the way around this Catch-22 is find people to do small projects and only do big projects with people you've already done small projects with. Doing a small project it's okay if things go south and you have to lick your wounds to start over with someone else.
> 3 votes

---
Tags: art
---


title: 2D Rope Collision Detection

text:
# Question
Title: 2D Rope Collision Detection
I'm wanting to create a rope that can collide with objects like in the following youtube video:

2D Game Physics Rope

I'm thinking that you implement the verlet integration which uses points and connects these points with lines. I'm trying to figure out what type of collision detection you would apply to the rope to get the effect in the video.

I'm thinking you would have to do some cd to each point. I would like to use box2D, so I'm wondering would making each point a rigid body work? Any advice would be appreciated.

# Answer
Since you're using Box2D, you can create a series of rectangles and use Box2D's joints to join them. There you have your rope.

In order to avoid corners poking out of a bent rope, I can imagine two options:

1. Give your rope segments rounded ends (so they won't be rectangles anymore)
2. Make this rope itself invisible and use it only for physics. Take the positions of the joints in each frame and use that to draw a rope on the fly that the player *will* see.

Warning: I have never tried this myself, but I fail to see how a series of joined rectangles can fail when the video you posted displays practically the same thing in disguise.

Edit: I just saw PaulZ and I realised the same thing. Go read his comment on the question as well.
> 6 votes

# Answer
A quick Google threw this up here. A demo, description and code (in Flash) using Box2D to implement a simple rope. The rope collides with itself and the block at the top of the scene.
> 2 votes

# Answer
Here is what I would do, make each each point on the line a circle, make enough points that the circles overlap. Tether each point to it's neighbour, rather than standard collision this tether should make the points stay a fixed distance from each other.

I don't know Box2D, but I'd guess the functionality required is there.
> 0 votes

# Answer
I remember this Allegro game: Cupid, from SpeedHack 2002. It contains an implementation for ropes that collide with the scenery. See PhysParticles and HeartTrails classes in heart\_tails.cpp file in its source code.
> 0 votes

# Answer
Originally Box2D had a rope bridge demo made of thin boxes joined with point-to-point constraints; that would be a fine place to start (I don't know if it still ships with that demo, but it would be straightforward to recreate).

It's easy enough to implement rope as particles with distance constraints independently of a rigid body simulator (as you mention, using a Verlet integration and constraint solving scheme like the one described in this article: http://www.gamasutra.com/resource\_guide/20030121/jacobson\_pfv.htm), but if you want rigid bodies to react to your rope (like in the video, with the dangling box) then it gets much more complicated. I'd start with a comprehensive suite of tools like Box2D and work backwards rather then try and build up from particles.
> 0 votes

---
Tags: collision-detection, box2d, rope-physics
---


title: How do I turn a game idea, into a game?

text:
# Question
Title: How do I turn a game idea, into a game?
I have an idea for a game, and I was wondering, how would I go about grabbing people in the gaming development community to help build this baby that is in my head. I am no coder, but I do understand coding concepts etc.

Are there sites for discussing possible game design ideas, or game concepts? (I'm hoping here is such a site :) )

# Answer
> 20 votes
Game development doesn't really take external ideas and fashion them into games. It's not like making films where you have a small chance of getting your script made into a movie if it lands in the right hands. It's more like writing a book where a first-time author is going to have to write every word himself before submitting it.

So, you're pretty much guaranteed to need to take a hands-on approach to getting your game made. There are essentially 3 routes:

* have a concrete skill to bring to the game-making process - typically game-specific such as art, design (not ideas, but concrete design), or programming. If you are willing to pull your weight, often you can find people willing to match your effort. (Whether they are capable of doing so is another matter.) Then you make the game for free in your spare time.
* money to pay people with so that they will do your bidding. Most people have bills to pay and will happily build someone else's idea if it'll put food on the table.
* join an existing company, again with a concrete game-making skill as above, and this time work on other people's games until you're in a senior enough position to be able to present your ideas to the team. This is the longest route and least likely to succeed, but is also probably the only route for games of a certain complexity and production standard.

There isn't really an alternative because game ideas are considered worthless on their own. They're not worthless, of course - but the two main problems you face are:

* most game developers already have more ideas than they have time to create (and have too little time in which to create them all). This is generally why they're into game development anyway - they had ideas, and so they picked up a skill to make them happen. The number of idle game coders waiting for someone to present them with a game idea is incredibly miniscule. I've been a moderator on Gamedev.net for 10 years and seen tens of thousands of posts there but I think I've only ever seen 3 people say, "I'm a game coder - give me something to code".
* it's generally not possible to spot the amazing ideas relative to the average ones until they are, at a minimum, prototyped into something playable. Nobody has set up a commercial 'slush pile' for games because you simply can't tell from a top-level concept whether the game would be fun, whether it would sell well, how long it would take to make, etc. Even if you restricted this to fully fleshed-out design documents, that only really helps with the development feasibility, not with determining how fun it'll be or how much it'll sell. So with this in mind, idea selection and production is left to the experienced - who will go with their own ideas (where possible - often they just end up making whatever the publisher is willing to fund).

# Answer
> 2 votes
There are game development communities on http://www.gamedev.net/ and http://www.indiegamer.com/

However nobody will react well to some random person just barging in with an idea, and it is crucial that you understand why. The first article on Sloperama addresses this issue: http://www.sloperama.com/advice/idea.htm

Although his advice talks about selling the idea, getting others to make it for you amounts to the same thing. Basically, you are going to have to build it yourself because noone else will do it for you. That doesn't mean you have to do every bit personally (ie. do all the programming, create all the art, compose all the music, etc.) but it does mean you have to work hard on it.

In order to get anyone else interested in your idea you have to be coming to the table with a lot. It helps a lot to have developed games in the past, so I might recommend setting your great idea aside temporarily and go develop a few small games (Tetris, Pacman, that sort of thing) on your own to develop rep.

ADDITION: Your use of the term "baby" in describing your idea is a red flag. That may mean you are too in love with your idea and expect other people to just do what you tell them. I hope this isn't the case, because you have to realize that unless you are hiring/paying them (up-front cash, not a promise of future profits) then this venture is just as speculative for them as for you and they'll rightly expect to have a lot of creative control too. Basically you should look at it like "hey does anyone else want to work with me on a shooter?" and then the details are worked out in collaboration with them.

---
Tags: project-management
---


title: Behaviour tree code example?

text:
# Question
Title: Behaviour tree code example?
http://altdevblogaday.org/2011/02/24/introduction-to-behavior-trees/

Obviously the most interesting article I found on this website. What do you think about it ?

It lacks some code example, don't you know any ? I also read that state machines are not very flexible compared to behaviour trees... On top of that I'm not sure if there is a true link between state machines and the state pattern... is there ?

# Answer
Behaviour trees are getting pretty big in the industry right now. Halo 3 uses them extensively for their AI (Halo 3 - Building a Better Battle).

Alex Champandard seems to be a big fan as well (Lots of articles on it on AIGameDev.com).

For code examples, take a look at:
http://magicscrollsofcode.blogspot.com/2010/12/behavior-trees-by-example-ai-in-android.html \- The example is in Java, but self-explanatory)

To answer your latter question: State Machines: State Object versus sequential check: what are the pro/cons?
> 20 votes

---
Tags: ai, state, tree, behavior
---


# Question
Title: Given a plane and a point, how can I determine which side of the plane the point is on?
Given the point

```
Vector pos = new Vector(0.0, 0.20156815648078918, -78.30000305175781, 1.0);

```

and the plane (triangle)

```
Vector a = new Vector(-6.599999904632568, 0.0, -78.5, 1.0);
Vector b = new Vector(6.599999904632568, 0.0, -78.5, 1.0);
Vector c = new Vector(6.599999904632568, 4.400000095367432, -78.5, 1.0);

```

I want to get a plane normal pointing in the direction of `pos`

```
//Getting plane normal
Vector ac = Vector.Subtract(a,c);
Vector bc = Vector.Subtract(b,c);
Vector planeNormal = Vector.CrossProduct(bc, ac);

//Testing which side of the plane the point is on
double dprod = Vector.DotProduct(planeNormal, pos);
if (dprod < 0)
{
    planeNormal.Negate();
}

```

But this method is wrong. The resulting `planeNormal` points in the negative Z direction, so it should not be negated. Is there a best practise for this? Please help me, I fail massively @ math :)

# Answer
Your method is mostly correct but misses one step. You can't simply use the point's position as the vector to get a dot product with, you need to create a direction vector from a point on the plane. Any point on the plane will do (the direction doesn't need to be exact) so just use one of the corners.
> 9 votes

---
Tags: collision-detection, normals
---


# Question
Title: Developing an Asteroids successor: which languages/tools/frameworks?
Currently I'm planning to run the Asteroids successor on the Java Virtual Machine, while writing the code in Scala (because that's the language I'm fluent in).

I have looked at different options, like using one of the various OpenGL bindings or using Java2D.

Having looked at some frameworks it seems that they either are targeted at 3D development or jump-and-run style games.

Are there any useful frameworks or should I try to combine libraries from different origins and roll my own "framework"?

Are other frameworks/tools like Flash/Flex vastly superior, so that learning a new language/platform would only be a minor drawback compared to huge benefits?

# Answer
> 2 votes
Flash has better penetration (everyone has the Flash plugin...), provides better tools for gaming (several 2d and 3d gaming engines like Flixel, PushButton, Alternativa, Away3d, Fisix) as well as better tools for creating graphics (Flash IDE, Vector based graphics). And to top it all off, you can port it to any mobile device using Air (iOS, Android, Playbook, Win7 in the works).

Flash gaming is a fairly big part of Flash in itself. It's been around forever. Very good community support as well.

---
Tags: java, flash, flex
---


# Question
Title: Is it useful to monitor framerate over the course of an arbitrary (but long) period of time?
How useful is it to keep a measurement of framerate over the course of long times (such as an hour) spanning multiple scenes/data environments?

I've had plenty of times where data throttling/pushing was based on a poll of what's going on in regard to framerate over the course of a minute. I've used ~10 minutes a few times when the game can be sensitive to upcoming high-detail/volume renders to task some unused processing power/memory bandwidth ahead of time.

Anyone come across any situations where long-term polling of frame speed is useful?

# Answer
> 11 votes
It may be more useful to create a diagram showing frames per second over a period of time. Ideally this diagram contains annotations about what happened in the world, for example changes of areas, starting and ending of fights.

In the sample diagram it is easy to see that the frame rate is a lot better in the home town than in the dungeon. And there seems to be something very fishy going on in the desert; likely a memory hole.

# Answer
> 9 votes
Seems almost as useful as a speed limit saying "2400 km/day" or "614400 km/year". Both are the same as "100 km/hour".

From the mathematical standpoint it makes no difference, but we humans have a narrow perception and we can deal much better with smaller numbers and time-frames.

If you throw 216,000+ FPH at me, I had no idea how long a frame is.

If you tell me 30 frame/s I can calculate without a calculator that 1 frame is 33.3 ms.

So no, I don't think it's a useful measurement, I've never heard somebody using it during several years in game-industry.

**Edit:** Now that I think about it, it would make sense, if 1 frame is very long, like 30 mins, then it is 2 frames/hour, but I doubt the fun factor of that game would be very high ;) So still "No" for game-industry

# Answer
> 5 votes
Frames per hour is an okay measurement if you're making a render farm or some other non-realtime rendering system. (A better measurement would be hours/hour though.)

Frames per second is not particularly useful either, and most developers that are any good at optimization will look at ms/frame instead, even if they still describe targets as X fps.

This question seems a bit artificial because I've never seen anyone actually describing measurements as such though.

# Answer
> 2 votes
No, there's no use for frames per hour, in a system that requires multiple frames per second. it would be like measuring speed in millimetres per hour or something.

Even if you did have a situation where you want to look forward 10 minutes (why?!) to predict some slowdown event, any problem will manifest itself as a sharp negative spike in the frame rate at that point. By merging that freak event into the more normal rendering 5 minutes either side of it and looking at the 10 minute aggregate, you actually make it harder to spot these problems, not easier.

Mathematically speaking, taking the average of a set of samples effectively applies a low-pass filter to the data, leaving you with less information than you started with. The larger the set of samples, the more the filter cuts out. Since there's nothing you can do with less information that can't be done with more information, there's no use for this value.

# Answer
> 1 votes
FPH? I had no idea what that meant till I clicked on this question.

And **no** I cannot see what could be useful about knowing how many frames per hour.

What would be useful is logging the frames per second over time to make a visual graph, or to analyze programmatically.

With frames per hour, you could have 60fps most of the time, and every 20 seconds 1fps, and the final reading wont look different than a solid fps that is lower than 60.

# Answer
> 0 votes
Quite a few years ago, when professional vehicle simulators were *very* expensive, I heard about a vessel simulator (e.g oil tanker type of vessel) which had a frame rate of 2 frames/second.

In *that* context a 120 frames/hour metric would be meaningful, perhaps even more useful compared to 2 frames/second, especially if you have reason to believe that those two numbers are not exact but something that has been estimated.

Assume the scenario that those numbers (120 and 2) are based on some values that are rounded to 120 or 2 respectively. In the case of 2, you could expect the frame rate to vary quite a lot, anywhere from 1.5 to 2.5 frames per second. In the case of 120, the frame rate could vary from 115 to 125 frames per hour, which is a bit more accurate.

But again, quite a hypothetical kind of simulator software these days.

# Answer
> -2 votes
There are times when it is necessary, for "serious" applications, such as real-life Flight Simulators.

*EDIT*: In a flight simulator environment, such as the ones used to train pilots in routine and adverse situations, it is entirely possible that the simulator knows what scenario is coming up, and would need to pre-plan out possible responses the pilot may make, which may include abrupt changes in altitude (height), attitude (roll and pitch), direction (yaw), all of which may quickly change the upcoming scenery. The simulator plans for this by preloading the data and precomputing visibility in the potential upcoming scenes.

The long-term polling of frame-rate is necessary to help ensure that the training was a valid experience for the pilot. If the frame-rate had dipped below an acceptable level, then the training regimen may not qualify for FAA (re)certification of pilot readiness.

# Answer
> -2 votes
Frames per hour says a lot more about your environment. It is a keen indicator for the long-term enjoyability of the game.

For example, you may have 50fps in some parts of the game, but in crowded areas, or areas of high intensity graphics or physics, you drop to 10 or 12.

If you graph the fph over the course of the game, you have a general idea of where you're at. It's no substitute for knowing that the frame rate drops in some circumstances, but if you're consistantly only at 15 or 20 fph you know there's a problem. The game should be high fps MOST of the time, if not ALL of the time. So having a moving average of the the long-term fps can help you achieve that goal.

---
Tags: rendering, game-mechanics, performance, frame-rate, data
---


# Question
Title: Is it possible to overlay EditText box on a GLSurfaceView on Android?
I am trying to add a "PlayerName" box on top of a opengl menu background, is this possible? I've tried various layouts, but they don't seem to allow an EditText box to appear on top

What is the typical way of doing something like this? Do I need to manually render the text and handle input or is there a better way? It seems like it should be possible to show the EditText on top of the GLSurfaceView somehow.

# Answer
> 12 votes
I found the correct way of doing this (This code is in the Activity class)

```
view = new MyGLSurfaceView(this, gameHandler);
editBox = new EditText(context);
editBox.setText("Hello Matron");

view.setRenderer(new OpenGLRenderer(gameHandler));
setContentView(view);

addContentView(editBox, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

```

The key is using **addContentView** method on the Activity class to add the editBox on top of the GLSurfaceView.

Hope this helps some googlers :)

Thanks! Ash

---
Tags: android, java, opengl-es, gui
---


title: Flash AS3 Tower Defense Problem

text:
# Question
Title: Flash AS3 Tower Defense Problem
I am working on a tower defense game in Flash. Right now most towers find the the nearest enemy in range (enemies are in an array), get the enemies coordinates, and fire a bullet. When it hits the coordinates \[bullet.hitTestPoint(x, y)\] it damages the enemy.

I want to design a tower that will shoot a bullet at the first enemy just like above, however, the bullet needs to go its max range and damage all enemies it hits along the way. I am having some trouble determining what enemies it is hitting.

The best way I have come up with so far is when the bullet reaches its max range, I draw a line from that point back to my tower. Then I loop through the enemy array and use \[enemies\[i\].hitTestObject(bulletLine)\]. If that returns true, it damages that enemy.

This seems to work okay, but I would like something more realtime and sometimes it seems like this is hitting enemies it shouldn't hit.

# Answer
> 3 votes
**Simple:**

Why not simply use your line idea, but instead of making a line for the whole path, make a line from the bullet's last position?

*how:*

Make the bullet an object, and give it a velocity and a direction (see vector), and then make a line from it's position in the last frame (make a variable to keep track of the previous position) and check against that!

This way you won't collide with any objects you shouldn't, and you can expand the game to something more complicated easily!

# Answer
> 2 votes
My first suggestion is to just not remove the bullet when it hits something and keep using hitTestObject like you do with other objects, but I'm wondering if there is a reason that approach wouldn't work.

For example, how fast is this bullet moving? Is it firing out to the max range instantaneously?

# Answer
> 1 votes
Hello you should consider using the dot product to compute the angle between two vectors.

Considering:

* A is the vector from the tower to the max distance point aligned with the first enemy.
* B is the vector from the tower to the enemy to test (one of the enemies list).

> θ = acos( (A . B) / (|A| |B|) )

* |A| is the vector magnitude of A.
* |B| is the vector magnitude of B.

|V| = square-root( V . V ) = square-root( Vx² + Vy² + ... )

Thus if θ is equal or close to 0° then they are parallels and in the same direction.

---

You could also consider using the cross product, but it's fit better for 3D. One of the use of the cross product is to determine if two vectors are parallels by checking whether the resulting vector is close to the zero vector, you can determine which enemies in your enemies list are aligned on the same vector as your first targeted enemy. It normally does apply to 3D vectors only, but as far as I remember you can use it with 2D vectors using a 0 value as Z value. (Take care they can be parallels and in opposite direction, ie: in the opposite side of the tower direction. You can use crossproduct to determine if they are the same direction)

Still considering the same A and B as in the dot product part:

> A **x** B = \[Ax, Ay, Az\] **x** \[Bx, By, Bz\]
>
> A **x** B = \[Ay\*Bz - Az\*By , Az\*Bx - Ax\*Bz , Ax\*By - Ay\*Bx \]

If this result vector is equal to (or "close to", depending of you needs) \[0,0,0\] then they should be parallels. then compute the dot product to verify if they are the same direction.

---

Finally, could also consider computing the distance between the segment (from tower position to the max radius using the first enemy direction) and the point (your current enemies list) : http://paulbourke.net/geometry/pointline/, or the distance from a point to a plane if you use 3D and flying enemies on top of grounded ones.

Using the above techniques (distance from a point to a plan/segment), you should also consider previously reducing the number of enemies in your current enemies table using a simple vector dot product (the vector from the tower to the max distance in the first enemy direction, dot-product the vector from the tower to the enemy to test). If your dot product is greater than 0 they point to the "same direction", if it is equal to 0 the vectors are perpendiculars and if the dot product is lower than 0, the vectors are in "opposite" directions. This way you can reduce the number of enemies to consider by keeping only those in the front direction... I beg this is useful only with a huge number of enemies, so it's up to you to decide if it worth it or not.

---

Edited: to reorganize the ideas...

I beg your pardon if this is not clear enough, as I'm not really fluent at English, it could be unclear... so if I'm not I will try to reformulate.

---
Tags: flash, collision-detection, actionscript-3
---


# Question
Title: Efficient player state architecture in Google App Engine
I am investigating Google App Engine for use in a browser based MMO. The player will make a server request when ever they build, buy or do any other action that the server needs to process. Therefore I am estimating a server request no faster than once per 10 seconds.

I want to store all my player data in one data structure (entity), because I have heard this is the most efficient way -- if not please correct me. So I figure that when a player causes a server request, I need to load/access the player's state data, carry out the action the player wanted to do and then store the result.

However, from an efficiency point-of-view, what is the best way to access the player data? I thought about using the datastore and maybe memcaching the result in memory for fast lookup. But don't I still need to write the data back out to the data store if it's cached? Should I write it out every time data changes? I looked at write behind caching but this seems to eat through your task queue quota.

Any ideas on the best approach? Best being defined as the most efficient method using the Google App Engine.

# Answer
> 2 votes
When a player is in the updating state (assuming this isn't a heavy-heavy write game like FPS or RTS), you need to either *batch*, or *heartbeat* (every 10 seconds or 100 updates) your updates. I ran into this problem with a Facebook isometric casual game. The basic idea is that a player needed to decorate their store/farm/whatever. If you try writing each time to the Player entity you'll run into huge problems. Also, it's not really a good idea to write only to cache ... it's not consistent and you could have cache evictions that make your players really mad that they just lost 5 hours worth of work.

For my game, I was thinking about using an eventually consistent, write behind cache, but it really is overkill.

My architecture looks something like this:

```
class MapTile(db.Model):
        """ Map tiles are very efficient way of storing what's on a tile, I just access  it by a key name like userid-x-y

            e.x MapTile(on='10001.180,20002.90')
        """
        on = db.StringListProperty() # a comma separated list of item ids on that tile and the rotation

class Item(db.Expando):
    """properties of a particular item, like a chair or a crop"""

```

Then when a new update comes along it will either be a sell,put away, purchase, or rotation. So I encode updates like `{a:ROTATE,x:1,y:1,r:NW}` and `{a:PURCHASE,x:1,y:2,id:10001}`

And batch them all up into a `mapUpdates = []` queue that gets flushed whenever the length is 10 or the heartbeat comes around, whichever is first. This way your client is never waiting around, trying to save dozens to hundreds of entities. You can also have some sort of "...loading" indicator that tells them you're saving.

When the updates get to the server just *write,blow cache,write cache*. Simple as that.

# Answer
> 2 votes
The most efficient way to organize the data depends on the kinds of operations you are performing on the data, and how often each of those operations will occur.

It sounds like you are making an MMO where players don't interact with each other, and where there's very little interaction with the game server (once every 10 seconds), so storing the player data in one data structure will probably work as long as it's not too large.

The way to find out is to try it. Start with the plain datastore. Measure it with a simulated load test. Find out if it's too slow. My guess is that if it's really once every 10 seconds there's no need for memcache or task queues or write behind caching or anything complicated like that. Once you test the performance, if you find it's too slow, then you'll be able to come here and point to the kinds of operations that are too slow, and we'll be able to help you with specific performance issues.

---
Tags: architecture, mmo, python, browser-based-games, google-app-engine
---


# Question
Title: FlxSprite ignore camera follow in flixel
I am using flixel v2.5 and am using `FlxG.camera.follow` to get the camera to follow the player. I have a background `FlxSprite` that I don't want to move with the camera. Is there a way I can set this `FlxSprite` to stay in the same place on the screen? I would also like to have a GUI HUD that stays fixed to the screen, and was thinking I could do this the same way.

# Answer
In previous versions, you could set the background/HUD's scrollfactor.x and scrollfactor.y to zero. Does that still work in 2.5?
> 2 votes

---
Tags: camera, flixel
---


title: OpenGL Insanely Slow

text:
# Question
Title: OpenGL Insanely Slow
I'm learning C++, and I'm writing my first OpenGL program. Unfortunately, it seems to be defaulting to Software Rendering (CPU uses bounces, GPU uses stays at 1%). I'm using SDL as the Windowing system. I've got no idea why, but when there is significant scaling, the program grinds to a halt. My PC should be able to handle it - I'm using an 8800GTX. My texture is 1024x1024, 32 bit RGBA and loaded with DevIL, and glGetString(GL\_VENDOR) is returning "NVidia Corporation". Any ideas?

I'm sorry to be dumping all the code, but I've got absolutely no idea at all what is doing it. I'm very new to OpenGL.

```
#pragma once
#include "SDL.h"
#include "SDL_opengl.h"7
#include "IL/il.h"
#include "IL/ilut.h"
#include <math.h>

const int SCREEN_WIDTH = 1024;
const int SCREEN_HEIGHT = 768;
const int SCREEN_BPP = 32;
const int FPS = 60;
const int XSIZE = 1024;
const int YSIZE = 768;

int main( int argc, char *argv[] )
{
    bool quit = false;

    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

    SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_HWSURFACE |  SDL_OPENGL);

    glEnable(GL_TEXTURE_2D);

    const GLubyte * Vendor = glGetString(GL_VENDOR);

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Clear the background of our window to red
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity ();
    glOrtho(0, XSIZE, YSIZE, 0, 0, 1);
    glMatrixMode (GL_MODELVIEW);

    glDisable(GL_DEPTH_TEST);

    GLuint image;

    ilInit();
    ilutRenderer(ILUT_OPENGL);

    ILuint texid;
    ILboolean success;
    ilGenImages(1, &texid);
    ilBindImage(texid);

    success = ilLoadImage("Textures.png");
    if (success)
    {
        success = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
        if (!success)
        {
            SDL_Quit();
            return -1;
        }
        glGenTextures(1, &image);
        glBindTexture(GL_TEXTURE_2D, image);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
        GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
        GL_NEAREST);
        glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH),
          ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE,
          ilGetData());
        ilDeleteImages(1, &texid);
    }
    else
    {
        SDL_Quit();
        return -2;
    }

    SDL_Event event;

    float x = 0.0f;

    while (!quit)
    {
        while ( SDL_PollEvent(&event) )
        {
            switch (event.type)
            {
                case SDL_QUIT:
                    quit = true;
                    break;
            }
        }

        glClear(GL_COLOR_BUFFER_BIT);

        glLoadIdentity();
        glTranslatef(200.0f, 200.0f, 0.0f);
        glRotatef(x,0.0f,0.0f, 1.0f);
        glScalef(1.0f+x, 1.0f+x, 1.0f+x);
        glBegin(GL_QUADS);
        glTexCoord2f(0.0f, 0.0f);
        glVertex2f(-100, -100);
        glTexCoord2f(0.0f, 0.119140f);
        glVertex2f(-100, 100);
        glTexCoord2f(0.091797f, 0.119140f);
        glVertex2f(100, 100);
        glTexCoord2f(0.091797f, 0.0f);
        glVertex2f(100, -100);
        glEnd();

        x += 0.1f;

        SDL_GL_SwapBuffers();
        glFlush;
    }

    return 0;
}

```

Edit : (24/04/2011 9.22 PM AEST) When run on an ancient card, on an ancient computer, it maintains ~60FPS.

# Answer
I've got no idea why, but it seems to have repaired itself. I even put a NPOT texture to test and I'm still getting very, very reasonable FPS rates. I don't think I've changed anything, and I've really got not idea at all why it is fixed. I'm sorry that this doesn't seem to be really answering the question. If anybody else can decipher why - you're doing better then me.

My final source is below:

```
#pragma once
#include "SDL.h"
#include "SDL_opengl.h"
#include "IL/il.h"
#include "IL/ilut.h"
#include <math.h>
#include <fstream>

const int SCREEN_WIDTH = 1024;
const int SCREEN_HEIGHT = 768;
const int SCREEN_BPP = 32;
const int FPS = 60;
const int XSIZE = 1024;
const int YSIZE = 768;

using namespace std;

int main( int argc, char *argv[] )
{
bool quit = false;

SDL_Init(SDL_INIT_EVERYTHING);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_HWSURFACE |  SDL_OPENGL);

glEnable(GL_TEXTURE_2D);

const GLubyte * Vendor = glGetString(GL_VENDOR);

glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Clear the background of our window to red
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho(0, XSIZE, YSIZE, 0, 0, 1);
glMatrixMode (GL_MODELVIEW);

glDisable(GL_DEPTH_TEST);

GLuint image;

ilInit();
ilutRenderer(ILUT_OPENGL);

ILuint texid;
ILboolean success;
ilGenImages(1, &texid);
ilBindImage(texid);

success = ilLoadImage("Textures.png");

    Uint32 startclock = 0;
Uint32 deltaclock = 0;
Uint32 currentFPS = 0;
startclock = SDL_GetTicks();
deltaclock = SDL_GetTicks();

fstream Log;
Log.open("log.txt", ios::out | ios::trunc);
Log.clear();

if (success)
{
    success = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
    if (!success)
    {
        SDL_Quit();
        return -1;
    }
    glGenTextures(1, &image);
    glBindTexture(GL_TEXTURE_2D, image);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
    GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
    GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH),
      ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE,
      ilGetData());
    ilDeleteImages(1, &texid);
}
else
{
    SDL_Quit();
    return -2;
}

SDL_Event event;

float x = 0.0f;

while (!quit)
{
    while ( SDL_PollEvent(&event) )
    {
        switch (event.type)
        {
            case SDL_QUIT:
                quit = true;
                break;
        }
    }

    glClear(GL_COLOR_BUFFER_BIT);

    glLoadIdentity();
    glTranslatef(200.0f, 200.0f, 0.0f);
    glRotatef(x,0.0f,0.0f, 1.0f);
    glScalef(1.0f+x, 1.0f+x, 1.0f+x);
    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f);
    glVertex2f(-100, -100);
    glTexCoord2f(0.0f, 0.119140f);
    glVertex2f(-100, 100);
    glTexCoord2f(0.091797f, 0.119140f);
    glVertex2f(100, 100);
    glTexCoord2f(0.091797f, 0.0f);
    glVertex2f(100, -100);
    glEnd();

    x += 0.1f;

    SDL_GL_SwapBuffers();

    deltaclock = SDL_GetTicks() - startclock;
    startclock = SDL_GetTicks();
    if ( deltaclock != 0 )  currentFPS = 1000 / deltaclock;
    static char buffer[20] = {0};
    sprintf( buffer, "%d ", currentFPS );
    SDL_WM_SetCaption( buffer,0 );

    if (currentFPS < 4) { quit = true ;}

    Log << buffer;

}
Log.close();
return 0;
}

```
> 1 votes

# Answer
What do you mean by insanely slow? You have no timing in your code. How many frames per second?

Your drawing very little, it's normal for the GPU to be mostly unused. You can't determine if it's software rendering just by looking at CPU/GPU usage.
> 4 votes

# Answer
You should not need to use glFlush(). Also it's advisable to use vertex arrays or VBOs instead of immediate mode, though it probably won't make a difference in a program as small as this.
> 3 votes

# Answer
Try to disable texturing before rendering (before while loop): glDisable(GL\_TEXTURE\_2D); - if it helps, there is problem with texturing. But I don't think it should help.

You can also try to comment everything from glBegin(GL\_QUADS); to glEnd(); - but you will not see if it helps. You would need some FPS counter.

Also try to sleep while loop at the end for some time (let's say for 20 ms). But I don't think it will help anyway.

And also try to change glOrtho(0, XSIZE, YSIZE, 0, 0, 1); to glOrtho(0, XSIZE, 0, YSIZE, 0, 1); Is your code rendering something?
> 1 votes

# Answer
Are your textures a power of 2 size? (4x4, 64x64 etc.) I think that could definitely slow things way down if they are not.
> 1 votes

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


# Question
Title: Help with Collision of spawned object(postion fixed) with objects that there are translating on screen
Hey guys I am creating a game using Corona SDK and so coding it in Lua. So there are 2 separate functions,

1. To translate the hit objects and change their color when they are tapped The link below is the code I am using to for the first function http://developer.anscamobile.com/sample-code/fishies
2. Spawn objects that will hit the translating objects on collision. Alos on collision the spawned object disappears and the translating object bears a color(indicating the collision). In addition the size of this spawned object is dependent on i/p volume level. The function I have written is as follows:

```
--VOICE INPUT CODE
local r = media.newRecording()
r:startRecording()
r:startTuner()

--local function newBar()
--    local bar = display.newLine( 0, 0, 1, 0 )
--    bar:setColor( 0, 55, 100, 20 )
--    bar.width = 5
--    bar.y=400
--    bar.x=20
--    return bar
--end

local c1 = display.newImage("str-minion-small.png")
c1.isVisible=false
local c2 = display.newImage("str-minion-mid.png")
c2.isVisible=false
local c3 = display.newImage("str-minion-big.png")
c3.isVisible=false

--SPAWNING
local function spawnDisk( event )
    local phase = event.phase

    local volumeBar = display.newLine( 0, 0, 1, 0 )
    volumeBar.y =  400
    volumeBar.x = 20
    --volumeBar.isVisible=false

    local v = 20*math.log(r:getTunerVolume())
    local MINTHRESH = 30
    local LEFTMARGIN = 20
    local v2 = MINTHRESH + math.max (v, -MINTHRESH)
    v2 = (display.contentWidth - 1 * LEFTMARGIN ) * v2 / MINTHRESH
    volumeBar.xScale =  math.max ( 20, v2 )

    local l = volumeBar.xScale
    local cnt1 = 0
    local cnt2 = 0
    local cnt3 = 0
    local ONE =1
    local val = event.numTaps
    --local px=event.x
    --local py=event.y

    if "ended" == phase then
        --audio.play( popSound )
        --myLabel.isVisible = false

        if l > 50 and l <=150 then
            --c1:setFillColor(10,105,0)
            --c1.isVisible=false
            c1.x=math.random( 10, 450 )
            c1.y=math.random( 10, 300 )
            physics.addBody( c1, { density=1, radius=10.0 } )
            c1.isVisible=true
            cnt1= cnt1+ ONE
            return c1

        elseif l > 100 and l <=250 then
            --c2:setFillColor(200,10,0)
            c2.x=math.random( 10, 450 )
            c2.y=math.random( 10, 300 )
            physics.addBody( c2, { density=2, radius=9000.0 } )
            c2.isVisible=true
            cnt2= cnt2+ ONE
            return c2

        elseif l >=250 then
            c3.x=math.random( 40, 450 )
            c3.y=math.random( 40, 300 )
            physics.addBody( c3, { density=2, radius=7000.0 , bounce=0.0 } )
            c3.isVisible=true
            cnt3= cnt3+ ONE
            return c3
        end
    end
end

buzzR:addEventListener( "touch", spawnDisk ) -- touch the screen to create disks

```

Now both functions work fine independently but there is no collision happening. Its almost as if the translating object and the spawn object are on different layers. The translating object passes through the spawn object freely.

Can anyone please tell me how to resolve this problem. And how can I get them to collide.

Its my first attempt at game development, that too for a mobile platform so would appreciate all help. Also if I have not been specific do let me know. I'll try to frame the query better :).

Thanks in advance.

# Answer
> 1 votes
I think the problem is that the objects are all inserted into a group in the Fishies code. That is, your comment that they seem to be on different layers is correct. Note line 113:

```
group:insert( fishOriginal, true )

```

Physics don't work between display groups. This was done on purpose so that you can move the group around without affecting anything in the group, in order to do a moving camera like the Egg Breaker demo.

---
Tags: iphone, collision-detection, lua, mobile
---