# Question
Title: 2D collision and getting closer to objects
Just curious what to do from here. So I am done with my tile editor program and currently have it set up so that my background (which is one large image) is mapped in XML to 32x32 tiles (again, a mapping, nothing is really split into tiles).

So when I have my character (this is a platformer rpg) comes across a tile which I have labeled as obstacle or something, they stop. This is nice and all except for some ugly space in between my character and tile where the edge of my rock is. I can't do pixel detection because it will never be sound.

For example, if my character's pinky ends up in the cell marked as an obstacle and for some reason, there is some black along an edge from a castle from the previous cell, this is a hit even though the player didn't actually touch any part of the rock but rather a part of the pinky hit that black edge.

The only thing I had which makes things seem to nicely lineup is to map it to a 16x16 array.

**Edit:** I will give the example with pic in the morning since site came back up but for now I'll give a better explanation.

My tile editor exports an XML file of my tile mapping...so, if I specified 32x32 tiles over an 800x600 image, my XML file will contain mappings for each 32x32 tile spread across the region. So I could have my XML file with tile 2 having a type of "Obstacle". I then in XNA just read the XML into a list storing each tile and their characteristics.

I then in my program do a collision check for now. In doing this, I create a rectangle around my player. Each time I move, I check for collision by doing this:

1. Does my rectangle intersect any collisions with a characteristic of obstacle or wall and so on...
2. If so, return true that a collision occurred.

So let's say that my background image has a blue background, a castle and a rock in the middle. In a tile I marked as being an obstacle, it contains a piece of the black wall of the castle and to the right of this is a piece of that rock along my path. So my character is now running to the right, will have an intersection with this obstacle tile and as a result, have something like 29 pixels between the player and the start of the rock. This collision occurred as the player hit a tile marked as an obstacle.

Using pixel color collision detection won't help either as a piece of my player could be hitting that black edge of the castle I talked about and the alpha values are never going to be 0.

I'll give a picture example but I am just detailing it a bit better for now.

# Answer
As an alternative to using cells, you could map the edges of your obstables with vectors (lines), this does not have to be highly accurate, just an approximation of the obstacle shape.

When you do your collision detection you can check if you characters bounding rect intersects with one of the vectors. You can map the vectors to a cell to limit the number of vectors you check against, so when you enter a cell you check your character against the vectors in the cell.
> 1 votes

---
Tags: xna, collision-detection
---


# Question
Title: Is it possible to use the GPU on a mobile device to accelerate a particle physics engine?
I am interested in answers for any mobile device but I am mainly considering the iPhone and devices that run Java.

I am developing a game that relies heavily on a particle physics engine for core gameplay (not just animation effects) and have been developing/testing on a PC up to now with the intention of porting it to iPhone and/or Android. The problem is that the particle physics engine (which I implemented myself) is still way too slow. I can barely reach the target frame rate on a netbook and I am guessing that most phones will be worse (maybe not the iPhone but that will be expensive to port so I want to be confident that it will be worthwhile.)

I've optimized the software implementation as far as I can and now I am wondering if it is possible to accelerate it in hardware. The GPU looks like the obvious thing to try first.

Has anyone researched this or do you know of an existing library that implements this?

# Answer
It is certainly possible to run a particle simulation on the GPU using vertex shaders, but you may be very limited in the kinds of behaviors that you can simulate, depending on the capabilities of the GPU.

In order to run the entire simulation on the GPU you cannot make use of the results of previous frames. Which means that the current state for any particle must be computable from a combination of its initial state and any global variables (such as the time). The requirements of a physics engine would usually rule out this approach.

One way you can get around this is to split the computation between the CPU and GPU. You could have the CPU update the particle positions from the physics simulation and use the GPU to calculate the vertex positions (do the billboarding math), color, etc.

More advanced GPUs will allow a vertex shader to write into a vertex buffer, effectively closing the loop and allowing the results of the previous frame to become the input for the next frame. This opens up far more possibilities but is probably out of reach for most mobile GPUs (I don't remember what version of OGL you would require).

In short, yes you can run particle simulations on a GPU, but the constraints imposed by the GPU capabilities might rule it out for your purposes.
> 4 votes

# Answer
If you mean drawing, you can certainly use OpenGL ES on both Android and iPhone, and OpenGL on PC (and if you also opt for DirectX you might get a bit better performance in Windows netbooks). It is just as functional for 2D acceleration as it is for 3D.

But I presume you mean computation. While I cannot give any experience in using GPU for computation, here are a few things you might not have thought of when optimizing your application:

* I assume you used a profiler, not just optimized by hand
* Are you using fast math functions for sin/cos/tan/sqrt? For example, using 1 / fast inverse square root instead of the slow sqrt function.
* Whenever possible you should use ints/shorts in place of floats, and really avoid doubles. From what I've learned, mobile processors typically have much slower floating point engines (FPUs). I don't know if that's true so much today.

Sorry if you already did the above; just trying to think of anything that might help.
> 3 votes

# Answer
Any device supporting Open GL ES 2.0 should support programmable shaders. Iphone 3GS and above supports Open GL ES 2.0.

Android phones only have Open GL ES 1.1 support as far as I know.

With Open GL ES 1.1 you could use Vertex Buffer Objects with point sprites as a substitute to the proper vertex and fragment shaders you can make in Open GL ES 2.

The PowerVR chip has some low level shading language for Open GL ES 1.1 if I recall correctly.

Check out the examples bundled with the PowerVR SDK. The 1.1 SDK has some particle effects sample. You should also read up on the differences in the API between 1.1 and 2.0.

EDIT: Gah, I realized I didn't answer the question at all. Ok, so here are some other tips not mentioned here: * Align the data you are doing computations on in such a way that you avoid cache misses. This probably depends a bit on your target architecture, and you should read about it for each platform you're targeting. There are some general guidelines though on how to make stuff quicker.

That is all I have time to write right now...
> 2 votes

# Answer
For particle computations with OpenGL ES 2.x (iPhone 3GS, 4 or many Android Phones), you can use the vertex shader but the equation must be very simple and depend on few variables.

The main idea is to send parameters with uniform or attributes:

* time elapsed: uniform
* initial position of particle: attribute
* initial velocity of particle: attribute
* color: attribute

You can use a static VBO to send these data one times. If you need advanced physics, this is probably not the solution and you must use the CPU. With Neon instructions, you can have a great speedup. Warning the Tegra2 (available on few android tablets) doesn't support this instructions set.
> 2 votes

---
Tags: optimization, physics-engine, particles, gpu
---


title: Is there a faster sine function?

text:
# Question
Title: Is there a faster sine function?
I am working on generation 3d perlin noise. The C# Math library seems like overkill for what I need since most of its functions use double percision. I use Math.Sin() in several places to generate the noise. Does anyone know of a faster sine function?

# Answer
You can use a parabola to aproximate the value of the sine function. This has the advantage of having the roots at exactly -pi/2 and pi/2 which is usually not the case with other fast approximations based on the TaylorSeries or MaclaurinSeries.

```
public float Sin(float x)
{
    const float B = 4 / PI;
    const float C = -4 / (PI*PI);

    return -(B * x + C * x * ((x < 0) ? -x : x));
}

```

Here is a comparison to the actual sine function:
> 32 votes

# Answer
What is the range of input values to your *sin()* function? For what you're using it for, it sounds like they might be limited, which means you could **pre-compute the values**. For instance, if you're rounding up the input values to the nearest degree, then you only have 360 possible values - just pre-compute them and store in a table.

If you need slightly more values, say to one decimal place, you could interpolate from the table - I'm not familiar with *perlin noise*, but the word "noise" seems to indicate it doesn't require high accuracy. :) (You could also just make a larger table, 3600 entries isn't much space).
> 12 votes

# Answer
You might want to read this too, it's got fast sine and cosine approximations
> 4 votes

---
Tags: xna, c#, mathematics
---


# Question
Title: Where can I find code examples of different variations of Perlin noise?
I have seen the PCG wiki, and it is a great resource. But a lot of the articles are very brief and it is hard to find good links on specific things.

I have been searching for ways to transform my Perlin noise height maps to make ridges, rivers, and other terrain features. I also can't find any articles on how to divide up the map into different areas for calculating texture coordinates or other values specific to the game. I have only been able to find websites detailing their software that can generate the different things, but no code or explanations. Are there any good sources of code examples/explanations on how to do the above mentioned with Perlin noise?

PS. This should probably be a community wiki. I don't know how to make it as one though.

# Answer
World Generation Breakdown
Perlin Noise
advanced perlin noise
NVidia GPU Gems 2. Chapter 26. Implementing Improved Perlin Noise
NVidia GPU Gems 3. Chapter 1. Generating Complex Procedural Terrains Using the GPU

Also 2 articles (in Russian) with source code:

http://blog.wonderville.ru/procedural-perlin-noise/
http://blog.wonderville.ru/perlin-noise-simplex-noise/
> 5 votes

# Answer
Most pages claiming to cover perlin noise actually cover something else. If you want the real deal, read Improved Noise reference implementation by Ken Perlin himself. There you will also find a link to the SIGGRAPH 2002 paper describing the algorithm in detail.
> 4 votes

---
Tags: procedural-generation
---


title: Balance in online PvP games

text:
# Question
Title: Balance in online PvP games
I don't know if there's an accepted solution to this wicked problem. I'm thinking about the design of an online PvP game. A key aspect of the game, something that is just a given, and not my choice, is that people will join the game at very different times. New players can still show up after there are already powerful players established.

How is it possible to balance such a game so that latecomers aren't immediately crushed by the powerful players? I've played several games like this, and the only way I've seen to mitigate this is to have regular restarts, where new game worlds are released periodically to give everyone a fair start. In one of my own games, I tried a protection system, where new players were immune from attack for 25 days. This worked, until the 25 days were up, whereby the crushing commenced as normal.

This scenario causes a lot of frustration with new players, and makes many of them quit right away. Are there any genius solutions that might help? One I have in mind is keeping new players more physically distant from old ones so it takes the powerful players a while to find the newbies, giving them time to defend themselves. Thoughts?

# Answer
> 17 votes
I like RuneScape's method (at least, the old method back when the wilderness was PvP).

Most of the game world is only PvE, but up north there is a huge desolate area called the Wilderness; it's PvP. When you first cross the clearly-marked border into the wilderness, you see an icon in the corner of your screen and it reads "Level: 1". So you're in level 1 wilderness; you can attack people +/- 1 combat level from yours (combat level being your character's overall level, determined by a formula from your more specific combat-related skills).

As you keep walking further north, deeper into the wilderness, the level keeps incrementing, and at any place in the wilderness you can attack other players who are +/- the wilderness level from your combat level.

This introduces some interesting dynamics. First, a lot of wimpy people sat at the border of the wilderness, hoping to find other people that were just +/- 1 or 2 levels and then attacking and stunning them (so they can't move). Second, you have something of an incline; someone who is not so brave can stay in the lower levels of the wilderness and try to find people near their level. There were some good resources near the back of the wilderness (around level-40 wilderness); some rare mining rocks and high-level monsters for training. But of course, by going that far, you are risking that someone 40 levels higher than you can come and beat you down in a few hits. And of course, when someone does attack you, you can try to run south and retreat to a level of wilderness that is outside the "range" of your attacker's combat level.

Nowadays, they switched it so that the wilderness is also PvE, but there are dedicated PvP servers in which the entire world is PvP. The only danger in the wilderness now are ghosts which are supposed to imitate the old PKers (player killers), but most players agree that the ghosts are much more powerful and have much worse rewards than PKers, so many people were upset by the change.

I think this level system would work well in an all-PvP game, if the "wilderness level" was implemented as the distance from the nearest city's borders. So the no-man's land between cities is PvP, but cities are safe zones except for structured, agreed-upon duels in the streets. Then you can also introduce some cash sinks, by having transportation NPCs which will take you from one city to another for a price (for those players that wish to avoid PvP entirely). There should also be plenty of training zones where players can fight NPCs without the danger of PvP, again for those who don't want to participate in PvP. But really, at some point you must draw the line between players who never PvP (like myself) and players who only find fun out of PvP.

# Answer
> 8 votes
I can see a bunch of possibilities (most of them should be mentioned by now, I guess). You can use any of them, but they work best in some kind of combination:

* Make character level / age / equipment have no meaning in respect to the PvP side. This turn your game into a player skill based MMO. An example of this would be Guild Wars - or any online FPS, really. Veterans will still have an edge over total newbies, but it won't be nearly as massive as it is with the exponential power curve most DikuMUD variants (EQ and WoW included) seem to feature.
* Make characters expand horizontally (giving them more options) as they level up instead of vertically. UO did this to a certain extent, as does EVE Online. Free Realms and Final Fantasy XIV feature a similar system with the tons of "jobs" / "classes" they have which you can freely switch between and which you level separately, though of course they aren't PvP games. A newbie can specialise and reach the same power level as a veteran in short amount of time under such a system - but *only* in his specialised area, whereas the veteran will be able to change his playing style to suit his needs and fill many different roles.
* Make the "big" things to fight over (control over areas, generally) be a group activity where lower levels have good reasons to work with the highest levels. This can be done by setting everyone's level to the same number upon start of the city sieges and similar scenarios, or simply giving the lower-level characters other important things to do while the higher-levels are on the front lines - operating artillery, ships or airships might be an example.
* Have some *very* harsh negative feedback loops preventing any single group or coalition of people from dominating a significant portion of the server.
* Have a *huge* world, where going out into the wilderness, disappearing for a few months with your pals to build up a small country far away from the rest of the player base, unseen and unfindable until you are ready to strike back from your hidden power base is an actual possibility.

# Answer
> 5 votes
Server restarts are always a very bad thing, that does not really solve the problem and also makes the game a much worst game in any case. That's lazy design.

"Noob protection" and any other kind of arbitrary limitation are also a very annoying and useless thing: again that's not really solving the problem (as you have already noticed).

If your game is so unfair that you need this kind of thing, you should fix the problem at its roots: trying to fix the symptom is pointless and will never give satisfactory results.

Don't make your game unfair. Really, you have no reason to do it:

1) design your game so that progressing means "more options" but not necessarily "more power", so that the game is still interesting as you go on, but not unbalanced

2) design it so that the actual skill of the player counts more than the power of the character, like in an FPS

3) design it so that players are surrounded by players of a similar level (such as divisions in a sport game, arenas in WoW, and I guess you can figure out something for whatever-your-game-is too)

