# Question
Title: Problem with impulses in my physics engine
I'm currently developing a small 3D impulse-based physic engine for a CS project. It uses GJK for collision detection and is kind of stable at the moment. Nevertheless, I'm not satisfied with my collision response as rigid bodies appear to gain more and more momentum with each bounce, although only under some configurations.

I use *Newton’s Law of Restitution* (pictured immediately below) for instantaneous collisions with no friction. I checked this formula again and again, and I also checked if the magnitude of the contact normal is 1, and all seems fine. The direction of the bounce and the induced rotation are convincing but the impulse is just sometimes too strong.

I think my problem may lie within the impulse application part; in my mind, the impulse is the force necessary to separate two touching points of two bodies plus a certain magnitude depending on the coefficient of restitution (0.7 in my tests). I compute an impulse for each detected contact point and apply it at the contact position.

For example if a cube falls right to the floor, there will be 4 impulses, each one at a vertex of the bottom face of the cube. For each of the four contacts, I do something like this:

```
J = computeImpulse(contact)
A.applyImpulse(J, contact.pos)
B.applyImpulse(-J, contact.pos)

```

I'm a bit confused. Is this the correct approach, or should I apply half of the impulse to each body? Or, should I rather apply a fraction of the impulse depending of the mass of the bodies? Or, is the problem just somewhere else (e.g., in the formula)?

I don't know if someone has an easy answer for me, as it's a rather specific problem, but thank you for your help. :)

# Answer
As you already suggested, you have to take the mass of the objects into account to calculate the change of velocity caused by the impulse. Namely, divide the impulse by the mass for each object.

You can find this and much more information in this paper "Impulse-based Dynamic Simulation of Rigid Body Systems" from Brian Vincent Mirtich.

Page 60 shows it in detail:

```
p       -> impulse
delta_v -> change of velocity caused by the impulse
m       -> mass

     p(t)       = m * delta_v(t)
so:  delta_v(t) = p(t) / m

```

Here is another paper about it called "A Real-time Capable Impulse-based Collision Response Algorithm for Rigid Body Dynamics" from Florian Schornbaum. You can find that calculation at Page 23.
> 6 votes

---
Tags: physics, physics-engine
---


# Question
Title: How do I get the seed of a randomly generated level?
I intend to use the Mersenne twister to generate a level using a seed , but I also want to make fixed levels, so for now I'm using XML to store data of the level (~40 numbers).

However, it would be awesome if I could get the seed of a specific level by reversing the process.

I guess if I used my own pseudo-random number generator I possibly could do it, but my question is can I do it with the Mersenne twister?

Here is an example of what I want to do:

If the seed `1234` gives output `25 65 78 01`, can I get the seed 1234 knowing only the generated output?

