# Question
Title: What do you use to bundle / encrypt data?
More and more games are going the data driven route which means that there needs to be a layer of security around easy manipulation. I've seen it where games completely bundle up their assets (audio, art, data) and I'm wondering how they are managing that? Are there applications / libraries that will bundle and assist you with managing the assets within? If not is there any good resources that you would point to for packing / unpacking / encryption?

This specific question revolves around C++, but I would be open to hear how this is managed in C#/XNA as well.

Just to be clear -- I'm not out to engineer a solution to prevent hacking. At the fundamental level we're all manipulating 0's and 1's. But, we do want to keep the 99% of people that play the game from simply modifying XML files that are used to build the game world. I've seen plenty of games bundle all of their resources together. I'm simply curious about the methods they're using.

# Answer
> 8 votes
A good strategy is to make your own archive format from scratch, and to make it an indexed one with a table pointing to data chunks instead of storing whole sequential files in your archive, then encrypt your index table and compress every chunk separately using LZMA/Bzip2.

Another approach is using bits of procedural data generators here and there (If you want to go that far you could even get the 'parameters' for said generators from an on-line server as an extra measure), And by offloading some of the work to the GPU you can also prevent full memory dumps and make up for some of the lost performance.

Yet I find such techniques to generally hinder performance and waste development time, all the while offering nothing to the end-user but potential problems and unneeded bugs.

Nevertheless, nothing is 100% secure.

# Answer
> 11 votes
Don't ship sensitive data.

There is no way to ship encrypted data so that only the game can access it. You can try really hard but you quickly get into the DRM issues.

If you want to keep your game assets away from prying eyes.

1. zip it up
2. `xor` the file
3. change the extension to something boring (ie not `my_level.zip.xor`, use `my_level.map`) .

That will stop 95% of mischeivieous users. The other 5% are going to get it no matter what you do.
You don't need to actually zip and `xor`. You could instead lzma and use AES with a known key. The point is to not spend a lot of time on it.

# Answer
> 4 votes
Spending any large amount of time on this is probably foolish. There are tools to grab texture and model data directly from the GPU, and sounds can easily be pointed at a virtual loopback device. Anything that needs to be truly secure needs to live on a server and work only via challenge/response. Doing client data validation is another story, something more like Valve's -verify\_all. That is still hard, since you can't trust the local executable to enforce it (or at least you can't trust it more than you trust your end-point anti-cheat system, which is also a silly idea).

# Answer
> 4 votes
My job is in antitamper software. I know somebody who is an old school game cracker. He cracks games like breathing. You can't stop people like him. If your game is popular enough, multiple cracked versions of your game will hit the torrent sites only a few days after release no matter what you do. My advice is to just do the bare minimum to keep out the average joe who thinks he might want to give this reverse engineering thing a stab.

# Answer
> 1 votes
Good question but this is a far from easy to question to answer.
From my experience with data security you have to think about the following:

1) What are you securing, from whom and what is the impact if that data is insecure - security is far more about risk assessment than systematic technical solutions
2) I assume your platform is desktop (e.g. Windows/OSX) in that case you have a different problem space than proprietary hardware such as PS3/Xenon which have their own attempts at kernel level security ( whether this is a valid solution is open for debate )
3) Encryption != security. Encryption only guarantees that your data can't be *read*, it does not guarantee that your data can't be *written* or replayed/proxied.

If your requirements are to make your data tamper proof then you need to think about hashing your data ( preferably with SHA-256 or SHA-512) To re-iterate though, think about why it's important and what you gain from adding security to your system.
It's also worth knowing that adding encryption tech to your product *may* have legal implications due to export restrictions ( encryption tech is classed as restricted weapons grade technology believe it or not ) so using libraries that have overcome these legal issues is advisable.
Finally - never, ever roll your own encryption tech - use well known, documented, researched algorithms such as AES, Blowfish, RSA etc

ps Public/Private Key is not suitable or practical for encrypting large amounts of data hence DRM/PGP etc use a hybrid RSA \+ symmetric system i.e secure the symmetric key with RSA then do standard symmetric encryption using that key

It's a very large complex subject and I've definitely not done it justice

Hope that helps

# Answer
> 1 votes
If you want an example of a format that was designed and built (probably overengineered) for being small (compressable), ridiculously secure and flexible, you should look to Blizzard's MPQ format.

http://wiki.devklog.net/index.php?title=The\_MoPaQ\_Archive\_Format

The general archive layout is as follows:

Archive Header File Data File Data - Special Files Hash Table Block Table Extended Block Table Strong Digital signature

This format has EVERYTHING. Blocktable, extended blocktable, data split into sectors (for easy streaming), support for 7 (!) compression algorithms (if you count sound compression) that can be combined arbitrarily, weak digital signature, strong digital signature and so on.

If you were to buy the API from Blizzard that deals with file architecture, you'd get everything you'd ever need and so much more.

# Answer
> 0 votes
As this has recently been resurrected, your question (and therefore all answers so far) only seems to deal with the file loading, which is only as secure as the executable that wants to load it. On the PC there's nothing that's really secure (you just delay people), you can check against stuff on servers, but even that check can be removed so modded exe's can be run no matter what. The consoles are still "pretty" secures so in most cases there I generate a hash of important files, then sign the hash with a private key, embed the public key in the code and verify the secure hash against the file.

I thought I'd throw another attack into the conversation, something I only came across last year as I don't tend to ship much on the PC. Cheat Engine is a very tidy little program that almost automates making your own hacks (which means anyone can use it). It's pretty advanced in what it can do, a lot of hacks/cheats that I've seen people sell are made by this or something very much like it from what I've seen (all the mass market ones). With some work you can protect against stuff like this again, I guess it all depends on how popular the game is and if someone cares enough to bother.

Opps, forgot to mention a good lib for encryption (in C++) is LibTomCrypt.

---
Tags: encryption
---


# Question
Title: Changing coordinate system from Z-up to Y-up
Blender's coordinate system is different from what I'm used to, in that Z points upwards instead of Y. What would be the simplest way of converting all the world data (so that all animations, texture coordinates, etc still work) so that Y points upwards?

Clarification:

Object positions are defined as matrices, so just switching translation/rotation/scale information in matrices is not a trivial task. (at least it does not seem like a trivial task to me)

# Answer
> 2 votes
Why can't you just make the rotation matrix to orient it correctly the first part of your World matrix?

If you want to fix it when loading, create the rotation matrix to orient it correctly (i.e. 90 degrees around the X axis). Apply this to all vertices, then change all existing matrices to (rotation * existing).

# Answer
> 10 votes
Downvote me if I am wrong, but I don't see why people are recommending swapping y and z. That would make your coordinate system from being right handed to left handed. Try this yourself, swap the y and z, and reorient the axis so that x points right and y points up. You will see that z points the opposite direction from its original (away from the screen). The proper way is to rotate around the x-axis, which is swap y and z, and then invert the sign of the final z.

I think the easier solution is to build your models with y value being up.

# Answer
> 6 votes
As Comrade Duck suggests, you can just swap Y and Z. If you need a matrix to do it, use this one:

```
| 1 0 0 |
| 0 0 1 |
| 0 1 0 |

```

or in homogeneous coordinates

```
| 1 0 0 0 |
| 0 0 1 0 |
| 0 1 0 0 |
| 0 0 0 1 |

```

# Answer
> 1 votes
If your matrix is:

```
x
y
z
w

```

Then why not:

```
temp = y
y = z
z = temp

```

Or whatever swap method you want.

# Answer
> 0 votes
When you load your meshes with whatever mesh loader code you're using, just switch the Z and Y values. The mesh will then be loaded in your game in the appropriate coordinate space and you can do whatever you like to it (apply rotations, translations, etc). It's a similar situation I had with 3DS Max.

---
Tags: mathematics, blender, coordinates
---


# Question
Title: How to transition between states and mix states in a finite state machine?
I don't understand how to use a finite state machine with the entity controlled by the player.

For example I have a Mario style game (2d platform). I can jump, run, walk, take damage, swim, etc. So my first thought was to use this actions as states. But what happens, if you are running when you take damage? Or jumping, taking damage and shooting at the same time?

I just want to add functionalities (actions) to the player in a clean way (not using it for all the actions in the entity update) .

# Answer
I guess the normal way is to have multiple state machines. This way you can stick to atomic states which often makes your live a lot easier than having to deal with complex states.

For example:

* Damage Mode: Normal, Invulnerable (as in just hit), invincible (as in got a star)
* Pace: Walking Mode, Running Mode
* Abilities: Normal, Super, Fire, Fly
* Movement Type: Walking, Swimming, Flying

In object oriented designed there is the sate pattern for this. It boils down to having one interface per state machine. And a class per possible state which implements this interface.

To give an example: There would be an interface DamageMode and subclasses NormalDamageMode, InvulnerableDamageMode and InvincibleDamageMode. Whenever the player collidates with an enemy the method DamageMode.collision(enemy) is called. It is handled by the class responsible for the current state.

So if damageMode == NormalDamageMode the player will be damaged and the state variable will be set to InvulnerableDamageMode. In InvulnerableDamageMode nothing happens and in InvincibleDamageMode the enemy will be damaged. Of course there needs to be timers to go back from InvulnerableDamageMode and InvincibleDamageMode to NormalDamageMode.

The main advantage of the state pattern compared to if-elseif-elseif-elseif-blocks is that it allows to structure your code better.
> 7 votes

# Answer
States are not actions, in your game they would control how the character is updated (e.g. each state could have its own update() function).

Take a look at the diagram on this page: http://en.wikipedia.org/wiki/State\_diagram. The states tell us something about the world (the door is open or closed). The actions show us what takes the world from one state to another.

In your case you could have states like:

* jumping
* running
* in pain
* falling
* dead

And the transition between states (the events / arrows between states) would be player inputs and reactions to the world, such as:

* hit by monster
* jump button pressed
* shoot button pressed

Each state needs to check if any relevant events have occurred. Typically this is done with if statements.

> But what happen when you are running when you take damage?

The `hit by monster` event would be triggered and transition the player into the `in pain` state.

> or jumping taking damage and shooting at the same time?

The player would transition into the `in pain` state again which is where you could display your "hit" sprite that shows the character falling backwards.

You probably aren't going to escape if statements, but you can avoid deeply nested statements.
> 7 votes

---
Tags: animation, fsm
---