4) make it *different* to attack lower players: think about the lower player as an insect and the bigger player as a human: two insects will fight against each other on the same level, but the fight between the human and the insect will be much more different, but still possible

# Answer
> 4 votes
There are a lot of solutions to this, and it's up to you as the designer to choose one (or more) that are right for your game.

Making PvP strictly "opt-in" solves the problem directly. Giving temporary "newbie protection" is a lesser version.

You can put restrictions on who can fight in PvP -- for example, only allowing players to affect those within 2 levels. (Reducing rewards for bashing people lower than you and increasing rewards for attacking those who are more powerful can curtail "newbie-bashing" in Achiever-type players who are trying to rise through the ranks, but not so much with Killer-type players who have more fun by ruining someone else's day.)

Only activating PvP when players reach the level cap (and/or just shortening the time it takes to reach the cap) reduces the problem as well.

Some games (think CCG/TCG type games, FPSs, or really any kind of purely skill-based online game) don't even have level progression as a core mechanic, and a new player can have just as much a chance of winning as an experienced player, other things being equal. The danger here is that experienced players tend to be better at the game so they will win on skill grounds; this can be lessened through ranking/rating systems (which again segregate players by skill level, if designed well), creating several servers for different play styles (casual, pro, family/kid friendly, etc.), or community management (giving experienced players and community leaders incentive to teach new players, for example).

For games where players continue progressing indefinitely (a lot of Facebook games are like this), the solution I've seen is a reset of some kind. This can either be on an individual basis (when a player reaches the level cap, they're given the opportunity and incentive to restart with a new character) or a server-wide basis (monthly server resets, or a reset when some player or group of players manages to reach some kind of "win" condition, which gets them into a permanent "winners" list and causes a reset). This doesn't fix the problem immediately, but it does mean that anyone new to the game knows there will be a level playing field soon enough, and they are free to explore the game mechanics in the current cycle without worrying about screwing up too much.

# Answer
> 4 votes
I find the most interesting method of player vs. player protection to be one that somewhat models itself after reality.

IRL, it is the threat of inevitable and pervasive society reprisal that keeps violent elements of society calm.

In game, it's great fun to have a system where npcs around the pcs react to unsanctioned violence by attacking the aggressor. So if you provide strong npcs in the general area of safe location, e.g. town guards in a starting city, that attack people who initiate pvp. The system isn't foolproof (there are a lot of chaotic effects that can occur: players can initiate attacks with full knowledge of the backlash, bystanders can be drawn into fights, for two example) but it's much more interesting and vibrant than any kind of mathematical "you are level 5, so you cannot attack a level 1" system.

Non-cities become wild places where attacks can happen, and population centers generally become safe-zones. Pretty realistic result.

# Answer
> 2 votes
I think one way to deal with this is to make it so it does not take very long to reach a competitive level in PvP. In Ultima Online, players had a "skill cap" of 700 at the start, and a 225 stat cap (if I remember correctly). It did not take too long to reach the skill/stat cap if you were active enough.

In other games like Darkfall Online, there are no caps on how many skills you can have and the stats take over 6-12 months if you don't use scripts to train them, so the gap between new players/veterans is massive.

If your game is level based then you could separate people into different regions depending on their levels. The biggest thing is the difference between power gamers and casual gamers. You must find a way to cater to both. If you can't do that then I would think catering to casual gamers would be more important if you are trying to reach high populations.

# Answer
> 1 votes
In MUDs it was common to physically disallow PvP between characters who aren't of a similar level. +/- 5 levels was a common range (in games which normally had 50 or 60 levels).

A more subtle approach is to not block this behaviour but punish it. Your reputation could drop if you prey on weaker players, bounties could be put on your head, etc.

# Answer
> 1 votes
Eve Online actually has several different solutions, all intermixed nicely.

First off, while your character gets "more powerful", it's not really getting all *that* much more powerful over time. The first few weeks of training (which, keep in mind, happens offline) give you access to most of the basic cheap powerful ships. You can pump months into some specialty niche topics, giving you more powerful ships, but those more powerful ships are far, *far* more expensive.

Second, Eve Online supports and strongly encourages group play, and groups are vastly stronger than solo fighters. Ten players with hundred-million-isk ships ("isk" is the game currency) can easily take down someone in a billion-isk ship. In fact, ten players in ten-million-isk ships can probably take down a billion-isk ship. Goonswarm, one of the most powerful alliances in-game for some time, got its start and its military backbone with sheer untrained numbers.

Third, you don't have to gamble a lot on PvP if you don't want to. Those low-tech easily-trained ships won't cause you to lose much if you get blown up. The later high-tech ships will cause you to lose huge amounts, but nobody's forcing you to use them, you can keep on using the cheap less-powerful ships. While your skills definitely give you significant edges in combat, with a lot of 10-20%'s here and there that add up quickly, the second biggest determiner of your combat abilities is the hull and gear you're using, so a six-year-trained pilot in a cheap ship will still rapidly lose to a six-month-trained pilot in a pricey ship.

(The biggest determiner is the player skill, of course - sheer character skill points comes as a rather distant third.)

