# Question
Title: Do iOS users use Facebook and Twitter buttons within games?
Does anyone have any insight or experience into the successfullness of placing Facebook or Twitter "share" buttons within an iOS game? For example, when a user gets a high score, presenting them with the option to share their score via Facebook or Twitter.

My reservations/bias against including Facebook or Twitter buttons in my game are:

* Distrust of buttons that auto-post without giving one the chance to format the text yourself
* I don't use themself because I tend to manually create tweets or Facebook wall posts on my own

On the other hand, the potential benefits of such buttons can obviously be profound. The question is simply: do iOS users actually use such buttons?

# Answer
One industry-sponsored study claims that only 22% of customers had a positive attitude toward social media advertising, and 8% of consumers abandoned an SNS (Social-networking sites) because of what they perceived as excessive advertising\[1\].

Schlosser, Shavitt and Kanfer reached the conclusion that users who "actively contribute content" view online advertisements more negatively than users that only consume it.\[2\]

Another study found that when SNA delivered content or impressions that provided entertainment or informational value, or offered social value, consumers appeared more likely to respond favorably toward the ad stimuli themselves. It also found that "these results suggested that one prerequisite to more successful SNA execution would be for advertisers to create messages that provide some sort of explicit value to \[...\] users. And by a wide margin, the value that appeared most likely to be highly regarded by SNS users was entertainment".\[3\]

Activision ran an extensive advertising campaign when releasing Modern Warfare 2, which included (amongst other advertising channels) Twitter, Youtube and Facebook\[4,5\]. When the game launched it grossed $550M in what Activision Blizzard calls the "biggest entertainment launch ever"\[5\].

Deviating a bit on the topic, a study by Nielsen Games polled some 534 "gamers" on whether they responded to advertising in games -- 11% said they purchased a brand, 19% said they talked about it and 10% said they recommended the product, 11% said they sought more information. (While no direct comparison rates were offered against other forms of media, 1% of consumers exposed to direct response advertising eventually buy the advertised product.)\[6\]

Estimates on how much a "fan" or "like" on facebook is worth ranges between 44 cents and $3.60; the issue seem to be that facebook lack the metrics necessary to correctly analyze advertising impacts on-site\[7\]. Luckily, facebook has agreed to partner with Nielsen Ratings, and Nielsen Ratings are planning to launch a new "Online Campaign Ratings" system that tracks ad performance and audience demographics\[8\].

It's clear that facebook advertising does have an impact, however; "Texas Pete Hot Sauce" ran a campaign on facebook which allegedly had a direct, measurable and effective result.\[9\]

--

There are obviously issues to deal with when looking at this data: it's only tangentially related to the question, there are no major studies done on advertising impact on SNS, and I am not an expert in the field of advertising or the research associated with it (I do know my statistics though).

The Activision ad campaign is largely anecdotal; given that we can't see any impact data, but I figured that the academical standards on gamedev.SE is slightly lower than peer reviewed journals, and as such it might be of some interest.