# Question
Title: How do I change the speed of an object without changing path travelled?
I have a ball which is being thrown from one side of a 2D space to the other. The formula I am using for calculating the ball's position at any one point in time is:

```
x = x0 + vx0*t
y = y0 + vy0*t - 0.5*g*t*t

```

where `g` is gravity, `t` is time, `x0` is the initial `x` position, `vx0` is the initial x velocity.

What I would like to do is change the speed of this ball, without changing how far it travels. Let's say the ball starts in the lower left corner, moves upwards and rightwards in an arc, and finishes in the lower right corner, and this takes 5s. What I would like to do is change it so the ball still follows the same curve and finishes in the same position, but takes 10s or 20s to do so.

How can I achieve this? All I can think of is manipulating `t` but I don't think that's a good idea. I'm sure it's something simple, but my maths are pretty shaky.

# Answer
Actually, you're correct -- without switching equations, the only way you have of altering speed without altering the path is to manipulate `t`.

For the given `x0` and `y0`, you need to record `t0`. Then:

```
rate = 0.25 // run path at one-quarter speed

t' = (t - t0) * rate

x = x0 + vx0*t'
y = y0 + vy0*t' - 0.5*g*t'*t'

```

Essentially what you are doing is slowing down time for the ball's path, without slowing down anything else.
> 7 votes

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


# Question
Title: database design help for game / user levels / progress
Sorry this got long and all prose-y. I'm creating my first truly gamified web app and could use some help thinking about how to structure the data.

### The Set-up

Users need to accomplish tasks in each of several categories before they can move up a level. I've got my `Users`, `Tasks`, and `Categories` tables, and a `UserTasks` table which joins the three. ("User 3 has added Task 42 in Category 8. Now they've completed it.") That's all fine and working wonderfully.

### The Challenge

I'm not sure of the best way to track the progress in the individual categories toward each level. The "business" rules are:

1. You have to achieve a certain number of points in each category to move up.
2. If you get the number of points needed in Cat 8, but still have other work to do to complete the level, any new Cat 8 points count toward your overall score, but don't "roll over" into the next level.
3. The number of Categories is small (five currently) and unlikely to change often, but by no means absolutely fixed.
4. The number of points needed to level-up will vary per level, probably by a formula, or perhaps a lookup table.

So the challenge is to track each user's progress toward the next level in each category. I've thought of a few potential approaches:

### Possible Solutions

1. Add a column to the users table for each category and reset them all to zero each time a user levels-up.
2. Have a separate `UserProgress` table with a row for each category for each user and the number of points they have. (Basically a Many-to-Many version of #1.)
3. Add a `userLevel` column to the `UserTasks` table and use that to derive their progress with some kind of SUM statement.

Their current level will be a simple int in the User table.

### Pros & Cons

(1) seems like by far the most straightforward, but it's also the least flexible. Perhaps I could use a naming convention based on the category ids to help overcome some of that. (With code like "`select cats; for each cat, get the value from Users.progress_{cat.id}`.") It's also the one where I lose the most data -- I won't know which points counted toward leveling up. I don't have a need in mind for that, so maybe I don't care about that.

(2) seems complicated: every time I add or subtract a user or a category, I have to maintain the other table. I foresee synchronization challenges.

(3) Is somewhere in between -- cleaner than #2, but less intuitive than #1. In order to find out where a user is, I'd have mildly complex SQL like:

```
SELECT categoryId, SUM(points) from UserTasks WHERE userId={user.id} & countsTowardLevel={user.level} groupBy categoryId

```

Hmm... that doesn't seem so bad. I think I'm talking myself into #3 here, but would love any input, advice or other ideas.

P.S. Sorry for the cross-post. I wrote this up on SO and then remembered that there was a game dev-focused one. Curious to see if I get different answers one place than the other....

# Answer
> So the challenge is to track each user's progress toward the next level in each category.

I'm not sure why is this a challenge? You can quickly and trivially calculate each of these 5 values from the contents of UserTasks, as I understand it:

* You know their level, as it's already cached as an integer as part of the User.
* This means you know how many points they need in each category, and therefore how many are needed overall.
* So, you total up all the points they've earned from relevant tasks so far. (Which tasks are relevant? I don't know as your schema is unclear. See my second comment on the question.)
* Then you can compare these against the total, whenever you need them.

Since you have a small number of categories I would suggest just performing 5 seperate queries, one per category, clamping each value against the maximum number of points that count at this level. Add them up, compare against the total.

If a task can count towards any given level (eg. you can do Task 10 at any point and collect the associated points towards your next level) then you might need a flag of some sort to show that the points for this task have been redeemed in order to go up a level. That flag allows you to exclude them from future queries.

You could presumably do something sneaky like set the points column in usertasks to zero to mark it as redeemed, but that sort of thing leads to unmaintainable code so I wouldn't recommend it.

So, something like: `select sum(points) from usertasks where redeemed=0 and category=1` \- that's how many category 1 points you've built up.

And: `select min(sum(points), 20) from usertasks where redeemed=0 and category=1` \- that's how many category 1 points that contribute towards your total if you only require 20 points in category 1.

If you had a separate table for 'category\_level' which had a field for a current level and a field for the number of points you needed in that category at that level, I think you could do all this with one query: join usertasks to categorylevel (via category if necessary), group by category, sum up the points, and take the point cap from the categorylevel table. But that's a lot of complexity when 5 simple queries will suffice.
> 0 votes

---
Tags: data-structure
---


# Question
Title: What are the performance difference between unsigned and signed integers?
I am aware of the performance hit when mixing signed ints with floats.

Is it any worse to mix unsigned ints with floats?

Is there any hit when mixing signed/unsigned without floats?

Do the different sizes (u32, u16, u8, i32, i16, i8) have any effect on performance? On which platforms?

# Answer
The large penalty from mixing ints (of any kind) and floats is because these are in different register sets. To go from one register set to the other, you have to write the value to memory and read it back, which incurs a a load-hit-store stall.

Going between different sizes or signed-ness of ints keeps everything in the same register set, so you avoid the big penalty. There may be smaller penalties due to sign-extensions, etc. but these are much smaller than a load-hit-store.
> 37 votes

# Answer
I suspect that information about the Xbox 360 and PS3 specifically are going to be behind licensed-developer-only walls, like most low-level details. However, we can construct an equivalent x86 program and disassemble it to get a general idea.

First, let's see what unsigned widening costs:

```
unsigned char x = 1;
unsigned int y = 1;
unsigned int z;
z = x;
z = y;

```

The relevant portion disassembles into (using GCC 4.4.5):

```
    z = x;
  27:   0f b6 45 ff             movzbl -0x1(%ebp),%eax
  2b:   89 45 f4                mov    %eax,-0xc(%ebp)
    z = y;
  2e:   8b 45 f8                mov    -0x8(%ebp),%eax
  31:   89 45 f4                mov    %eax,-0xc(%ebp)

```

So basically the same - in one case we move a byte, in the other we move a word. Next:

```
signed char x = 1;
signed int y = 1;
signed int z;
z = x;
z = y;

```

Turns into:

```
   z = x;
  11:   0f be 45 ff             movsbl -0x1(%ebp),%eax
  15:   89 45 f4                mov    %eax,-0xc(%ebp)
    z = y;
  18:   8b 45 f8                mov    -0x8(%ebp),%eax
  1b:   89 45 f4                mov    %eax,-0xc(%ebp)

```

So the cost of the sign extension is whatever the cost of `movsbl` rather than `movzbl` is - sub-instruction level. That's basically impossible to quantify on modern processors due to the way the modern processors work. Everything else, ranging from memory speed to caching to what was in the pipeline beforehand, is going to dominate the runtime.

In the ~10 minutes it took me to write these tests, I could easily have found a real performance bug, and as soon as I turn on any level of compiler optimization, the code becomes unrecognizable for such straightforward tasks.

This isn't Stack Overflow, so I hope no one here will claim microoptimization doesn't matter. Games often work on data that is very large and very numeric, so careful attention to branching, casts, scheduling, structure alignment, and so on can give very critical improvements. Anyone who has spent a lot of time optimizing PPC code probably has at least one horror story about load-hit-stores. But in this case, it really doesn't matter. The storage size of your integer type doesn't affect performance, as long as it's aligned and fits in a register.
> 12 votes

# Answer
Signed integer operations can be more expensive on nearly all architectures. For example, division by a constant is faster when unsigned, e.g:

```
unsigned foo(unsigned a) { return a / 1024U; }

```

is going to be optimized to:

```
unsigned foo(unsigned a) { return a >> 10; }

```

But...

```
int foo(int a) { return a / 1024; }

```

will optimize to:

```
int foo(int a) {
  return (a + 1023 * (a < 0)) >> 10;
}

```

or on systems where branching is cheap,

```
int foo(int a) {
  if (a >= 0) return a >> 10;
  else return (a + 1023) >> 10;
}

```

Same goes for modulo. This also holds true for non-powers-of-2 (but the example is more complex). If your architecture doesn't have a hardware divide (e.g most ARM), unsigned divides of non-consts are also quicker.

In general, telling the compiler that negative numbers can't result will aid optimization of expressions, especially those used for loop termination and other conditionals.

As for different size ints, yes there's a slight impact but you'd have to weigh that vs moving less memory around. These days you probably gain more from accessing less memory than you lose from size expansion. You're very far into micro-optimization at that point.
> 4 votes

# Answer
Operations with signed or unsigned int have the same cost on current processors (x86\_64, x86, powerpc, arm). On 32bits processor, u32, u16, u8 s32, s16, s8 should be the same. You can have penalty with bad alignement.

But convert int to float or float to int is a costly operation. You can easily find optimized implementation (SSE2, Neon ...).

The most important point is probably memory access. If your data doesn't fit in L1/L2 cache, you will loose more cycle than conversion.
> 3 votes