I haven't seen any attempt to import these mechanics into a conventional fantasy MMORPG, but I think doing so could be extremely fun and interesting.

# Answer
> 1 votes
Regular Restarts is absolutely not the answer. If you have regular restarts, everybody is going to quit. Thats the exact OPPOSITE of the point of an MMORPG, which is all about character development and time investment. And if you're talking about a more traditional competative online PvP system, then what do you mean restarts? Are you talking about an RPG with character development? Then again, you don't want to undo people's advancement. Are you talking about a skill based game? Then you CANT erase people's skill. So what?

If you're talking about games like WoW, which regularly releases expansion packs to keep the game interesting, you are misunderstanding the game design involved. Thats not a restart.

The way they balance the game is not with character restarts, but with a "levels" system. Players who have played longer are more powerful, but they are higher level. Higher level players move on to higher level areas, and as such are not near the low level players.

To keep someone who has been playing the game since it came out non-stop from being unstoppable, nearly every successful MMORPG has implemented level caps. So once you hit the highest level, your character cannot gain stats any further. Furthermore characters cannot usually challenge characters who are X levels lower than them, or at least receive a penalty for doing so.

You can't force high level characters to be far away from low level characters, thats just not fair. Players need to have control. However, like I said, if you have proper level design that takes into account character progression, then high level players will have moved on to higher level content, and will naturally be farther away. But this does not prevent them from running back to the low level areas, and gank low level players. And this definitely happens all the time.

If, however, you're not talking about an open-world persistant MMO, then I don't see what your problem is. If you're just talking about a traditional online pvp game, then you're just talking about a matchmaking system.

Record a skill level for each player, and then increase or decrease that skill level after each "game" they play pvp, with increase for a win and decrease for a loss, and the amount being based upon the difference between the players' skill levels. See ELHO.

So you just match up the high level players to fight each other, and the low level players to fight each other. See: Halo, Warcraft3, League of Legends, etc. etc. etc.

# Answer
> 0 votes
It seems like the only real "solution" to this is to make PvP an opt-in experience only. Something similar to PvE servers in WoW combined with level-capped Arenas.

# Answer
> 0 votes
The example I refer to, OGame, is a real time building type game, but I'm pretty sure you could adapt it to PvP in MMOs or similar.

All the time, PvP went on; you couldn't 'opt-out' of the chance of someone raiding your planet. However, the way it worked I found was very nice: (You gained points for having resources, building structures, building ships, etc)

* If you had less than 5,000 points - which is about a month or so of being fairly active - you could only attack or get attacked by people with under 5,000 points and who had +/- 25% of your score. So your little 250 point planet couldn't be attacked by veterans or even 4,900 point planets which would easily overwhelm you.
* If you had between 5,000 and 25,000 points - this is a good few months of solid playing - again you could only be attacked by people in that boundary, but (IIRC) the boundary went up to +/- 50%.
* Over 25,000 points - you could be attacked by anyone over 25,000 points.

Obviously you wouldn't have points, but some skill calculations maybe?

# Answer
> 0 votes
You could always have a flag that allows the player to be involved in PVP. This can't be set or turned off only during timed intervals of logged time. By default it should be off. This makes it the players choice.

You can also set it up so that anybody who actually PK's will not be to set it off so easily (extra penalty on ability to set the flag)

---
Tags: game-design, multiplayer, balance, pvp
---


# Question
Title: AS3/Flash Game Dev: Looking for good & current step by step
Flash tutorials and examples have been around so long it is hard to know what sites to actually read for good, current AS3 game dev.

I'm looking for a good start to finish for flash game development, covering things such as:

Preloader (when to use, how to implement) UI (AS3 only, no FLEX) OOP architecture. (I come from C++/C# world)

I'm just trying to create a simple game, sort of an "escape the room" style.

# Answer
> 3 votes
I think you can use Kirupa and also the Actionscript forum. They helped me a lot when I was a beginner. Also you might find useful the numerous tutorials and source code provided from GotoAndPlay. This is one site which made me interested into the gaming side of flash programming.

# Answer
> 1 votes
Try this site: http://flashgameu.com/

I found those tutorials quite useful.

# Answer
> 1 votes
I will recommend the book "ActionScript 3.0 Game University" which has many step by step tutorials for all genre of games (puzzle, match-3, platform, maze, shooter). His site is also full of examples not in the book. One of the better books out there (though there aren't really many game development books for AS3).

A new edition of the book seems to be on the way.

# Answer
> 0 votes
If you don't mind using a Flash-Game-Framework such as FlashPunk or Flixel, I suggest you have a look at the Flash Game Dojo. It's not a very extensive site, but a good place to start.

# Answer
> 0 votes
Kongregate's "Shootorials" (shooting tutorials) are second to none! They walk you through the process of creating a side-scrolling space shooter from start to finish (they even provide all the assets!). The tutorials were originally written for AS2, but they do provide a link to the AS3 source code here, and a mobile version written in AS3 here. I found that going through the tutorials and looking at the AS3 source code was enough for me to understand what was going on, so I'm sure you'll be able to pick it up in no time. :)

# Answer
> 0 votes
Well you need 2 things: the first one is this book: http://oreilly.com/catalog/9780596526948 and the second one is - lot of beer. Furthermore you want to learn about flash events and events handling, display list model and drawing api. When you re done with that you can take a tour in collision detection principles, sprites animation, orthogonal and isometric projection methods unless you want to go 3D. After all that learned you are fine to go, not meaning you can't learn in progressing thriugh your project. Good luck!

# Answer
> 0 votes
While this question is a little old now http://gamedev.michaeljameswilliams.com/2008/09/17/avoider-game-tutorial-1/ seems to be exactly what you are after.

---
Tags: flash, actionscript-3
---


title: Tools for developing C64 Games

text:
# Question
Title: Tools for developing C64 Games
Just wondering what people nowadays use for developing Commodore 64 Games?

I've got the Programmer's Reference Guide which goes into all the details, but in the modern Age I assume I won't have to do development on an actual C64 itself?

Are there tools that run on Windows or Mac OS X that are a bit like an IDE that offers some help and some debugging facilities (e.g., by hooking into an Emulator) or easy packaging into .d64 disk images?

Is 6502 Assembler the one chosen language, or is C development feasible? (Ignoring BASIC here)

# Answer
I'm far from being an expert on this, since I'm just picking c64 stuff up again as well, but I'm really liking Kick Assembler.

It has a nice macro syntax, which makes things feel a bit higher-level. eg. 6510 assembler with lists, loops, hash tables, easy import of image/sound data...

Written in java, so it should run fairly painlessly on windows & OS X ("works for me" on windows & linux).

There are a bunch of other tools listed over at the C64 Codebase site, including a c compiler, and some other useful cross-platform dev info (debugging via emulator, putting your PRG's into a D64 file, etc).

The c compiler looks really cool, but I haven't tried it yet. Just about all the sample code "out there" tends to be in one of the assembly flavours, so for me it's easier to go with the flow for now. If you're already well versed, it might be an easy switch for you.
> 5 votes

---
Tags: tools
---


# Question
Title: Is it possible to skin Qt 4.5 such that it has a 'game-like' interface?
Is it possible to skin Qt 4.5 such that it looks less like an application framework but more of a game? I guess this probably means replacing the canvas, the title-bar and the artwork of the various widgets. Will such an approach be platform independent too?

# Answer
> 4 votes
Yes you can, and such an approach will be platform independent.

See Qt reference and this tutorial for a quick run-down on how to do it.

---
Tags: gui
---


# Question
Title: Discussion about Serious Games : Their lacks and forces
I would like to start a little discussion about serious video games. Do you think serious games DO have their place in today's world ? What kind of serious games do you think the most interesting in term of education / work tools ?

I've recently read an article about the educational power of such games in early ages. Do you think serious video games could become a ubiquitous learning tool in primary school ?

Any experience, title share or ideas are heightly appreciated, I want to get a feel of this question from experienced game developper that are interested of writing an answer !

# Answer
I know serious games have gained a lot of momentum over the past few years, with the growth of the simulation industry, and are beginning to gain more and more attention in the game industry, as serious game developers have started utilizing commercial game technologies.

Do I think serious games have a place in today's world? Absolutely! Video games are an incredibly powerful medium, and I think that leveraging the medium to educate, train, and raise awareness of important topics is something we as a community should wholeheartedly embrace. That being said, I do believe there is still a lot of value to traditional education and learning, and that the best use of serious games is as a supplement to traditional education, not as a replacement.

Are serious games new? Absolutely not! Although it wasn't too long ago, I remember playing a number of educational video games in my youth - and between you and me, I remember a couple of them being a lot more fun than some of today's supposed AAA games. :P

## Resources

Here are some resources I think you may find useful in your quest for information on serious games:

This list is by no means definitive, but my hope is that these resources will give you a good starting point for your research. :)
> 5 votes

# Answer
I'm not sure why this is "today's world": growing up in the 80s, I have fond memories of Where in the World is Carmen Sandiego, Reader Rabbit and Math Rabbit, Number Munchers, and the various standalone Speak and Spell devices.

I work in a game company now. We do maybe 70% commercial titles to keep the company busy, but the remaining 30% are educational, philanthropic, or otherwise socially responsible. We've done or prototyped (often for academia or government or both) games targeted at teaching science to young kids, games to teach better practices to third world denizens, and even games to help people with specific health issues.

We also regularly aim our commercial games slightly high for the intended audience, at least in terms of dialogue and story. I like to think of this as the "Rocky and Bullwinkle" phenomenon: you can teach kids very well by having something that is basically fun, zany, and engaging, and throw in more "adult" themes. Almost all of Jim Henson's work falls in this category too.

The lines blur a bit. I'm not sure I like the term "serious games" due to the connotations of "serious"; people play complicated flight or submarine simulators for fun, health-related games are often more effective with fun and/or addictive content, and on the opposite end of the spectrum, children learn more when their zany entertainment has a literate, political, social, or scientific underpinning.

The goal is to prey upon our nature: find something that sparks the desire to explore, to create, to solve problems, or even to compete. Get to a place we'll naturally be intrigued or enjoying ourselves, where we'll naturally want to do more (play more of the game, do more related activities or exploration) and the learning follows.

I don't ever see games taking over entire cirricula. I think you need balance between forms of learning, otherwise you wear things out and you don't form as many associations to strengthen knowledge.

But I *do* strongly believe that games will make a great part of that particular balanced breakfast. Even for adults concerned with ongoing education and expansion of their abilities; even for reflex training, exercise, or the like.

As an aside, you may be interested in Games in Education; it's a conference held in the northeast each year, which is fairly teacher-centric. Many educators come to speak about their experiences using games to teach -- what has worked, what hasn't, etc. There should be video on the site, somewhere.
> 3 votes

# Answer
Great question. I am currently working in the education department as a developer in Australia. My role, and the people I work with, is to create resources to be used by teachers and students.

In the past year or so we have been pushing hard to try and develop more game orientated solutions. The great thing about using games as a teaching tool is that kids don't realise that they are learning, to them it is a fun game, but in the process they are learning and thinking.

Traditionally we have developed fairly boring multiple choice forms, drag and drop activities, etc. The problem with these activities is that it does not really engage students to think (who can blame them). If they want, they can just randomly click until they get something right. This passive learning has limited value. Games on the other hand force a child to actively think, I mean how many times have we subconsciously learnt things when playing AAA "non educational" games?

So if a game has educational value, then it's a win/win scenario - they get to have fun while they learn. Also, this will help foster an environment where they enjoy and look forward to "learning", which is one of the hardest things to achieve.

Unfortunately, being a lowly developer means that our vision and ideas are often overlooked. It certainly has been a struggle to create the few games that we have done. Managers tend to be much older and perhaps have not been exposed to games in the same way that Gen Y has. Perhaps there is also the association that games mean fun only and school shouldn't be fun :S
> 2 votes

---
Tags: game-design, education, serious-games
---


title: Game timings and formats

text:
# Question
Title: Game timings and formats
There are more or less standardized TV-show/movie formats and recommended timings:

1.

> By the early 1960s, television companies commonly presented half-hour long "comedy" series, or one hour long "dramas." Half-hour series were mostly restricted to situation comedy or family comedy, and were usually aired with either a live or artificial laugh track. One hour dramas included genre series such as police and detective series, westerns, science fiction, and, later, serialized prime time soap operas. Programs today still overwhelmingly conform to these half-hour and one hour guidelines. Source

2.

> In the United States, most medical dramas are one hour long. Source

3.

> Traditionally serials were broadcast as fifteen minute installments each weekday in daytime slots. In 1956 As the World Turns debuted as the first half-hour soap opera. All soap operas broadcast half-hour episodes by the end of the 1960s. With increased popularity in the 1970s most soap operas expanded to an hour (Another World even expanded to ninety minutes for a short time). More than half of the serials had expanded to one hour episodes by 1980. As of 2010, six of the seven US serials air one hour episodes each weekday. Source

Interesting. **Are there any standards of timing in game development?**

Well, 5-20 minutes casual games, of course. There is even a "5-minutes-game" site. And 1-hour-gamer site. **Are there 1-week, 1-year, 1-eternity game formats?** Chess and Go - deep games that you can study all your life; but they are played in hour or several days (pro games). Addictive long-term online role-playing games (without win-condition) are played in monthes and, possibly, years. Replayability is an important factor to consider.

It's good when game design document contains a line: "A game is designed for solving in X hours". **How can it be measured before there is any prototype or demo?** When you know your game format, you know your audience (and vice versa). It is practical question.

**Are there psychological researches about dynamic of gaming interest and involvement?**

And **is there a correlation between game format and game genre?**

# Answer
The thing to take note of is that standard episode times exist to make TV channel scheduling simpler. There's no equivalent of that in games, so why should designers worry about standard times?

We know gamers will only play a given game for so many total hours. We *are* those gamers. However that's not a function of the time we spent, we didn't look at our watch, notice we'd chalked up ten hours total on Mario and suddenly ceased to enjoy it. We stopped enjoying a game because our relationship to the experience changed over time: it no longer had anything we enjoyed. It became too easy or predictable, for instance. Difficulty is a large contributor to how long a player will stick around.
> 5 votes

# Answer
Good question. But I don't think it can be done effectively. TV shows have fixed durations and nothing the viewer can do will extend that. However most games progress at the speed of the player. Even the best estimate is not going to apply in some cases.

> When you know your game format, you know your audience (and vice versa). It is practical question.

Even knowing your audience isn't enough. I play FPS games but I play them quite stealthily. I found I was taking 4x longer on certain Doom levels than other people I know because instead of running around shooting wildly I was creeping around every corner, picking off the demons, then retreating.

Obviously it's possible to measure how long it takes a tester to complete the game, but they aren't necessarily representative of a typical player.

Also, another danger of using such figures is that they don't translate well to different types of game. MMOs might provide virtually infinite continual content, whereas other games might only provide a handful of hours - but do the latter games have replayability? How do you meaningfully compare an RTS (many short sessions) against an RPG (one long session)?
> 2 votes

---
Tags: game-design
---


title: Advice for a first year CS major

text:
# Question
Title: Advice for a first year CS major
I'm coming to the end of my first year of CS which has been primarily a Java based course. I'd like to get my feet wet with some game development but I'm not sure where to start.

Some people have suggested I start with game maker which has a C-styled scripting language(which should be easy to pick up) as it is probably the simplest and allows me to focus mainly on the game design and how the whole game fits together.

I see a lot people recommended XNA, as it has good abstraction of opengl and directX through its APIs. I also hear C# is very similar to Java.

I have also considered game programming in Java since I am quite comfortable with it and have been doing extra reading on multi-threading and the 2d graphics APIs.

Finally, a friend has recently shown me pygame which also sounds very good although I don't know all that much about it.

I don't know if C++ is a good starting point, a lot of the posts I've seen for beginner game devs don't recommend it for a first game project.

I'd appreciate any input, especially from those who got into game dev from a Java background

# Answer
There are lots of good choices. (I teach CS1 and CS2, as well as game programming.) First, of course, learn to think like a computer scientist. Don't get too tied up in the language, because the concepts truly are universal.

Java is a pretty good language, but building a game in Java is a bit tedious. There are some interesting engines out there that make the process a bit easier. Unfortunately, it can be kind of painful to attach a game engine to your editing tool.

I like the FANG engine (sadly I can't post hyperlinks yet, so look it up on Google.) One interesting part of this project is the online editor. This means you can start right away without having to mess with eclipse settings.

I'm really not a fan of Game Maker. The GUI is fine for people who don't want to learn how to program, and it's a decent (but not great) prototyping tool. However, there are two things about it I don't like. First, it's commercial. That isn't a bad thing, but if there are free open-source alternatives that are just as good (and there are) maybe you should look into them first. The bigger problem with Game Maker is the scripting language. Eventually you're going to outgrow the GUI, and you'll want to actually start writing code. The Scripting language in GM is pretty backwards-thinking. Since you're a CS major, you are (I hope) interested in code re-use, elegance, clarity, efficiency, and modularity. The GM language will disappoint you.

I love Python and Pygame. (In fact, I wrote a book about them. See all my notes and online videos on my site if you want. You're welcome to those resources whether you have the book or not.) Python is a nice elegant language that isn't too difficult to learn (especially if you already know how to program.) Pygame is a wrapper on the popular SDL 2D engine. In fact, I've added a second wrapper to pygame to make it about as easy to work with as Flash.

Speaking of Flash, I don't think that's worth it. (I know you didn't ask) It's a good platform, but the cost and uncertainty about how it will fare on mobile devices means it may not be that great a learning tool. (I wrote a book about game dev in Flash, too, but I don't teach Flash any more.)

Here's some other great things to try. Get a copy of scratch from MIT: scratch.mit.edu It's made for kids, but don't let that put you off. It is an absolutely incredible game and animation tool. The programming uses tiles, so it's easy to get started with. You'll be utterly amazed at what you can do with it.

You might also try Alice from Carnegie Melon www.alice.org The latest (3rd) edition is actually an extension to Java, which uses Sims2 Models.

Both Scratch and Alice are free.

One more great tool to look into is Blender www.blender.org

It's a 3D modeling tool, but many people don't know it's also a complete game engine with a drag-and-drop programming interface. Once you've outgrown the tiles, it has Python support built in.

Now I'm quite interested in HTML5 (Which is barely HTML - It's really HTML, CSS, and JavaScript.) It isn't quite there as a game development environment, but I believe it will be a big player. My next book will be on game development in HTML5.

Best of luck to you, and let me know if you have more questions.
> 14 votes

# Answer
It depends on what your goal is, and what part of game development you want to get into.

Are you more interested in the actual nuts and bolts of how game engines work and building something from the ground up or do you want to get into the game parts of development as quickly as possible.

**Nuts and bolts:** XNA is a nice way to dip your toes into that arena. The framework does a lot for you, but you can slowly replace each piece with your own code as you become more comfortable with C#. Learning C# is good for the future game development positions as tools are often built with C#.

**Gameplay programing:** Unity is a good option here. Free, and lets you code in multiple languages including JavaScript and C#. You'll be able to get things up and running quickly which is a nice motivation boost. Plus you can transition to another language and even mix languages to help you practice broadening your understanding.

The nice bit is that they are both free to play around with and can be connected to a variety of hardware for at pretty minimal cost.
> 5 votes

# Answer
Could always do some java based games, nothing wrong with those (http://zetcode.com/tutorials/javagamestutorial/)

XNA and AS3 are very close, and can create games as complicated or as simple as desired. (though same holds true with java)

One thing to remember is always practice, and just play around with the code.
> 4 votes

# Answer
## **Java Monkey Engine**

If you are most comfortable with Java, you could use Java Monkey Engine for a framework to use while making games. It also has a decent amount of documentation/tutorials including instructions for integrating with Netbeans and Eclipse.
> 3 votes

# Answer
# Unity

I would say try **Unity**. They have a free version and you can get your feet wet in few hours to get the basic idea by following two tutorials provided by Unity:

The other cool thing about unity is that you can use JavaScript as a scripting language and you can publish your game on Windows, MacOS, Web, iPhone and now with the version 3 on Android devices as well.

Also they are using StackExchange engine for the Unity Answers and they have wonderful community for all your Unity related questions.
> 2 votes

# Answer
Any of those would be a good start, speaking as a dev whose initial CS education was in Java.

C# is very close to Java (I sometimes joke that it's limited-platform Java with better libraries), so XNA might be a good choice. Minecraft is developed in Java with the lwjgl game library, so if you want to stick with Java, that's a good method. Of course, 3D development is kind of complicated; depending on your knowledge, experience, and perseverance, you might want to wait on 3D (or even 2D in a 3D-based system) until you get more education under your belt.

For 2D solutions: Game Maker is very simple, and has been used to make some great games. You should be able to pick up its scripting language quite easily, but it might be *too* simple for someone with a year of Java experience. I develop in Flash using pure AS3 (tutorial), which is close enough to Java for your skills to easily translate.
> 1 votes

# Answer
I would strongly recommend going with XNA. It's a pretty capable and well-supported platform with a growing community. XNA is really starting to find its "place" in the ecosystem now that the framework is shipping on more platforms than ever (including Windows Phone 7). More importantly, however, using XNA will force you to learn C# and general .NET development. It would behoove you to gain experience with this platform regardless of whether you decide to go into game development, as .NET development is growing and has a very healthy job market. Java, on the other hand, has been slowly dying for some time now, and recent events have only served to hasten its demise. If your CS program, like the one I completed, is heavily Java-centric, then it would serve you well to learn C#/.NET on your own time.

Even if Java does live on, and you decide to pursue a career in Java development, you will likely end up having to integrate with .NET systems anyway. So, however things turn out, the experience would only help you in the long run.
> 1 votes

# Answer
If you're interested in game *design*, why not start with making a card game, or something that requires no programming at all? That will allow you to focus on the design and mechanics of the game rather than fighting your way through APIs, languages and frameworks you're not familiar with.
> 1 votes

# Answer
A non programming related advice from me:

Create a neat project and show it off to your professors.

That's how I got summer-jobs as a programmer after the first and second year at school.
> 0 votes

# Answer
If you're just looking for game development, why learn another language at the same time? I would stick with Java, unless you want to learn a new language.

Main options for Java I know about are jMonkeyEngine, which is a 3D graphics engine and generally considered pretty good.

And there's jOGL, which is a Java wrapper over OpenGL. This is naturally a lot lower level.

If you're just starting out and want to work with the logic more than dealing with buffers and shader binding and the like, go with jMonkeyEngine. If you want to get deep in to start, go with jOGL.

If you want to learn a new language, out of C# and Python I would probably say C#. The syntax is very similar to Java, and XNA and SlimDX are very good for graphics. XNA being higher level, and having done some things for you. However, this does come with a Windows-only restriction, without Mono.

Python is a very easy language to get (took me about a week at max with little attention from a book, coming from a year of C++). Pygame is a wrapper around the SDL libraries from C, so probably doesn't have the same amount of functionality as XNA.
> 0 votes

# Answer
You might also enjoy using http://Processing.org. It is a great environment for learning graphics programming. While not strictly a game-dev tool it has a lot to offer. It's language is an extension/simplification of java and it will be quick to learn.
> 0 votes

# Answer
Another vote for Unity. You will have plenty of time in your next few years of CS study to engage C++ and other languages. If your goal is to develop a game, getting tied up in what is essentially the work of developing an engine is going to take too much time. If you want to be an engine designer, definitely come back and try lower level implementation.

The Unity engine will allow you to abstract away most of the details so you can focus on gameplay programming. The community on the forums and the Stack Exchange based Unity Answers are incredibly helpful. You can program in either Javascript or C#. Coming from Java, I started with Javascript because a lot of the tutorials were written for it, but switched to C# (which was quite an easy switch).

I think XNA and Pygame could also be good (since they abstract some of the more tedious stuff away), but I don't have experience with them.

Finally, don't aim too big with your first game. It can be very easy to underestimate how time consuming it is to implement features into a game. Start with a core game mechanic that allows you to get the game in a playable state quickly. Then you can start adding other elements.

Have fun!
> 0 votes

# Answer
XNA is a great solution if you're coming off Java. C# will look and read almost IDENTICALLY to java for you, so you'll be able to jump in really fast without learning new syntax. The XNA framework provides tons of good APIs to work with, and there are lots of free "microsoft permissive licence" open code to get you started on some projects.

I wouldn't recommend you use Java, most of the graphics APIs are terrible, there's not a ton of 3d support, and generally Java just runs slow; not a big deal for most java apps, but videogames need LOTS of performance.

C++ is the way to make videogames, pretty much period. However, going from java -\> C++ is going to be pretty jarring. Not to mention that most low-level hardcore graphics programming is really C style, not C++, so you're going to do a bunch of pointer arithmetic to try to squeeze out more performance. It can be interesting, but time consuming. It can also take alot to get you started.

There are lots of good game engines out there like Ogre, but then you have to spend tons of time learning how to do things with it first, it can feel overly complicated.

Be careful, as awesome as many of your gaming ideas may be, remember that video games are expensive, take a long development time, and have large development teams.

If you want to make a game and be the only person who works on it, you're almost going to HAVE to make it a 2D game (though you should start with 2D anyways) and you're going to have to start REALLY, REALLY simple.

Almost anything you can imagine that would be fun is likely too ambitious for right now.

My advice: Get the free visual studio 2010 express if you don't have it. Download the XNA game studio, and the .net framework 4. Download an XNA demo. Run the demo, then look through the code and see what does what. Try reading some documentation on how XNA does 2D games.

THEN, Pick your favorite, old school, super easy game. Pac-man? Pong? Asteroids? Space Invaders? Mario? Pick something STUPID, STUPID easy. Then just remake the game exactly as it was. You've got enough to worry about with programming and learning a new API that you DO NOT need to bother with game design; it will just distract you.

Then, once you've got your mario clone going or whatever you made, you can start to experiment with gameplay and try adding new things.

Start small, baby steps, and it'll be much more fun and you'll learn alot more.

Try to jump into modifying the Quake3 source code in C++ to make a game and you're going to get really frustrated, and even if you make it work, you're not going to learn alot from doing it.

JUST HAVE FUN :D
> 0 votes

# Answer
**Flash**

Flash's AS3 is a fantastic language for wrapping your head around important OOP concepts without having to worry about memory management and writing header files. It's also pretty much a complete 2D game engine, with a display tree, event system, and all kinds of other handy features.

There is a HUGE community of Flash game developers out there, and contrary to popular belief, you can develop Flash games using open source tools. If you're on Windows, I'd recommend FlashDevelop.

I would argue that Flash is even more cross platform friendly than Java or really any other technology except maybe Unity. 99% of people can view Flash stuff in their desktop browser, so it's easy to share your creations with the world. Most smartphones are slowly getting Flash support, and for iOS, the one platform that won't support Flash in-browser, you can create apps with Flash CS5 (although that does have a cost).

I think it'd be a shame for you to have to struggle with something more complex like C++ or even C# when you could start learning the basics of game creation right now with AS3. Once you understand AS3, it'll be easy to switch to other languages later. In my own case, I was a Flash developer, but I learned how to program with Objective-C and managed to make a hit iPhone game. Do yourself a favor and visit http://www.flashgamedojo.com/ \- I don't think you'll be disappointed!

**Unity**

Unity has a lot of the same benefits of Flash, but in 3D.

With Unity, you can program in C# or in UnityScript (which is javascript-y). It's not open source, but it is free. It's very well supported and there's a great community. The problem with developing 3D games is that for most games you'll need lots of art and assets. This can also be an issue with 2D games, but generally, 3D art takes a lot longer and it's a lot harder to make "programmer art".

**A note on open source**

There is nothing wrong with using open source software, but you're shortchanging yourself if you're only using it **because** it's open source. Choose the best language and tools that'll help you learn the fastest with the least friction. Along the same lines, the mentality of "learn the hardest thing first" (ie. C++) is crazy. What you really should be learning is logic, not syntax, so learn whichever language has the least baggage and barriers to entry. In my opinion, that's AS3.
> 0 votes

---
Tags: game-design, java
---


# Question
Title: How should I isolate game entities with their concrete Drawable components (in C#)?
I've designed my game entities using a common pattern of separating the entity from its components. In my case, I've used the Strategy pattern to give each of my entities an IDrawable component.

I construct my entities using a factory, which constructs the entity and adds an appropriate drawable, e.g.:

```
public static PlayerEntity CreatePlayerEntity(...)
{
   PlayerEntity playerEntity = new PlayerEntity(...);
   SpriteDrawable spriteDrawable = new SpriteDrawable(...);
   playerEntity.Drawable = spriteDrawable;

   ...

   return playerEntity;
}

```

Now here's the question: If I later want to update the player drawable in some way (e.g. modify the sprite, change the animation, etc.), how and where should I do this?

My first thought is to have C# events that the PlayerEntity publishes and the Drawable subscribes to, but this gets tricky from a purist standpoint, because it's hard to do this without the Drawable requiring a reference to a PlayerEntity. My current hacky solution is to subscribe to these events from within the CreatePlayerEntity() method itself, using anonymous delegates, which can take advantage of the fact that you've still got a reference to the concrete IDrawable implementation. It just doesn't seem right for the factory to have this responsibility, though:

```
public static PlayerEntity CreatePlayerEntity(...)
{
   PlayerEntity playerEntity = new PlayerEntity(...);
   SpriteDrawable spriteDrawable = new SpriteDrawable(...);
   playerEntity.Drawable = spriteDrawable;

  playerEntity.SomeEvent += new EventHandler((sender, e) => { spriteDrawable.Texture = blah; });

   ...

   return playerEntity;
}

```

What is a better, approved way to accomplish this communication between concrete implementations?

# Answer
> 2 votes
Instead of having a reference to the Drawable in the Entity, I'd have a reference to the Entity in the Drawable. I'd also make the Drawables observe the Entity so that when the Entity changes, the Drawable is notified and can pull any relevant changes.

eg. Your entity changes action, so it notifies all observers that something has changed. The Drawable calls entity.getAction() to find out what action is underway, and sets its own animation accordingly.

# Answer
> 1 votes
> Now here's the question: If I later want to update the player drawable in some way (e.g. modify the sprite, change the animation, etc.), how and where should I do this?

Well, what should be responsible for making those changes? One thing is for sure: whatever is responsible it must know about the specific type of Drawable it is operating on, you can't change the texture without knowing it has a texture. You did this in CreatePlayerEntity, because at that point the type of drawable is known. If you want to do it elsewhere then you may need to rethink your design.

If the PlayerEntity has state that controls entirely how it is drawn, pass the PlayerEntity state into the SpriteDrawables draw function. That does mean that there's a coupling between PlayerEntity state and SpriteDrawable. Note that the PlayerEntity state could be a separate class (e.g. PlayerEntityState). If don't want this coupling, or you want to control arbitrarily how it is drawn depending on other state in your game then have the object that aggregates PlayerEntity directly aggregate the Drawable so you can control it there.

# Answer
> 0 votes
A lot of people are still getting used to component systems, and there can be debate on the good or bad ways of doing this. But why not use a reference to PlayerEntity?

I would suggest giving all components a reference to their parent Entity. Your player entity does have a base class, right? And that class should also have a method for adding components, where it sets the `component.Parent = this`. The property setter for the component can handle all the subscriptions. If you need, you can have a method on the entity that fetches any desired component. Myself, I used a generic method and stored a dictionary from types to components:

```
public Component GetComponent<T>()
{
    if (components.ContainsKey(T)) return components[T];
    return null;
}

```

That exact code may have syntax / semantic errors, it's off the top of my head.

# Answer
> 0 votes
Some of the approaches are described here:

http://gameprogrammingpatterns.com/component.html

I suggest you have a look at the Mediator pattern and messaging. This is a nice way to avoid coupling.

Why do you need to change Drawable from the outside? Maybe you need another type of component(s)?

I would do something like:

DyingComponent -\> {send message via Entity/Mediator} -\> DrawableComponent {receive message and switch to death animation}.

# Answer
> 0 votes
I've been researching component-based designs pretty heavily myself, and while I'm still in some pretty heavy confusion, I think I can offer some thoughts on this.

According to Gerold Meisinger in a blog post, there are basically two ways to address the problem of inter-component communication: looking it up on the parent, and message/event passing. A third would be reference holding, which is what you were debating. My own attempts to implement such a system basically showed the same thing.

The basic foundation is that you have an Entity class whose only job is to hold parts and manage them. If you wanted to change the animation (say the player's state changed) then you'd have a StateComponent or maybe a PlayerState component, and it would need to communicate "My state has changed" to any other parts that need to know that.

Method 1 (Look-ups) would be that the DrawComponent knows it needs to check state before drawing. It calls "GetComponentWithType(Type t)" to get the StateComponent (or more likely an IState interface), checks the state, then draws. Ditto position, rotation, etc.

Method 2 (Events) would be that the StateComponent emits a message when it changes, and any subscribers to that event get alerted. Typically the factory would wire that up, adding a DrawComponent, then setting it to have message handlers to watch StateComponent for changes.

You could also use the parent Entity as a kind of message board, holding a log of posted messages that each component checks for interesting messages. This is a slight optimization since it makes both the sender and the receiver "lazy." Each sender only posts one message (to the host) and each receiver only asks for messages when it needs them to update, and then only gets the latest message, ignoring any irrelevant in-between states.

Method 3 (Reference) is an optimization of method 1. Instead of asking for a reference to the component, it just has one already. Either the factory gave it one, or it stored the reference after it asked for it the first time.

You'll note that each method has complexities and problems that would have to be worked around. If you stick with OOP though, I would say that's just part of what you have to pay for flexibility though. I was very confused about the whole thing until I realized that the Factory pattern is essential because the factory is the only thing that actually knows how to hook it all up in the first place.

I think I've mostly come into agreement with Gerold Meisinger though, and have been looking into F# as an alternative. Because I think a post he made on StackOverflow is very accurate: the more componentized I've tried to make the design, the smaller and more function-like each component becomes until I've just got a messy bag of states and chained functions trying to pass the states around.

But that is to say that there's a spectrum: at present you've only got 1 entity containing some state and one component. I'd probably opt to have the drawable component receive packets of "DrawableInfo" through events. But just keep an eye on the complexity or pretty soon you too will be wondering if switching to a functional language might not be better.

---
Tags: architecture
---


title: Approach to implement space junk

text:
# Question
Title: Approach to implement space junk
Ogre3D

I would like to put some space junk in my game environment. Make it look like the first 2 search results. Those junks don't need to be interactive. Just need to have a 3D junk circling around the earth.

Can the community give some suggestion on how to implement this? Should I use particle in Ogre3D or create entities for those junks, or any other approach? If using particle, how should I make the object still and spread out around the earth? Thanks.

# Answer
Particles would be a decent solution. It really depends on how close the player will get to the junk.

For positioning each piece of junk you can generate a random direction vector, and a random float called distance. You would then position that piece of junk at direction * (minimumJunkDistance+distance).

To have it circle the earth I would simple apply trigonometry to have it move on a fixed orbit at a fixed velocity.

I'm not sure if Ogre automatically does this, but it would be nice if the junk fades out before it hits the camera's near plane to stop it from dissapearing suddenly.
> 2 votes

# Answer
Use an Ellipsoid emitter for your particles.

There is an example of the Ellipsoid here: http://www.ogre3d.org/tikiwiki/ParticleExampleSun&structure=Cookbook

Since you want the particles fixed in space, you will need to experiment with the time\_to\_live, duration, etc.
> 1 votes

---
Tags: ogre
---


# Question
Title: What can cause ALT-TAB to be 'annoying'/slow/glitchy?
This is more of an open ended question, but I hope to get some good insight on how to avoid the issue.

When playing Games on Windows, I might want to ALT-TAB out of it. Some games have no problems, others are not so easy: They may take AGES to switch out and back in. Some are even prone to crashing or to weird behaviour like graphic distortion or stuttering sound.

I just wonder what causes this behavior? Is this more a DirectX or an OpenGL thing? Is it caused by Games being 'clever' and caching/wiping the cache whenever the screen settings change? (I assume they do get some sort of signal when I ALT-TAB?)

I don't have any problem of my own, but I'd like to know what to avoid and which 'clever' trick may cause this type of horrible customer experience?

# Answer
> 17 votes
In some situations ALT-TAB will cause the DirectX device to be lost. When the device is lost all GPU resources (vertices, textures, shaders and so on) must be considered invalid and cannot be used again. MSDN reference here.

These lost resources must be released, and then recreated when the device is restored. In the case of most games restoring these resources requires a lot of data to be loaded from disk again - often the same loading procedure as done at the start of the game/level.

**What can be done to avoid this?**

* You can keep a cache of your data in ram so transferring it back to the GPU will be faster than reloading from HD. I believe there's a way to make DirectX do this automatically.
* Use a new version of DirectX. This quote (source) is from MSDN on DirectX 9Ex:

> Devices are now only lost under two circumstances; when the hardware is reset because it is hanging, and when the device driver is stopped. When hardware hangs, the device can be reset by calling ResetEx. If hardware hangs, texture memory is lost.

# Answer
> 7 votes
In Direct3D a device can become lost when you ALT-TAB out of the full screen window. If that happens you have to release and restore the resources and reset the device. This can be hard to do properly depending on the complexity of the game or the laziness of developers (hi Valve!). I don't think OpenGL suffers from the same problem because the driver is responsible for keeping the OpenGL context for you, but I'm not sure.

There's a question on StackOverflow about the best practices for ALT-TAB support in a DirectX app which includes useful links from MSDN and other sources.

# Answer
> 0 votes
It can be the available amount of free ram. If it is too low, when your game runs, Windows hides most of its services into the swap area (i.e it takes most of the data loaded in RAM and put it in a special area of your hard drive instead) in order for your game to have as mush available RAM space as possible.

Then, when you alt+tab from the game to windows, it needs these services to be loaded in RAM in order to work, so it will take your game data from the RAM, store it in the swap, and pull the windows data from the swap to the RAM.

And as you know, writing to the hard-drive can take AGES compared to the RAM. The same thing actually also happens when you quit a heavy game. That's why having enough RAM space for both a game and windows can be really more comfortable.

---
Tags: architecture, windows
---


# Question
Title: How to render glass with XNA or DirectX 9
Any good pointers on how to get the refractive look of glass? I'm looking to create a think piece of glass type of look, sort of the type that you'd have on bathroom shower doors.

# Answer
> 3 votes
I am a little confused about what you are asking. I think you might be asking how to create water droplets in an indirect way. I will answer both. =)

If you want to create water droplets you can use a very simple distortion shader to offset the current pixel coordinates. However, there are many ways to do water droplets. Here is one which works well: Link

If you want to create the refractive look of glass then you are going to have to create an environment map. This essentially is your scene rendered from the 6 sides of a cube, if you choose a cube map. I suggest using XNA 4 because it now comes with a built in `EnvironmentMapEffect` shader.

> **EnvironmentMapEffect** — An environment map effect uses a diffuse texture to color or detail an object, and a cube map texture containing an environment map to shade the object due to the environment. Because the object reflects the scene, this makes the object look more like it is in a real scene. Also, you can use the fresnel parameter to tune the amount of light reflected (shininess) based on the geometry of the surface.

Here are some articles which describe the process in more detail (keep in mind the new EnvironmentMapEffect for XNA 4.0):

http://digierr.spaces.live.com/blog/cns!2B7007E9EC2AE37B!585.entry?wa=wsignin1.0&sa=736960100

http://xna-uk.net/blogs/randomchaos/archive/2009/01/06/basic-hlsl-lighting-techniques-episode-6-environment-maps-reflection-amp-refraction.aspx

# Answer
> 0 votes
If you want refractions, you will need to copy your back buffer to use as a texture for a distortion pass. There are a couple of ways to do this pass, but the most common is to create a distortion buffer some where early in your rendering pipeline after your Z has been written where you blend in your distortion directions.

You can then do a pass where you find it suitable (after opaque and before transparent for example) where you copy screen to a texture and distort back onto the screen using your distortion map. It will not be correct but it will be quite fast.

An alternative is to copy screen for each glass that is supposed to distort, this will give you a more correct look but it will cost a lot.

---
Tags: xna, shaders, directx, graphic-effects, materials
---


title: GL_EXT_draw_instanced vs VBO's

text:
# Question
Title: GL_EXT_draw_instanced vs VBO's
I'm having trouble understanding the benefit of the newer GL\_EXT\_draw\_instanced over traditional VBO's. Don't both keep geometry cached on the gpu for faster redrawing? VBO's seem much more flexible.

# Answer
> 6 votes
The advantage to instancing is to allow multiple objects to be drawn in a single draw-call, reducing the overhead of calling the API.

Typically as well as the geometry, you would also have a buffer containing multiple transforms, and perhaps other per-object data. This could be used in the shader to vary the appearance of each object by modifying its colour, or using a different texture (generally the texture variations would be achieved by using a texture atlas to pack multiple textures into a single texture).

# Answer
> 3 votes
Instancing should be used in conjunction with VBOs, and is most useful in OpenGL3/4.

The "correct" usage is to have a uniform-array of transform matrices, one for each instance. You then use one instanced draw call to render all the objects that use the same mesh. In your vertex shader, you can then select which transformation matrix to use based on the index ID.

You can do the same for any other number of attributes, but the more attributes you want to change, the fewer instances you can draw at once, due to constraints on the number of uniforms available. If you just want to use a transform matrix, for example, thats 4096/16=256 instances at once on the latest-and-greatest hardware. (assuming no other uniforms in your shaders). If you add colors to that, you're down to 4096/20=204 instances at once.

---
Tags: opengl
---


# Question
Title: What techniques enable web based games to update player's resources frequently?
Long ago there was this web-based game called Utopia (and I'm sure it is still around), turns are by per hour. You only get new gold/lumber or what-not every hour.

Some newer web based games have resources incrementing in finer resolution, like per minute. So say a player has a food production rate of 5 per minute - the player will have his food amount incrementing every minute. I am not sure if it is wise to constantly set a CRON job to update the SQL database, which I am assume what they are using, as it is web-based. Perhaps I am wrong, every minute.

What techniques do those web-based games use? **Added on Edit:** And can database can really handle the load?

# Answer
> 7 votes
It seems to me that you could just store the production rates, the base resource level, and a last-updated timestamp. Then, whenever you need to know the actual resource level, you could just multiply the production rate by the elapsed time.

Whenever the actual resource level changes - simply update the base level. Whenever the production rate changes, update the base level to the actual level, and the timestamp to the current time.

This way, instead of updating every player (presumably including those not currently logged in) every minute, you're updating only rows that are actually actively being used by players.

(If your game "ticks" once a minute, I imagine a "turn number" of some sort might be better than an actual timestamp.)

A side-benefit of this system is that you can use the *same* logic used to update the database, and to predict values without modifying them - to only send the necessary information to the client (rather than updating once per minute), and to predict values on the client.

# Answer
> 5 votes
Modern SQL databases that are commonly used (MySQL,Postgres,Oracle,MSSQL,etc) allow you to schedule stored procedures to be run with arbitrary time intervals. It's a very light weight method of running updates like this and removes the need to invoke external script or program to do it for you.

This also allows the database to optimize the query you run just once, instead of doing it every time external script invokes it, so it's very useful from performance standpoint. Of course this only applies if your updates are trivial enough to be programmed in your databases own scripting language. Resource updates, automatic time interval log outs, record purging and the likes are excellent candidates for these scheduled stored procedures.

Most likely the load your database is experiencing comes 99.9% from page loads, game engine updates and the like, as a popular game can easily have hundreds of thousands of queries per second. Compared to the load that arises from running a few queries (although ones that touch large portion of a table) once a minute or so, the load should not be an issue. That is, unless you update values that are indexed by the database. You should avoid updating indexed columns at all costs if you worry about performance.

# Answer
> 2 votes
Regarding the updates:

Some use CRON jobs that hit a certain PHP page every so often.

Some use CRON jobs, this time running a certain process.

Another approach is to do 'just in time' updates - whenever any page is loaded, run through any pending updates and perform them at that point. This is generally what you have to do if you can't run CRON jobs or long-running processes.

Finally, others are running the whole web application as one process, so they can update whenever they see it is time.

The final system is the best if you have that option available as you can store the data in memory. Updating a few thousand players once per minute is trivial if you're just changing data in RAM rather than having to write to a traditional SQL database.

But if you don't have that luxury, you can use some sort of caching. Something like memcached may be one option (dependent on your hosting) which is a half-way point between memory and a database. You can store transient values in memcache and only save them to the DB when absolutely necessary.

Between memcache and a traditional SQL database there are other options, eg. the various key/value stores or document stores: stuff like MongoDB, CouchDB, the Amazon or Google offerings, etc... ie. all the systems under the umbrella term NoSQL. These typically don't give you the generic querying power nor always all the same safety guarantees of a traditional database but are often much faster in operation. (Which is not so surprising, as they are doing less for you.)

But this is all assuming a normal database can't handle the load. In fact, in most cases it probably can. If I have to issue 10,000 UPDATE calls per minute to increase resource levels, that's not very scalable once you start adding everything else on top. But if you change that to update the resource for everybody with 1 SQL call, suddenly things look a lot more positive. So don't overestimate how expensive a certain feature is, as it can often be implemented in a more efficient form.

# Answer
> 0 votes
I am in favor of KISS: "Keep It Simple, Stupid!"

I see no reason why a cron job wouldn't work, and the upside is that cheap web hosting options often don't let you directly run commands, but they do allow you to run cron commands. So there's no need for an expensive dedicated server.

You can also do your update code in PHP or your language of preference, by having the cron command either `wget --spider http://yoursite.com/secretphppage.php` or use the `lynx` text browser. The instructions at Configuring cron jobs have several example commands which you could use to ping your own page at an interval.

# Answer
> 0 votes
I remember having a look at some Planetarion clone's code. Everything's PHP, but the ticker code is in raw C - with C MySQL bindings. Because the data model was very simple the updates happen really fast.

---
Tags: web, databases
---


title: Scripting engine for XNA

text:
# Question
Title: Scripting engine for XNA
Say I'm making this big game in C# with XNA.

What options do I have to include a scripting feature to my code base?

# Answer
> 15 votes
I advocate **not using a scripting language in C#**. C# is already solves the vast majority of problems that a scripting engine is used to solve. Just use C# in the way you would use a scripting language.

Because I've been over this several times before, here is some reading material for you:

---

UPDATE: If you want a live-editing workflow, try this cheeky method for using Edit and Continue.

# Answer
> 1 votes
If you plan on targeting the XBox360 or Windows Phone 7, then your options are limited. Those platforms do not support runtime code generation, so your only option would be an interpreted language. I would recommend steering clear of interpreted languages, as their performance tends to range from "sub-par" to "abysmal".

If you are only targeting Windows, and you really need/want a scripting language, then have a look at IronPython or IronRuby. Both target the DLR and perform very well (for being dynamic languages).

---
Tags: xna, c#, scripting
---


# Question
Title: Building a Plattformer - How to determine if a player is allowed to jump?
I'm building a simple Plattformer Jump n' Run Style game. I do not use tiles - instead i've geometrical shapes for my level entities (and the player is one too). I finished my collision detection code and everything works fine so far.

Next, I wanted to implement jumping. Just checking if the player hits the appropriate key and add some upwards velocity. Works fine. But it works even if the player is in-air, which is not what I want. ;-)

So, I have to check if the player stands on something. My first idea was to check if there was a collision in the last frame and mark the player as "able to jump", but this would even trigger if the player hits a wall in-air. As my math skills aren't that good, i ask for help - even hints would do how to implement this.

Thanks!

# Answer
> 14 votes
Two options spring to mind:

* First thought is to tag the geometry with an ID and then check to see if the collision is with geometry tagged as floor. This offers the most control of jumpable surfaces but at a cost in level creation time.
* Second is to check the normal of the collision, if it's pointing up then allow jump. Or within some margin of up, depends on if you have slanting floors. This is flexible and doesn't require any tagging, but if you have slanted floors and walls you might get some jumping where you don't want it.

# Answer
> 8 votes
You surely should implement some kind of surface type. Think of it, how will you manage if you can climb up a ladder if you can't know if your character just collided a wall or a ladder? You could simply use OOP to manage a type hierarchy using heritage, but I would suggest you to use "categories" implemented using an enumerated type:

Here is the idea: A "Collisions" enumeration has a flag for each category. For example:

```
namespace Collisions
{
    enum Type
    {
        None   = 0,
        Floor  = 1 << 0,
        Ladder = 1 << 1,
        Enemy  = 1 << 2,
        ... // And whatever else you need.

        // Then, you can construct named groups of flags.
        Player = Floor | Ladder | Enemy
    };
}

```

With this method, you will be able to test if the player juste collided anything that you should manage, so your engine can call a "Collided" Method of the entity :

```
void Player::Collided( Collisions::Type group )
{
   if ( group & Collisions::Ladder )
   {
      // Manage Ladder Collision
   }
   if ( group & Collisions::Floor )
   {
      // Manage Floor Collision
   }
   if ( group & Collisions::Enemy )
   {
      // Manage Enemy Collision
   }
}

```

The method use bitwise flags and the bitwise "Or" operator to assure each group have a different value, based on category's binary value. This method works fine and is easily scalable so you can create customs collision groups. Each Entity (Player, Enemy, etc.) in your game has some bits called a "filter", which are used to determine what it can collide with. Your collision code should check to see if bits match and react accordingly, with some code that might look like:

```
void PhysicEngine::OnCollision(...)
{
    mPhysics.AddContact( body1, body1.GetFilter(), body2, body2.GetFilter() );
}

```

# Answer
> 1 votes
If you consider your character's foot as alway under the character by a certain distance, and if you're not moving away from the surface then your character is on the ground.

In rough pseudo-code:

```
bool isOnGround(Character& chr)
{
   // down vector is opposite from your characters current up vector.
   // if you want to support wall jumps, animate the vecToFoot as appropriate.
   vec vecToFoot = -chr.up * chr.footDistanceFromCentre;

// if feet are moving away from any surface, can't be on the ground
   if (dot(chr.velocity, down) < 0.0f)
     return false;

// generate line from character centre to the foot position
   vec linePos0 = chr.position;
   vec linePos1 = chr.position + vecToFoot;

// test line against world. If it returns a hit surface, we're on the ground
   if (testLineAgainstWorld(line0, line1, &surface)
     return true;

`return false;
}`

```

---
Tags: mathematics, collision-detection
---


title: Mouse-driven Movement

text:
# Question
Title: Mouse-driven Movement
I'm trying to write a game where player picks where they are going by just mouse-clicking on that position and it goes there (just like RuneScape's point-and-click mouse interface).

I'm trying to get it working on the `jme3test.bullet.TestWalkingChar` example.

I've tried:

```
character.setLocalTranslation(
    cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f));

```

Also tried:

```
Vector3f worldCoordinates = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f);
Vector3f localCoordinates = null;

character.worldToLocal(worldCoordinates, localCoordinates);
character.setLocalTranslation(localCoordinates);

```

and:

```
Vector3f worldCoordinates = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f);
Vector3f localCoordinates = null;

character.setLocalTranslation(character.worldToLocal(worldCoordinates, localCoordinates));

```

But it's just teleporting the player to some unrelated coordinates.

Any ideas?

BTW: If there's a complete example on how to do that, it'd be great. I don't care about game engine - I prefer jME3 but it doesn't really matter for me.

# Answer
Turns out that there is built-in functionality for this in the jMonkeyEngine framework:

```
Vector3f origin = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f);
Vector3f direction = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.3f);

direction.subtractLocal(origin).normalizeLocal();

CollisionResults results = new CollisionResults();
rootNode.collideWith(new Ray(origin, direction), results);

if (results.size() > 0) {
    character.setLocalTranslation(results.getClosestCollision().getContactPoint());
}

```

Thanks anyway!
> 2 votes

# Answer
You're taking **absolute** world coordinates and feeding them to *setLocalTranslation* which, being a translation, sounds like it should take **relative** coordinates.

i.e. if your character is at (10,10) and you click (10,20), I'll bet your character will move to (20,30) - it moved 10 horizontally and 20 vertically, not *to* (10,20).

Instead you should find a method which takes absolute coordinates.

If that method doesn't exist (I will be genuinely surprised if it doesn't), you can instead determine the relative coordinates and feed them to *setLocalTranslation* instead. However this approach involves a lot of unnecessary calculations.

How to determine those relative coordinates, as pseudocode:

```
Vector clickedPos
Vector characterPos
Vector translation
translation.X = clickedPos.X - characterPos.X
translation.Y = clickedPos.Y - characterPos.Y
translation.Z = et cetera...
...
character.setLocalTranslation(translation)

```
> 3 votes

---
Tags: java, mmo, movement, mouse
---


title: How can I create my own sky maps?

text:
# Question
Title: How can I create my own sky maps?
What are the methods/tools for generating realistic skies with clouds and atmospheric shading?

FOSS alternatives and spherical projections get extra points.

# Answer
I've seen someone generate impressive skymaps by modeling a scene in Blender, complete with elaborate particles, shaders, post processing, etc., and then use six 90-degree cameras to render out the skybox (which you could then convert to spherical, if you wanted. Might even be able to render directly to spherical.) This is of course most useful if you've got some kind of fantasy or surreal environment that'd be difficult to capture with photography.
> 3 votes

# Answer
If the 3D package you are using supports render-to-texture functionality you could always unwrap a sphere/hemisphere and bake an environment (your skybox in this case) to the unwrapped sphere texture. You can do this with a 6-sided box as well. I've played around with this in 3DS Max but I think Blender can do it too.
> 1 votes

# Answer
Try using Bryce to generate sky bitmaps for use with your skydomes. There is a lot of variation in Bryce's generated imagery.
> 0 votes

---
Tags: rendering, textures, sky
---


# Question
Title: Custom Rule-Based System for Action Recognition in a Game
I want to make objects in a side project interatible with each other. For this, I want to be able to create rules so "Collisions" (Interactions) can be recognised by testing the rules. The rules should be able to reference what object does the player is trying use, in what state the object is, with which object does he try to interact with (could be nothing) and the state of this object. Maybe the rules will need to consider the state of the game as well.

With this in mind, here is my question. How could I create a rule-based system that I could use ? What design patterns could I use to create something scalable and that will allow me to add, remove and modify rules without having to regenerate the project ?

# Answer
> 2 votes
There are Objects and Actions (Interactions). Callback for interacting can be selected via multiple dispatch (multimethods).

For example, Action: *"Look at A"* is selected by Action "Look at" and Object A (double dispatch).

Action: *"Mix A and B"* is selected by Action "Look at" and Object A and Object B (3 arguments).

Read *Item 31 of Scott Meyers's book "More Effective C++"* and *"Modern C++ design" by Andrei Alexandrescu*, Chapter 11, for different double dispatcher implementations in C++. Another article.

Example of usage:

```
Dispatcher2 action_mix;
action_mix.registerInteraction<ObjectType1, ObjectType2>(callback_1_2);
action_mix.registerDefaultInteraction(callback_default); // for unregistered pairs
//...
action_mix.call(object1, object2);

```

Another example:

```
Dispatcher2<BaseActionType, BaseObjectType> any_action_to_any_obj;
any_action_to_any_obj.registerInteraction<ActionType1, ObjectType1>(callback_a1_t1);
//...
any_action_to_any_obj.call(action, object);

```

# Answer
> 2 votes
It depends on the requirements of your design. For example, do you want one unique/global "Activate" action, or do you want discrete activation actions for different types of objects? Is the "Activate" action for a light switch the same as the "Activate" action for a coffee maker, but with different behavior? Or are they completely different actions with identical names?

If you want to be able to bind actions to input gestures (e.g. keystrokes), then you'll probably want to go with the first option. In that case, you probably don't want the action to know every object on which it can be performed. You might not want a rigid set of actions supported by each object, either. Instead, your design could enable you to *bind* (or *attach*) action handlers to potential targets, delegating the behavior out to a callback. Action bindings could be bound to object types (metadata) or to actual object instances (or both).

Let's say I have a light switch, and I want it to support the Activate action. My code might look something like this:

```
lightSwitch.ActionBindings.Add(
    new ActionBinding(
        StandardActions.Activate,
        delegate (object target)
        {
            var lightSwitch = (LightSwitch)target;
            if (lightSwitch.IsDestroyed)
                return false;
            lightSwitch.IsActivated = !lightSwitch.IsActivated;
            return true;
        }));

```

This is simplified a bit, but the idea is that the behavior is injected via a callback, and the callback could return a value indicating success. In practice, you would probably want a second "can execute" callback in addition to the default "execute" callback.

Now, when the player hits the key bound to the "Activate" action, the target object should be queried to see if it has an ActionBinding for the "Activate" action. If so, the "can execute" callback should be checked (if one exists), and on successful evaluation, the "execute" callback should be invoked. If the action succeeds, stop. Otherwise, walk up the object tree until you find an object which will accept the action. That last step is only necessary if your objects are grouped in a hierarchy, i.e. the object is part of a larger composite object which might be the "true" action target.

Your callbacks could easily query the target object or game state as necessary. You might consider exposing services or state using a Service Locator pattern.

# Answer
> 1 votes
You can use Prolog (as a *logic, declarative* scripting language) as it provides model of rule-based deduction process. One my friend has used his own Prolog-like language in games with success.

> The program logic is expressed in terms of relations, represented as facts and rules. A computation is initiated by running a query over these relations.

If your host program is in C++, here some links to bind C++ and Prolog:

http://www.amzi.com/articles/prolog\_cpp.htm
http://www.google.lv/search?q=Prolog+C%2B%2B

---
Tags: software-engineering, design-patterns
---