Thanks in advance! (For those who wonder why I'd want to do this; my XML parsing is a lot slower than generating a level, plus XML files are bigger than seed numbers.)

# Answer
No, you cannot get a seed for a sequence of numbers that you have created yourself. You could possibly get a seed from a sequence of generated numbers by brute force.

Coincidentally, in the infinite monkeys writing Shakespeare way, if you used large enough seed numbers, you probably *could* find a seed that generates your sequence, but linearly searching for one specific number in the range of (potentially) a 256bit or greater integer is not possible in a real time.

I do not see why you are needing to store 40 numbers in an XML file. Why not use a text file? Heck, why not hardcode them into an array?
> 9 votes

# Answer
In general, no, you can't do that. Random number generators are one way functions from the current seed to the value.

A simple thought experiment should clarify why you can't do this. Say you're using your random number generator to generate the numbers for a level like `25 65 78 01`. Lets say your seed is a four digit number and each of those levels is a two digit number. Given that, there's 100,000,000 possible different levels but only 10,000 different seeds. Obviously each level can't have its own unique seed then, there aren't enough to go around.
> 1 votes

# Answer
In case this wasn't obvious from @Communists' answer: there is no reason every level needs to be stored in the same format.

If you want to store your hand-made levels by storing every detail, but store your randomly-generated levels by only storing the seed, that's fine. Just add a parameter in the level-file describing which it is eg. `<level type="random" seedvalue="1234567890">`
> 0 votes

---
Tags: random, procedural-generation
---


title: Creating addons for any game?

text:
# Question
Title: Creating addons for any game?
I want to be able to create addons for any game, the example I will use is League of Legends. With addons I mean, for example when my level integer changes I want to play a sound in the background.

The programming language I want to use is C#.

What I want to know is how I'm able to read my level integer inside C#, from there on I should be able to do anything I want.

What I've found out is, with a program like Cheat Engine you can look for memory values and adresses inside your RAM. And I think there is a way to assign a variable in C# to the value of a memory adress. But how can I find the value of my level in the first place? The memory adress might change each time I start the game or even level up. I think it has something to do with pointers, but where do I find the pointer?

But the biggest problem is that I can't even find some values I look for iside the memory. Maybe it encrypts the values? How can I find out what it does and where it puts it? An example is Flash games. If you look for the variable money that has a value of 100 you need to multiply it by 8 and look for 800 iside the memory of that process.

* How do I find the correct memory adress each time?
* How do I find out the way it might save a variable?

I'll give any extra information about the problem if you want.

# Answer
> 8 votes
You can do this in C#, but you'll likely need to P/Invoke a lot of the functionality you'd need. C or C++ is probably more well-suited to the task -- you'll have fewer hoops to jump through. There are a few open source "cheat engine" projects out there you can look at for a better idea of what you're going to have to do.

> How do I find the correct memory adress each time?

Mostly through trial and error. A *lot* of trial and error. Once you've found it the first time, you may be able to rely on the fact that it will be located at a fixed offset from the load address of the program, but this will only be true for a very small subset of the data manipulated by any given program. You will likely need to relocate the variable in memory every time.

> How do I find out the way it might save a variable?

By reading the disassembled machine code of the program, you may eventually be able to locate how it modifies a particular variable. This will be extremely tedious.

I think you are biting off way more than you can chew here, but the basic (naive) premise here is that you have to scan the process memory for a value that matches the one you are after -- if you have 100 hit points, you start walking the entire thing looking for values of 100 (as 8, 16 and 32 bit values) and keeping track of the addresses you find. Once you have that initial set, you change the value you are looking for -- get hit, for example, so you now have 94 hit points. Then you scan the addresses you found before to see which ones are now 94. You can eventually narrow down the address in question this way.

Of course this doesn't always work; sometimes you'll only find a display value and not the real representation of health (which may be stored as a float from 0 to 1 instead of an integer from 1 to 100) in which case modifying that integer won't really impact game play at all -- you'd still die, you'd just have a full health meter when you did so. Games and technology vary wildly, and what works for one will usually not work for others.

This is generally a very complex topic and the above is only a very naive, superficial overview. Practically speaking you're probably much better off simply *using* an existing tool or contributing to an open source project oriented at making one, because the way you've phrased your question honestly makes it sound like you aren't ready for this kind of project.

# Answer
> 1 votes
I've found the answer myself, excuse me for such a hesitant post.

To find a static memory address you can use Cheat Engine. Scan for your health variable, right-click it and press Pointer scan for this address. A pointer basically points to another memory address that might hold a useful value. It is possible that you have a multilevel pointer, a pointer to a pointer to a pointer to a pointer to your health variable. This scan will look for all memory addresses that have the value of your variables address. This list can be gigantic when finished scanning, therefore you must close and reopen your game, look for your health variable again and open your old pointer scan results. Now you need to rescan the pointers with the new memory address of your health, each time you do this cycle your list will get narrower and narrower until you get an accurate base pointer that is always correct.

If the memory values are 'encrypted', for example flash player multiplies your variable by 8 before putting it into memory and divides it when utilising it. In order to find your variables and base pointers you can use Cheat Engine scanning methods to scan for Unknown initial value. Lose some health in the game and look for decreased values, heal in the game and look for increased value. Repeat this cycle until you get an accurate result. Now you can find out the ratio between the health value displayed in the game and the value you have found in Cheat Engine.

I've been able to read my League of Legends Health, maxHealth and Level variables since yesterday. I've learned a lot and for what I'm aiming for I will have to learn A LOT more.

Thanks for trying to help me anyway, everyone!

# Answer
> 0 votes
The question you want an answer to is inherently unanswerable ... at least in this format. You want to start poking around in the memory, which, with most modern programs can be an exercise in futility when you take into account garbage collection and memory defragmenting algorithms. That means that values will shift around in memory, and only the program itself will know the value addresses.

Without modifying the program, you probably won't be able to do what you're looking for.

---
Tags: c#, platformer, memory-efficiency
---


title: How do I use Ogre with CodeBlocks?

text:
# Question
Title: How do I use Ogre with CodeBlocks?
I want to start writing games using ogre in combination with the CodeBlocks compiler but am struggling with the installation. I got the latest version of the compiler as well as the ogre engine from their respective websites. I have installed the compiler but cannot find my way in the integration of ogre though I read their installation guide, which I found confusing.I need clear step by step guide please.

# Answer
> 2 votes
Here is a step by step installation guide

---
Tags: ogre
---


title: Can you make a 3d game in eclipse java?

text:
# Question
Title: Can you make a 3d game in eclipse java?
Hello can you make a 3d game like minecraft using java?

# Answer
Yes. You can create a 3D game like Minecraft in Java using Eclipse as your source code editor, but that's not all you'll need...

An MMORPG will require a lot of work (MMORPGs aren't known to be small projects), so you'll need a variety of tools for other aspects of the project:

* graphics editors for various graphics (e.g., logo for the game)
* 3D modeling tools (to create/modify 3D graphics)
* word processor for the planning documents (a detailed plan is highly recommended)
* word processor for writing story-lines (assuming there is at least one story-line)
* word processor for documentation (your users will want some documentation)
* web site development/maintenance tools (assuming there will be a web site)
* accounting software (if your users need to pay for anything)
* database management tools (you need to save user data and game state at the very least)

(If I've missed some important tools: Please make mention of each tool {and its use}, each in a separate comment {if nobody else has}, and I will likely *upvote* it.)
> 4 votes

---
Tags: java, 3d, software-engineering
---


# Question
Title: XNA, SpriteBatch: Slow when rendering lots of sprites?
I've just now tested rendering a lot of sprites using XNA's SpriteBatch class. What I basically do is this:

Somewhere in the code, I have a list which contains all sprites that have to be rendered. I prefilled this list with **2500** Sprites, all of which have the same rotational angle, texture, position etc.

I then draw them like this:

```
    spriteBatch.Begin();
    foreach (Sprite spr in sprites)
        spriteBatch.Draw(spr.Texture, spr.Position+spr.Center, spr.SourceRect, spr.Color,MathHelper.ToRadians( spr.Rotation ), spr.Center, spr.Scale, SpriteEffects.None, spr.Depth);

    spriteBatch.End();

```

and I'm getting really poor performance. I only average about 15FPS with my Radeon HD 6850 graphics card and i5 2500k CPU.

This is **very** surprising to me, since I average about 70 FPS doing exactly the same thing with my own custom OpenGL engine, which uses old OpenGL rendering (meaning one draw call for every single sprite). I actually expected XNAs rendering to be a ton faster, since it draws everything in one draw call.

Am I rendering this the wrong way? Playing around with SpriteSortMode settings has made almost no difference, some of them just make it a tiny bit slower (depth sorting etc.).

# Answer
I am not sure, but I think you have each sprite with an instance of its own texture. Meaning instead of doing 1 sprite batch, you are doing 2500 sprite batches. Try replacing spr.Texture with a single local Texture instance.

Also you do arithmetic and call functions from inside the spritebatch function call, which could slow it down more. Try to have all your calculations done somewhere else, and try to store the rotations in the correct format instead of what you are doing.
> 6 votes

# Answer
Take a look at this question and answer: **Optimizing an XNA 2D game**.

I would guess you are either hitting a fill/texture-fetch limit (a GPU limit) or a batch limit (a CPU limit, as described in that linked answer).

Try setting the position of all of your sprites off-screen, and seeing if it makes it faster. If it does, you're hitting a fill limit. You need to reduce the amount of over-draw or simply reduce the amount of stuff you're drawing.

If you're hitting the batch limit, then `SpriteSortMode.Texture` is likely to give you an enormous speed-up. If you cannot use this as a real-world solution, then the correct solution is to use sprite-sheets to reduce texture swaps. (Of course, if you're only using one texture already, or your textures are pre-sorted, then this won't help.)

I *seriously* doubt the maths operations are dominating your CPU usage. There are faster alternatives to the `+` operator and `ToRadians`, but it's not like these are slow! (If you're accessing each sprite's information through properties - each property access has the *same* overhead - you'd be better off switching to fields rather inlining those functions.)

One thing that might be eating your performance is *cache coherence*. If each `Sprite` is a reference type (ie: `class`), then you're likely suffering a huge number of cache misses as you loop through them. Try making `sprites` an array of value types (ie: `struct`). (see this answer)

A possible worst-case is if they are already value types and you're accessing them through an interface - in that case you're doing an *epic* amount of boxing (slow and allocates memory).

(Of course, there could be other things wrong, but that's all I can think of at the moment based on what you've posted.)
> 9 votes

# Answer
About XNA sprite sheet example: https://stackoverflow.com/questions/726921/recommend-sprite-size-for-games-xna

This also may be usefull to you.
> 1 votes

---
Tags: xna
---


# Question
Title: Do any of the current gen console or handheld compilers support C++11?
I am not asking for full support but do any of the current gen support C++11? I know VS C++ supports lambda and the auto keyword and I believe gcc supports both as well. Do any of the current gen consoles or handheld (3ds, sony vita) support it?

# Answer
Most of the major gaming consoles do not have public development kits, and forbid sharing much information about the underlying SDKs. They do tend to trail a few years behind other platforms for cost and stability reasons. If you have development kits for these consoles or the resources to get them, you should be able to contact your licensor for details on C++0x support.

So I can't answer for any of the major gaming consoles, but perhaps more important for independent development, the iOS toolchain does not. Xcode is still based on GCC 4.2, and they're moving forward by switching to Clang/LLVM, not newer versions of GCC. Clang keeps a feature matrix for C++0x support, and it's not nearly as complete as GCC's. Picking some major features, variadic templates, auto, and rvalue references are present, but constexpr, defaulted/deleted methods, and lambdas are not.
> 7 votes

---
Tags: c++
---


# Question
Title: Tried and true basic movement physics (jumping, not walking through stuff)?
If I sat down long enough, I'm sure I could make this happen, but I don't want to reinvent the wheel if I don't have to, especially if XNA has patterns in place for doing this.

For now, I'm working in a very low resolution world, minecraft style. Everything is a simple cube that's 1x1x1. Currently I can move and look around but the camera is floating above the cubes, it doesn't use the cubes to determine where the camera is or where the camera should not be.

I'm just looking for the simplest of physics, such as not walking through blocks, if I walk off a cliff the character (camera) should fall and land the proper height above the ground, and general movement physics that you would expect out of even the most basic of games.

My first approach was to have a BoundingSphere for the character and a BoundingBox on each cube but when I detect a collision between the sphere and any box, how do I correct the character's placement to not intersect anymore?

I'm open to any alternatives and techniques that are out there.

# Answer
> 1 votes
Well normally I'd recommend you read a book about game engine physics, like the book 'game engine physics', but since you want it to be very simple I would suggest this:

Define a gravity constant. Every frame, attempt to move the camera downwards with that constant. if the camera intersects with any block, using boundingboxes/spheres. Have your collision detection also return how far your sphere intrudes into the block (in the case of 1px blocks I would advice you group them together for the sake of collision detection) and just move your camera back up the amount of intrusion. If you want to be like minecraft, do damage to your character relative to how much intrusion took place.

Note that if your character falls from a high cliff or something like that, it might go so fast it goes through a block in less than a frame, causing you to miss the collision, for this you might want to stretch the boundingbox/sphere between the last frame and the current frame.

Note these are all very 'arcade' physics suggestions, they are not realistic at all and will most certainly fail in more complex environments.

---
Tags: xna, physics, movement
---


# Question
Title: How can I cause the latest touch event to interrupt a prior event in Cocos2D?
In Cocos2D for iPhone, I want the latest touch event to interrupt another and ignore the last touch. Let me know if I need to elaborate more, but basically my game consists of a lot of finger dragging, and if the player ever switched fingers, there may be some overlap, and for the way things are setup, it may detect it as a new touch.

I think I have things almost on the right track, but my third touch does not work correctly. For instance:

* Touch A begins and held
* Touch B begins and held
* Touch A let go
* Touch A begins and held \<-This should interrupt Touch B

In my delegate I put \[glView setMultipleTouchEnabled:YES\]; because I believe I need multiple touches enabled.

In my CCLayer class with my added map and sprite I am using targeted touch delegate (i.e. ccTouchBegan NOT ccTouchesBegan, etc)

I am accessing a touch object with touch = \[\[\[event allTouches\] allObjects\] objectAtIndex:0\];, however I don't have much understanding what index is considered the latest touch or even a process to always get the latest touch.

# Answer
Look at these links, they might help:

I would try to do it this way:

1. store the events in a list
2. examine this list in a function which is called after all input has been processed (there might be an event handler for it).
> -1 votes

---
Tags: cocos2d-iphone, multitouch
---


# Question
Title: What do you look for in a scripting language?
I'm writing a little embedded language for another project. While game development was not its original intent, it's starting to look like a good fit, and I figure I'll develop it in that vein at some point.

Without revealing any details (to avoid bias), I'm curious to know:

**What features do you love in a scripting language for game development?**

If you've used Lua, Python, or another embedded language such as Tcl or Guile as your primary scripting language in a game project, what aspects did you find the most useful?

* **Language features** (lambdas, classes, parallelism)
* **Implementation features** (performance optimisations, JIT, hardware acceleration)
* **Integration features** (C, C++, or .NET bindings)
* Or something entirely different?

# Answer
> 4 votes
I'm looking for two things- speed, and integration. Usually the two go together, and with familiarity. Unfortunately, for C++, there are pretty much no languages that offer speed and integration. I've used Lua and it sucked, horrifically. I spent the whole time writing bindings and nowhere near enough time actually writing code.

Language features? The point of embedding a scripting language is not so that it can have whizzy dynamic language features that my original language didn't have, it's so that it can *be interpreted at run-time*. I really don't care beyond that, as long as it's basically functional, then that's fine- and fits with my host language (in this case C++). However, amazingly, languages that are designed to be integrated into host applications utterly fail the the part about *integration*.

Do I need co-routines? No, I do not need co-routines. Do I need dynamic typing? No, I need to *know* what types are coming back at me from my scripting language, and since all of my existing code is built around very strong typing, I'd really like my script code to be able to respect that too. Do I need garbage collection? No, my types already manage their own resources, and I definitely do want deterministic destruction. Do I want goto? No- I want to throw exceptions.

The trouble I found was that basically all the existing scripting languages were designed to extend C, not C++, and don't properly support the C++ model in many ways, and in addition to this, they have totally different semantics. How on earth am I going to translate `shared_ptr`, which is automatic deterministic destruction, into a garbage-collected environment? You can write whatever wrapping libraries you want, you won't change the underlying language semantics being incompatible with the language you're trying to extend with it. How can I ensure that this `void*` is the right type? How can I deal with inheritance? How do I throw and catch exceptions? It just doesn't work.

A good scripting language for C++ would be statically typed, value semantics, deterministically destructed, throw and catch exceptions and respect my destructors/constructors/copy constructors, because then all my types will just work, nice and easy, and the resulting language will be fast and support all my original semantics, easy to bind to.

# Answer
> 2 votes
For web-based gaming, three important factors for me are:

* Familiarity
* Speed
* Integration

I particularly like Perl, partly because I am already familiar with the language, and because with a web server module like mod\_perl2 there is a huge performance and integration benefit -- mod\_perl2 keeps a compiled version of the scripts in RAM (which are only interpreted upon first loading) that gives it a major speed advantage over other interpreted languages that don't have compilation options, and it also integrates into the Apache HTTPd server with a feature-rich API that provides access to a lot of very powerful features.

These factors can be useful for web-based game development (and where database access is needed, caching the database connections helps to further reduce response times for users). Of course, this may not be the most ideal solution for everything as each language has its advantages (and disadvantages), but it has always worked well for my needs.

# Answer
> 2 votes
Arranged in the order of (decreasing) importance:

* Readable at a glance. Actually, that's a requirement for *any* language I want to use, but for scripting it's arguably more important: scripts, by definition, change more often than "core" code. So, no LISP or PERL.
* Terseness. Scripts are constantly written and rewritten, and typing lots and lots of "boilerplate" code is inefficient.
* Easy debugging. Preferably with breakpoints, step-through etc.
* Easy integration with my chosen "core" technology. If I'm using C++ for my game, I'd need good C++ bindings, like in LUA. If the game is in C#, I'd choose a CLI-based language: C#, IronPython, Boo.
* Language features: easy associative arrays, coroutines, maybe lambdas. Actually, this mostly depends on what I'm going to use the scripts for. AI scripts are different from, say, initialization scripts.
* Good documentation. C# has a whole MSDN dedicated to it, and Boo has only sources. that's why C# is way better.
* Good development environment. VS or Eclipse beats Notepad every time.

---
Tags: scripting, tools
---


# Question
Title: Simple Math Multiplayer game - is Ajax sufficient?
I'm planning to create a simple math multiplayer game and I plan to just use Ajax for the server/client communication but I'm not sure if this is sufficient or if I need a socket server.

The game will look like this:

* 2-4 users
* all get a simple math task (like: "37 + 14")
* they have to solve it as fast as possible
* first user who solves it is the winner

I will track the time for each user, since the game started, on the client side and everytime a user gives an answer, the answer and the passed time will be send to the server. Additionally I'll add a function which will check every 3 seconds if the other users finished, how much time they needed and who won.

Do you think this is possible just using Ajax? What alternatives are there?

# Answer
I think that Ajax is easily sufficient for this task.

The alternatives I can think of are:
> 1 votes

# Answer
> Do you think this is possible just using Ajax? What alternatives are there?

Yes for the communication ajax is a valid channel to use.

But if by AJAX you mean sending single ajax requests using something like jQuery then no it's not a valid choice, merely because there are better options.

I highly recommend you use either

* WebSockets and a range of fall-back techniques for older browsers
* or COMET techniques.

For WebSockets I recommend you use an abstraction layer like socket.io (for node.js) or APE (for PHP).

Both of those use feature detection to use the best communication channel possible. This will pick WebSockets, COMET or a flash websocket bridge and those technologies support a wide range of browsers whilst still emulating a proper socket connection for you.

Arguably you can also use a SilverLight or Java websocket bridge but those are less common and not as well supported.

As for COMET the techniques are too highly integrated into the server-side stack/language to give generic advice.

If you need technology that interfaces well with a particular server side stack feel free to ask.
> 3 votes

---
Tags: mathematics, multiplayer, javascript
---


# Question
Title: What are reasons for Unity3D's owners to force rich guys buying Pro version?
Well, I have to say that Unity is a really nice thing that can save one a dozen of hours on coding (letting instantly work on gameplay). But what's the idea of *forcing* (EULA) any party, which made over 100k last fiscal year, to purchase Pro instead of using normal edition!?

It feels that this kind of licensing provides hidden benefits to rich guys over me, poor sloven, who can afford buying $3.5k license but obviously will not receive any additional cookies from it.

And, by the way, anyone estimated how much Unity's source + Playstation + Xbox license will cost?

# Answer
> 7 votes
The guys at Unity are spending a lot of money doing R&D, as well as licensing 3rd party tech to include in their software.

The only reason it's *free* in the first place is that they want to get as many people using it as possible, so when the big boys (read: people who are actually making money doing this and can afford to actually buy software) are investigating tech to use, there's a large group of people who are experienced with using it and can recommend it to the people who have control of purse strings. Plus they have a vested interest with their web plugin to have as many people developing games for it as possible, and most web games don't make a lot of money.

The concept is very similar to a lot of software that's "free for non-commercial use". In this case, it's "free for insignificant commercial use".

---
Tags: unity, licensing, support
---


# Question
Title: App Store: Profitability for Game Developers
Recent days, I've been spending significant time in discovering chances of profitability of AppStore for developers.

I have found many articles. Some of them are highly optimistic, while other are extremely skeptical. This article is extremely skeptical. It even claims to have backed its conclusions by objective sales numbers. This is another pesimistic article saying that games developed by single individuals get 20 downloads a day.

Can I kindly ask to clarify from business viewpoint **whether average developers publishing games and software on AppStore can cover their living expenses, even, whether they can become profitable?**

Is it achievable to generate revenues of 50.000 USD yearly on AppStore for a single developer?

I would like to stay as realistic as possible. Despite the question might look subjective, a good business man will be able to esitmate chances for profitability and prosperity within AppStore.

# Answer
> 7 votes
> Is it achievable to generate revenues of 50.000 USD yearly on AppStore for a single developer?

Of course it is, I can simply point to a single example of this being the case and it's "achievable". The thing is, in order for *you* to do it there are a lot of factors at play.

Can you make games quickly/cheaply? With the race to the bottom in terms of purchasing price, if you eat up too much time and money on a single game you're not likely to get any return on that investment

Do you monetize properly? The freemium model is getting more and more popular, for example. If you're not going freemium, you need to know how to price yourself in the market. You have to be fulfilling some kind of strong desire to place yourself above the $1 price point.

Are the games you're making high enough quality that people will *want* to tell their friends about them? Word of mouth is a very strong sales driver. If people aren't saying "hey you should play this", you're not going to make any money.

Is the content of the games appealing to the mass market? You can't just target the 17-34 male demographic with the games you're making if you want to go really wide with it.

Can you advertise properly? This isn't a case where "if you build it they will come". You have to send out demo codes to the right people. Try to get reviewed. Try to get popular bloggers, etc. to recommend it. Be active in community groups (facebook, forums, youtube, etc.).

Basically, the point that a lot of people in the comments are making is that it seems you're asking for the impossible analysis. You're giving a specific profitability number without talking about *the product* you're making *at all*.

# Answer
> 1 votes
I personally would run as far away as fast as possible from the AppStore.

If you are aiming for iPad, iPhone, you need some really good marketing to get the initial market penetration. Without this, your App will fall into the oubliettes of the AppStore, which is much more difficult to navigate on a handheld than on a PC.

You also need to think about your game development if you are aiming at portable platforms. You need 'casual' games; games with short game sessions (5-10 mins) that have good feedback and make the player want to continue.

If this is what you are looking at, I would definately try to use something like Unity so you can aim for Android and iPhone with the same source (but it will cost more), and maybe make a PC version available; if your game is really good and people want to play it while going to work, they'll buy it.

If the question was about App Hubs in general (which I doubt) lots of Indie developers go for Steam, I remember reading a 2DBoy article (World of Goo) saying the guys at Steam were cool and they managed to negociate the percentages.

Of course the beauty about using Unity is that you could also sell a PC version.

In any case, I would search for project post-mortems from Indie developers that make AppStore games, and maybe even try and contact some.

GLHF.

# Answer
> 1 votes
More than a half of the market games are really:

* school projects
* a result of investments into casual (freelance) programmers (teachers are paying for guitar sheet and chemical apps, animation studios are putting out cartoon toys for children - I ever seen a Nickelodeon themed netbook)

And the most of other projects are developed as any other shareware (what the thing with the amateur game developers calling shareware a freemium? did they completely missed a good class on CS history?), that formalizes a normal workflow of *"how much we're paying to our outsourced programmers, we need that game TBD in a month or so"*. So if you're writing a casual shareware - sit down, start coding, and get ready to reap some minor profits.

Or, say to yourself "I'm about to create a multiplatform game where user needs to throw * from * to hit * off the \*", think about it, and keep coding - having a warm feeling of doing something new || something of personal interest. But the end is very same, unless you're suddenly able to take this project to your boss and ask him for letting you code games in a work hours, asking him also to fund the project (e.g. buying MacBooks for a home-brew team - one for a cat, one for a dog).

---
Tags: ios, game-industry, monetization, appstore
---


title: Infinite loop during A* algorithm

text:
# Question
Title: Infinite loop during A* algorithm
The A\* algorithm is used by enemies to have a path to the goal. It's working but when sometimes I placed a tower in a grid (randomly) it produces a stack overflow error. The A\* algorithm would iterate the enemy and find its path and pass the list to the enemy's path.

I added debug logs and the list that I'm getting it looks like it would arrive from start cell to goal cell.

Here's the log -

```
06-19 19:26:41.982: DEBUG/findEnemyPath, enemy X:Y(4281): X2.8256836:Y3.5
06-19 19:26:41.990: DEBUG/findEnemyPath, grid X:Y(4281): X3:Y2
06-19 19:26:41.990: DEBUG/START CELL ID:(4281): 38
06-19 19:26:41.990: DEBUG/GOAL CELL ID:(4281): 47
06-19 19:26:41.990: DEBUG/Best : 38(4281):  passThrough:0.0
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 38
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 38
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 38
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 38
06-19 19:26:41.990: DEBUG/Best : 39(4281):  passThrough:8.875
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 39
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 39
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 39
06-19 19:26:41.990: DEBUG/Best : 40(4281):  passThrough:7.9375
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 40
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 40
06-19 19:26:41.990: DEBUG/Best : 52(4281):  passThrough:8.9375
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 52
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 52
06-19 19:26:41.990: DEBUG/Best : 53(4281):  passThrough:7.96875
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 53
06-19 19:26:41.990: DEBUG/Best : 28(4281):  passThrough:8.9375
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 28
06-19 19:26:41.990: DEBUG/Best : 65(4281):  passThrough:8.984375
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 65
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 65
06-19 19:26:41.990: DEBUG/Best : 66(4281):  passThrough:7.9921875
06-19 19:26:41.990: DEBUG/Neighbor's Parent:(4281): 66
06-19 19:26:42.000: DEBUG/Best : 78(4281):  passThrough:8.99609375
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 78
06-19 19:26:42.000: DEBUG/Best : 79(4281):  passThrough:7.998046875
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 79
06-19 19:26:42.000: DEBUG/Best : 80(4281):  passThrough:6.9990234375
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 80
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 80
06-19 19:26:42.000: DEBUG/Best : 81(4281):  passThrough:5.99951171875
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 81
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 81
06-19 19:26:42.000: DEBUG/Best : 82(4281):  passThrough:4.999755859375
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 82
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 82
06-19 19:26:42.000: DEBUG/Best : 83(4281):  passThrough:3.9998779296875
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 83
06-19 19:26:42.000: DEBUG/Best : 71(4281):  passThrough:2.99993896484375
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 71
06-19 19:26:42.000: DEBUG/Best : 59(4281):  passThrough:1.99951171875
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 59
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 59
06-19 19:26:42.000: DEBUG/Neighbor's Parent:(4281): 59
06-19 19:26:42.000: DEBUG/Best : 47(4281):  passThrough:0.99951171875

```

Then, the goal cell would be iterating its parent till start cell to break off the loop.

```
private void populateBestList(Cell cell, List<Cell> bestList) {
        bestList.add(cell);

        if (cell.parent.start == false) {
            Log.d("ID:", ""+cell.id);
            Log.d("ParentID:", ""+cell.parent.id);
            populateBestList(cell.parent, bestList);
        }
        return;
    }

```

The log with error above would show like this -

```
06-19 19:26:42.010: DEBUG/ID:(4281): 47
06-19 19:26:42.010: DEBUG/ParentID:(4281): 59
06-19 19:26:42.010: DEBUG/ID:(4281): 59
06-19 19:26:42.010: DEBUG/ParentID:(4281): 71
06-19 19:26:42.010: DEBUG/ID:(4281): 71
06-19 19:26:42.010: DEBUG/ParentID:(4281): 59
06-19 19:26:42.010: DEBUG/ID:(4281): 59
06-19 19:26:42.010: DEBUG/ParentID:(4281): 71
06-19 19:26:42.010: DEBUG/ID:(4281): 71

```

71 and 59 would switch over and goes on.

I thought the grid is the issue due to the fact that enemies are using the single grid so I make the parent, start, and goal clear before starting the A\* algorithm for an enemy.

```
for(int i = 0; i < GRID_HEIGHT; i++) {
            for(int j = 0; j < GRID_WIDTH; j++) {
                grid[i][j].parent = null;
                grid[i][j].start = false;
                grid[i][j].goal = false;
            }
        }

```

That didn't work. I thought it might be something related to this code, but not sure if I'm on right track -

```
neighbor.parent = best;
openList.remove(neighbor);
closedList.remove(neighbor);
openList.add(0, neighbor);

```

Here's the code of the A\* algorithm -

```
private List<Cell> findEnemyPath(Enemy enemy) {

    for(int i = 0; i < GRID_HEIGHT; i++) {
        for(int j = 0; j < GRID_WIDTH; j++) {
            grid[i][j].parent = null;
            grid[i][j].start = false;
            grid[i][j].goal = false;
        }
    }

    List<Cell> openList = new ArrayList<Cell>();
    List<Cell> closedList = new ArrayList<Cell>();
    List<Cell> bestList = new ArrayList<Cell>();

    int width = (int)Math.floor(enemy.position.x);
    int height = (int)Math.floor(enemy.position.y);

    width = (width < 0) ? 0 : width;
    height = (height < 0) ? 0 : height;

    Log.d("findEnemyPath, enemy X:Y", "X"+enemy.position.x+":"+"Y"+enemy.position.y);
    Log.d("findEnemyPath, grid X:Y", "X"+height+":"+"Y"+width);
    Cell start = grid[height][width];
    Cell goal = grid[ENEMY_GOAL_HEIGHT][ENEMY_GOAL_WIDTH];

    if(start.id != goal.id) {

        Log.d("START CELL ID: ", ""+start.id);
        Log.d("GOAL CELL ID: ", ""+goal.id);
        //Log.d("findEnemyPath, grid X:Y", "X"+start.position.x+":"+"Y"+start.position.y);
        start.start = true;
        goal.goal = true;
        openList.add(start);

        while(openList.size() > 0) {
            Cell best = findBestPassThrough(openList, goal);
            //Log.d("ID:", ""+best.id);
            openList.remove(best);
            closedList.add(best);
            if (best.goal) {
                System.out.println("Found Goal");
                System.out.println(bestList.size());
                populateBestList(goal, bestList);
                /*
                for(Cell cell : bestList) {
                    Log.d("ID:", ""+cell.id);
                    Log.d("ParentID:", ""+cell.parent.id);
                }
                */
                Collections.reverse(bestList);
                Cell exit = new Cell(13.5f, 3.5f, 1, 1);
                exit.isExit = true;
                bestList.add(exit);
                //Log.d("PathList", "Enemy ID : " + enemy.id);
                return bestList;
            }
            else {
                List<Cell> neighbors = getNeighbors(best);
                for (Cell neighbor : neighbors) {
                    if(neighbor.isTower) {
                        continue;
                    }
                    if (openList.contains(neighbor)) {
                        Cell tmpCell = new Cell(neighbor.position.x, neighbor.position.y, 1, 1);
                        tmpCell.parent = best;
                        if (tmpCell.getPassThrough(goal) >= neighbor.getPassThrough(goal)) {
                            continue;
                        }
                    }
                    if (closedList.contains(neighbor)) {
                        Cell tmpCell = new Cell(neighbor.position.x, neighbor.position.y, 1, 1);
                        tmpCell.parent = best;
                        if (tmpCell.getPassThrough(goal) >= neighbor.getPassThrough(goal)) {
                            continue;
                        }
                    }
                    Log.d("Neighbor's Parent: ", ""+best.id);
                    neighbor.parent = best;
                    openList.remove(neighbor);
                    closedList.remove(neighbor);
                    openList.add(0, neighbor);
                }
            }
        }
    }
    Log.d("Cannot find a path", "");
    return null;
}

public double getPassThrough(Cell goal) {

        if (start) {
            return 0.0;
        }

        return getLocalCost(goal) + getParentCost();
    }

public double getLocalCost(Cell goal) {
        if (start) {
            return 0.0;
        }

        localCost = 1.0 * (Math.abs(this.position.x - goal.position.x) + Math.abs(this.position.y - goal.position.y));
        return localCost;
    }

public double getParentCost() {

        if (start) {
            return 0.0;
        }

        if (parentCost == 0.0) {
            parentCost = 1.0 + .5 * (parent.getParentCost() - 1.0);
        }

        return parentCost;
    }

```

When the error occurs - O is empty, X is a tower. S is start, goal is G. The enemy would be created before the Start cell and proceed its path to goal. The infinite parent would happen - P. it looks like it'll happen in two places. one s to left and other s bottom.

```
O O O O O O O O T O O O
O O P O O O O T O O O O
O T P O O O T O O O O O
S T O O O O O O O O O G
O T O O T P O O O O O O
O O T T O P O O O O O O
O O O O O O O O O O O O

```

# Answer
> 5 votes
Right, so it looks like you're calling populateBestList recursively forever. This would happen if your linked list of Cell.parent values is circular for some reason.

Normally, this isn't possible, because you only ever set a parent value on a node just taken off the open list, and you set it to point to a cell you already handled and put on the closed list, and so the parent links would always point backwards along the nodes you 'closed' further into the past.

However, if a closed node were to end up back in the open list, you could end up creating a parent loop, because the node you set its parent to may already point back at this one - or, it might point to a node whose parent points back to this one, and so on. And then after creating this cycle, if any of the cycle appears in the final path, you'll be unable to complete the path and will get the error you see.

You do have code which potentially resurrects nodes from the closed list, back into the open list, based on these `getPassThrough` values. So, I would suggest double checking getPassThrough - is that definitely handling distance travelled + estimated distance remaining properly? Is it possible that it is wrongly saying that you reached a cell on the closed list by a cheaper path, and thus putting it back on the open list when it shouldn't be? If getPassThrough gets the costs wrong then the parenting links will also end up wrong.

# Answer
> 0 votes
Maybe the width and height are exchanged.

In the loops:

```
for(int i = 0; i < GRID_HEIGHT; i++) {
        for(int j = 0; j < GRID_WIDTH; j++) {

```

you use i for height, and j for width

In the cell:

```
int width = (int)Math.floor(enemy.position.x);
int height = (int)Math.floor(enemy.position.y);

```

x is used to width.

I suspect this because usually x is related to i, and y to j and your case is backward.

---
Tags: algorithm, path-finding
---


# Question
Title: Bloom shader makes it impossible to render black?
I am playing around with the bloom shader from the XNA sample page, to do some glow shading. I am rendering primitive vector-ish squares of linelists/linestrips, on a background. However, I am facing a few problems.

With a black background and white squares, I can actually see the squares. However, with a white background and black squares, I can't see them at all.

Why is this happening, and is there any way of me fixing it?

Can I modify my bloom shader to also "glow" dark elements, if that's what is causing it?

# Answer
> 2 votes
The function of a bloom filter:

* Apply a threshold to the source image to extract bright colours.
* Blur the result.
* Composite the blurred effect over the source image.

Your problem is that the shader targets bright colours (greater than the threshold) when it ought to target dark colours (less than the threshold). As a result, the dark shapes are being covered by the blur effect on the white background. Solution: change the direction (\> vs. \<) of the test.

If you want bloom on shadows as well as lights, try:

> (Colour \< Shadow Threshold || Colour \> Highlight Threshold)

But it probably won't look great.

---
Tags: xna, bloom, glow
---


title: Real-Time Strategy Gameplay

text:
# Question
Title: Real-Time Strategy Gameplay
I am working on building a HTML5 RTS game, and my current state is that I am building the Campaign mode of the game, and want to define the gameplay (The Scoring, Unit Behaviors/Attributes).

I am searching for links/articles/books about how to define the gameplay, for me this:

* The scoring
* Figuring out levels of control (in any RTS game, there is units, individuals and squads)
* Unit action/attributes/properties
* point timing (how long it will take to play?)
* Achievements
* ..etc

I want to see how they usually define these areas in RTS games, I expect to see general document discussing this concept that I can use to build the gameplay.

Any idea? Is my question clear or I need to provide more details?

# Answer
> 7 votes
A lot of this depends on what **type** of RTS you want to create.

For example, if it is more casual, just multiply all scores by 100 and make sure that each game session is short :P.

RTS games are very mathematical, the balance needs to be perfect because players will find how to exploit any bad balancing, and while this may not be a bad thing, it can break your game. This is why I think it is imperative to read about this stuff.

There are some interesting articles on RTS design here.

I would first though, define the game experience. What you want the player to do in general, what the game will be like, etc. Your question seems more about balancing and macro/micro controlling, which are mechanics used to **implement** your game, they **shouldn't** influence your design (but most probably will).

You need to ask if you want to give advantages between races, unit types, etc. then you need to study the mechanics to balance your game out so in any situation you have the rock-paper-scissors effect.

---
Tags: game-design
---


# Question
Title: Render angles of a 3D model into 2D images?
Is there a tool out there that you can give a 3D model file, and it will output 2D renders of it from various angles? For example if you were making a 2D RPG but you want to make your character look nice, you might make the character in 3D and then just render the character from 8 or more angles into images which then are used by the 2D engine to give a pseudo-3D look.

Does such a tool exist or will it need to be custom-written or done manually?

# Answer
> 5 votes
I guess you can use 3dmax/maya or other modeling tools and just render you objects there. you can render your object with very high quality and with complex rendering tools like raycasting. if you want you can also create orthographic camera in modeling tools to create a real 2d image for you.

# Answer
> 3 votes
In your question you make rendering a 3d model to a 2d texture sound like it's so trivial that there are tools that do that, but as big feature (which actually is trivial) do it multiple times and append them in a spritesheet.

In practice, you and your artist decide on a good renderer (many good ones exist, some cost a lot of money, some come with the artists 3d modelling tool). These renderers are scriptable, so your artist can define all the positions of your model, and then you can script the renderer to render each of the poses.

On the internet you can find tools that append multiple images into a single spritesheet like this one.

So in short, the tools to create the parts are out there, but you need to glue them together yourself.

# Answer
> 0 votes
http://blogs.silverlight.net/blogs/msnow/archive/2009/03/02/silverlight-tip-of-the-day-97-creating-sprites-from-3d-models-envygames.aspx

---
Tags: 2d, 3d
---


title: Pixel Shader Giving Black output

text:
# Question
Title: Pixel Shader Giving Black output
I am coding in C# using Windows Forms and the SlimDX API to show the effect of a pixel shader. When I am setting the pixel shader, I am getting a black output screen but if I am not using the pixel shader then I am getting my image rendered on the screen. I have the following C# code

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using SlimDX.Direct3D9;
using SlimDX;
using SlimDX.Windows;
using System.Drawing;
using System.Threading;

namespace WindowsFormsApplication1
  {
     // Vertex structure.
[StructLayout(LayoutKind.Sequential)]
struct Vertex
{
    public Vector3 Position;
    public float Tu;
    public float Tv;

    public static int SizeBytes
    {
        get { return Marshal.SizeOf(typeof(Vertex)); }
    }

    public static VertexFormat Format
    {
        get { return VertexFormat.Position | VertexFormat.Texture1; }
    }
}

static class Program
{
    public static Device D3DDevice;         // Direct3D device.
    public static VertexBuffer Vertices;    // Vertex buffer object used to hold vertices.
    public static Texture Image;            // Texture object to hold the image loaded from a file.
    public static int time;                 // Used for rotation caculations.
    public static float angle;              // Angle of rottaion.
    public static Form1 Window =new Form1();
    public static  string filepath;
    static VertexShader vertexShader = null;
    static ConstantTable constantTable = null;
    static ImageInformation info;
    [STAThread]
    static void Main()
    {

        filepath = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Garden.jpg";

        info = new ImageInformation();
        info = ImageInformation.FromFile(filepath);

        PresentParameters presentParams = new PresentParameters();

        // Below are the required bare mininum, needed to initialize the D3D device.
        presentParams.BackBufferHeight = info.Height;         // BackBufferHeight, set to  the Window's height.
        presentParams.BackBufferWidth = info.Width+200;          // BackBufferWidth, set to  the Window's width.

        presentParams.Windowed =true;
        presentParams.DeviceWindowHandle = Window.panel2 .Handle;                       // DeviceWindowHandle, set to  the Window's handle.

        // Create the device.
        D3DDevice = new Device(new Direct3D (), 0, DeviceType.Hardware, Window.Handle, CreateFlags.HardwareVertexProcessing, presentParams);

        // Create the vertex buffer and fill with the triangle vertices. (Non-indexed)
        // Remember 3 vetices for a triangle, 2 tris per quad = 6.
        Vertices = new VertexBuffer(D3DDevice, 6 * Vertex.SizeBytes, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
        DataStream stream = Vertices.Lock(0, 0, LockFlags.None);
        stream.WriteRange(BuildVertexData());
        Vertices.Unlock();

        // Create the texture.

        Image = Texture.FromFile(D3DDevice,filepath );

        // Turn off culling, so we see the front and back of the triangle
        D3DDevice.SetRenderState(RenderState.CullMode, Cull.None);

        // Turn off lighting
        D3DDevice.SetRenderState(RenderState.Lighting, false);

        ShaderBytecode sbcv = ShaderBytecode.CompileFromFile("C:\\Users\\yashwinder singh\\Desktop\\vertexShader.vs", "vs_main", "vs_1_1", ShaderFlags.None);
        constantTable = sbcv.ConstantTable;
        vertexShader = new VertexShader(D3DDevice, sbcv);

        ShaderBytecode sbc = ShaderBytecode.CompileFromFile("C:\\Users\\yashwinder singh\\Desktop\\pixelShader.txt", "ps_main", "ps_3_0", ShaderFlags.None);
        PixelShader ps = new PixelShader(D3DDevice, sbc);

        VertexDeclaration vertexDecl = new VertexDeclaration(D3DDevice, new[] {
                            new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0),
                            new VertexElement(0, 12, DeclarationType.Float2 , DeclarationMethod.Default, DeclarationUsage.TextureCoordinate , 0),
                            VertexElement.VertexDeclarationEnd
            });

        Application.EnableVisualStyles();

        MessagePump.Run(Window, () =>
            {
                // Clear the backbuffer to a black color.
                D3DDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);

                // Begin the scene.
                D3DDevice.BeginScene();

                // Setup the world, view and projection matrices.

                //D3DDevice.VertexShader = vertexShader;
                //D3DDevice.PixelShader = ps;

                // Render the vertex buffer.
                D3DDevice.SetStreamSource(0, Vertices, 0, Vertex.SizeBytes);
                D3DDevice.VertexFormat = Vertex.Format;

                // Setup our texture. Using Textures introduces the texture stage states,
                // which govern how Textures get blended together (in the case of multiple
                // Textures) and lighting information.
                D3DDevice.SetTexture(0, Image);

                // Now drawing 2 triangles, for a quad.
                D3DDevice.DrawPrimitives(PrimitiveType.TriangleList   , 0, 2);

                // End the scene.
                D3DDevice.EndScene();

                // Present the backbuffer contents to the screen.
                D3DDevice.Present();

            });
        if (Image != null)
            Image.Dispose();

        if (Vertices != null)
            Vertices.Dispose();

        if (D3DDevice != null)
            D3DDevice.Dispose();

    }
    private static Vertex[] BuildVertexData()
    {
        Vertex[] vertexData = new Vertex[6];

        vertexData[0].Position = new Vector3(-1.0f, 1.0f, 0.0f);
        vertexData[0].Tu = 0.0f;
        vertexData[0].Tv = 0.0f;

        vertexData[1].Position = new Vector3(-1.0f, -1.0f, 0.0f);
        vertexData[1].Tu = 0.0f;
        vertexData[1].Tv = 1.0f;

        vertexData[2].Position = new Vector3(1.0f, 1.0f, 0.0f);
        vertexData[2].Tu = 1.0f;
        vertexData[2].Tv = 0.0f;

        vertexData[3].Position = new Vector3(-1.0f, -1.0f, 0.0f);
        vertexData[3].Tu = 0.0f;
        vertexData[3].Tv = 1.0f;

        vertexData[4].Position = new Vector3(1.0f, -1.0f, 0.0f);
        vertexData[4].Tu = 1.0f;
        vertexData[4].Tv = 1.0f;

        vertexData[5].Position = new Vector3(1.0f, 1.0f, 0.0f);
        vertexData[5].Tu = 1.0f;
        vertexData[5].Tv = 0.0f;

        return vertexData;
    }

}
}

```

And my pixel shader and vertex shader code are as following

```
 // Pixel shader input structure
 struct PS_INPUT
 {
    float4 Position   : POSITION;
    float2 Texture    : TEXCOORD0;
  };

 // Pixel shader output structure
struct PS_OUTPUT
 {
    float4 Color   : COLOR0;
 };

// Global variables
 sampler2D Tex0;

 // Name: Simple Pixel Shader
 // Type: Pixel shader
 // Desc: Fetch texture and blend with constant color
 //
 PS_OUTPUT ps_main( in PS_INPUT In )
 {
   PS_OUTPUT Out;                             //create an output pixel

    Out.Color = tex2D(Tex0, In.Texture);       //do a texture lookup

    Out.Color *= float4(0.9f, 0.8f, 0.0f, 1);   //do a simple effect

    return Out;                              //return output pixel
  }

 // Vertex shader input structure
 struct VS_INPUT
 {
    float4 Position   : POSITION;
    float2 Texture    : TEXCOORD0;
  };

  // Vertex shader output structure
  struct VS_OUTPUT
  {
      float4 Position   : POSITION;
      float2 Texture    : TEXCOORD0;
  };

  // Global variables
  float4x4 WorldViewProj;

  // Name: Simple Vertex Shader
  // Type: Vertex shader
  // Desc: Vertex transformation and texture coord pass-through
  //
    VS_OUTPUT vs_main( in VS_INPUT In )
  {
     VS_OUTPUT Out;                      //create an output vertex

     Out.Position = mul(In.Position,
                   WorldViewProj);  //apply vertex transformation
       Out.Texture  = In.Texture;          //copy original texcoords

     return Out;                         //return output vertex
   }

```

---

I have done the following Chane to my pixel shader where just i am returning a colour but still it is giving me a black output

```
// Pixel shader input structure
  struct PS_INPUT
 {
    float4 Position   : POSITION;
    float2 Texture    : TEXCOORD0;
  };

  // Pixel shader output structure
   struct PS_OUTPUT
   {
         float4 Color   : COLOR0;
     };

    // Global variables
  sampler2D Tex0;
   texture2D FirstTexture : register(t0);

   sampler texsmp : register(s0) = sampler_state
   {
      Texture   = <FirstTexture>;
       };

         // Name: Simple Pixel Shader
      // Type: Pixel shader
       // Desc: Fetch texture and blend with constant color
       PS_OUTPUT ps_main( in PS_INPUT In )
       {
           PS_OUTPUT Out;                             //create an output pixel
       Out.Color = float4(1,1,0,1);
       return Out;
      }

```

Can you please tell me the reason behind this problem

# Answer
You're calling SetTexture in your main program (effectively). This binds the texture to a sampler index, not a named sampler variable in shader code... you're not assigning `Tex2D` in the shader anything. So when you sample it, you get black (all-zero) and multiplying all-zero the way you do will of course still yield all-zero.

You could confirm this by simply outputting a flat color from the shader instead -- don't multiply by the sampled color -- and you should see something.

To fix this, you could use the Effect interface and call SetTexture on a compiled effect, or you could indicate that your sampler should be bound to register 0 (which is what you're setting the texture to):

```
texture2D FirstTexture : register(t0);
sampler texsmp : register(s0) = sampler_state
{
    Texture   = <FirstTexture>;
};

```
> 4 votes

# Answer
I think the correct syntax to josh's solution is using

```
texture2D FirstTexture : register(t0);
sampler texsmp : register(s0) = sampler_state
{
    Texture   = <FirstTexture>;
};

```

Using `register(0);` (without the "s") will result in a compiler error, see register (DirectX HLSL)
> 3 votes

---
Tags: c#, shaders, slimdx
---


# Question
Title: Doing powerups in a component-based system
I'm just starting really getting my head around component based design. I don't know what the *"right"* way to do this is.

Here's the scenario. The player can equip a shield. The the shield is drawn as bubble around the player, it has a separate collision shape, and reduces the damage the player receives from area effects.

### How is such a shield architected in a component based game?

Where I get confused is that the shield obviously has three components associated with it.

* Damage reduction / filtering
* A sprite
* A collider.

To make it worse different shield variations could have even more behaviors, all of which could be components:

* boost player maximum health
* health regen
* projectile deflection
* etc

---

1. Am I overthinking this? Should the shield just be a super component?
I really think this is wrong answer. So if you think this is the way to go please explain.
2. Should the shield be its own entity that tracks the location of the player?
That might make it hard to implement the damage filtering. It also kinda blurs the lines between attached components and entities.
3. Should the shield be a component that houses other components?
I've never seen or heard of anything like this, but maybe it's common and I'm just not deep enough yet.
4. Should the shield just be a set of components that get added to the player?
Possibly with an extra component to manage the others, e.g. so they can all be removed as a group. (accidentally leave behind the damage reduction component, now that would be fun).
5. Something else that's obvious to someone with more component experience?

# Answer
> Should the shield be its own entity that tracks the location of the player? That might make it hard to implement the damage filtering. It also kinda blurs the lines between attached components and entities.

Edit: I think there's not enough "autonomous behaviour" for a separated entity. In this specific case, a shield follows the target, works for the target and does not outlive the target. While I tend to agree that there's nothing wrong with the concept of a "shield object", in this case we're dealing with behaviour, which fits just fine in a component. But I'm also an advocate of purely logical entities (as opposed to full-blown entity systems in which you can find Transform and Rendering components).

> Should the shield be a component that houses other components? I've never seen or heard of anything like this, but maybe it's common and I'm just not deep enough yet.

See it in a different perspective; adding a component adds other components as well, and upon removal, the additional components are gone too.

> Should the shield just be a set of components that get added to the player? Possibly with an extra component to manage the others, e.g. so they can all be removed as a group. (accidentally leave behind the damage reduction component, now that would be fun).

This could be a solution, it would promote reuse, however it is also more error prone (for the issue you mentioned, for instance). It's not necessarily bad. You might find out new spell combinations with trial and error :)

> Something else that's obvious to someone with more component experience?

I'm going to elaborate a bit.

I believe you noticed how some components should take priority no matter when they've been added to an entity (this would answer your other question as well).

I'm also going to assume we're using message-based communication (for the sake of discussion, it's just an abstraction over a method call for the moment).

Whenever a shield component is "installed", shield component message handlers are chained with a specific (higher) order.

```
Handler Stage    Handler Level     Handler Priority
In               Pre               System High
Out              Invariant         High
                 Post              AboveNormal
                                   Normal
                                   BelowNormal
                                   Low
                                   System Low

In - incoming messages
Out - outgoing messages
Index = ((int)Level | (int)Priority)

```

The "stats" component installs a "damage" message handler at the In/Invariant/Normal index. Every time a "damage" message is received, decrease the HP by its "value" amount.

Fairly standard behaviour (put in some natural damage resistance and / or racial traits, whatever).

The shield component installs a "damage" message handler at the In/Pre/High index.

```
Every time a "damage" message is received, deplete the shield energy and substract
the shield energy from the damage value, so that the damage down the message
handler pipeline is reduced.

damage -> stats
    stats
        stats.hp -= damage.value

damage -> shield -> stats
    shield
        if(shield.energy) {
            remove_me();
            return;
        }
        damage.value -= shield.energyquantum
        shield.energy -= shield.energyquantum;

     stats
        stats.hp -= damage.value

```

You can see this is pretty flexible, albeit it would require careful planning when designing component interaction, as you're going to have to determine in which part of the message handling pipeline component message event handlers are installed.

Makes sense? Let me know if I can add more detail.

Edit: regarding multiple component instances (two armour components). You can either keep track of the total instance count in just one entity instance (this kills per-component state, however) and just keep adding message event handlers, or make sure your component containers allow for duplicate component types in advance.
> 11 votes

# Answer
> 1) Am I overthinking this? Should the shield just be a super component?

Maybe, depends on how reusable you want your code to be and if it makes sense.

> 2) Should the shield be its own entity that tracks the location of the player?

Not unless this shield is some sort of creature that can walk around independently at some stage.

> 3) Should the shield be a component that houses other components?

This sounds a lot like entity, so the answer is no.

> 4) Should the shield just be a set of components that get added to the player?

It is likely.

> "Damage reduction / filtering"

* core shield component functionality.

> "A sprite"

* is there a reason you cannot add another SpriteComponent to your character entity (in other words more than one component of certain type per entity)?

> "A collider"

* are you sure you need another one? This depends on your physics engine. Can you send a message to character entity's ColliderComponent and ask it to change shape?

> "Boost player maximum health, health regen, projectile deflection etc."

* other artifacts might be able to do this (swords, boots, rings, *spells/potions/visiting shrines* etc.) so these should be components.
> 4 votes

# Answer
> Should the shield be a component that houses other components?

Maybe not houses other components, but controls the lifetime of sub components. So in some rough pseudo code, your client code would add this "shield" component.

```
class Shield : Component
{
    void Start() // happens when the component is added
    {
        sprite = entity.add_component<Sprite>( "shield" );
        collider = entity.add_component<Collider>( whatever );
        //etc
    }

    void OnDestroy() // when the component is removed
    {
        entity.remove_component( sprite );
        entity.remove_component( collider );
    }

    void Update() // every tick
    {
        if( ShouldRemoveSelf() ) // probably time based or something
            entity.remove_component( this );
    }
}

```
> 3 votes

# Answer
A shield, as a *physical* entity, is no different from any other *physical* entity, e.g. a drone which circles around you (and which in fact, could itself be a type of shield!). So make the shield a separate logical entity (thus allowing it to hold its own components).

Give your shield a couple of components: a Physical/Spatial component to represent it's collision form, and a DamageAffector component which holds a reference to some entity to whom it will apply increased or reduced damage (eg. your player character) every time the entity holding the DamageAffector takes damage. Thus your player is taking damage "by proxy".

Set the shield entity's position to the player's position every tick. (Write a reusable component class that does this: write once, use many times.)

You will need to create the shield entity, eg. on collecting a powerup. I use a generic concept called an Emitter, which is a type of entity component that spawns new entities (usually through the use of an EntityFactory which it references). Where you decide to locate the emitter is up to you -- eg. put it on a powerup and have it trigger as the powerup is collected.

---

> Should the shield be its own entity that tracks the location of the player? That might make it hard to implement the damage filtering. It also kinda blurs the lines between attached components and entities.

There is a fine line between logical subcomponents (Spatial, AI, Weapon slots, Input-processing etc. etc.) and physical subcomponents. You need to decide which side of it you stand on, as this strongly defines what sort of entity system you have. For me, the Physics subcomponent of my Entity handles the physics-hierarchical relationships (such as limbs in a body -- think scenegraph nodes), while the logic controllers noted above are typically what are represented by your entity components -- rather than these representing individual physical "fixtures".
> 3 votes

# Answer
If your component system allows scripting, the shield component could be almost a super component that just calls a script for its "effect" parameter. That way you maintain simplicity of a single component for shields, and offload all the logic of what it actually does to custom script files that get fed to shields by your entity definitions.

I do something similar for my Moveable component, it countains a field that is of keyreaction script (a subclass of script in my engine) this script defines a method that follows my input message. as such i can simply do something like this in my tempalte definition file

```
camera template
    moveable
    {
        keyreaction = "scriptforcameramoves"

    }

player template
    moveable
    {
        keyreaction = "scriptfroplayerkeypress"

    }

```

then in my moveable component during message registering i register the scripts Do method (code in C#)

```
Owner.RegisterHandler<InputStateInformation>(MessageType.InputUpdate, kScript.Do);

```

of course this relies on my Do method following the pattern of functions that my RegisterHandler takes. In this case its (IComponent sender, ref type argument)

so my "script" (in my case also C# just runime compiled) defines

```
 public class CameraMoveScript : KeyReactionScript
{
 public override void Do(IComponent pSender, ref InputStateInformation inputState)
 {
    //code here
 }
}

```

and my base class KeyReactionScript

```
public class KeyReactionScript : Script
{
      public virtual void Do(IComponent pSender, ref InputStateInformation inputState);
}

```

then later when an input component sends a message of the type MessageTypes.InputUpdate with the type as such

```
 InputStateInformation myInputState = InputSystem.GetInputState();
 SendMessage<InputStateInformation>(MessageTypes.InputUpdate, ref myInputState);

```

The method in the script that was bound to that message and datatype will be fired and handle all the logic.

The code is fairly specific to my engine, but the logic should be functional in any case. I do this for many types in order to keep the component structure simple and flexible.
> 0 votes

---
Tags: architecture, component-based, entity-system
---


title: Projectile Motion - Arrow

text:
# Question
Title: Projectile Motion - Arrow
In a 2D game, I simply want to draw the trajectory of an arrow in flight. With the code below, the trajectory (the parabola) looks right, but the angle (or rotation) or the arrow isn't.

```
float g = -9.8f;
float x = (launchVelocity * time);
float y = (launchVelocity * time) + (0.5f * g * (float)Math.Pow(time, 2));
float angle = (float)Math.Tanh(y / x);

```

What am I missing? Thanks.

# Answer
> 10 votes
`Arctanh` gives you the tangent for the hyperbolic curve! As far as I know your parabola isn't a hyperbola.

But we have good news: finding the tangent for your parabola is easier. The equation is

Where s is your `launchVelocity`. Now the slope of your arrow is:

You can safety use `Arctan` now if you like.

Some additional info about physics:

The approximate trajectory you are simulating applies to the center of mass of your arrow. When you say "position" (x,y) you are talking about the center of mass' position. The center of mass for an arrow is slightly forward from the midpoint and you should take that into account if you are going to draw the arrow.

Keep in mind that you are not considering the inertial momentum of the arrow (which can vary a lot if you are firing a giant ballista) and you are not considering the arrow's fluid dynamics: bow arrow flight won't follow a parabolic path!

# Answer
> 4 votes
You want the angle of the arrow at any point in time. You remembered that in order to compute an angle, there's a tangent. But here's where your thinking started to go wrong:

1. What you want is delta y / delta x, because the slope is the rate of change (mentioned in one of the other answers). Note that x is just the position where you are at any moment in time, not dx.

Ok, so if you neglect air friction, then the x-velocity of the arrow is a constant.

First, decompose velocity into x and y components. You could be shooting at an angle of 45 degrees or 60 degrees. So you need launchVelocity and an angle, it's not a scalar.

Second, compute everything as double, not float. You're not numerically sophisticated enough to know when roundoff error won't kill you, so don't try. It's not a great time saver in any case.

Third, don't use Math.pow, it's slow and not as accurate as multiplying for integer powers. Also you can save a lot of time by using Horner's form (see below)

```
final double DEG2RAD = Math.PI/180;
double ang = launchAngle * DEG2RAD;
double v0x = launchVelocity * cos(ang); // initial velocity in x
double v0y = launchVelocity * sin(ang); // initial velocity in y

double x = (v0x * time);
// double y = (v0y * time) + (0.5 * g * (float)Math.Pow(time, 2));
double y = (0.5 * g * time + v0y) * time

```

If you are desperate for performance, you can even precompute 0.5\*g, but the above code will take you 90% of the way there without doing anything too crazy. Benchmark doing this 10 million times if you like, it's admittedly not a huge amount of time but percentage-wise it's pretty big -- libraries are very slow in Java

So, if you wanted the angle at which the arrow should go, what you want is

```
atan(dy/dx)

```

And in this case, that would work because dx is a constant. But in general, dx can be zero, so you usually want to use:

```
atan2(dy, dx)

```

which is a function specifically designed for this job.

But as I said, library functions in Java are hideously slow, and in this case there's a better way of doing it without as alluded to by @FxIII above.

If the horizontal velocity is always v0x, and the vertical velocity is:

```
double vy = v0y - 0.5 * g * time;

```

then your delta is: vx,vy

You don't need the angle. If you wanted to draw an arrow, use something nominally like:

plot( x, y, x+vx, y+vy);

I don't know what you're drawing, so if you do need the angle to rotate it (like you're using JOGL) then sure, use the angle.

Don't forget if you are using opengl to turn the angle back into degrees, because ATAN2 returns radians:

```
final double RAD2DEG = 180 / Math.PI;
double ang = Math.atan2(vy,vx); // don't forget, vy first!!!
double deg = ang * RAD2DEG;

```

# Answer
> 2 votes
Tanh() (hyperbolic *tangent*) takes an angle as a parameter, but you've fed it the ratio of the sides.

What you really want is to use the hyperbolic *arctangent*, which takes the ratio of the sides as a parameter, and returns the angle. (Naming on this may be "atanh", "atanh2", "arctanh", or something else similar; seems to vary a lot between different maths libraries)

---
Tags: projectile-physics
---


# Question
Title: Splitting a tetris game apart - where to put time-management?
I am creating a tetris game in C++ & SDL, and I'm trying to do it "good" by making it object-oriented and keeping scopes small. So far I have the following structure:

* A main with some lowlevel SDL set up and handling input
* A game class that keeps track of score and provides the interface for main (move block down, etc)
* A map class that keeps track of the current game field, which blocks are where. Used by the game class.
* A block class that consists of the current falling block, used by game.
* A renderer class abstracting low level SDL to a format where you render "tetris blocks". Used by map and block.

Now I have a though time where to place the time-management of this game. For example, where should be decided when a block bumps the bottom of the screen how long it takes the current block locks in place and a new block spawns?

---

I also have an other unrelated question, is there some place where you can find some standard data on tetris like standard score tables, rulesets, timings, etc?

# Answer
my Tetris loop looks a bit like this:

```
blockDown = false    // a boolean flag, we'll need this in a minute
timer = 0
while true:
    get user input, try to rotate and move blocks left/right
    timer += timeSinceLastTick
    if timer > 1 second:
        timer -= 1 second
        step()

```

So the player can try moving or rotating the block at their own pace while once every second the *step()* function is being called (emphasis lies on **TRY**!! If the block can't move, ignore the input!). It looks roughly like this:

```
function step():
    try to move block down
    if that doesn't succeed:
        if blockDown:
            enter next block
        else:
            blockDown = true
    else:
        blockDown = false

```

Again, the emphasis is on **TRY** to move the block down. If it doesn't work, because it would collide with a block under it, set the *blockDown* variable to true (Now the player has until the next execution of *step()* to rotate the block or move it left and right). If this means that by the next execution the block can move down again, set *blockDown* to false again. Last case: The block can't be moved down and the *blockDown* flag is already set to true, the player already had his chance: Leave the block where it is and insert the next one.

**Edit**: Of course I'm not actually using **try** / **catch** statements for this. The *move()* and *rotate()* functions simply return *true* or *false* :-))
> 1 votes

# Answer
I would create a separate class called *CollisionDetection* or something that would check if the block reached the bottom of the screen or collided with other blocks, and if there was a collision, update the overall block data to add the current falling shape's blocks and create the next shape. The same class could contain a method to check if lines are completed and act accordingly.

Pseudocode for collision detection:

```
if shape is colliding with bottom of the screen or other blocks:
    undo collision
    if collision was from the bottom:
       add the blocks owned by the shape to the overall block data
       create next shape

```

Pseudocode for line check:

```
foreach lines in block data
   if line is filled
      clear line
      move down the blocks above
      give according score to player(depending on the amount of lines cleared with this shape)

```

I would call the methods from this class from your Game class.

This is how I made my own Tetris. As for the standard information for Tetris, I would be interested in finding such information too. If you don't get an appropriate answer from this question, I think you should make a separate question.
> 2 votes

---
Tags: c++, sdl, timing
---


# Question
Title: How do you transition to playing in XNA?
I have two classes in my game, a Main Menu and the main playing screen. How can I swap through classes? E.g I click on "New Game" in the menu class and it changes it too the Game class. A transition animation explanation would be nice.

# Answer
You need some kind of gamestate-management system in place.

I could write a long answer explaining this, but people who are a lot more experienced with XNA and game programming than me have already done that, so I shall point you towards them.

Personally I've found this example to be excellent: http://create.msdn.com/en-US/education/catalog/sample/game\_state\_management

It shows a gamestate-management system with the ability to easily add as many gamestates as you like, as well as defining transitions in and out of the gamestate.

You should give it a read!
> 3 votes

# Answer
You probably want to look into state machines. Here's a popular App Hub tutorial on game state management, and here's another random Google result for XNA state machine information (it's not really a topic that needs to be specific to XNA, so you can get broader search results in Google if you exclude the "XNA" bit, if you want to research the topic more yourself).

Once you have the basic implementation of such a system, you can expand it by adding (for example) animations that play as you transition in or out of states.
> 1 votes

# Answer
Game State Management is what you're after. Once you have the states sorted out, when they transition you can create whatever effect you desire (fade out, in, black out, white out, etc) and that's what shaders are for. But that's probably a slightly separate question.

Another article that could be interesting is this which describes an actual application of it.
> 1 votes

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


title: Physic of an arrow in flight

text:
# Question
Title: Physic of an arrow in flight
What are the formulas which represent the horizontal and vertical displacement of an arrow in flight (as well as it angle)? I would like to make sure that I take into consideration the arrow's fluid dynamics and center of gravity.

# Answer
> 4 votes
I actually answered this in your other question, but since this one is here, this is the place to do it cleanly on its own.

What you are asking is the trajectory problem. First, consider it neglecting air friction.

For an initial velocity v0 and angle a

```
v0x = v0 * cos(a)
v0y = c0 * sin(a)

```

for velocities as a function of time:

```
vx = v0x
vy = v0y - g * t

```

You need a reality check if you think you are going to handle instability, tumbling, or anything like that. You don't have the math for it, and it will take years to get it right, as well as massive amounts of CPU you don't want to devote in a game. You can try to fake that if you like. But if you want somewhat realistic slowing down of the projectile, that's relatively easy.

```
v = sqrt(vx*vx+vy*vy)
a = c * v*v*v

```

The coefficient c is a small number, and friction will tend to slow down the projectile so it always operates in the opposite sign of the moving projectile. You need the direction of the projectile, which is the vector:

```
(vx, vy)

```

but this is scaled according to the velocity. If you want to apply a negative acceleration, first compute the magnitude (already computed as v above)

Now you can generate a vector 1 unit long in the direction of the projectile:

```
(vx/v, vy/v)

```

to apply the acceleration in reverse:

```
-a * vx/v, -a * vy/v

```

This will have the effect of slowing down the projectile and making it fall short of what it would do with no air friction. the higher your constant c, the shorter the trajectory.

If you have wind, then just add to vx in your 2d game, in either + or - direction.

If you really want to show the projectile tumbling once it moves slowly enough, ask another question, but that will be a discussion of how to fake it, not how to do the real physics.

If you want to see just what you are getting yourself in for with simulating the drag on a projectile, this should be a survey paper that will show you the different approaches out there. http://raphael.mit.edu/peraire/SequeiraWillisPeraire.pdf

# Answer
> 2 votes
the simplest form you can simulate it is to use two weights connected to each other with a spring, resembeling head and tail of the arrow. and you have to just give the following object a little more thrust that the heading one to cause the arrow move like a real one, it just needs some tuning before it get's well, but it'll create a realistic movement. you can also make some diffrences for other parameters of head and tail weights, for example tail object has more air friction than the head one.

---
Tags: physics, projectile-physics
---


# Question
Title: Detect click on Triangle and Circle buttons
How can I detect clicks on a texture (which will be a button in my game) which has the form of a triangle or circle. I only know the rectangle solution which uses the position, width, and height; which won't work because clicks will be detected on transparent pixels.

I have heard of pixel-perfect collision, would that be the right way to do this?

It would be great if someone could give me a example for such a solution.

# Answer
I wouldn't bother with pixel-perfect collision if you only need to detect clicks on triangles and circles.

For circles you can use a basic distance check from the center of the button.

```
if ( radius >= Math.sqrt( Math.pow( clickX - centerX, 2 ) + Math.pow( clickY - centerY, 2 ) ) )
    // we have been clicked

```

And for triangles you can use a point-in-triangle test. If you have a triangle with vertices A, B, and C:

```
/**
 * Return true if p1 and p2 are on the same side of BA
 */
public static boolean SameSide(Vector2 p1, Vector2 p2, Vector2 A, Vector2 B)
{
    // Convert points to Vector3 for use the Cross product, which is Vector3-only
    Vector3 cp1 = Vector3.Cross(new Vector3(B-A, 0), new Vector3(p1-A, 0));
    Vector3 cp2 = Vector3.Cross(new Vector3(B-A, 0), new Vector3(p2-A, 0));
    return Vector3.Dot(cp1, cp2) >= 0;
}

/**
 * Return true if the point p is in the triangle ABC
 */
public static boolean PointInTriangle(Vector2 p, Vector2 A, Vector2 B, Vector2 C)
{
    return SameSide(p,A, B,C) && SameSide(p,B, A,C) && SameSide(p,C, A,B);
}

```

There is also the Barycentric technique, which increases computational efficiency at the expense of clarity. XNA provides a `Vector2.Barycentric` method which can help alleviate that issue.
> 10 votes

# Answer
If you had extremely complicated shapes, using pixel testing might be a good way to go, but if you have just circles and triangles, you use different methods that will be faster to set up, and execute faster as well.

For a circle all you have to do is know the radius, and when the user clicks, call a method that calculates the distance between the center of the circle and the point where the user clicked, if that distance is lower than the radius, then the user has clicked the circle.

```
private static double GetDistance(PointF point1, PointF point2)
{
    //pythagoras theorem c^2 = a^2 + b^2
    //thus c = square root(a^2 + b^2)
    double a = (double)(point2.X - point1.X);
    double b = (double)(point2.Y - point1.Y);

    return Math.Sqrt(a * a + b * b);
}

```

Code via http://www.daniweb.com/software-development/csharp/code/217149

Triangles are a bit more complicated, but this page explains two different methods on how to accomplish it.

http://www.blackpawn.com/texts/pointinpoly/default.html
> 2 votes

# Answer
Well the circle is even easier than the rectangle actually, all you need to know is the radius and the centerpoint of the circle then you can do the hit testing in a way similar to the rectangle. The Triangle is much harder, for complex shapes sometimes what people will do is to create a bunch of bounding spheres or boxes and just do a hit test on all of those, where the hit is not perfect but an estimate, sometimes this is ok sometimes not.

There are algorithms for arbitrary polygons, which solves it for a very general case but assumes you have polygon data. You could possibly also scan every pixel in the texture and look at it's alpha value but I think you'll find that very slow for a lot of textures. So I think for the triangle what you want to do is to, in addition to the texture, keep track of the points of the triangle. If you do that you can do hittesting for that shape pretty easily.

I did something similar in javascript not long ago, except for polygons: Determine if two points are on the same side of a line in javascript

You could translate that algorithm to C# and assume 3 points instead of 6.
> 0 votes

---
Tags: xna, c#, collision-detection
---


# Question
Title: What resources are available for Mac OS game development?
Are there are any modern resources on how to develop games for Mac OS? I suppose this would include objective c, cocoa and opengl 3+.

The book Beginning Mac OS X Game Development with Cocoa looks very promising but isn't out until early next year.

# Answer
Have you considered using something like Unity 3d? It has the advantage of running on multiple platforms (web/iphone/ipad/andriod/wii/pc/mac and soon ps3 & xbox360).

Here are some resources for Unity 3d,
> 2 votes

# Answer
Inside the Xcode IDE, you have access to a lot of material related with programming in Mac OS X, iPhone/iPad.

With Xcode 3

Help -\> Developer Documentation

With Xcode 4

Help -\> Documentation and API reference

A window will be open and you will can navigate along a lot of topics. For example, search a document called "OpenGL Programming Guide for Mac OS X". The documents can be viewed inside Xcode or downloaded in PDF format.

If you didn't know, you can mix code written in Objective-C and C++, even in the same file, try to rename a Objective-C file with .m extension to .mm extension. There are many games written in C++ for Mac OS X and iPhone. To make a game in C++ for Mac OS X, you can do a wrapper mixing C++ and Objective-C that deals with the OS native calls ( graphics, input, etc. ). Once this abstraction layer has been constructed, the game can be programmed entirely in C++.
> 0 votes

# Answer
I'm developing a NES emulator with SDL.
ALthough not exactly a game, I'm implementing almost the same features a game would, and of course, SDL is mainly pointed towards game development.
And you get a plus which is 100% portable code you can deploy on Windows and Linux too.
Although its graphic functions draw exclusively in 2D, it's fully integrated with OpenGL for 2D and 3D rendering if desired.
> -1 votes

---
Tags: opengl, objective-c, cocoa, macos
---


# Question
Title: How to detect collisions between sprite and a user generated shape of some sort?
How to detect a collision between a sprite and a user-generated shape of some sort.

For example. There are some objects on the screen. The user takes their finger and draws a circle shape around an object (The selection rule is painting circle around the sprite, but the painting shapes may be various). I need to detect which object selected, which just like:

(demo images):

# Answer
If the shape is drawn primarily with line segments from the user (or Bezier curves with control points), you can implement a fairly widely used algorithm known as Separating-Axis-Theorem. Simply put: if there is an axis (unit-vector representing a direction) on which the shapes don't overlap (their projected values do not result in a positive difference), the objects are not overlapping. I have used this in the past and it has worked like a charm.
> 2 votes

# Answer
If shape is hand-drawn like in Crayon Physics, you can hold an array of straight lines and check collisions with each of them. Despite of straight lines you can use Bezier curves or something like that.
> 1 votes

# Answer
* Create a buffer of same size as screen (or surface where are Your shapes). At each position it contains boolean whether there is sprite; then, check all "pixels" of user shape whether at their position is the sprite (by checking value of that boolean). Alternatively, You can create more sprites there by storing their ID instead of boolean; but this was case of 1 sprite.
* If user generated shape can be represented by sequence of lines, then You can check whether each such line crosses sprite. Since sprite has rectangular shape and user shape is a line just Look for "line rectangle intersection" ... (separating axes algorithm si one way to do it)

Approaches depend on what data structures You choose, whether they are bitmaps or vectors.

First approach can handle arbitrary complex shapes, is simple to implement but uses more memory. Actually You can reduce memory overhead by using compression and speed it up by using hierachical data strutures (octrees) ...

Second approach , is not so simple to implement but uses more processing power.

In each case measure if it matters. I would try to do first one because it is simpler to implement. Good luck. :)
> 0 votes

---
Tags: collision-detection
---