# Answer
Jon Purdy says above (I can't comment) that unsigned might be slower because it can't overflow. I disagree, unsigned arithmetic is simple moular arithmetic modulo 2 to the number of bits in the word. Signed operations in principle can suffer overflows, but they are usually turned off.

Sometimes you can do clever (but not very readable things) like pack two or more data items into an int, and get multiple operations per instruction (pocket arithmetic). But you gotta understand what you are doing. Of course MMX allows you to do this naturally. But sometimes using the largest HW supported word size and manually packing the data gives you the fastest implementation.

Be careful about data alignment. On most HW implementations nonaligned loads and stores are slower. Natural alignment, means that for say a 4byte word, the address is a multiple of four, and eight byte word addresses should be multiples of eight bytes. This carries over into SSE (128bit favors 16byte alignment). AVX will soon extend these "vector" register sizes to 256bits then 512bits. And aligned loads/stores will be faster than unaligned ones. For HW geeks, an unaligned memory operation may span things like cacheline and even page boundaries, for which the HW has to be careful about.
> 2 votes

# Answer
It is slightly better to use signed integers for loop indexes, because signed overflow is undefined in C, so the compiler will assume that such loops have fewer corner cases. This is controlled by gcc's "-fstrict-overflow" (enabled by default) and the effect is probably hard to notice without reading the assembly output.

Beyond that, x86 works better if you don't mix types, because it can use memory operands. If it has to convert types (sign or zero extensions) that means an explicit load and the use of a register.

Stick with int for local variables and most of this will happen by default.
> 1 votes

# Answer
As celion points out, the overhead of converting between ints and floats has largely to do with the copying and conversion of values between registers. The only overhead of unsigned ints in and of themselves comes from their guaranteed wraparound behaviour, which necessitates a certain amount of overflow checking in the compiled code.

There is basically no overhead in converting between signed and unsigned integers. Different sizes of integer *may* be (infinitesimally) faster or slower to access depending on platform. Generally speaking, the size of integer that's closest to the word size of the platform will be the fastest to *access,* but the overall performance difference depends on many other factors, most notably cache size: if you use `uint64_t` when all you need is `uint32_t`, it may be that less of your data is going to fit in the cache at once, and you may incur some load overhead.

It's a bit excessive to even think about this, though. If you use types that are appropriate for your data, things ought to work perfectly fine, and the amount of power to be gained by selecting types based on architecture is negligible anyway.
> 0 votes

---
Tags: c++, performance
---


# Question
Title: Popular genres in Asian (non-Japanese) markets?
From time-to-time I've wondered what kind of games are popular in Asia (India, China, Korea, Singapore, etc...). I hear about developers in the US and UK who outsource work there, but what goes into the games they make for themselves?

Related, you hear these days about how Japanese developers have been marketing their games more for American audiences these days (with mixed success). In what ways could American developers aim their development toward Asian audiences?

# Answer
First, Asian players most of all are interested in **MMOG's**. The market for them is growing rapidly, while in US it is stagnating. I provided some links in the end. While the Western RPG market is dominated by World of Warcraft, Asian MMORPGs are still booming. Worldwide, analysts expect the market to reach revenues of $8 billion in 2010, according to a Strategy Analytics report on BusinessWire.

The U.S. market has been slowing, but not stopped, and Asian market growth has led to an overall global revenue increases. The market exceeded $5 billion in 2009, a 17% growth over the prior year. If the market hits the predicted $8 billion this year, companies will take it as a sign to continue pursuing free-to-play models.

Highest interest goes into free games, or so called **Freemium model** s, where one can play for free, but get additional benefits by donating some money. The reason for such popularity may be the amount of piracy in Asia, where big companies just refuse to enter the market with single-player games as they are quickly pirated. The freemium model or usual subscription-based model is better suited for the market.

Another big one is the **apps in social networks**, renren,com , 51.com and kaxin001.com Clones of Farmville with paid virtual items are hugely popular among casual gaming crowd. But here arises the problem of entering the market - you have to find out the details of what is popular and what is not, not even talking about language barrier here, as those networks are traditionally native-languages only.

If we talk about Korea as a separate market, **Starcraft** is the main player there. There is half a dozen TV-channels streaming games 24/7 there, so you might get the perspective. For additional overview you may check article on wikipedia.
> 2 votes

---
Tags: marketing, outsourcing
---


# Question
Title: i want to move arrow by dragging and than want to toss/throw when i give swipe event
> In My Application I Have One Arrow Image With Fix Center and i Can rotate it by touch move method on same center but i also need to Toss/trow the arrow after doing some rotation with dragging or without doing that How Can I Put The Toss/Throw Action in MyApplication

Thank You Very Much In/ advance

# Answer
> 1 votes
Not sure about your specific application, but in general it would work like this.

```
float startPos = /* touchStart */;
float endPos = /* touchEnd */
float angle = atan2f(startpos.y - endpos.y, startpos.x - endpos.x);
float force = 10;

float velocityX = cosf(angle) * force;
float velocityY = sinf(angle) * force;

/** Move object every frame using velocityX / velocityY **/

```

---
Tags: iphone
---


# Question
Title: Ruby: implementing alpha-beta pruning for tic-tac-toe
So, alpha-beta pruning seems to be the most efficient algorithm out there aside from hard coding (for tic tac toe). However, I'm having problems converting the algorithm from the C++ example given in the link: http://www.webkinesia.com/games/gametree.php

Players are either 1 or 0, so doing 1 - player will switch the player

```
  WIN = 1
    LOSS = -1
    DRAW = 0
    INFINITY = 100
    def calculate_ai_next_move
        best_move = -1
        best_score = -INFINITY

        cur_player = COMPUTER
        self.remaining_moves.each do |move|
          self.make_move_with_index(move, cur_player)
          score = -self.alphabeta(-INFINITY,INFINITY, 1 - cur_player)
          self.undo_move(move)

          if score > best_score
            best_score = score
            best_move = move
          end
        end

        return best_move
    end

    def alphabeta(alpha, beta, player)
      best_score = -INFINITY
      if not self.has_available_moves?
        return WIN if self.has_this_player_won?(player) == player
        return LOSS if self.has_this_player_won?(1 - player) == 1 - player
      else
        self.remaining_moves.each do |move|
          break if alpha > beta

          self.make_move_with_index(move, player)
          move_score = -alphabeta(-alpha, -beta, 1 - player)
          self.undo_move(move)

          if move_score > alpha
            alpha = move_score
            next_move = move
          end
          best_score = alpha
        end
      end
      return best_score
    end

```

currently, the algorithm is playing terribly. It will initially pick the last space, and then choose the first (from left to right) available space after that.

Any idea with whats wrong with it?

Also, I've been doing TDD, so I know that self.has\_this\_player\_won?, self.undo\_move and self.remaining\_moves is correct.

# Answer
You need a minimal test case that reproduces the problem - input a board that will be solved with one step of the algorithm, and follow it with a debugger, or print statements if that isn't possible.

You can find out which return is actually returning the nil value - you could insert a breakpoint on the line previous to each return statement, or add a unique print statement before each return. Then track backwards to discover where the nil was introduced.

Another way would just be to step through the whole get\_best\_move function using a debugger and check it's doing what you expect (the code is short enough for this approach to be realistic).

Other observations:

* COMPUTER isn't defined
* This looks more like minimax than alpha-beta
* It's not clear from your question if it's the calculate\_ai\_next\_move or the get\_best\_move that is returning nil.
> 2 votes

---
Tags: c++, algorithm, ai, ruby
---


title: Bohemia Interactive's bio2s format

text:
# Question
Title: Bohemia Interactive's bio2s format
Does anyone have specifications for the bio2s scripting language from Bohemia Interactive? They develop Operation Flashpoint, Armed Assault (ArmA), and Virtual Battlespace.

These scripts are sometimes called O2 or Oxygen scripts and are used in their terrain and modeling tools. Oxygen is Bohemia Interactive's modeling tool.

I found additional examples of the format in this VBS2 tutorial and this ArmA forum thread.

EDIT: I clarified the purpose of the bio2s format and provided some links to examples.

# Answer
Check if this is what you´re looking for:

Oxygen 2 Manual

**From the scripting section**: For those who would like to explore the possibilities available in O2 scripting, a command reference can be found at P:\docs\oxygen2 comref\comref.html.
> 1 votes

---
Tags: scripting
---


# Question
Title: Doubt about texture waves in CG Ocean Shader
I'm new on graphical programming, and I'm having some trouble understanding the Ocean Shader described on "Effective Water Simulation from Physical Models" from GPU Gems. The source code associated to this article is here.

My problem has been to understand the concept of texture waves. First of all, what is achieved by texture waves? I'm having a hard time trying to figure out it's usefulness.

In the section 1.2.4 of the article, it does say that the waves summed into the texture have the same parametrization as the waves used for vertex positioning. Does it mean that I can't use the texture provided by the source code if I change the parameters of the waves, or add more waves to sum?

And in the section 1.4.1, is said that we can assume that there is no rotation between texture space and world space if the texture coordinates for our normal map are implicit. What does mean that the "normal map are implicit'? And why do I need a rotation between texture and world spaces if the normal map are not implicit?

I would be very grateful for any help on this.

# Answer
> 1 votes
The point of the waves generated in a texture is to use them as normal maps, allowing the appearance of more detail to the waves than would be possible without spending a lot of actual geometry on the water surface.

It's been a while since I did much actual graphics work, but I believe the point regarding the wave parameterization is just mentioned as a convenience -- if you change the vertex wave parameterization you can still use the original to generate the waves in the texture. It won't break the effect, although too much divergence might produce an undesired result. You should try experimenting.

Earlier in the article the author explains that "implicit" texture coordinates are, in this case, referring to texture coordinates that are derived from the vertex position and not passed along explicitly by the CPU side of the pipeline. The implicit texture coordinates are computed by scaling the vertex position so that the vertex position within the water plane is transformed to a \[0,1\] texture coordinate range, that's all.

---
Tags: textures, shaders, cg
---


# Question
Title: Breakout clone, how to handle/design for collision detection/physics between objects?
I'm working on a breakout clone, and I wish to create some realistic physics effects for collision - angles on the paddle should allow the ball to bounce, as well as doing curve balls etc. I could use per-pixel based collision detection, but then I thought it might be easier with line/circle intersection testing.

So, then I naturally consider making a polygon class for the line-based objects and use the built-in circle class for the circular objects. That sounds like an OK approach, right? And then just check for collision using the specified algorithm based on the objects that might be within each other's range?

# Answer
> 2 votes
That seems like a good approach, you can utilize the separating axis theorem to perform your collision detection.

---
Tags: collision-detection, physics
---


# Question
Title: Adding 2D vector movement with rotation applied
I am trying to apply a slight sine wave movement to objects that float around the screen to make them a little more interesting. I would like to apply this to the objects so that they oscillate from side to side, not front to back (so the oscillation does not affect their forward velocity).

After reading various threads and tutorials, I have come to the conclusion that I need to create and add vectors, but I simply cannot come up with a solution that works.

This is where I'm at right now, in the object's update method (updated based on comments):

```
Vector2 oldPosition = new Vector2(spritePos.X, spritePos.Y);

//note: newPosition is initially set in the constructor to spritePos.x/y
Vector2 direction = newPosition - oldPosition;

Vector2 perpendicular = new Vector2(direction.Y, -direction.X);

perpendicular.Normalize();

sinePosAng += 0.1f;
perpendicular.X += 2.5f * (float)Math.Sin(sinePosAng);

spritePos.X += velocity * (float)Math.Cos(radians);
spritePos.Y += velocity * (float)Math.Sin(radians);

spritePos += perpendicular;

newPosition = spritePos;

```

# Answer
> 5 votes
EDIT: Based on the discussion in the comments and your updated code, I suggest you try doing something like this:

```
// oldPosition is a member variable, it holds the real position of the
// object (without the "wobble" applied).
Vector2 newPosition = oldPosition;
newPosition.X += velocity * (float)Math.Cos(radians);
newPosition.Y += velocity * (float)Math.Sin(radians);

// This gives us a vector from the old position to the new position, indicating
// the direction our object is moving.
Vector2 direction = newPosition - oldPosition;

// We normalize the perpendicular vector so that we can scale it reliably later.
Vector2 perpendicular = new Vector(direction.Y, -direction.X);
perpendicular.Normalize();

float offset = 5.0f * (float)Math.Sin(sinPosAng);
sinPosAng += 0.01;f

// By keeping spritePos independent from oldPosition, we allow the wobble to visually
// affect the object without logically affecting it's real location; this prevents
// the wobble from feeding back on to itself.
spritePos = newPosition + (offset * perpendicular);

// For the next frame, the old position will be what is currently the new position.
oldPosition = newPosition;

```

If you have a perpendicular vector and you normalize it, you can then scale it by the result of `Math.Sin(sinePosAng)` and then scale it again to achieve the desired total offset, which you then add to the new position. The purpose of the normalization is to ensure the scale is reliable each frame -- you know the length of the vector before you scale it, so you know the results will be exactly what you expect.

The other thing you'll want to watch out for is that you may want to the old/new positions distinctly from the offset position (after the "wobble" is applied) -- this is because otherwise the "wobble" applied on frame N will factor in to the computation of the direction vector on frame N + 1 and if the scale of the wobble is large enough, you're object may start to curve in an undesired fashion. In the example above, I assume that both `oldPosition` and `spritePos` are member variables -- `spritePos` will contain the location of the sprite (which has the wobble applied), but `oldPosition` contains the un-wobble'd position.

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


title: Shadow Mapping and Transparent Quads

text:
# Question
Title: Shadow Mapping and Transparent Quads
Shadow mapping uses the depth buffer to calculate where shadows should be drawn.

My problem is that I'd like some semi transparent textured quads to cast shadows - for example billboarded trees. As the depth value will be set across all of the quad and not just the visible parts it will cast a quad shadow, which is not what I want.

**How can I make my transparent quads cast correct shadows using shadow mapping?**

# Answer
> 15 votes
Your problem will solve rendering with 1bit alpha. Which means you specify some alpha of source texture which is not rendered (mostly 0.5).

You have to write your own shader for saving depth from light and use instruction `discard`. Discard exists in hlsl, glsl and in cg as well. It exists only in pixel/fragment shader and discards curent fragment from the rendering into backBuffer and into z-buffer.

```
if (texSample.a < 0.5)
   discard;

```

Advantage is that you don't need to change yours 2nd pass rendering, only rendering of light's depth. Also i have prove that it works:

If you want to render correct shadows for multiple transparent objects you will have to use multiple depth textures, with depth and opacity information rendered using depth peeling. And for smoke, hair etc. Deep opacity or Fourier opacity maps are best solution (I mostly recommend Fourier opacity maps)

edit: I just realized that i forgotten to add credits. As always. The tree model is from loopix project which is just great if you are looking for some lowpoly, one texture and free models of vegetation.

# Answer
> 6 votes
With programmable pipeline you should do it how @notabene instructed. However it's easy to do with fixed pipeline as well without writing any shaders. In OpenGL glAlphaFunc is what you want. For example:

```
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.5f);

```

# Answer
> 2 votes
You need a custom shader for the shadow map generation, so you can output a valid occluder when the transparency of the pixel/fragment is greater than the treshold you specify. This whay, the depth map will be generated per pixel and not per polygon.

# Answer
> -1 votes
The only way I can think of doing this is creating a separate depth map texture, rendering the trees into it, outputting for depth where alpha != 0, otherwise outputting depth = 1, then combining this shadow map texture with the scene shadow map texture, which should be simple enough; simply take the smallest of the two values and set that to the final depth map.

This doesn't solve blending orders though; if you output a depth behind an alpha texture it will be overridden when you render the quad with the texture on it, so for this effect to work you're going to have to render each quad individually into the depth map texture...

---
Tags: shadows, shadow-mapping, depth-buffer, transparency
---


# Question
Title: How do you publish a Xbox Live game on Windows Phone?
Curious if any of you have gone through the process? How did you kick it off? Is there anything in particular that we should be aware of when trying to make a Live game?

# Answer
You should check at this blog post from Andre Vrignaud, he was responsible for windows LIVE strategy.

**From the post:**

> The bar is pretty high for titles to be able to use Xbox LIVE services – we’re aiming for a very high-quality, managed portfolio. But if you feel you’ve got the ideas and the chops to hit that bar, both our publishing partners and ourselves are interested in talking with you!
>
> Feel like you’ve got game? Here’s what you do:
>
> 1. Email wpgames@microsoft.com with a description of your game and your contact information. We’ll send you a content submission form. We love playable demos!
> 2. If your game is accepted, you’ll hear from the developer relations staff and we’ll work with you to get you the resources required to get started.
> 3. We’ll take care of the rest – game integration, promotions, marketing, data analysis and community support.

It has begun! First sessions on developing games for windows phone at gdc
> 3 votes

# Answer
You need a contract with Microsoft. Your should contact them directly (hard) or through one of their partners that work on WP7 (somewhat easier).
> 1 votes

---
Tags: windows-phone-7, xbox-live
---


title: Mental Ray render loss in Maya?

text:
# Question
Title: Mental Ray render loss in Maya?
The option in the rendering menu of Maya doesn't say "Mental Ray" anymore. Please help me to get it back, or even a better plugin for Maya game quality rendering.

# Answer
> 1 votes
A quick google search says that sometimes it "deactivates itself" and it has to be reactivated on the plugin manager (`Window > Settings/Preferences > Plug-in Manager`)

EDIT: According to this other post, Mental Ray's dll is called `Mayatomr.mll`

---
Tags: rendering, animation, scene-graph
---


# Question
Title: Creating a 2D skeleton animation system for use with Panda3D
Hey. I want to be able to create a system for 2D skeletal animation in my game. I'm using panda3d as my game engine. I'd like to be able to make simple bone structures and skin them with my sprites. I would prefer to do this with straight code and algorithms, but if I have to use a 3D modeler or something, then I can try to (I didn't do a great job last time I tried using Blender... \>.\<)

# Answer
> 1 votes
Not really sure about panda3d, but I am pretty sure you need to start thinking about the algorithms and structure / pattern of making bones then moving them, then skinning them with your sprites.

Once these concepts are strong in your mind, you should then apply them to panda3d (what ever language / scripting it uses) or look up specific panda3d existing 2d animation systems using bones.

Similar to - how to learn 2d animation

How to learn 2d animation?

---
Tags: 2d, animation, skeletal-animation, python
---


# Question
Title: Bluring behind something then drawing text?
I want to basically make a blur shader in glsl and use it like Windows 7 does for Windows. I want to for example draw something and then blur a rectangle, then draw text over it.

If someone could point me in the right direction on how to do this I'd be very grateful.

Thanks

# Answer
This kind of effect is known as a Guassian blur. It's a relatively common effect, so you can find information about the algorithm and even some sample shaders relatively easily: for example, here, here and here were the first three Google results that looked vaguely worthwhile.

The general idea is that you're going to have to render the scene you want blurred into a render target texture, then bind that texture for a second render phase during which you'll compute the blur effect.

To render *sharp* images on top of the blur (for example, your text), you can render the blurring phase into a render target texture as well, and bind that texture for the final pass where you'd render your text over the scene.

You may also want to look for discussion of GPU post-processing systems to get a feel for how you might architect you render pipeline to be generally scalable to these sorts of multi-phase effects.
> 3 votes

---
Tags: c++, shaders, glsl, blur
---


# Question
Title: How to make a video game map that can be used by Android?
I am interested in developing games for the Android OS. I have played Replica Island and I have browsed over the source. I found that the levels/maps were in a .bin format. I could execute them because they were in an Android format. So how could I make a game map/level that could be used in my game? What program would I use? How could I load the map in Java (for Android)?

# Answer
> 3 votes
I think you're missing it a bit here. What happens is that your game or app is run, and that then opens and reads in the data from a map file. The map file is not actually executable, it simply holds data.

Say you have a tile map of 10x10 in a 2d array. Say that it is all water (tile ID 0) and grass (tile ID 1). You would save this into a file, row by row, probably in a binary (not human readable) format. So if your map had a few rows like this:

```
0001011101
0010111101
0001011101
0010111101
0001011101
0010111101
0001011101
0010111101
0001011101
0010111101

```

(It's repeating, but it's an example. All the 0s are water and 1s are land)

You would go through each row and save it to a file. So your file would just be, in binary:

```
0001011101001011110100010111010010111101000101110100101111010001011101001011110100010110010111101

```

When you come to read it in, you would read in number by number, and you know that a 0 is water (and you would set that tile to be water) and the 1 to be land.

Of course, this is very simple. But the chance is you would have an ID system, so rather than saving 'water water land' you can do '001'. Same for items - instead of 'sword, location 1,0; axe, location 3,0' you would maybe write yours in binary as '45 1 0 76 3 0'.

For Java, look up any kind of file API documentation.

# Answer
> 1 votes
Usually, you make a map like lets say a 2D array, and then output it in whatever format. Binary is small and fast, so you might want to use that. You would then have a reader in your game which would parse through that file (binary or whatever) and load your "level" data structure accordingly.

---
Tags: game-design, android, maps
---


title: MeshBuilder, assembly missing

text:
# Question
Title: MeshBuilder, assembly missing
I'm trying to build a terrain starting from a heightmap. I've already some ideas about the procedure, but I can't even get started. I feel like I have to use a MeshBuider. The problem is that Visual Studio (I'm using the 2008 version) wants an *assembly*. Effectively on the MSDN there's a line specifying the assembly needed by the MeshBuilder, but I don't know how to import/load it.
Any suggestions?

Thanks in advance :)