As for a "personal" answer (remember folks: anecdotal evidence is not data), I'd say that yes, a portion of users will probably post stuff on facebook, if it's either relevant or amusing (for instance, Doodle Jump posts your high score and checks your friends list to see if they have any high scores you can compare against. I'd go with "Friends, Fans and Followers: Do Ads Work on Social Networks?" as the most relevant study for your question. Unfortunately, they reach the same conclusion I do: "Anecdotal evidence indicates that social-networking advertising (SNA) can be effective when users accept it, but the perception of excessive commercialization may lead to user abandonment. Empirical support for these propositions, however, is lacking." and then goes on to look at how users attitudes toward SNA (Social Network Advertising) are affected by things like content, structure and social factors.

--

\[1\]: AdReAction. “Brands + Consumers + Social Media: What Marketers Should Know About Who’s Getting Social and Why.” Dynamic Logic, January 26, 2010 \[URL: http://tinyurl.com/ycxfewn (dynamiclogic.com) \] -- Removed, but accessible at http://tinyurl.com/3mwmnda (Google Docs QuickView)
\[2\]: Schlosser, A. E., S. Shavitt, and A. Kanfer. “Survey of Internet Users’ Attitudes toward Internet Advertising.” Journal of Interactive Marketing 13, 3 (1999): 34–54.
\[3\]: Friends, Fans, and Followers: Do Ads Work on Social Networks?. (2011). Journal of Advertising Research, 51(1), 258-275. Retrieved from EBSCOhost.
\[4\] http://modernwarfare2.infinityward.com/
\[5\] http://adage.com/article/digital/modern-warfare-2-vanquished-harry-potter/140755/
\[6\] Beirne, Mike. 2008. "Study: Gamers Respond to Ads." Brandweek 49, no. 32: 6. Academic Search Elite, EBSCOhost (accessed August 16, 2011).
\[7\] Bruner, Jon. 2011. "What's a "Like" Worth?." Forbes 188, no. 2: 28-30. Academic Search Elite, EBSCOhost (accessed August 16, 2011).
\[8\] http://www.insidefacebook.com/2011/08/16/nielsen-online-campaign-ratings/
\[9\] http://www.insidefacebook.com/2009/09/22/nielsen-deal-part-of-facebooks-ad-momentum/
> 19 votes

# Answer
I'm the creator of Trainyard for iOS. It's a puzzle game, and when players solve a puzzle, they can share their solution on Facebook, Twitter, or directly on the Trainyard site.

I don't do in-app analytics, but I can tell you that players do use the buttons. You can do a simple twitter search to see the people that have tweeted from the game in the past week: https://twitter.com/#search?q=trainyard.ca

A *ton* of players press the share button to share their solutions on trainyard.ca without taking that link and posting it on Twitter or Facebook. To date, over 1.5 million solutions have been shared. You can see them here http://trainyard.ca/solutions
> 6 votes

# Answer
I think the Sword & Sworcery is a great example of how to effectively implement social media posting into a game. In this case it was strictly twitter, but I think they owe a large portion of their success to this feature.

Instead of posting scores or progress in a traditional sense, all of the story in the game is broken into 140 character chunks, which the user has the option to share as they want. Other people seeing these random, but interesting phrases showing up in their friend's feeds investigated and checked out the game. It also gave it quite a lot of press and buzz that wasn't directly related to its gameplay.

It offered a way for people to share aspects of their experience without it feeling like an ad.

This article offers a decent summary of how they made it work for their game: http://geraldonascimento.net/sworcery-how-4-four-guys-managed-to-hijack-the-world/

For some more empirical results, the superbrothers team estimates over 200,000 tweets sporting their #sworcery hashtag http://www.swordandsworcery.com/news/2011/6/7/applause.html
> 5 votes

# Answer
In our games, Bunny Shooter and Ant Smasher people use those buttons, not many of them do, as a simple twitter search reveals. But they were easy enough to implement, so we will put them on our next projects.
> 0 votes

# Answer
Personally, I think that it's really annoying when I go to a friend's FB profile or my profile and I see all is this:

Nevertheless, I think that it is a huge marketing tool that can make your game grow extremely fast. I've seen few games on the iOS that use FB and twitter in their game. One game I've seen that does it the best is Haypi Kingdom, it only posts to your wall when you level up.
> 0 votes

---
Tags: ios, marketing, facebook, social, twitter
---


# Question
Title: C# Game Setting message Takes away first character
So If you set it to like

> abcdefg

it will come out like

> bcdefg

Here's changing the message

Here's the result

Here's the code

```
//Set Welcome msg
else if (Type == 6)
{
    if (Character.Network.Stall.isOpened) return;
    short length = Reader.Int16();
    Character.Network.Stall.WelcomeMsg = Reader.Text3();
    Character.Network.Stall.Send(Packet.StallWelcome(Character.Network.Stall.WelcomeMsg));
}

```

Any help?

# Answer
> 9 votes
char is 16 bits, are you sure you aren't reading the first char when you try to read the length?

Try reading the whole block as text:

```
else if (Type == 6)
{
    if (Character.Network.Stall.isOpened) return;
    Character.Network.Stall.WelcomeMsg = Reader.Text3();
    Character.Network.Stall.Send(Packet.StallWelcome(Character.Network.Stall.WelcomeMsg));
}

```

---
Tags: c#
---


# Question
Title: How can I measure the "creative/entertainment value" of video-game requirements?
I realize this question is complex and subjective, but bear with me for a moment.

I firmly believe that video-game software is essentially different from, for example spreadsheet software, as from a user point of view, some games have more similarities with film art than with regular software. However, when it comes to requirements prioritization methods that help developers sort out which feature or idea is most important, there is none that facilitate the **creative aspects** of video games. Most available techniques only aid regular software development where focus is on the risk and cost of requirements, and do not take into account the creative aspect of video-game requirements.

To illustrate the problem, think of a requirement (i.e. feature idea) such as the one seen in Super Paper Mario, where Mario can exit the 3D world and enter a 2D world, and vice versa in order to go around obstacles. This is a fairly challenging requirement to implement and probably costly, but definitely crucial to the success of the game. Available prioritization methods overlook the **creative/entertainment value** of this requirement and mainly just estimate how costly and (technologically) risky implementation is. Of course, this is a very simplistic example, but you can imagine a case where there is a pool of great game ideas (functional and non-functional requirements) and not enough resources to realize them all. When it comes to value calculation, academic research doesn't provide game developers with an adequate way to estimate the value of game requirements.

**UPDATE / Clarification:** In my research, I study available software product management solutions (more specifically requirements prioritization algorithms) and try to find out why are they not suitable for game development. It seems that it is the creative or entertainment nature of the software itself that introduces this incompatibility. It is the (available) techniques inadequacy, to recognize the core value of the software and its conceptually different purpose.

With regular software, it is the user or his/her needs that most often help estimate the value of requirements. Moreover, it is the user that produces most requirements. In video-game software, it is the creative vision that drives the requirements. With regards to requirements origin, it is the outside in vs. the inside out paradigm. Having established this fundamental difference, we can deduce that if requirements prioritization (RP) algorithms focus on user ideas/needs in order to estimate the value of requirements for regular software, then in the case of video-game software, the RP algorithm should satisfy the creative vision. By creative/entertainment value of a requirement, I refer to the degree to which the core vision relies on this particular requirement.

What I try to do is find a way to prioritize the requirements according to their relevance/importance to this core creative vision. This will ultimately provide a creative value, but it is relative to the central idea and the stakeholders’ ability to subjectively assess the requirements. This is just one side of the RP algorithm, as other factors such as risk and cost need to be taken into account as well, but the available RP solutions already offer adequate ways to do that, and they are compatible with the needs of game development.

The reason I’m writing here is because I am trying to see how developers deal with these problems (PR and focusing on the core idea) when dealing with more complex projects.

I try to refine part of the preproduction process by developing a requirements prioritization method tailored to the needs of game development industry. A pivotal element in such a method is the ability to identify and estimate the creative/entertainment value of requirements. However, in order to do that, I need to understand how game developers perceive this creative/entertainment value of requirements. In a nutshell, **I am seeking answers to the following questions**:

Question 1: **How would you define the creative/entertainment value of video-game requirements?**

Question 2: **How would you measure it?**

Question 3: **Who should measure it?**

I would love to see how these issues are perceived by game developers and I would appreciate your take on them here, but if you want to contribute to this research – receiving my eternal gratitude and a proper credit/citation in the research and all the publications that will follow, please fill up my extremely short survey (just 7 questions, 3 of which you already see above):

The extremely short survey which will cement you as my personal hero.

## Research information and trigger

This research is being conducted at Utrecht University, The Netherlands, as part of an Information Science master’s thesis.

Game development is in many ways similar to product software development as developers follow certain software development processes. Following a poor development method (or none at all) could result in longer development times, going over budget and/or delivering buggy products (Bethke, 2003). What makes video games different is the creative game vision that must be shared by the entire team to ensure that the end product is consistent and of good quality. This is especially true for full-blown game titles where from a user point of view, there are more similarities with film art than with any other software. Unfortunately, this curious creative aspect renders many software product management techniques unadoptable by the gaming industry.

I am quite interested in working towards improving the game development process in the preproduction stage, by creating a requirements prioritization method tailored to the specific needs of the game industry and **I need your help!** The easiest way to contribute to the research is by filling up my short survey (link above). If you find this research interesting, please contact me at a.cherv@gmail.com

**Researcher information**

My name is Alex Chervenkoff, an avid gamer and quite excited about this research! You can contact me at: a.cherv@gmail.com

Degree in BSc Computer Science, The University of Sheffield, UK.

Currently doing MSc Information Science at Utrecht University, The Netherlands.

**Thank you!**

# Answer
The only real way we have to test such things is with, well, *testing*. Professional game developers will tell you all the time that the single most effective way to know if certain gameplay is working and fun is to give it to players and observe.

Indeed, one of the reasons that achievements are everywhere these days in games is because they give invaluable information to the developer. If you want to know where players stopped playing your game, make an achievement for completing each level. If you want to know how many players *aren't* playing a certain race in Civilization, look at how many people got the achievement for playing that race. And so on.
> 3 votes

# Answer
> Question 1: How would you define the creative/entertainment value of video-game requirements?

I don't know. I'm not convinced the science is ready, yet.

> Question 2: How would you measure it?

We can't.

> Question 3: Who should measure it?

Us. :(

Right now, the only useful metrics we have are sales figures and ratings (eg. MetaCritic). We don't understand the domain well enough to do much more than that, which is why you see a lot of copycat games - taking a game that we know to have worked and tweaking the formula a bit gives a good chance of having a second game that works. *'The acorn doesn't fall far from the tree'*, and all that.

Some designers have attempted to come up with broad checklists or systems for judging the quality of a game or its mechanics. eg. In Jesse Schell's *'The Art of Game Design'* he describes 100 'lenses' which are each a way of critically evaluating a game. This provides a system of measurement, but the measurements themselves are still fairly subjective. Similarly the MDA system (Mechanics/Dynamics/Aesthetics) broadly implies that your mechanics should combine to form dynamics, and your dynamics should support the aesthetic, but again this provides a tool for measurement but no units of measurement.
> 1 votes

# Answer
As mentioned in other answer(s), the definitive answer is testing.

The usual "silent observer" method of user testing I suspect is sufficient for a lot of metrics with follow up questions to explore any areas of confusion about what the testers might be feeling.

Sidenote: I would suggest that your core premise that games are fundamentally different to applications due to the entertainment factor is incorrect. Sneak a peek at something like Danc's "Princess rescuing application" presentation ( http://blog.iainlobb.com/2008/10/princess-rescuing-application.html ) and see what you think.
> 0 votes

---
Tags: tools, game-industry, methodology, requirements
---


# Question
Title: Blender - exporting .obj with texture coords
I'm writing a game which uses obj files. I created an object in blender and I applied texture without UV coordinates and my question is: how to export this object to obj file, but with texture coordinates?

# Answer
> 13 votes
As you already noticed, there's no way around UV coordinates for games. Thankfully, blender comes with some very good UV unwrapping tools.

The simplest way to get UV coordinates from a 3D model in blender is to use *Smart UV Project*. You can do that by pressing `U` while in edit-mode and then select "Smart UV Project" from the menu.

This creates UV "patches" given some angular threshold. The result can look like this:

Done, you've got UV coordinates now. However, these coordinates are most likely not that useful, since you'll end up with a ton of seams. A good unwrapped mesh has less seams, preferably at places where they can easily be hidden (eg. where an uniform color meets) or where the seams will be obstructed by other geometry. That's why you usually mark the seams yourself (in edit-mode select the edges that should be a seam and press `Ctrl` \+ `E` and select "Mark Seam" in the menu). Then use the regular "Unwrap" (not "Smart UV Project") to unwrap the mesh,

Good UV unwrapping is hard and requires practice. This video-tutorial might help you getting started.

---
Tags: 3d, textures, coordinates, blender, obj
---


# Question
Title: Which platform and what strategies can I use
There's this game, that I've been wanting to make for quite some time. It's a project that I've started and had to abandon in the middle a couple of times. However, this time I'm determined to finish it. I want to make a RPG (tile based) game, I'm okay with having it be 2D but am considering something in the middle of 2D and 3D. I would also like the game to be at least partially multilayer if not an MMO. I'm not a bad programmer, so I can work my way through any problems I might come across, I just don't have any experience making games, so I'm interested in any technologies I can use that I might not yet be aware of, or what type of architecture I can implement and what strategies I can use to make a decent (and secure game).

I made this game (2D tile based and partially multiplayer) before using MySql, PHP and JavaScript/Ajax. But now I would like it to be a bit more advanced with fluid graphics, and multiplayer where user's (or at least friends) can explore the maps together.

My first thought was to use Flash, PHP and MySql. Where Flash calls to a php file that returns an xml object with coordinates and etc., but I'm not sure how fast or efficient this will be.

With all that said, I'm wondering if anyone has any suggestions to what other technologies are out there that I can use. I would prefer that the game is browser based, but if it has to be run on the desktop I would like it to be at least cross-platform. I am familiar with HTML, JavaScript/jQuery, PHP, Flash, C#, WPF/XAML already and would prefer a combination of what I already know, but I don't mind learning something new either.

Any helpful links on this are appreciated as well.

Thanks in advance!

# Answer
> 3 votes
**Flash.** For single player, can't see why not. I've written a pseudo-3D display engine in AS3 that performs very well and is adapted to any sort of isometric game, about as intensive as view logic gets without going full 3D. If, however, you plan multiplayer -- and its probably best to make the decision ASAP -- and yours is eg. an action game, you'll have problems with your Flash/PHP/MySQL; HTTP requests (which run over TCP) are not known for their speediness; then there's the DB calls too (which, while very fast, are another overhead). It's reasonable to expect 250-500ms ping if packets start dropping over TCP. Bear in mind that you will have to pay for bandwidth and maintain your server. That's why there are cost-effective server solutions like Player.IO and SmartFox Server out there. See link below.

**HTML5** as @heishe said. I've used HTML5 + the canvas tag briefly for rendering. You can't easily rely on it being fast as Flash across different browsers and platforms... although on some, and for very specific things, and on very specific browsers eg. Chrome and IE9, it is undoubtedly faster. The full set of HTML5 rendering technologies (such as compositing which you get right off the bat in Flash) aren't fully implemented yet. Sound is the biggest problem with HTML5 right now. As a result, a number of engine solutions actually use Flash just to do the sound bit (obviously they abstract this away from the engine user inasmuch as possible). Having said all this, there are numerous game engines out there for HTML5 which attempt to address it's biggest flaws i.e. reliable cross-browser rendering efficiency and sound.

**Unity**. About as cross-platform and web-deployable as you'll get until HTML5 becomes more production-worthy. With the free version, and DropBox for source control, you can do a lot. There are tutorials out there on how to do 2D in Unity -- it's been done a lot. You can also deploy to desktop if you like. You write your code in C#, JS or a Python variant. It's got a nice IDE, if you like such things. It's also very easy to import 3D models into (though I'm not suggesting you go 3D).

**C++ with SDL**. Desktop only, but cross-platform, very mature, good for 2D stuff, only need use OpenGL if you want to. Of course, stepping into the realms of C++ may be more than you want to deal with right now.

You could even go with something like the Google Web Toolkit for your game.

**Multiplayer**, have a look at this comparison chart of socket servers. It's on the Unity forums, but because they're socket servers, it doesn't matter what your client is written in... although it is nice to have client and server in the same language, eg. C#.

# Answer
> 2 votes
Don't use XML, it is in all ways an unnecessary resource hog with a big overhead on both data size and parsing time. You could use JSON, the size overhead is manageable (though it depends a lot on your specific implementation), and parsing in JavaScript is quick.

For the back end, you should avoid storing time critical data in a database, keep it in application memory instead. That means PHP is out, I'm not sure if you can get ASP.NET to behave, but I wouldn't bet on it. Node.js seems like a prominent candidate for the back end code, being both easy to use and relatively fast.

If I were to do this I'd code the front end in old school HTML 4.01, once you have learned the quirks it works okay for 2D stuff, within the inherent limit of not being able to rotate images that is. Flash is the more traditional choice, and a decent one as well. Digging into the new fancy HTML 5 features is dangerous, you risk losing a significant amount of users due to not supporting their browser of choice.

---
Tags: 2d, multiplayer
---


# Question
Title: What would it take to create a clone of Frozen Synapse?
For the independent game studio Mode 7 it took 4 years and 3 developers plus contractors. Do you think it could have been done faster (according that you have played it) ?

What would it take to just make a clone of that game ? **for another indie that is**, not for a big studio.

# Answer
It depends on whether you've ever made a game before, whether you have money, time, resources or a team, or any one of other many things it takes to make this happen.

It really depends on the skill level of your artists and programmers, the clarity of your design document, and what resources you have available. If this is a full time job for everyone, it will go faster than if it's an "on the side" evenings and weekends job.

Also, if you have previous game development experience it will go faster. If you don't, it will go slower. If you have a reliable team, it will go faster. If your team is not reliable, it will go slower.

Perhaps others can fill in more dependencies in the comments.

If you REALLY stick to making a clone and not changing the game, it will go faster. If you start making changes and tweaking, it may take longer.

To the point about the original game you're cloning...

Probably a lot of what went into that original 4 years of development time was design, trial and error, prototyping and polishing the idea. If you're going to just copy them, clearly you don't need to spend time on thinking much - just coding and art.

And lastly for some advice from the mouths of pros who've cloned other games..

You might find this article interesting. It's about how Farmville was created in 5 weeks. It was a clone of various games and so the developers didn't need to come up with a completely original idea.
> 1 votes

---
Tags: project-management
---


# Question
Title: What would be a good Facebook credits price point for a puzzle game on Facebook?
I have a successful puzzle game and I'm thinking about doing a new version and bringing that new version to FB, and selling it using FB credits. Does anyone have ideas on what the FB credits price point should be? I have some idea, and obviously I know what some of the virtual goods price points are, but I'm curious what peoples views would be on a price point for an entire game, and if the availability of free facebook credits could hurt sells etc.

# Answer
I know of very few games that actually charge admission. You most likely won't make any money that way, simply due to the fact that people can easily find something else to play with their time.

There are a few examples I remember seeing that lock certain modes behind a paywall, but if people are getting enough enjoyment out of the free one then they won't feel obligated to try the other one (this is the same problem with demos that give away too much). It also isn't as good of a monetization strategy because it's something the user only buys once.

If you want to bring a puzzle game to facebook, my suggestion it to look and see what Popcap did with Bejeweled Blitz and Zuma Blitz. They basically added a monetization layer on top of the existing games with things like purchasable powerups and the like. They also made it very social with the weekly tournament idea and very visible friends scores.
> 1 votes

---
Tags: facebook
---


# Question
Title: What distinguishes a free to play game from one worth paying for?
There's a heck of a lot of free games available out there, some of which are as good as games that you have to pay for. My question is, what makes the difference between a game that people will be willing to pay for, and one which is best left as a free to download/play online game subsidised with advertising?

# Answer
It's a decision made by the developers/publishers. In markets where a price-tag is an obstacle (eg. Apps), a lot of developers choose to go with a free-to-play game and get their revenue from ads or in-app purchases.

This business-model is also very common in browser-games. I'm not aware of any browser game that you actually buy before you can play it.

That being said, it's not a matter of how "good" a game is that makes it fall into the category of free-to-play or pay in advance.

As with everything else you want to sell, you'll have to study your target market/audience and find the appropriate way to sell your game. Also you'll have to decide whether or not you want to release a demo (or light) version of your game *and* a paid version, or if you want to just ship one version which is free-to-play and has in-app purchases.
> 6 votes

# Answer
I think you're conflating two unrelated concepts - "free-to-play" and "advertising supported". A lot of the free-to-play games have *many* ways you can plow money into the game if you so choose, and they encourage you to do so at every opportunity. See Puzzle Pirates for an elegant example of this and Age of Wonders Online for a significantly more hamfisted version. Both of those games are "free to play", neither of them have advertising, and both of them make money off users anyway.

(Puzzle Pirates, with true design elegance, manages to make money off even the users who aren't interested in putting money in.)
> 3 votes

# Answer
David Edery (Spry Fox) posted a piece earlier on Google+ discussing this topic. I think you'd find his post and the followup comments and discussion worth a read for this particular question.

Rather than copy and paste the text, I'm linking to it below. Do read it.

https://plus.google.com/104582272037881191614/posts/PLqGbor8q9J
> 1 votes

---
Tags: marketing, free-to-play
---


# Question
Title: What are some good podcasts for game developers to listen to?
This could include specific game dev, general dev or general game podcasts.

Please provide a brief description along with links.

# Answer
> 61 votes
Another Castle \- Professionals talk game design.

Game Developers Radio \- Great guests, a different game or development platform discussed each week.

Brainy Gamer \- Game design from designer, journalist, academic and player perspectives.

DigiPen \- Professionals and educators talk games.

IndieGamePod Interviews with developers about their games.

A life well wasted Arty, philosophical trip around gaming culture.

Game Audio Podcast: Self-explanatory. Found it while searching for a talk on footsteps in games.

The Debug Log Professionals talks game dev; Relevant guests is invited, and relevant approaches and software is discussed.

Doom Ninja Podcast: Indie studio Doombrowski talks games and development. Also includes video game live streaming perspective from co-host.

# Answer
> 13 votes
There is Industry Broadcast which describes itself as "Bringing the Collective Insight of the Gaming Industry to your ears".

Basically it features audio versions of existing online articles ... if you prefer to listen rather than read or you have time to kill on your commute then they may be of some use!

# Answer
> 8 votes
Irrational Behavior \- Developers at Irrational Games discussing various aspects of development.

# Answer
> 7 votes
Infinite Ammo Podcast: Interviews with indie game developers.

Looking Glass Podcast: Interviews with developers who once formed that great team.

# Answer
> 5 votes
Another Castle is a game design podcast that focuses on the game development scene in the New York area. Sometime the audio isn't that good (they record a lot in restaurants) but the interviewees are always interesting.

# Answer
> 4 votes
I've listened to some of the GameDevRadio ones, there are not a lot and they come rarely but they are often fun to check out.

They talk about varied topics, the ones there now are Flash (2 part), SDL, Unity, Push Button Engine for example.

The shows are roughly an hour, often more.

# Answer
> 3 votes
Flammable Penguins \- New casual podcast with me and my co-workers from Mere-Mortals. Feedback always appreciated.

The dev casts I listen to have all been listed already.

# Answer
> 2 votes
The Kingdom of Loathing guys run an entertaining podcast (or two - Video Games Hotdog) that often talks about game design, balance and interacting with their community. Video Games Hotdog talk about video games in general.

# Answer
> 2 votes
Hey guys I am the creator of "The Game Developer's Radio" want to say thanks for linking to my show! It's been on a bit of a Hiatus for a while, but I finally released a new episode :-D And will be releasing plenty more, very soon!

Also if you want a list of more game dev podcast links id recommend checking out this blog post http://blog.iainlobb.com/2010/07/gamedev-and-indie-games-podcasts.html has tons of links to game dev podcasts.

# Answer
> 1 votes
I find the Giant Bombcast pretty entertaining, even if it's not so much game-development as it is just gaming

# Answer
> 0 votes
Great lists here.. Glad to see www.industrybroadcast.com plugged. Back recording articles again after a nice almost year long hiatus. The podcast is certainly a bit more dry and serious as the topics covered can get insanely indepth, theoretical and technical.

Outside of my biased opinion though I have to say A Life Well Wasted tops my list, not just in this genre but of any podcast I have ever listened to.. It is absolutely and purely brilliant

# Answer
> 0 votes
IndieGames.com Podcast has a lot of good interviews with indie developers. The interviews tend to be framed from a journalist/player perspective, but there's still a lot of decent design talk.

---
Tags: education
---


# Question
Title: Help streaming resources (maps, sounds, music, etc) from many files for contiguous world
So I'm creating a game and I would like to know how to perform resource streaming (rather than loading the whole file into the buffer) for things such as my maps, sounds, music, etc. I'm using C++ and DirectX9 if in case you need to know.

# Answer
> 7 votes
A note, setting off multiple reads will be slower because the disk I/O keeps seeking around to pull bits of data from each open request.

To get around this I created an intermediate streaming traffic cop that prioritized multiple async read requests and serialized them to the OS. In your own game you can create priorities based on data type or how soon the new data will be needed so that audio can come in first to avoid skipping and far away data will be loaded last.

A note on audio: you do want to stream audio because data is pretty large, but you want your game to stream the data before it's needed because waiting for the actual "Play sound" call before loading will cause all sorts of delay and spoil the user experience.

Since background loading and preparing data is a complex sequence of events involving threads, callbacks and voodoo that spans several systems in your game I suggest designing the interactions carefully before laying down any code to avoid massive debugging headaches later.

# Answer
> 3 votes
It's more than just streaming the assets — the disk itself is a mechanical device and you need to minimize seeks and simultaneous parallel streams. So you need to chunk up your data so it can be streamed en masse, and then evicted all at once without any risk of leaks.

I liked DoubleFine's GDC talk about their chunking solution.

# Answer
> 2 votes
Specifically re streaming world data, I believe it was GPG's Dungeon Siege that was the first well-known title to achieve this really efficiently for a really large 3D world. It enabled the modern MMO (post the whole tile-based Ultima Online era).

Here's an article where Scott Bilas outlines the solutions they used. I don't doubt it would help to do further searches on the same topic. I seem to recall a GamaSutra article, but not too sure. Could be the same one.

I am sure things have come a long way since then, but that should get you started.

# Answer
> 1 votes
You want to use the concept of chunks or pack files or the like where the entire chunk is streamed. The chunk should contain the data that it needs when used in the game. World Geo, specific models for that area, textures, sound effects, scripts and the like. It should not contain background audio, that should be a streaming system on its own.

You really dont want to read an individual packed file for each of these, but you definitely do not want to read each individual asset. The FileIO will kill any overhead. (Ideally the chunk files are all packed together into one large file you can just fseek() through to get to the right chunk you want to load)

Hope this helps.

---
Tags: assets, resource-management
---


# Question
Title: Is there an open source rhythm / music game framework?
I'm trying to build a very simple rhythm game (as a one-off art installation, not a commercial project) demonstrating a novel controller, but I've got an extremely short timeframe to do it in. Are there any open-source rhythm games or frameworks out there that I could use instead of writing such a game from scratch?

I could probably bang the code together in PyGame or Processing over a few days, but any time I can save on programming can be spent instead on the physical build, which would make the overall installation better. The requirements for the game itself are super simple -- I just need to scroll notes across the screen, register points based on how well the player matches them, and play a song (ducking one of the channels when a note is missed).

The custom controller is Arduino-based, sending its data as bytes over a serial port, so I don't need any fancy DirectX support. Just something that can run with \<60ms latency.

# Answer
It probably would be more effort to strip them down, but if you're curious both StepMania and Frets on Fire are open source.
> 4 votes

# Answer
Demo programming opensource, also links to some other demo/game engines : http://elsewhere.stc.cx/demoprogramming/
> 0 votes

---
Tags: music, prototyping
---


# Question
Title: Data Structure (or algorithm) for fast distance-based entity lookups
For example, your game has 100 enemies (on different teams) running around and their AI wants to inspect the nearby entities to see which it should attack. What is a fast way to organize those entities so that each enemy does not have to calculate the distance between itself and all other entities?

In short, what is a fast way for an AI entity to answer the question "Who is near me?"

# Answer
You want a spatial index such as quadtree (2D) or octree (3D).
> 8 votes

# Answer
The simplest solution is a grid. Lay a 2D grid over your level. Each cell in the grid maintains a collection of which entities are currently occupying it. As the entities move, take them out of the cell they're leaving and add them to the one they enter.

You can then find nearby entities just by examining the nearby cells. A quadtree refines this by recursively subdividing the grid, but sometimes a flat one is adequate, especially if your level size is fixed and relatively small.
> 5 votes

---
Tags: 3d, ai, entity-system, data-structure
---


# Question
Title: computer language like arduino language for visualization or game development
Is there a language similar to Arduino language (c++ language with fewer functions) for software visualization?

# Answer
Processing is probably exactly what you want.
> 4 votes

# Answer
You might check out Lua. It's a lightweight scripting language.

Here's an article about game development using it...

http://gamedevgeek.com/tutorials/getting-started-with-lua/
> 3 votes

# Answer
You should also look into Scratch. It is educational programming language to create games. The good thing is you'll find many open source projects in Scratch to study.
> 1 votes

---
Tags: c++, visualization
---


# Question
Title: How can I get my objects to move at the same speed regardless of frame rate?
I tried using the methods on lazyfoo's site for frame rate independence. One problem I'm having though is that my game is running at different speeds on different computers. The differences are drastic. For example, on a Core 2 Duo 2.4 ghz 2gb ram PC, the ball will move extremely fast, but the paddle moves slowly. On an Intel Centrino laptop running Win7 w/plenty of ram, the ball moves slowly, but the paddle moves fast. On older computers like a Pentium 4 2.4 ghz, 768 ram computer, the ball moves realllllllllyyyyyyy sllllooowwww. Yes, that slow.

What might be some reasons this is happening, and how can I fix it? I can only assume that the code I wrote that deals with frame rate independence is wrong. Here are the relevant parts of the code. (btw, it's a breakout clone).

Code to move the ball

```
bool Ball::MoveBall( Uint32 deltaTicks )
{
    // X-COORDINATE
    xOffset += cos( radians ) * ( ballVelocity / 1000.f ) * flipx;
    ballPosition.x = (Sint16)xOffset;

        .......

    // Y-COORDINATE
    yOffset += sin( radians ) * ( ballVelocity / 1000.f ) * flipy;
    ballPosition.y = (Sint16)yOffset;

    .....
}

```

Code to move the paddle

```
void Paddle::Move( Uint32 deltaTicks )
{
    xOffset += xVel * ( deltaTicks / 1000.f );
    paddlePosition.x = (Sint16)xOffset;
}

```

Main loop

```
    while ( SDL_PollEvent( &gEvent ) )
    {
        handle.PaddleInput( &gEvent, stick );

        if ( gEvent.type == SDL_QUIT || gEvent.key.keysym.sym == SDLK_ESCAPE )
            quit = true;
    }
    stick.Move( time.GetTicks() );

    if ( ball.MoveBall( time.GetTicks() ) )
        wallSound.Play();

    if ( ball.CheckPaddleCollision( stick ) )
        paddleSound.Play();

    if ( ball.CheckBrickCollision( brickmap ) )
        brickSound.Play();

    if ( ball.IsBallDead() ) {
        ball.ResetBallPosition();
        stick.ResetPaddlePosition();
        stick.SetPaddleState( Paddle::RESET );
        launched = false;
        draw.GameObjects( lvl, brickmap, stick, ball );
    }

    draw.GameObjects( lvl, brickmap, stick, ball );
    time.Start();
    draw.Refresh();

```

# Answer
The movement of your ball varies from platform to platform because you're not using the delta-time at all for your movement calculation.

First of all you should convert your ticks to seconds in your update loop and then call the `Move` functions with the delta-time in seconds.. otherwise you'll have to convert to seconds in every `Move` function.

All your speed definitions should be in units per second. Eg. `ballVelocity` would be `100` if your ball should move at a rate of 100 units (pixels) per second.

Then a simple `Move` method could look like this:

```
bool Ball::MoveBall(float dt)
{
    ballPosition.x += cos(radians) * ballVelocity * dt;
    ballPosition.y += sin(radians) * ballVelocity * dt;
}

```

A further optimization would be to not always calculate cos/sin, but rather have a `direction` vector that you only recalculate whenever the direction changes... Then it would turn into: `ballPosition.x += direction.x * ballVelocity * dt;`
> 12 votes

---
Tags: frame-rate
---


# Question
Title: Minimalistic JavaScript sprite manipulation libraries
Are there (or can someone recommend) any minimalistic JavaScript based libraries for sprite(s) manipulation? Preferably DOM oriented.

# Answer
EaselJS does sprite animation with HTML Canvas if that is something you could use. It's not really minimalistic, but does a really good job of handling sprite sheets.

The source is split across multiple files, so with a bit of work you could probably pull apart just the bits to do sprite animation (BitmapSequence).
> 1 votes

---
Tags: javascript, sprites
---


# Question
Title: How to properly handle the landing part in a jump animation
Look at this sprite sheet.

It is clear that frame 1-3 are the "jump up" frames after which the last frame will be fixed until the "peak" of the jump (when gravity starts pulling back). When moving back down frame 4-7 are used and it all ends with an "idle" frame (which is not shown here in this jump sprite).

My question is about frame 6 and 7 in this sprite. When the entity "lands" after a jump it is suppose to run animation 6-7 as the "landing" animation. When moving down in a jump frame 4-5 are easy because they are the "start" of the animation. Frame 5 can be kept for as long as you fall... but what is the appropriate way to go from frame 5 to 6-7-x? Do you check if the frame after the next is a fall and then "initiate" landing or do you do that when you have actually hit the ground?

It can't be timed because of various scenarios such as jumping off a cliff or jumping under a low roof hitting your head and bouncing you back down.

Any ideas?

# Answer
> 18 votes
I guess the usual approach is to have three jump-related states: *Jumping* (a hero rises to the highest point of jump), *Falling* (from the highest point of jump to the ground), *Landing* (jump ends with hero standing on the ground).

There are several ways of detecting these states, usually it's a several collision checks setting state flags. For example, in a character's physics step we may check for collisions below, and if there aren't any, then character is in the air. Now if a character has positive vertical speed, it's a *Jumping* state, otherwise it's a *Falling* state. If it's a *Falling* state, and we detected a collision below, than it's a *Landing* state, so lets switch to the landing animation.

This animation usually plays when hero has actually hit the ground. The animation sequence is short, so landing will look high-speed, also it creates a feeling of crisp and precise controls. Sometimes character can do a long landing sequence, but then it's possible for a character to cancel landing animation and start running, e.g. Castlevania: SotN.

# Answer
> 5 votes
I've seen this done two ways:

1. When the bounding box first collides with the ground make a fast transition 5-\>6-\>7.
2. Have a second 'ghost' bounding box, that extends a small portion below the actual bounding box to initiate the 5-\>6, then upon the actual bounding box colliding do 6-\>7.

---
Tags: animation, sprites
---


# Question
Title: How do I get the current location when using slick 2D library?
I'm developing a map kind of simple game using slick 2D library, and I want to get the current location of the user. When the user runs into a special location (ex: hole) to indicate that is dangerous. How can I achieve this? I'm a new comer to games.

# Answer
Assuming that I understand what you are trying to do, that is, a 2D dungeon-like tiled game, here is what I would do:

The current location of the player can be stored in a Point class, and the entire player entity into a sprite, as is typically done in simple 2D game. I.e.:

```
class Sprite {
  Point position;
  Texture texture;
  ...
  public Point getPosition() {
     return this.position;
  }
}

```

So, to move your player all you do is listen for keyboard events and update the location:

```
class MyGame implements KeyListener
{
    Sprite player;
    ...
    public void keyPressed(int key, char c) {
        if (key == Input.KEY_W) {
            player.getPosition().X += 1;
        } else if (key == Input.KEY_S) {
            player.getPosition().X -= 1;
        } else if (key == Input.KEY_A) {
            player.getPoisition().Y -= 1;
        } else if (key == Input.KEY_D) {
            player.getPosition().Y += 1;
        }
    }
}

```

As for informing the player of dangerous locations, have a list of triggers that will fire whenever the player is inside an area. The triggers could be a rectangular location, a circle or anything. In general, you would have something like this:

```
class Level implements TriggerListener {
  List<LevelTriggers> levelTriggers;
  Sprite player;

  ...

  void initialize() {
     // Initialize all triggers (usually you read this part from a file)
     for (int i = 0; i < numberOfTriggers; i++) {
        LevelTrigger trigger = new LevelTrigger();
        trigger.addListener(this);
        levelTriggers.add(trigger);
     }
  }

  void update(...) {
     ...
     for (LevelTrigger trigger : levelTriggers) {
        if (trigger.isIn(player.getPosition())) {
           trigger.fire();
        }
     }
  }

  ...

  void triggered() {
     // Show your message
  }
}

abstract class LevelTrigger {
    List<TriggerListeners> triggerListeners;

    void addListener(TriggerListener triggerListener)
    {
       triggerLIsteners.add(triggerListeners);
    }

    void fire()
    {
       for (TriggerListener listener : triggerListeners)
       {
          listener.triggered();
       }
    }

    abstract bool isIn(Point position);
}

interface TriggerListener
{
    triggered();
}

```

EDIT: Totally forgot to mention the "current location" part.
EDIT2: OK, I GOT to stop writing C# code in Java questions :/
> 1 votes

---
Tags: java, maps, slick
---


# Question
Title: What engines and tools do high end games use?
First of all, I am a beginner developer so please don't get me wrong. I just want to know what programs do high end games use. By high end I mean games that me and you would buy, say Splinter Cell, Starcraft, WoW, GTA and the list goes on. Do they use Visual Studio? Unity? I have no idea :P

PS: Sorry for the tags, not sure if I chose the best I could.

# Answer
> 4 votes
A lot of big development companies will have their own engines, others will pay for licenses to use some of the big-name engines like:

Doing a quick google reveals that Splinter Cell uses the Unreal engine, WoW and Starcraft use proprietary engines, and the GTA series uses Rockstar's own RAGE engine.

---
Tags: architecture, ide
---


# Question
Title: how to get the current location in the map surface - slick 2D
```
@Override
public void mouseMoved(int oldx, int oldy, int newx, int newy) {
  super.mouseMoved(oldx, oldy, newx, newy);
}

```

we can get the mouse location in this method via newx, newy . i want to know is there any such way to get the location in slick2D? when we press the arrow keys and move a image of a man on the game surface(tile map)?

# Answer
> 1 votes
I think you are confusing some concepts..... If you use your **keyboard** to move your player, then you usually store the location of the player's position in the player's object.

If you use your **mouse** to move the player, then you use the location of the mouse on the screen to set the player's position on the game.

So, there is no such thing as *location of keyboard* as there is for *location of mouse pointer*.

In any case, whichever way you update the location of your player, his position is still stored in the object. I.e.

```
class Sprite {
    Point position;
    Texture texture;
}

class Level implements MouseListener, KeyListener {
    Sprite player;
    ...
    void update(...) {
        // THIS IS THE POSITION OF YOUR PLAYER
        //whether you updated it with mouse or keybaord
        Point position = player.getPosition();

        // Do something with this...
    }

    // Update player position using mouse
    public void mouseMoved(int oldx, int oldy, int newx, int newy) {
        player.setPosition(new Point(newx, newy);
    }

    // Update player position using keyboard
    public void keyPressed(int key, char c) {
        if (key == Input.KEY_W) {
            player.getPosition().X += 1;
        } else if (key == Input.KEY_S) {
            player.getPosition().X -= 1;
        } else if (key == Input.KEY_A) {
            player.getPoisition().Y -= 1;
        } else if (key == Input.KEY_D) {
            player.getPosition().Y += 1;
        }
    }
}

```

Hope this helped clear some things...

---
Tags: java, slick
---


title: How to deal with D3DX .dll hell?

text:
# Question
Title: How to deal with D3DX .dll hell?
There's a large number of versions of the D3DX dll, from each SDK update, each version having a unique name (list of D3DX dll names).

All-too-often, people have versions missing. So even though they have a compatible version of DirectX, your D3D-based project won't run on their machine.

I want to be able to distribute games (little spare-time projects, game jam entries, etc) as a simple zip file, without the need for an installer. But a significant percentage of users run into missing D3DX .dll errors. And without an installer, Microsoft's official solution (the DirectX web installer/updater) isn't really much of a solution.

Unfortunately, Microsoft still won't give us the option of static linking to D3DX (which would be a nice clean solution). And avoiding using D3DX isn't very practical, especially if you're working with shaders (and no, I'm not switching to OpenGL, at least for now)

Does anyone have clever solutions to avoiding this DLL hell?

# Answer
> 18 votes
Unfortunately, there isn't a good, legal solution for this except to make an installer, because your hands are tied by the distribution rights granted to you by the DirectX SDK, which provides the D3DX DLLs. Under the terms of the license agreement you are bound to by using the SDK (which is located in `(SDK Install Directory)/Documentation/License Agreements/` you are only permitted to redistribute the binary forms of certain subsets of the SDK, along with some of the sample and utility code.

As of the June 2010 SDK, you allowed to redistribute anything in the "Redist" directory and when doing so you must include certain components (DSetup32.dll, DSetup.dll, DXSetup.exe, DXupdate.cab and dxdllreg\_x86.cab). The Redist directory includes the .cab files for the D3DX DLLs, *but not the DLLs themselves* so you are out of luck.

It isn't terribly hard to build an installer, fortunately, that just runs the appropriate D3DX web installer or whatnot that *is* something you redistribute. Simple .msi installers are just as easy for a user to use (double-clicking is generally all that's needed) and can be configured to allow installation into arbitrary directories, if you are concerned for some reason about "polluting" the Program Files directory with these small throw-away programs. The overhead in download size of an appropriately configured installer can be quite small, as well, so that shouldn't be too much of a problem.

EDIT: Here is a good page about DX installation stuff.

EDIT 2: Struck out the "web" bit in response to a correction in the comments.

# Answer
> 2 votes
Four main solutions spring to mind.

First one is to use an older version of the DirectX SDK. I seem to remember that versions from roundabout 2004 or earlier were statically linked (but if a larger executable size frightens you that might not be an option), and it's also the case that if you use a version from 2006/2007 or earlier then the D3DX DLLs you need will stand a much higher chance on being on the machine. Downside of this is that you'll be missing out on bugfixes, performance enhancements and improved functionality in the newer SDKs (it also rules out any version of D3D other than 9).

Second solution is to use LoadLibrary and GetProcAddress on the D3DX functions. You pick a maximum and minimum supported version (say, from \_42 to \_34), then go into a loop from max to min, construct the DLL name, and attempt to LoadLibrary it. If you load it OK, you then do a bunch of GetProcAddress calls and use your function pointers instead of the raw D3DX functions. Kind of like OpenGL extensions, if you know what I'm talking about. This one's potentially a little hairy, and you might still have to deal with the case where you can't find any DLL in your range. But I have used this one in the past and it works well enough.

Third solution is to just not use D3DX. Might be an option in some cases, might not be an option in your case.

Fourth and final solution is to just tell your users to upgrade their Direct 3D. They really should be doing this anyway, it's a small and fast download from Microsoft, and it's an instant problem solver. Your users may not like to have to do so, and you may have to deal with questions like "I've already got D3D11, why do I need to upgrade my D3D9", but on balance it may work out more economical overall to take it on the nose.

---
Tags: directx
---


# Question
Title: How do we keep ourselves from being sued for unknown patent infringements?
There's breaking news about Zynga being sued over some very obvious implementations. This is making me think that the game industry is full of landmines to be stepped on at every turn. What input does everyone have to minimize the damage?

Latest:
http://www.gamasutra.com/view/news/36657/Zynga\_Sued\_Over\_Prize\_Redemption\_Patents.php

Another example:
https://w2.eff.org/patent/wanted/patent.php?p=sheldon

# Answer
There is no way to write software to avoid infringing patents, period, in the US right now. There are steps you can take to mitigate the problem.

* Get a relationship with a lawyer. They don't have to be on your staff. They don't even have to be on retainer. But scout some out ahead of time and know who you can trust if you do get an infringement notice.
* Don't educate yourself about specific patents in your field unless you intend from the start on licensing them. Knowingly infringing a patent carries more damages than ignorantly infringing one. Whatever you're doing, *it violates patents*; only worry about specificity when it happens.
* Don't build up a defensive patent portfolio. It'll just waste your time and money. The nature of a patent troll is that they own many/broad patents, threaten indiscriminately, and don't actually do anything so won't counter-infringe. The MAD strategy defensive portfolios are based on only works if you're capable of destroying the other company, and the other company is rational. Unless you're EA/Activision/etc you can't do the former, and if you're up against a patent troll you can't count on the later. (There are other reasons to build up patent portfolios, like if you want to inflate your company's perceived value to investors - but this road only leads to your patents being used to troll other people in the future.)
* Don't lose sleep over it. Zynga's getting sued. Would you swap your company's financials with Zynga's despite that? I sure would. They are getting sued because someone wants a piece of that gigantic Zynga pie, not because there's a company somewhere actually disadvantaged because Zynga did not license their patent. If you don't have fat stacks of cash, most of those organizations won't come knocking.

Oh, and

* Don't be a dick and copy someone else's game wholesale and try to undercut them just because it's probably legal. You'll still be a dick. Take good ideas when you find them, but be open and honest about your influences, and make the game you want to make because it's the game you think is important to make, not because it's the game you think you can get away with.
> 31 votes

---
Tags: legal, game-industry
---


title: Data structures in older games

text:
# Question
Title: Data structures in older games
I'm curious about the data structures used when programming older games like Super Mario Brothers for NES and Super Mario World for SNES. My understanding is that games of this period were written in assembly. Did the programmers define/use any data structures?

For example: when a group of coins appears on the screen how are they stored? Did the programmers just use arrays? Or perhaps they had linked-lists?

Cheers!

**Edit**: I'm interested in various approaches... not necessarily a universal approach.

**Edit 2**: In a few of my games I use a (potentially bad) approach towards collections and I want to know if any of the older games used a similar approach. I like to do the following:

```
// statically allocated arrays (max number of coins is 4)
int coinsXs[4] = {0, 0, 0, 0};
int coinsYs[4] = {0, 0, 0, 0};

// bitset that keeps track of which coins are active
int coinsActive = 0;

// ...

// update the active coins in an update function
for(int i = 0; i < 4; i++){
    if(coinsActive & (1 << i)){
        // update ith coin
    }
 }

```

# Answer
Even in the 16-bit days, game consoles were basically just small, embedded computers running realtime software, and the data structures we used are the same ones you'd find anywhere in computer science: arrays, matrices, heaps, trees. Not many linked lists because they're so slow (indirect lookups have a long latency).

The difference is that before the STL, and with performance so critical, we usually had to write the structures and algorithms ourselves!

David Braben did a fun lecture at the 2011 GDC where he talked about all the crazy tricks he used to fit *Elite* onto a BBC Micro in 1984. You can watch it for free at the GDC Vault.
> 13 votes

# Answer
Here is an interesting discussion on GameDev.net for the Super Mario Bros source code: Super Mario source code
> 5 votes

---
Tags: data-structure
---


# Question
Title: How to code the animations of attacks in RPG game
I have an attack class that has the basics like damage and cost and works in the game. Originally I slapped it together to the the ai targeting algorithm so you choose your attack and you see the enemy take damage.

The problem is now I want to animate the attacks I find they don't conform to a single pattern like the other graphics. If you thing of a final fantasy game there is attacks the shoot fire balls so a single image would move across the screen. attacks that are like laser beams so an image would grow as it moves across the screen. attacks the would have things come from the top of the screen is a variety of manners.

I thought of making the class i have now a abstract class with an animation method and deriving several types of attack class from it but im worried about all the extra complexity that would add. I could override the animation method but that would make the attack class huge and waste memory.

Does anyone have any advice on what I can do ?

# Answer
> 1 votes
I asked myself a similar question a while back and here is what I came up with (using a component-based system):

Create an `AnimationFrame` class which only has a duration. When this updates, it updates the time passed. (If you have a `baseObject` class, make sure this derives from it)

Create an `ImageAnimation` class derived from `AnimationFrame`, which has a `SpriteSheet` variable to hold your image, and possibly a `matrix` to resize/crop the spritesheet. When this updates, it draws the image (cropped/resized). It should also `super.update()` to update the time passed.

Create a `SpriteSheetManager` class that can hold `ImageAnimation` objects. When `SpriteSheetManager` updates, it updates the current `ImageAnimation` object - ie the current frame. When the current `ImageAnimation` is done (duration has passed), the manager should move on to the next `ImageAnimation`. You would have to manually add in `ImageAnimations` and specify the image/duration/matrix (or somehow pull it from a data file).

Add the `SpriteSheetManager` to your Player objects, so they update when Players update.

Now if you had a `baseObject` class and your game objects are stored as an array of `baseObjects`, then you can add `SpriteSheetManager` to the game objects so it updates then. This would be useful for large spells that take up the whole screen.

You can also enhance the `ImageAnimation` class (or create a derived class) to handle scrolling images.

Hopefully this could give you some ideas...

# Answer
> 1 votes
Like mentioned above, it really depends on the way you wrote your code. But this seems like a general method that woudn't be too hard to implement:

(Pseudo code)

```
    public class User {

    public void ExecuteAttack(Enemy target, string selectedAttack){

        //calculates damage
        int dmg = (baseDamge * somedamageformula);
        Animation animation = AttackDictionary.getAnimation(name)

        Animator.animateAttack(animation, damage); //executes the animation, might want to show damage number in animation
    }

}

public class battle{

    array enemies;
    array party;
    //etc

    public void ExecuteAttack(PartyMember user, Enemy target){

        user.attack(target, selectedAttack);

    }

    private void animationComplete(e Event){

        nextTurn();
    }

}

public class AttackDictionary{

    enum attacks{

        //long list of all atacks, could be an array an enem or you could collect it from xml or whatevr
    }

    public static void getAnimation(String attackname){

//you could prevent a big switch statement by using xml or a different method that
//allows you to couple info in 1 item (associative array for example)
        switch attacks.attackname{

            case attacks.slash{

                return new slashanimation.png; //return the animation (spritesheet, model etc)
            }
        }

    }
}

```

I'm not saying that this is the best method, this just what I would have done :)

# Answer
> 0 votes
This really depends on how your code is organized, I don't think anyone can give a really good answer to what you should and shouldn't do without knowing your code and style in depth. In any case, it doesn't sound like a problem that is prone to consuming problematic amounts of memory. But it could cause problems for you the programmer to manage because it is a lot of code. So don't worry too much about memory, worry about making something that you can work with.

# Answer
> 0 votes
I suspect this is one of those things that isn't elegant, just involves a lot of code. You can try to come up with reasonable building blocks to create attacks. You can try to generalize things massively. But you may spend more time trying to invent generalization than you would just coding it a dubious way, and there's no way you're accomplishing this without a significant chunk of code.

I'd just start coding new visual effects, either via a branch in your animation method, or via inheritance. Generalize where it makes sense (i.e. it's silly to write "animate fireball hitting enemy" and "animate energy bolt hitting enemy" classes, just write "animate image hitting enemy" and specify the image based on the spell.) As you write more visual effects, look for ways to combine them sensibly into a larger structure. Maybe one will become apparently. Maybe it won't! Maybe it's just annoyingly complex code.

---
Tags: c++, design-patterns
---


# Question
Title: Quaternions and rotation around world axis
Disclaimer: I am a professional games programmer, and use quaternions most days but they are close to black magic to me. I am relatively at home with math but imaginary numbers always confused me. I tend to treat quats as useful and end up reversing multiplications more than once. I try to reason about them like I would with matrices with limited success.

Anyhow....

What baffles me, is the following. When I want to rotate an object around it's local axis I multiply its rotation with the quaternion that represents the rotation I want to apply. It is therefore a rotation in local space.

Now if I want to rotate it around an axis in world space, my reasoning would be: Take the rotation in world space as a quaternion. Multiply the inverse of my object rotation with this quaternion. This will bring my world rotation in local space. Multiply my rotation with this new quaternion. ie: newRot = oldRot * (inverse oldRot * worldRot)

However, what I need to do is newRot = oldRot * (inverse oldRot * worldRot) * oldRot.

Why do I, after multiplying with the inverse quat still need to multiply with my own quat before applying it? I know there must be a perfect valid reason, but I can't reason my way out of it and it's frustrating as heck to me. I tried the various faqs and whatnot, but most go to deep in the math, making it less clear to me.

Anyone who can explain this to me like I'm a 5 year old?

# Answer
Quaternions are associative:

you mention that your solution is:

```
newRot = oldRot * (inverse oldRot * worldRot) * oldRot

```

which is the same as:

```
newRot = oldRot * inverse oldRot * worldRot * oldRot

```

which is the same as:

```
newRot = identity * worldRot * oldRot
newRot = worldRot * oldRot

```

which actually brings you back to what's really happening:

```
localTransformed = oldRot * rot
worldTransformed = rot * oldRot

```

The order of application is changing, that is all. Going back to matrices, when you apply an object matrix to a transform matrix and store that as your new object matrix, that's your local space transformation. When you apply the transform matrix to the object matrix and store that, that's you world transformation. It's all about the order of application and nothing more.
> 15 votes

---
Tags: quaternion
---


# Question
Title: Efficient Method of Rendering Massive Terrain in XNA
I'm creating an XNA game that requires a huge space for players. Currently, the test heightmap I'm using is 4096x4096, and is saved as a 4-bit BMP.

What I'm trying to do is take that huge heightmap file and render it in the game. The problem I'm running into is the fact that it's inefficient to load the entire terrain into memory at once, as it will use majority of available memory.

Another problem I've run into is that I cannot render the terrain all in one primitive because of a hard-limit set within XNA.

With that said, I've come across a number of solutions, all of which I have listed below:

* Rendering based on the current user's location - basically drawing a square around the user no matter their orientation within the world. This isn't exactly what I wanted either, because you're still rendering space that the user does not see.
* Rendering based on the user's orientation and position - I found a formula to retrieve a triangle that is supposed to have what pixels of the heightmap are supposed to be rendered, but this proved to be very difficult.
* Splitting the terrain into multiple chunks and rendering which ones are closest to the user - Still not very efficient as you're still rendering chunks that people won't see. And it's work-intensive because then I have to split my heightmap into several pieces, and scalability becomes a large problem.

After trying those solutions, I'm fresh out of ideas for what to do. I've received some answers where people are telling me to do these complex algorithms, but I simply have no idea even how to approach doing them.

So basically I'm asking for a simple, straightforward way of rendering humongous terrains in XNA with utmost efficiency.

I'm rather new to game development in general, but I am willing to research if it seems promising.

**Update 1:** After researching the geoclipmapping method, I started to code with that. I have all the math done, and the game runs. However, it is extremely inefficient - which is probably bad coding on my part. It runs at 2FPS and uses an entire core of my CPU. I'm going to try and improve the code, but I think I'll need more help, so here is a Pastebin of the code for the Terrain manager class. I'll post back with more results later if I ever get it to be more efficient.

# Answer
The chunks approach is typically what is used. Rarely is it efficient to test every triangle out of hundreds of thousands to see if you should be rendering it. Instead most terrain rendering algorithms employ a *spatial data structure* to dynamically render the visible parts of the terrain.

An easy to implement data structure is called a quadtree. In short, to use a quadtree you would find the player's viewing frustum, intersect it against the top level of the quadtree, and for any chunks that are partially viewable (ie, the frustum planes intersect the chunk) you subdivide and test all the children chunks, omitting ones outside the frustum. This will give a pretty close approximation to the actual visible geometry with only a few levels of recursion.

More advanced terrain renderers use an algorithm to tune not only the viewable geometry but the detail of that geometry as well. Geomipmapping (and its relative geoclipmapping) is relatively popular at the moment for doing that but isn't a trivial thing to implement.

**edit:** Here is a decent description of both geoclipmapping and the frustum culling.

I also have some doubt as to whether 4 bits for the heightmap is actually enough to produce a nice looking terrain unless you're doing a lot of smoothing on the result.
> 5 votes

# Answer
Any approach that requires you to do per-frame work to load data onto the GPU is going to be flawed.

Here's a rough outline of one approach that should perform well:

You should be dividing your terrain up into (fairly large) chunks, loading those chunks into fixed vertex buffers (the bit-depth of your height-map doesn't matter!). Those vertex buffers will simply sit in GPU memory, waiting to be rendered. You'll have to experiment with what is an appropriate chunk size, but 128x128 is perhaps a good place to start.

For a 4096x4096 terrain you're a little bit beyond the limit of what I'd be comfortable loading onto the GPU at once - it's probably a few hundred MB of vertex data (although you could get it down to ~64MB if you're clever). So you may have to load and unload vertex buffers from the GPU in the background.

(If you implement background loading of chunks, this should be extremely scalable!)

*After* you have the vertex data on the GPU it is an appropriate time to do visibility culling on a *per-chunk* basis. There is no need to send the command to render a chunk, if you know it's behind the camera.

**You should almost never be doing *per-triangle* culling on the CPU!**

The GPU will cull triangles that are off-screen *much* faster than you'll ever be able to.

For more information about performance, take a look at this answer over on the Game Dev site.
> 3 votes

# Answer
I'm not an expert at XNA by any means so please correct me if I am wrong but I was under the impression that there is actually built in optimization for situations like this. I know you are able to set a render distance and after that point it does not render anything, in your case it would be the remaining terrain. However this leaves a fairly unattractive edge to your rendered world, so you would have to implement something like fogging that most open world games have.
> 0 votes

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


# Question
Title: Component entity system - Updates and call orders
In order to get components to be able to update **every frame** (and leave this functionality out of components that don't need to) I got the idea to make an UpdateComponent component. Other components like `MovableComponent` (which holds velocity) would inherit from the `IUpdatable` abstract class. This forces `MovableComponent` to implement an `Update(gametime dt)` method and another `RegisterWithUpdater()` that gives `UpdateComponent` a pointer to the `MovableComponent`. Many components could do this and then `UpdateComponent` could call all of their `Update(gametime dt)` methods without having to care about who or what they are.

My questions are:

1. Does this seem like anything that is normal or used by anyone? I cannot find anything on the subject.
2. How could I maintain an order to the components like physics then position change? Is this even necessary?
3. What are other ways of insuring that components that should be process every frame are in fact processed?

**EDIT**
I think I will be concidering how to give the entity manager a list of types that are updatable. Then ALL of the components of that type can update rather than managing it per entity (which are just indexes in my system anyway).

Still. My questions remain valid to me. I don't know if this is reasonabl/normal, or what others tend to do.

Also, the people at Insomniac are awesome! **/EDIT**

Boiled down code for previous example:

```
class IUpdatable
{
public:
    virtual void Update(float dt) = 0;
protected:
    virtual void RegisterAsUpdatable() = 0;
};

class Component
{
    ...
};

class MovableComponent: public Component, public IUpdatable
{
public:
    ...
    virtual void Update(float dt);
private:
    ...
    virtual void RegisterWithUpdater();
};

class UpdateComponent: public Component
{
public:
    ...
    void UpdateAll();
    void RegisterUpdatable(Component* component);
    void RemoveUpdatable(Component* component);
private:
    ...
    std::set<Component*> updatables_;
};

```

# Answer
> 16 votes
One of the primary benefits of a component system is the ability to take advantage of caching patterns - good icache and prediction because you run the same code over and over, good dcache because you can allocate the objects in homogeneous pools and because the vtables, if any, stay hot.

The way you have structured your components, this advantage disappears completely, and in fact can become a performance liability compared to an inheritance-based system, as you're making far more virtual calls and more objects with vtables.

What you should be doing is storing pools per type, and iterating each type independently to perform updates.

> Does this seem like anything that is normal or used by anyone? I cannot find anything on the subject.

It's not as common in large games because it is not advantageous. It's common in plenty of games, but it's not technically interesting, so no one writes about it.

> How could I maintain an order to the components like physics then position change? Is this even necessary?

Code in languages like C++ has a natural way to order execution: type the statements in that order.

```
for (PhysicsComponent *c : physics_components)
    c->update(dt);
for (PositionComponent *c : position_components)
    c->update(dt);

```

In reality, that doesn't make sense because no robust physics system is structured that way - you can't update one single physics object. Instead, the code would look more like:

```
physics_step();
for (PositionComponent *c : position_components)
    c->update(dt);
// Updates the position data from the physics data.

```

# Answer
> 3 votes
What you're talking about is reasonable and fairly common, I think. This might give you some more information.

# Answer
> 0 votes
I like these approaches:

Shortly: Avoid keeping update behavior within components. Components **are not** behavior. Behavior (including updates) can be implemented in some single-instance subsystems. That approach might also help to batch-process similar behaviors for multiple components (maybe using parallel\_for or SIMD instructions on component data).

The IUpdatable idea and Update(gametime dt) method seems a bit too restrictive and introduces additional depencencies. It might be fine if you are not using subsystems approach, but if you do use them, then IUpdatable is a redundant level of hierarchy. After all, the MovingSystem should know that it must update the Location and/or Velocity components directly for all entities which have these components, so there is no need for some intermediate IUpdatable component.

But you could use Updatable component as a mechanism to skip updating some entities despite of them having Location and/or Velocity components. The Updatable component could have a bool flag which can be set to `false` and that would signal every Updatable-aware subsystem that this particular entity currently should not be updated (although in such context, Freezable seems to be more appropriate name for the component).

---
Tags: c++, component-based, entity-system
---


title: deciding user movement path - slick 2D

text:
# Question
Title: deciding user movement path - slick 2D
i'm going to describe what need to be done... "there are circular areas marked in a map, large areas a person can easily move in to them and out of them" what i'm trying to do is deciding weather the person is moving in to or moving out of that circular area. i can get the user location and see weather it falls inside the circle(weather the person is inside the circle) by pure mathematics theories(theories of circle), but how can we decide weather the person in moving in to the circle or moving out of the circle? please give me some advice guys?

# Answer
> 3 votes
You can do this by using the dot product of the velocity of your player.

First, you need to store your player's velocity and use it to update his position. Then, for each trigger in your level you will test if the user is moving towards the center of the trigger (using the dot product between the velocity and the trigger):

```
Sprite {
    Point position;
    Point velocity;
    Texture texture;
}

class Level implements MouseListener, KeyListener {
    Sprite player;
    List<LevelTrigger> triggers;
    ...
    void update(double deltaTime) {
        //Update player's position
        player.getPosition().X += player.getVelocity().X * SPEED * deltaTime;
        player.getPosition().Y += player.getVelocity().Y * SPEED * deltaTime;

        // Get player velocity and normalize its components
        Point velocity = player.getVelocity();
        velocity = velocity.normalize();
        for (LevelTrigger trigger : triggers) {
            // Get a vector that points to the trigger's center
            Point raycast = trigger.getCenter().substract(velocity);
            // Get the angle between the raycast and the velocity
            double angle = Math.acos(velocity.dot(reycast));
            // The narrower the angle, the more "focused" his moving view is
            if (angle < 30 && raycast.length() < 10) {
                trigger.fireIsArriving();
            }
        }
    }

    // Update player position using mouse
    public void mouseMoved(int oldx, int oldy, int newx, int newy) {
        Point newVelocity = new Point(newx, newy).normalize();
        player.setVelocity(newVelocity);
    }

    // Update player position using keyboard
    public void keyPressed(int key, char c) {
        if (key == Input.KEY_W) {
            player.getVelocity().X += 1;
        } else if (key == Input.KEY_S) {
            player.getVelocity().X -= 1;
        } else if (key == Input.KEY_A) {
            player.getVelocity().Y -= 1;
        } else if (key == Input.KEY_D) {
            player.getVelocity().Y += 1;
        }
    }
}

```

# Answer
> 1 votes
Store the position of the person at this frame and the position of the person at the last frame.

Measure the distance to the circle center at this frame, and the distance to the circle center at the last frame.

If the distance to the circle center at this frame is less than at the last frame, then the person is moving toward the circle, otherwise the person is moving away from the circle.

---
Tags: java, slick
---


# Question
Title: Some practical issues with component-based game object systems
I am creating my own game engine just for fun and brain development. I have chosen various free and open-source libraries to integrate and now I have come to the engine architecture.

I intend to use server-client architecture and I prefer to be more "data-driven" so I can organize my game state in MySQL database. I recently read about a component based design which plays nicely with data-driven systems. The idea is that game object components are bare properties and the behavior is implemented in so-called subsystems. Each subsystem (like Physics, Render, Animation, Sound) "knows" only about related components and also is able to tie itself to other systems if needed. Those subsystems are singletons (single instances).

I can use the observer pattern so each subsystem can subscribe to property changes which are important for the particular subsystem. The subsystems subscribe to prop change events in some particular order thus creating subscription chains. But this can create one problem: SystemA detected change in propA and needed to change some propB, but SystemX is listening to propB changes and affects propA .. and we have an infinite loop. **Is this a common weakness of such systems or I have wrong implementation ideas?**

The last system in the subscription chain could be the NetworkSystem, which sends out a small package on every subscribed property change ... **or it is a bad idea and I should pack more changes together?**.

I guess, rendering and physics will be separate threads where RenderSystem (client-side only) is polling the entities for their properties which have changed since last frame and PhysicsSystem is modyfing properties on each iteration; InputSystem (client-side only) and NetworkSystem also are modifying properties and WorldClockSystem could modify some properties on timer events.

But the major problem is when I think how to implement custom scripting in such systems. Let's say, users are allowed to upload their custom logic and animation script called Respect which has one property called goodDeeds with a rule "if a person with goodDeeds\>100 passes by, I run some RespectAnimation". So I would install a global RespectSystem which subscribes to position changes of every character and checks for the Respect component and goodDeeds property and then somehow tells to Animation system to run Respect animation on this object. **Is this the way it is supposed to work, isn't it dangerous that the behavior now is a global object and not a property of the entity which uses it?** If I think again about the problem of neverending loops of observed/modified properties, it means that one wrong xxxSystem script could stall the entire server (but from the other hand, the admin of the server should have enough sanity to see such problems before allowing the user to upload that script).

Anyway, it would be great to find some book or article which better describes how to use component-based systems where components are properties and behavior are singletons, but somehow all articles I have read, explain only the idea itself but not how to attach it to a real game engine with scripting and networking.

# Answer
> Is this a common weakness of such systems or I have wrong implementation ideas?

It's not a weakness in the system, but a weakness in your game logic. If the value of propA depends on propB and probB depends on propA then you have cyclic dependencies. It doesn't matter what system you use, this can't work.

Of course, it could happen by accident, but it's easy to detect cyclic dependencies, so you can provide diagnostics in those cases.

Do you have a particular example of where you think this might happen, or are you just thinking ahead?

> ... or it is a bad idea and I should pack more changes together?.

Generally, you want to pack things together as much as possible in a network situation because each packet will necessarily have some overhead.

Also, sending property changes across the network isn't going to work in the general case. There are many approaches to networking games, and each approach is designed for particular types of games, and won't work in others. For example, sending the property changes of each unit in an RTS game is simply not going to work. There are no silver bullets in game networking -- it needs to be designed on a per-game basis.

> Is this the way it is supposed to work, isn't it dangerous that the behavior now is a global object and not a property of the entity which uses it?

Why does it have to be a global object?

If you allow users to upload scripts then you basically need to be **very** careful with what you allow. If you allow arbitrary scripts then they will need to be run in a VM where you can limit their resource usage. You would probably be better off with a more restricted "scripting" system where you only have control over a very specific subset of the game behaviour (e.g. pre-define a set of triggers and behaviours, but allow the users to combine them in any way they like, but design the triggers so that nothing bad can happen).
> 5 votes

---
Tags: networking, component-based, scripting
---


# Question
Title: Rendering multiple RenderTargets to the screen
Let's say I have a background and a set of entities.
I have managed to draw the background into a Texture2D using a RenderTarget
I have also managed to draw all my entities into another RenderTarget

Now I want to take these two Textures and render them on the screen as so:

```
// Top-level rendering
entitiesSystem.Process();
background.Process();
Texture2D entitiesTexture = entitiesSystem.EntitiesTexture;
Texture2D backgroundTexture = background.BackgroundTexture;

graphicsDevice.SetRenderTarget(null);
graphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
spriteBatch.Draw(
    backgroundTexture,
    LevelManager.LEVEL_RECTANGLE,
    null,
    Color.White,
    0.0f,
    Vector2.Zero,
    SpriteEffects.None,
    1
);
spriteBatch.Draw(
    entitiesTexture,
    LevelManager.LEVEL_RECTANGLE,
    null,
    Color.White,
    0.0f,
    Vector2.Zero,
    SpriteEffects.None,
    0
);
spriteBatch.End();

```

Here is how the background system renders the background:

```
graphicsDevice.SetRenderTarget(BackgroundTexture);
spriteBatch.Begin();
for (int i = 0; i < 2; i++)
    spriteBatch.Draw(textures[i], positions[i], Color.White);
spriteBatch.End();

```

Almost the same thing happens for the entities: I set the render target to the relevant one (not the same as the one for the background), start the spritebatch (again, not the same one), draw the entities and end the spritebatch.

If I set BlendMode to additive, the result is correct (they blend together). However, if I set to to AlphaBlend, then I can only render one of them (depending on the SpriteSortMode).

I have come as far as understanding that the problem lies in not preserving... something, but I am not sure how to preserve it :P

By the way, I read that multiple render targets are not supported for the XBOX... Soooooooo... what is the alternative of doing what I am doing now?

# Answer
Is your entities texture created with a format that has an alpha channel, and cleared to transparent before use?
> 1 votes

# Answer
In my 2D XNA-based game, I have multiple layers like this too. I just draw the background, then draw the foreground. Using multiple render targets is often reserved for special effects and taking screenshots. Here is some doc on multiple render targets: http://msdn.microsoft.com/en-us/library/bb975911%28XNAGameStudio.31%29.aspx#ID4E4F
> 0 votes

# Answer
Setting a render target will clear it by default, as this is the only fast path on Xbox 360.

You can adjust this by setting the appropriate `RenderTargetUsage`.

See this blog post for details.
> 0 votes

---
Tags: xna, rendering
---


# Question
Title: Obstacle Avoidance or Wall Avoidance for Tiles ?
I have a enemy in my game that is supposed to chase the player around the world and I thought it be a good idea for the enemy not to pass through the walls like a ghost, the levels are tile based, I've initially gone with the wall avoidance since a tile is essentially four lines, but I'm beginning second guessing the idea.

So should I go with Wall Avoidance Steering Behavior or Obstacle Avoidance Behavior ?

# Answer
> 6 votes
Pure obstacle avoidance algorithms in situations like this will create incredibly odd-looking behavior. For example, the creature will look like it's drunk when it's wiggling around some static obstacle in the middle of the way. Or it might take a very long route to get around some obstacles when going around the other way would've taken the enemy a tenth of the time to get to you.

It can also introduce some bugs. For example, if you mark your blocking tiles as obstacles and let the enemies steer away from them based on both distance to the obstacle and distance to you (both in terms of magnitude as well as direction), you might get a situation like this, where the algorithm will make the enemy walk away from the player instead of towards him or where the creature simply may get stuck:

Or your enemy looks like a dumbass:

(or like a cheater if it simply pushes through the small passage :P)

These are pretty dumb examples since it assumes that your avoidance algorithm is very simple (and stupid), but these kinds of scenarios occur sometimes, no matter what kind of algorithm for steering or avoidance you use.

The reason for this is that the enemy has no "whole path"-information, which means that while its current decision based upon the currently relevant obstacle may be correct, it may push him into a state towards the next obstacle where this kind of equilibrium or false decision behavior occurs.

There are probably weird things that you can incorporate into your avoidance algorithm which minimizes these scenarios or makes them go away completely, but I can't help but think that this is ugly.

Instead, just use a regular path finding algorithm like A\* to search a path towards your character. Especially in tile-based games, where the cost between nodes (your tiles) usually stays constant, that kind of algorithm is an easy choice.

A\* is usually pretty costly if you want to recalculate the path at every frame, but as long as it stays simple (just a couple of enemies) this shouldn't be a problem at all (processors are **fast**).

You can also opt to only update the path every couple of frames or so since the player won't notice it if the path was calculated once or twice in those 60 frames during the last second.

By the way, if you look for some good explanation for the A\* algorithm, I can really recommend the chapter on it in Game Programming Gems 1 (3.3 to 3.5). The book may be hard (or expensive) to come by (it's been a while, but when I searched for it a while ago it was pretty expensive if you wanted to buy it new), but it's worth the money.

# Answer
> 1 votes
You should get Programming Game AI by Example

Yes, steering behaviours are easy to implement, but the seek/pursuit behaviour only works as a decent "hunting" behaviour when there are no obstacles between the player and the enemy. If there are obstacles or walls, then you're pretty much screwed in most situations.

You should seriously consider using A\* to generate a path between the enemy and the player. It's not a very difficult algorithm to implement and there are countless examples on the internet. If by "realism" you mean you don't want your enemy to rigidly follow a list of points on a path, that's absolutely fine. Just seek to each point in the path. It will still give a realistic looking hunting motion without getting stuck anywhere.

That being said, your implementation of the wall avoidance algorithm should not be causing you that much hassle if you know how to get it working with lines. Your agent should have a feeler extending from its front that intersects with the line and you can calculate the repulsion force from:

Force = Penetration Depth of Feeler x Wall Normal

Regardless of your wall being a tile (assuming a tile here means a square or rectangle), each side of the tile will have a normal and this combined with the feeler is the key to getting wall avoidance right.

Buckland's implementation of Obstacle Avoidance created two more "feelers" for the agent heading forward-left and forward-right of the agent. When any three of the feelers intersects and object the appropriate repulsion force is calculated and applied to the agent.

***TL;DR*** \- Use A\*! Wall Avoidance is the same whether you're using a single line or a square/rectangle/hexagon. Each side of the shape has a normal.

---
Tags: ai
---


# Question
Title: What's the difference with how Box2D and Farseer behave in terms of collisions?
I've ported my engine to iOS and have been using the C++ version of Box2D. Everything runs fine except on collisions, it seems Box2D and Farseer handle collisions somewhat differently.

Anyone know what these differences are exactly and if I can disable the difference and make them mimic one another?

Initial behaviours tend to be fine, for example falling speeds and the first moment of impact both cases exhibit the exact same behaviour, velocities etc.

Just after the first impact is resolved however the second impact (which occurs as a result of bodies being bumped around) is different. box2d records a higher velocity on a second collision than the first and shows less 'bounce back' from the collision.

Velocity, position iterations are the same, as are the bodies masses, densities etc. Pretty sure everything in Farseer.Settings matches up with Box2Ds settings.

# Answer
You cannot really expect two different physics engines to get binary identical results. They all do their computations differently, and thus they will come up with different results.
> 1 votes

---
Tags: iphone, box2d, windows-phone-7, farseer-physics-engine, porting
---


title: Bouncing effect in Farseer WP7

text:
# Question
Title: Bouncing effect in Farseer WP7
I'm not quite sure what I need to do, but I have a ball falling from the sky and it needs to bounce when it hits an object. Do I configure the ball in some way or do I need to setup a spring object or possibly do something on collision?

# Answer
I figured it out. Requires a bit of tweaking but it works as I expect.

```
Body ball1 = PrefabBodtFactory.CreateBody(PrefabType.Ball, _world, new Vector2(3.8f, -0.75f));
            ball1.CreateFixture(new CircleShape(0.25f, 0.5f));
            ball1.FixtureList[0].Restitution = 1f;
            ball1.ApplyLinearImpulse(new Vector2(0.1f, 0));
            _bodies.Add(ball1);

```
> 1 votes

---
Tags: windows-phone-7, farseer-physics-engine
---