# Answer
Okay, then you need to add a reference to the content pipeline assemblies from your game project. XNA by default won't do this.

In VS -\> Project Menu -\> Add Reference. Under the .NET tab, you'll find everything. It's helpful to sort by component name. You're looking for the component Microsoft.Xna.Framework.Content.Pipeline.

Don't add the importers, those are for converting resources into XNA's internal format in content pipeline projects.
> 2 votes

---
Tags: xna, importing
---


# Question
Title: XNA Required information to represent 2D Sprite graphically
I was thinking about dividing my game engine into 2 threads: render thread and update thread (I can't come up on how to divide update thread from physic thread at the moment).

That said, I have to duplicate all Sprite informations, what do I really need to represents a 2D Sprite graphically?

Here are my ideas (I'll mark with **?** things that I'm not sure):

```
Vector2 Position
float Rotation ?
Vector2 Pivot ?
Rectangle TextureRectangle
Texture2D Texture
Vector2 ImageOrigin ? (is it tracked somewhere else?)

```

If you have any suggestion about using different types for datas, it's appreciated

Last part of the question: isn't this a lot of data to copy in a buffer?what should I really copy in the buffer?I'm following this tutorial:

http://www.sgtconker.com/2009/11/article-multi-threading-your-xna/3/

Thanks

**UPDATE 1:**

Newer values at the moment:

```
Vector2 Position
float Rotation
Vector2 Pivot
Rectangle TextureRectangle
Texture2D Texture
Color Color
byte Facing (can be left or right, I'll do it with an enum)

```

I re-read the tutorial, what I was doing wrong is not that I need to pass all those values, I need to pass only **changed** values as messages.

**UPDATE 2:**

```
Vector2 Position
float Rotation
Vector2 Pivot
Rectangle TextureRectangle
Texture2D Texture
Color Color
bool Flip
uint DrawOrder
Vector2 Scale
bool Visible ?

```

Mhhh, should Visibile be included?

# Answer
If you want to use that method of multi-threading, for each object in the game you ideally just want to the information that it needs to render.

* Location
* Rotation
* Scale
* Reference of image to draw for Sprite
* Draw order
* Anything the draw thread needs to know to draw.

**You do not want to be copying the actual graphics back and forth, just references to data, and any small data that is unique to each one.**
> 4 votes

# Answer
My question is why do you wanna to do that? :)

Separate draw and update into two threads is really important for games performance. But XNA does helps you in this. There are

```
protected override void Update(GameTime gameTime)
protected override void Draw(GameTime gameTime)

```

callbacks. And XNA calls them properly. As you are making some 2D game i'm pretty sure that you dont need multithreading performance benefit. But if you wanna to try multithreading... ok.

To your question. Data that you want to share between threads seems to be right. But maybe imageOrigin==pivot. And also you are propably not going to change textures every frame, they may be saved in both threads and changed only when needed.
> 2 votes

# Answer
Responding to Update #1

**Pivot**

Are you planning on rotating the sprites around some point other than their center? If not then this seems like a duplicate of position.

**Facing**

Not sure what this is for although with your enum of Left/Right I'm assuming it's for backface culling? If you are just drawing a quad at a 2D point in space then you don't need to worry about which side you are on.

**Draw Order**

Your update 1 is still missing a draw order index, which AttackingHobo also mentioned. You'll want that to force some sprites to the top as well as keep them consistent when crossing over one another.
> 2 votes

# Answer
I think notabene is write in that the Pivot does equal ImageOrigin. The XNA draw call takes an origin that is the pivot for rotation and the image origin, they are one in the same.

Anyway, I would suggest adding a Color field for tinting and make sure that you allow the TextureRectangle to have some null value. (I think adding a "?" at the end of Rectangle would do the trick, but might cause boxing due to Nullable???) Probably set the TextureRectangle to new Rectangle(-1, -1, -1, -1) as a way to communicate that it's a null source rectangle.

Also, you should consider doing some benchmarking if your not completely sure if you need to do this, don't optimize needlessly. You could throw in a SpriteEffects enum field in there, but I doubt you'll need it.
> 1 votes

# Answer
Basically if you want total control over spritebatch, you'd probably want to use variables for ALL of its overloads, (with the exception of spriteEffect and rectangle unless you're doing a side-scrolling platformer) like so:

```
public class Character()
{

     Texture2D texture; (optional variable)

     Vector2 position;
     Vector2 origin;
     float rotation = 0f;
     float scale = 1.0f;
     float depth = 0;
     Color color = Color.White;
}

```

i.e

```
   spriteBatch.Draw(character.texture, character.position, null, character.color, character.rotation, character.origin, character.scale, SpriteEffects.None, character.depth);

```
> 0 votes

---
Tags: xna, 2d, graphics, sprites, data
---


# Question
Title: How to apply Data Oriented Design with Object Oriented Programming?
I've read lots of articles about Data Oriented Design (DOD) and I understand it but I can't design an Object Oriented Programming (OOP) system with DOD in mind, I think my OOP education is blocking me. How should I think to mix the two? The objective is to have a nice OOP interface while using DOD behind the scenes.

I saw this too but didn't help much: https://stackoverflow.com/questions/3872354/how-to-apply-dop-and-keep-a-nice-user-interface

# Answer
> 16 votes
I would say that Noel Llopis's blog is probably the best instruction for a combination of object-oriented programming and data-oriented design. He is one of the originators of the DOD term, is a strong C++ programmer, and has written a good deal about his style and how he takes advantage of C++'s OO features.

I guess if I were to call out the key elements of combining them, according to Noel:

* Use POD and non-member, non-friend functions as much as possible. Non-member, non-friend functions improve encapsulation and are a key part of data-orientation because they keep the data, data.
* Avoid storing "temporary" state on your objects. Temporary state clogs up your data. If you need to cache something (e.g. for performance) then that belongs in a new class, with non-member non-friend functions linking the two types, not a is-a nor a has-a relationship.
* Avoid objects that can be in state A or state B. Prefer switching between two objects, one of which is A, and one of which is B.
* Avoid polymorphism, avoid virtual functions, avoid templates, avoid anything that makes your data have the *syntactic appearance* of sameness rather than *actual* sameness.

The other big name in DOD propaganda right now is Mike Acton of Insomniac, but reading what he's written I'd say he's not really pro-OO (or anti-OO, as long as it's still data-oriented).

---
Tags: c++, architecture
---


title: Direct3D Error Code 80070057

text:
# Question
Title: Direct3D Error Code 80070057
I'm getting a failure returned when calling Direct3DDevice-\>CreateDepthStencilSurface(). But rather than returning one of the values that the documentation says it should return (D3DERR\_NOTAVAILABLE, D3DERR\_INVALIDCALL, D3DERR\_OUTOFVIDEOMEMORY, E\_OUTOFMEMORY), it returns error code 80070057. What does this mean?

# Answer
> 7 votes
Use the DirectX Error Lookup tool that's found in the SDK.

Passing this value in it returns the following result:

HRESULT: 0x80070057 (2147942487)
Name: E\_INVALIDARG
Description: An invalid parameter was passed to the returning function
Severity code: Failed
Facility Code: FACILITY\_WIN32 (7)
Error Code: 0x0057 (87)

You have an invalid argument passed into the function. Check the contents of your parameters.

---
Tags: directx9
---


# Question
Title: Collision detection of convex shapes on voxel terrain
I have some standard convex shapes (cubes, capsules) on a voxel terrain. It is very easy to detect single vertex collisions. However, it becomes computationally expensive when many vertices are involved.

To clarify, currently my algorithm represents a cube as multiple vertices covering every face of the cube, not just the corners. This is because the cubes can be much bigger than the voxels, so multiple sample points (vertices) are required (the distance between sample points must be at least the width of a voxel). This very rapidly becomes intractable.

It would be great if there were some standard algorithm(s) for collision detection between convex shapes and arbitrary voxel based terrain (like there is with OBB's and seperating axis theorem etc).

Any help much appreciated.

# Answer
> 4 votes
In my engine I perform collision detection/physics against the extracted surface mesh, rather than the underlying voxel data. This avoids the type of problem you describe - the physics engine doesn't know there are voxels involved at all and perfroms standard mesh to mesh calculations.

Of course, I can appriciate that using the voxel data has certain advantages (and it's something I would like to research in the future) but I found my current approach quite satisfactory. You can see a video of it in action and/or download a demo from my website: http://www.thermite3d.org

# Answer
> 1 votes
It seems to me that bounding box techniques still apply - even though you might consider your cubes "supersampled". I would approach the problem in a hierarchical manner: you should know the maximal extents of the cube (even though a number of points might exist "between" those points) - so consider those maximal vertices as the cube's bounding box.

Assuming you have some sort of BB structure defined for the landscape, your can then use BB intersection techniques as a high-level hit-test. From there, you can "dive down" into the cube in order to determine precisely which vertices intersected.

# Answer
> 0 votes
Look into the GJK algorithm, which may be used for convex shape collision. You may be able to make appropriate adjustments to make it work with your voxels, I wouldn't know. Here's a great video explaining it: https://mollyrocket.com/849

I think if you can create a function which can give the position of the voxel furthest along in a certain direction (ie, the support), you can probably make the algorithm work. Of course, you need to constrain your support vector function for voxel terrain to some region around the object you're testing collision with, since it makes no sense to check far away terrain.

---
Tags: 3d, collision-detection, algorithm, voxels
---


title: 2.5D game development

text:
# Question
Title: 2.5D game development
> 2.5D ("two-and-a-half-dimensional"), 3/4 perspective and pseudo-3D are terms used to describe either:
>
> * graphical projections and techniques which cause a series of images or scenes to fake or appear to be three-dimensional (3D) when in fact they are not, or
> * gameplay in an otherwise three-dimensional video game that is
> restricted to a two-dimensional
> plane.
>
> *(Information taken from Wikipedia.org)*

I have a question based on 2.5D game development. As stated before, 2.5D uses *graphical projections and techniques* to make fake 3d or a gameplay restricted to a *two-dimensional plane*.

A good example is a TQ Digital made game: Zero Online (screenshot) the whole map is made of 2d images and only NPCs and players are 3d.

The maps were drawn manually by hand without any 3d software rendering. As I'm playing the game I feel like I'm going from a lower part of the map (ground) to a higher one (some metal platform) and it feels like I'm moving in 3 dimensions. But when I look closely, I see that the player size didn't change and the shadow too but I'm still feeling like I'm somehow higher then before (I had rendered a simple map myself that I made in 3dmax but it didn't quite give the result I wanted).

How can you accomplish such an effect?

# Answer
To achieve such an effect, you can use a 3D Projection without perspective (called parallel projection). That will render all your objects at the same size and from the same angle, no matter where they are positioned. Something like this is mandatory if you're using a painted background.

Here's a nice overview of some possible projections.

In addition to the background image, you'll have to store some sort of topological information for the ground. E.g. the height per "cell", so that you can move your characters up/down accordingly. If you have a ramp, you can interpolate the height values between the upper and the lower cell.
> 9 votes

---
Tags: 2d, maps, 2.5d
---


# Question
Title: XNA: How to make the Vaus Spacecraft move left and right on directional keys pressed?
I'm currently learning XNA per suggestion from this question's accepted answer:
Where to start writing games, any tutorials or the like?

I have then installed everything to get ready to work with XNA Game Studio 4.0.

> **General Objective**

Writing an Arkanoid-like game. I want to make my ship move when I press either left or right keys.

> **Code Sample**

```
    protected override void Update(GameTime gameTime) {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here
#if WINDOWS
        if (Keyboard.GetState().IsKeyDown(Keys.Escape))
            this.Exit();
        else {
            if (Keyboard.GetState().IsKeyDown(Keys.Left))
                MoveLeft(gameTime);
        }
#endif

        // Move the sprite around.
        BounceEnergyBall(gameTime);

        base.Update(gameTime);
    }

    void MoveLeft(GameTime gameTime) {
        // I'm not sure how to play with the Vector2 object and its position here!...
        _vausSpacecraftPos /= _vausSpacecraftSpeed.X; // This line makes the spacecraft move diagnol-top-left.
    }

```

> **Question**

What formula shall I use, or what algorithm shall I consider to make my spaceship move as expected left and right properly?

---

Thanks for your thoughts! Any clue will be appreciated. I am on my learning curve though I have years of development behind me (already)!

# Answer
It looks like you want to do something like: `_vausSpacecraftPos.X += _vausSpacecraftSpeed.X;` -- you may also want to scale by the elapsed time stored in the GameTime object so you get frame-rate independent movement.
> 4 votes

# Answer
You could use some inertia by making the keys apply a force to the spacecraft rather than just applying speed:

```
const float MOVE_FORCE = 5.0f; // tweak this constant for more responsive movement
float force = 0.0f;
if (Keyboard.GetState().IsKeyDown(Keys.Left))
{
    force -= MOVE_FORCE;
}
else if (Keyboard.GetState().IsKeyDown(Keys.Right))
{
    force += MOVE_FORCE;
}

// we add in air resistence to cap the max speed of the spacecraft
const float AIR_RESISTENCE = 0.1f; // tweak this to change top speed
float airResistenceForce = _spacecraftSpeed.X * _spacecraftSpeed.X * AIR_RESISTENCE;
// air resistence is always applied against the current speed direction
if (_spacecraftSpeed.X < 0.0f)
{
    force += airResistenceForce;
}
else
{
    force -= airResistenceForce;
}

const float MASS = 1.0f; // tweak for more/less inertia
float acceleration = force / MASS;

_spacecraftSpeed.X += acceleration * timeStep;
_spacecraftPos.X += _spacecraftSpeed.X * timeStep;

```

You have a few constants to tweak in here to get the handling exactly right. I'd reccomend hooking up some code to tweak them at runtime.

You can go crazy and add more forces to the spacecraft - maybe an "autoaim" force that pushes the spacecraft towards a target point? Or a powerup/punishment random force that makes the spacecraft hard to control?
> 1 votes

---
Tags: xna, algorithm, movement, keyboard
---


# Question
Title: In OpenGL, how can I discover the depth range of a depth buffer?
I am doing a GL multi-pass rendering app for iOS. The first pass renders to a depth buffer texture. The second pass uses the values in the depth buffer to control the application of a fragment shader. I want to rescale the values in the depth buffer to something useful but before I can do that I need to know the depth value range of the depth buffer values. How do I do this?

# Answer
The range of the values written to the depth buffer are whatever you want them to be. Typically they fall in the 0-to-1 range. The actual value that is written in to the depth buffer is computed during the viewport transformation, based on the Z value of vertex in NDC space (after the perspective divide by w in clip space).

The NDC depth value (Z, after the perspective divide by W) is scaled by depth portion of the viewport transformation (which brings your X and Y coordinates into a coordinate space you'd associate with pixels in the window), and then scaled by `(2^n-1)` -- that's meant to be read as "two to the power of `n`" -- `n` is the bit precision of the depth buffer. The resulting value is written to the depth buffer.

OpenGL splits definition of the viewport transformation matrix into glViewport and glDepthRange calls. glDepthRange is what controls the scale factor responsible for determining the depth range you are asking about. You can call glGetFloatv with the `GL_DEPTH_RANGE` selector to recover the current range. This will allow you to make use of the range without assuming it's 0 to 1 (although 99.9% of the time, in practice, nobody ever changes it).

Further reading, if you want some insight on how to reconstruct the math to follow the Z value all the way from eye space to the depth buffer.
> 10 votes

# Answer
Values in depth buffer are always in range between 0-1. Zero is that rendered fragment is in depth of near plane and 1 is that fragment is in depth of far plane. And everything between it.

If you want to know real depth in world space it is easy to compute it from depth buffer.

```
depth = nearPlane + ( farPlane - nearPlane ) * depthBufferValue;

```

And thats why you specify the near and far planes in your projection matri, to gain more accuracy of depth buffer.

Also be aware of difference between depth and distance when using depth buffer values.
> 7 votes

---
Tags: opengl, opengl-es, depth-buffer
---


# Question
Title: WoW lua: Getting quest attributes before the QUEST_DETAIL event
**I'd like to determine the attributes of a quest (i.e., information provided by functions such as QuestIsDaily and IsQuestCompletable) *before* the player clicks on the quest detail.**

I'm trying to write an add-on that handles accepting and completing of daily quests with a single click on the NPC, but I'm running into a problem whereby I can't find out anything about a given quest unless the quest text is currently being displayed, defeating the purpose of the add-on. Other add-ons of this nature seem to be getting around this limitation by hard-coding information about quests, an approach I don't much like as it requires constant maintenance.

It seems to me that this information must be available somehow, as the game itself can properly figure out which icon to display over the head of the NPC without player interaction. The only question is, are add-on authors allowed access to this information? If so, how?

---

EDIT: What I originally left out was that the situations I'm trying to address are when:

1. An NPC has multiple quests
2. The quest detail is not the first thing that shows up upon right-click

Otherwise, the situation is much simpler, as I have the information I need provided immediately.

# Answer
> 4 votes
GetGossipAvailableQuests allows you to get available quests from the NPC once you have triggered the GOSSIP\_SHOW event and allows you to determine if it is a daily quest. GetGossipActiveQuests allows you to get active quests from the NPC under the same condition and returns a value for each one that indicates whether or not it is complete. Assuming the "one click" is a right-click within range of the NPC, this would work.

If you're looking for something that's available via a left-click at any range, I'm unfamiliar with such an API function.

---
Tags: world-of-warcraft-modding, quests
---


# Question
Title: Wikipedia A* pathfinding algorithm takes a lot of time
I've successfully implemented A\* pathfinding in C# but it is very slow, and I don't understand why. I even tried not sorting the openNodes list but it's still the same.

The map is 80x80, and there are 10-11 nodes.

I took the pseudocode from here Wikipedia

And this is my implementation:

```
 public static List<PGNode> Pathfind(PGMap mMap, PGNode mStart, PGNode mEnd)
    {
        mMap.ClearNodes();

        mMap.GetTile(mStart.X, mStart.Y).Value = 0;
        mMap.GetTile(mEnd.X, mEnd.Y).Value = 0;

        List<PGNode> openNodes = new List<PGNode>();
        List<PGNode> closedNodes = new List<PGNode>();
        List<PGNode> solutionNodes = new List<PGNode>();

        mStart.G = 0;
        mStart.H = GetManhattanHeuristic(mStart, mEnd);

        solutionNodes.Add(mStart);
        solutionNodes.Add(mEnd);

        openNodes.Add(mStart); // 1) Add the starting square (or node) to the open list.

        while (openNodes.Count > 0) // 2) Repeat the following:
        {
            openNodes.Sort((p1, p2) => p1.F.CompareTo(p2.F));

            PGNode current = openNodes[0]; // a) We refer to this as the current square.)

            if (current == mEnd)
            {
                while (current != null)
                {
                    solutionNodes.Add(current);
                    current = current.Parent;
                }

                return solutionNodes;
            }

            openNodes.Remove(current);
            closedNodes.Add(current); // b) Switch it to the closed list.

            List<PGNode> neighborNodes = current.GetNeighborNodes();
            double cost = 0;
            bool isCostBetter = false;

            for (int i = 0; i < neighborNodes.Count; i++)
            {
                PGNode neighbor = neighborNodes[i];
                cost = current.G + 10;
                isCostBetter = false;

                if (neighbor.Passable == false || closedNodes.Contains(neighbor))
                    continue; // If it is not walkable or if it is on the closed list, ignore it.

                if (openNodes.Contains(neighbor) == false)
                {
                    openNodes.Add(neighbor); // If it isn’t on the open list, add it to the open list.
                    isCostBetter = true;
                }
                else if (cost < neighbor.G)
                {
                    isCostBetter = true;
                }

                if (isCostBetter)
                {
                    neighbor.Parent = current; //  Make the current square the parent of this square.
                    neighbor.G = cost;
                    neighbor.H = GetManhattanHeuristic(current, neighbor);
                }
            }
        }

        return null;
    }

```

Here's the heuristic I'm using:

```
    private static double GetManhattanHeuristic(PGNode mStart, PGNode mEnd)
    {
        return Math.Abs(mStart.X - mEnd.X) + Math.Abs(mStart.Y - mEnd.Y);
    }

```

What am I doing wrong? It's an entire day I keep looking at the same code.

# Answer
> 10 votes
I see three things, one wrong, two suspicious.

1) You're sorting on every iteration. Don't. Either use a priority queue, or at the very least do a linear search to find the minimum. You don't actually need the whole list to be sorted at all times!

2) openNodes.Contains() is probably slow (not sure about the specifics of C#'s List, but I bet it does a linear search). You can add a flag to each node and do this in O(1).

3) GetNeighborNodes() could be slow.

# Answer
> 9 votes
In addition to the point already made that you should use a priority heap, you've misunderstood the heuristic. You have

```
if (isCostBetter)
{
    ...
    neighbor.H = GetManhattanHeuristic(current, neighbor);
}

```
But the heuristic is supposed to be an estimate for the distance to the destination. You should set it once, when you first add the neighbour:
```
if (openNodes.Contains(neighbor) == false)
{
    neighbor.H = GetHeuristic(neighbor, mEnd);
    ...
}
```

And as a further minor point, you could simplify the A\* by filtering out impassable nodes in `GetNeighbourNodes()`.

# Answer
> 4 votes
The meta-answer: you should *never* just spend a day staring at code looking for performance problems. Five minutes with a profiler would show you exactly where the bottlenecks are. You can download a free trail of most profilers and get it hooked up to your app in a few minutes.

# Answer
> 3 votes
It is not clear what you are comparing when you compare the F of different nodes. Is F a property defined as G + H? It should be. (Side-rant: This is an example of why the uniform access principle is crap.)

More important though, you are re-sorting the nodes every frame. A\* calls for the use of a priority queue, which allows efficient - O(lg n) - sorted insertion of a single element, and a set, which allows quick checks for closed nodes. As you have written the algorithm, you have O(n lg n) insertion + sort, which raises the run-time to useless proportions.

(You might get O(n) insertion + sort if C# has a good sorting algorithm. It's still too much. Use a real priority queue.)

# Answer
> 2 votes
http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html

* At one extreme, if h(n) is 0, then only g(n) plays a role, and A\* turns into Dijkstra’s algorithm, which is guaranteed to find a shortest path.
* If h(n) is always lower than (or equal to) the cost of moving from n to the goal, then A\* is guaranteed to find a shortest path. The lower h(n) is, the more node A\* expands, making it slower.
* If h(n) is exactly equal to the cost of moving from n to the goal, then A\* will only follow the best path and never expand anything else, making it very fast. Although you can’t make this happen in all cases, you can make it exact in some special cases. It’s nice to know that given perfect information, A\* will behave perfectly.
* If h(n) is sometimes greater than the cost of moving from n to the goal, then A\* is not guaranteed to find a shortest path, but it can run faster.
* At the other extreme, if h(n) is very high relative to g(n), then only h(n) plays a role, and A\* turns into Best-First-Search.

You are using 'manhatten distance'. This is almost always a bad heuristic. Additionally, from looking at that info from the linked page, you can guess that your heuristic is lower than the true cost.

# Answer
> 2 votes
In addition to the other top answers (which are undoubtedly more significant than this suggestion), another optimisation is to change the closed 'list' into some sort of hash table. You don't need it to be an ordered collection, just to be able to quickly add values and to quickly see if they exist in the collection.

# Answer
> 1 votes
Your Cost and your Heuristic need to have a relationship. It should be a clue that H is calculated in two different spots but never accessed.

---
Tags: c#, path-finding, optimization, .net
---


title: Moving my sprite in XNA using classes

text:
# Question
Title: Moving my sprite in XNA using classes
Hey, im a newbie at this programming lark and its really frustrating me. I'm trying to move a snake in all directions while using classes. Ive created a vector2 for speed and ive attempted creating a method which moves the snake within the snake class.

Now I'm confused and not sure what to do next.

Appreciate any help. Thanks :D

This is what i've done in terms of the method...

```
  public Vector2 direction()
        {
                Vector2 inputDirection = Vector2.Zero;

                if (Keyboard.GetState().IsKeyDown(Keys.Left)) inputDirection.X -= -1;
                if (Keyboard.GetState().IsKeyDown(Keys.Right)) inputDirection.X += 1;
                if (Keyboard.GetState().IsKeyDown(Keys.Up)) inputDirection.Y -= -1;
                if (Keyboard.GetState().IsKeyDown(Keys.Down)) inputDirection.Y += 1;

                return inputDirection * snakeSpeed;

        }

```

Appreciate any help. Thanks :D

EDIT:
Well let me make everything clear. Im making a small basic game for an assignment. The game is similar to the old snake game on the old Nokia phones. I've created a snake class (even though I'm not sure whether this is needed because im only going to be having one moving sprite within the game). After I written the code above (in the snake class), the game ran with no errors but I couldn't actually move the image :(

EDIT2: Thanks so much for everyones responses!!

# Answer
> 2 votes
Although I am also a newbie in game development, my bet would be that you are always reinitializing your `inputDirection` variable to `Vector2.Zero`.

I don't know much about game development, but as for object-oriented programming, that is another thing! **Here what I have come with after having read your comment about classes.**

```
public class Snake {
    private Texture2D _snake; // Represents your snake's sprite.
    private Vector2 _snakePos; // Field that determines your snake's position.
    private Vector2 _snakeSpeed = new Vector2(10.0f, 10.0f); // Field that determines the number of pixels your snake will move at once while moving.

    public Snake(Vector2 initialPosition) {
        _snakePos = initialPosition;
    }

    public void MoveDown() {
        _snakePos.Y += _snakeSpeed.Y;
    }

    public void MoveLeft() {
        _snakePos.X -= _snakeSpeed.X;
    }

    public void MoveRight() {
        _snakePos.X += _snakeSpeed.Y;
    }

    public void MoveUp() {
        _snakePos.Y -= _snakeSpeed.Y;
    }
}

public class Game Game1 {
    private Snake _snake = new Snake();

    protected override void Update(GameTime gameTime) {
        Keys[] keys = Keyboard.GetState().GetPressedKeys();

        if (keys != null && keys.Length > 0)
            switch (keys[0]) {
                case Keys.Escape:
                    Exit();
                    break;
                case Keys.Down:
                    _snake.MoveDown();
                    break;
                case Keys.Left:
                    _snake.MoveLeft();
                    break;
                case Keys.Right:
                    _snake.MoveRight();
                    break;
                case Keys.Up:
                    _snake.MoveUp();
                    break;
                default:
                    break;
            }
    }
}

```

I hope this helps, and to be on the right direction to a viable solution! =)

# Answer
> 2 votes
I use code like this to move my sprites, it tends to work quite well for me, it also uses "GameTime" to ensure movement is consistent across frame-rates.

```
// Sprite Protecteds
Vector2 direction;
Vector2 position;
float speed;

// Sprite Code
void Update(GameTime time, KeyboardState kb)
{
    // reset to zero for no keys pressed
    direction = Vector2.Zero;

    if (Keyboard.GetState().IsKeyDown(Keys.Left)) direction.X = -1;
    if (Keyboard.GetState().IsKeyDown(Keys.Right)) direction.X = 1;
    if (Keyboard.GetState().IsKeyDown(Keys.Up)) direction.Y = -1;
    if (Keyboard.GetState().IsKeyDown(Keys.Down)) direction.Y = 1;

    position += direction * speed * time. Milliseconds;
}

// Game "Update" method (not sure of exact code here)
sprite.Update(gameTime, Keyboard.GetState());

```

Obviously you may want to provide more parameters to the sprite during its update process, so you may very the speed or other things as well.

# Answer
> 2 votes
This question needs more lambdas.

Note this is from a WIP, so there's some unused and implied-but-unimplemented features. Where you see the `() =>` add your `inputDirection.X -= -1;`. I realize this is for a Gamepad and you're using a keyboard, but the grouping principle, or at least the notion of the action map still applies.

This is probably overkill, but lots of fun!

Setup function that maps the controls:

```
public void SetController(MyGamePad controller)
{
    controller.ClearActions();

    controller.BindAction(Buttons.Start, ButtonGroup.FullyExclusive, () => sine.play());

    controller.BindAction(Buttons.A,
        ButtonGroup.FaceButtons, () => showText("A!"));
    controller.BindAction(Buttons.A | Buttons.B,
        ButtonGroup.FaceButtons, () => showText("A and B!"));
    controller.BindAction(Buttons.B,
        ButtonGroup.FaceButtons, () => showText("B"));
    controller.BindAction(Buttons.B | Buttons.Y,
        ButtonGroup.FaceButtons, () => showText("B and Y!"));
    controller.BindAction(Buttons.Y,
        ButtonGroup.FaceButtons, () => showText("Y!"));
    controller.BindAction(Buttons.Y | Buttons.X,
        ButtonGroup.FaceButtons, () => showText("Y and X!"));
    controller.BindAction(Buttons.X,
        ButtonGroup.FaceButtons, () => showText("X!"));
    controller.BindAction(Buttons.X | Buttons.A,
        ButtonGroup.FaceButtons, () => showText("X n A, I made a funny!"));
    controller.BindAction(0x0,
        ButtonGroup.FaceButtons, () => showText("Nothing on the face buttons."));

    controller.BindAction(0x0,
        ButtonGroup.ShoulderButtons, () => showText("No shoulder buttons"));
    controller.BindAction(Buttons.LeftShoulder,
        ButtonGroup.ShoulderButtons, () => showText("Left shoulder button!"));
    controller.BindAction(Buttons.RightShoulder,
        ButtonGroup.ShoulderButtons, () => showText("Right shoulder button!"));

    controller.BindAction(0x0,
        ButtonGroup.DirectionalPad, () => showText("Nothin' on the dpad!"));
    controller.BindAction(Buttons.DPadUp,
        ButtonGroup.DirectionalPad, () => showText("DPAD UP!"));
    controller.BindAction(Buttons.DPadDown,
        ButtonGroup.DirectionalPad, () => showText("DPAD DOWN!"));
}

```

The game component that makes it work (instantiate 1 per player):

```
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;

namespace MyGame
{
    [Flags]
    public enum ButtonGroup
    {
        NonExclusive            = 0x00,
        FaceButtons             = 0x01,
        DirectionalPad          = 0x02,
        ShoulderButtons         = 0x04,
        LeftSide                = 0x08,
        RightSide               = 0x10,
        FullyExclusive          = 0xFF,
    }

    class MyGamePad : GameComponent
    {
        private Buttons FaceButtons;
        private Buttons DirectionalButtons;
        private Buttons ShoulderButtons;
        private Buttons LeftSideButtons;
        private Buttons RightSideButtons;
        private Buttons AllButtons;

        private PlayerIndex playerIndex;
        private Dictionary<KeyValuePair<Buttons, ButtonGroup>, Action> actionMap = new Dictionary<KeyValuePair<Buttons, ButtonGroup>, Action>();

        public InstrumentPad(Game game, PlayerIndex playerIndex) : base(game)
        {
            this.playerIndex = playerIndex;
        }

        public void ClearActions()
        {
            actionMap.Clear();
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            updateButtons();

            foreach (KeyValuePair<Buttons, ButtonGroup> pair in actionMap.Keys)
            {
                switch (pair.Value)
                {
                    case ButtonGroup.DirectionalPad:
                        if (DirectionalButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.FaceButtons:
                        if (FaceButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.ShoulderButtons:
                        if (ShoulderButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.LeftSide:
                        if (LeftSideButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.RightSide:
                        if (RightSideButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.FullyExclusive:
                        if (AllButtons == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                    case ButtonGroup.NonExclusive:
                        if ((AllButtons & pair.Key) == pair.Key)
                            actionMap[pair].Invoke();
                        break;
                }
            }
        }

        public void BindAction(Buttons buttonCombo, ButtonGroup buttonGrouping, Action action)
        {
            KeyValuePair<Buttons, ButtonGroup> pair = new KeyValuePair<Buttons, ButtonGroup>(buttonCombo, buttonGrouping);
            if (!actionMap.ContainsKey(pair))
                actionMap.Add(pair, action);
            else
                actionMap[pair] = action;
        }

        private void updateButtons()
        {
            GamePadState padState = GamePad.GetState(playerIndex);
            LeftSideButtons = 0x0;
            RightSideButtons = 0x0;

            FaceButtons = 0x0;
            if (padState.Buttons.A == ButtonState.Pressed)
                FaceButtons |= Buttons.A;
            if (padState.Buttons.B == ButtonState.Pressed)
                FaceButtons |= Buttons.B;
            if (padState.Buttons.X == ButtonState.Pressed)
                FaceButtons |= Buttons.X;
            if (padState.Buttons.Y == ButtonState.Pressed)
                FaceButtons |= Buttons.Y;

            RightSideButtons |= FaceButtons;

            DirectionalButtons = 0x0;
            if (padState.DPad.Up == ButtonState.Pressed)
                DirectionalButtons |= Buttons.DPadUp;
            if (padState.DPad.Down == ButtonState.Pressed)
                DirectionalButtons |= Buttons.DPadDown;
            if (padState.DPad.Left == ButtonState.Pressed)
                DirectionalButtons |= Buttons.DPadLeft;
            if (padState.DPad.Right == ButtonState.Pressed)
                DirectionalButtons |= Buttons.DPadRight;

            LeftSideButtons |= DirectionalButtons;

            ShoulderButtons = 0x0;
            if (padState.Buttons.LeftShoulder == ButtonState.Pressed)
            {
                ShoulderButtons |= Buttons.LeftShoulder;
                LeftSideButtons |= Buttons.LeftShoulder;
            }
            if (padState.Buttons.RightShoulder == ButtonState.Pressed)
            {
                ShoulderButtons |= Buttons.RightShoulder;
                RightSideButtons |= Buttons.RightShoulder;
            }

            AllButtons = LeftSideButtons | RightSideButtons;

            if (padState.Buttons.Start == ButtonState.Pressed)
                AllButtons |= Buttons.Start;
            if (padState.Buttons.Back == ButtonState.Pressed)
                AllButtons |= Buttons.Back;
        }
    }
}

```

# Answer
> 1 votes
> Now I'm confused and not sure what to do next.

Does this mean your code isn't doing what you think it should be doing or do you have some feature that you need to implement that you don't know how or do you want advice on what feature to implement next?

Either way...

```
if (Keyboard.GetState().IsKeyDown(Keys.Left)) inputDirection.X -= -1;
if (Keyboard.GetState().IsKeyDown(Keys.Right)) inputDirection.X += 1;

```

You don't want to subtract a negative for one direction and add a positive in the other. Those two evaluate to the same thing.

# Answer
> 1 votes
Here's how I'm doing this in one of my games on Windows Phone. Bear in mind that I have made some simplifications for the sake of example. In my game, enemies follow a set of waypoints along a path.

In the `Update` method inside my `Enemy.cs` class, I evaluate `Enemy.Waypoints.Peek() - Enemy.Position` (normalized) to determine which direction the enemy should be moving.

```
this.Direction = this.Waypoints.Peek() - this.Position;
this.Direction.Normalize();

```

Then, I calculate the velocity (direction + speed) for the current frame using the direction.

```
this.Velocity = Vector2.Multiply(this.Direction, Settings.Speed * this.Speed);

```

Finally, I adjust the actual position of the enemy.

```
// Adjust the position according to the velocity.
this.Position += this.Velocity;

```

It helps to understand the math involved, but this is how you can move an object.

---
Tags: xna
---


# Question
Title: What 3D engine should I use for the browser, iPhone, and Android platforms?
I have a C++ game that has a 3D engine that works only in Windows. I'm wondering which engine I should use so that it can be used in a browser or in iPad (iPhone) and Android environments? Does anyone have an idea of the size of the task to migrate from one 3D engine to another?

# Answer
There are only two engines I know of that work on iPhone, Android, and in a browser:

Unity and ShiVa 3D.

> Does anyone have an idea of the size of the task to migrate from one 3D engine to another?

This isn't an answerable question as-is. How much code you have and what engine you're using are going to matter.

I don't know about Shiva, but in Unity you're going to need to rewrite all your game code to one of the languages they support: C# or Javascript.
> 8 votes

# Answer
ShiVa personally would be the better pick. "The ShiVa Authoring Tool is available for Windows, Mac, Linux, Wii, iPhone, iPad, Android, HP WebOS and Airplay SDK for free." Unlike unity which is only Windows and Mac, iphone and Android.
> 2 votes

---
Tags: browser-based-games
---


# Question
Title: Using gluLookAt to move camera in 2D iPhone game?
I'm trying to use gluLookAt to move the camera in my iPhone game, but every time I've tried to use gluLookAt my screen just goes "blank" ( grey in this case )

I'm trying to render a simple triangle and to move the camera, this is my code:

to setup my scene I do:

```
glViewport(0, 0, backingWidth, backingHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glRotatef(-90.0, 0.0, 0.0, 1.0); //using iPhone in horizontal mode
glOrthof(-240, 240, -160, 160, -1, 1);
glMatrixMode(GL_MODELVIEW);

```

then my "triangle rendering" code looks like:

```
GLfloat  triangle[] = {0, 100, 100, 0, -100, 0,};
glClearColor(0.7, 0.7, 0.7, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnableClientState(GL_VERTEX_ARRAY);
glColor4f(1.0, 0.0, 0.0, 1.0);
glVertexPointer(2, GL_FLOAT, 0, &triangle);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);

```

This draws a red triangle in the middle of the screen, when I try to apply gluLookAt ( I got the implementation of the function from Cocos2D so I asume it's correct ), i do:

```
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,1,0,0,0,0,0,1); // try to move the camera a bit ?

GLfloat  triangle[] = {0, 100, 100, 0, -100, 0,};
glClearColor(0.7, 0.7, 0.7, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnableClientState(GL_VERTEX_ARRAY);
glColor4f(1.0, 0.0, 0.0, 1.0);
glVertexPointer(2, GL_FLOAT, 0, &triangle);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);

```

This leads me to grey screen (glClearColor is grey), I've tried all sort of things and read what I've found about gluLookAt on the net, but no luck :(, if someone could explain me or show me how to move to move the camera in a top-down fashion ( zelda, etc ), I would really appreciate it.

Thanks!

# Answer
> 3 votes
There's generally\** no reason to use gluLookAt in a 2D game, it is meant for setting the camera position in 3D space. Use the simpler and faster glTranslatef instead.

If you really want your specific example to work then something like:

```
gluLookAt(200,0,1,200,0,0,1,0,0);

```

would move everything up by 200 pixels. But you could get the same effect by replacing gluLookAt with glTranslatef:

```
glTranslatef(-200, 0, 0);

```

\** cocos2d supports this method of setting the camera for special '3D' effects. If that's what you want then you need to better understand how gluLookAt works. The projection example by Nate Robin can be a good place to start visualizing how projection works with that command. With that said, you should still be able to get similar 3D effects with just translation/scaling/rotation.

Edit: About gluLookAt

gluLookAt describes the position and orientation of the eye/camera in space. The first 3 arguments specify where the eye is located, the next 3 arguments specify where the eye is looking, and the last 3 specify the up direction that tells us how the camera is tilted. What this really does is define a viewing transformation by building a matrix.

In the gluLookAt example I gave, the eye position is (200, 0, 1). Because you rotated the projection matrix around the z axis earlier, I have to change x to move vertically and y to move horizontally. For the z coordinate, the point that we're looking at (200, 0, 0) should be in front of the eye, meaning you can't use a z coordinate of -1 for example because the look at point would be behind the eye. In this example it doesn't matter what z value you use as long as it is positive (comes before the look at point which has a z of 0).

The camera normally always looks straight ahead in 2D games so we use the same x and y for the look at point (200, 0) but we move it away from the camera in z direction (0). Finally we need to define a vector that specifies the up direction, this is normally (0, 1, 0) because the x-z plane represents the ground in many games. Since you rotated the projection matrix around the z axis I guess you could also use (1, 0, 0) and then you wouldn't need to swap x and y coordinates when specifying the position of the eye and look at point.

I still think it's simpler to just use the glTranslate and glRotate functions. If you familiarize yourself with their use you can easily write a simple camera class without the overhead of calling gluLookAt.

---
Tags: opengl, iphone, opengl-es
---