# Question
Title: Algo for rotating tower towards enemy - Unity
I have made a grid and placed towers and moving a enemy on it. Now i want to rotate towers face towards enemy when enemy comes in the range of tower.

I have a solution that whenever enemy comes to its range ( 2 grids far ) it starts do something, lets say when tower finds enemy is on left side it starts firing like that when enemy moves up/down ( when it finds there is a tower on very next tile) tower starts rotating with enemy position uniti enemy's range that is 2 grids far. So its mean tower has to rotate whenever enemy comes to its range and moves up/down.

What would you people suggest me a optimized way or any helpful scripting function ?..thnx

# Answer
http://unity3d.com/support/documentation/ScriptReference/Transform.LookAt.html

It might help to offset the target world position to have the same height as the tower, otherwise the tower will look down/up. But that might be valid if the tower has a seperate turret model.
> 5 votes

# Answer
Unity provides functions for LERP/SLERP and those would probably work well. Basically create a target point at the same position as the enemy except moved to the tower's height, and then slerp the tower to that location.

For an example, look for the command Vector3.Lerp() in this code:

http://www.unifycommunity.com/wiki/index.php?title=SeekSteer

BONUS: You can say "I'm slerping the towers!"
> 3 votes

# Answer
Don't know about the specific functions to use in Unity, but if you want to get the actual angle of the entity relative to the tower's turning point I suggest you look at polar coordinates: http://en.wikipedia.org/wiki/Polar\_coordinate\_system

When you store the angle the tower currently has and calculate the one it needs to be in achieving the rotation becomes a fairly simple process, I'm sure.
> 0 votes

# Answer
It might help you to look at the problem in terms of 2D instead of 3D. Taking out the height/altitude component in your angle calculations reduces the problem to simple trigonometry.

So the basic algorithm becomes this (pseudocode):

```
// Assume Up is <0,1,0>
Vector2 target_position( target.X, target.Z ),
        tower_position( tower.X, tower.Z );
// Quaternion construction using axis and angle.
double angle = tower_position.angle( target_position );
Quaternion tower_yaw( Vector(0,1,0), angle );
// Then concantonate the current rotation with the rotation you calculated, or you can interpolate with a slerp function if you wish.

```
> 0 votes

---
Tags: unity
---


# Question
Title: How can I handle transferring a character from one collision surface to another?
I've been trying to modify some slope code from an example I've found but I've come across an issue the way the method is designed it attaches the current slope and then based off that slope determines if the character is on it or not.

```
 protected CollisionPath attachedPath;

```

The issue with this though is when you try and lay down several slopes to make one continuous slope it doesn't work properly as this piece of code kicks in and makes you fall off the current slope you are standing on.

```
if (position.X < attachedPath.MinimumX || position.X > attachedPath.MaximumX)
{
    attachedPath = null;
}

```

While this isn't the case when you jump from one slope to another. I've tried to adapt the code used for jumping to one slope to another to solve the issue to no avail. The method in its entirety is below. any help with this would be really appreciated.

```
private void HandleSlopeCollisions( GameTime gameTime)
{
    collisionPaths = level.collisionPaths;
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

    if (velocity.Y >= 0)
    {
        if (attachedPath != null)
        {
            isOnGround = true;

            position.Y = attachedPath.InterpolateY(position.X);
            velocity.Y = 0;

            if (position.X < attachedPath.MinimumX || position.X > attachedPath.MaximumX)
            {
                attachedPath = null;
            }
        }
        else
        {
            Vector2 footPosition = position;
            Vector2 expectedFootPosition = footPosition + velocity * elapsed;

            CollisionPath landablePath = null;
            float landablePosition = float.MaxValue;

            foreach (CollisionPath path in collisionPaths)
            {
                if (expectedFootPosition.X >= path.MinimumX && expectedFootPosition.X <= path.MaximumX)
                {
                    float pathOldY = path.InterpolateY(footPosition.X);
                    float pathNewY = path.InterpolateY(expectedFootPosition.X);

                    if (footPosition.Y <= pathOldY && expectedFootPosition.Y >= pathNewY && pathNewY < landablePosition)
                    {
                        landablePath = path;
                        landablePosition = pathNewY;
                    }
                }
            }

            if (landablePath != null)
            {
                velocity.Y = 0;
                footPosition.Y = landablePosition;
                attachedPath = landablePath;

                position.Y = footPosition.Y;
            }
        }
    }
    else
    {
        attachedPath = null;
    }
}

```

# Answer
> 0 votes
Are your slopes perfectly in line such that one starts exactly after the other slope? If so, try overlapping them. Overlapping collision surfaces is a very common technique to avoid problems such as yours.

EDIT: You must change your logic a little bit with the above. In the above case, two surfaces will report collisions at some point. Simply add all the surfaces to an array (or stack) and when the array/stack reaches 0, the character should fall.

EDIT2: Something like this: (Note the name of the variables... the code is NOT going to work right off the bat, you will have to declare variables/containers etc.)

```
private void HandleSlopeCollisions( GameTime gameTime)
{
    collisionPaths = level.collisionPaths;
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

    if (velocity.Y >= 0)
    {
        if (attachedPathArray.size() > 0)
        {
            isOnGround = true;

            for (unsigned int i = 0; i < attachedPathArray.size(); i++) // convert to foreach
            {
                position.Y = attachedPathArray[i].InterpolateY(position.X);
                velocity.Y = 0;

                if (position.X < attachedPathArray[i].MinimumX || position.X > attachedPathArray[i].MaximumX)
                {
                    attachedPathArray.remove(i);
                    --i; // otherwise we would skip a path because the size just decreased
                }
            }
        }
        else
        {
            Vector2 footPosition = position;
            Vector2 expectedFootPosition = footPosition + velocity * elapsed;

            CollisionPath landablePath = null;
            float landablePosition = float.MaxValue;

            foreach (CollisionPath path in collisionPaths)
            {
                if (expectedFootPosition.X >= path.MinimumX && expectedFootPosition.X <= path.MaximumX)
                {
                    float pathOldY = path.InterpolateY(footPosition.X);
                    float pathNewY = path.InterpolateY(expectedFootPosition.X);

                    if (footPosition.Y <= pathOldY && expectedFootPosition.Y >= pathNewY && pathNewY < landablePosition)
                    {
                        landablePathArray.Add(path);
                        landablePosition = pathNewY;
                    }
                }
            }

            if (landablePathArray.size() > 0)
            {
                velocity.Y = 0;
                footPosition.Y = landablePosition;
                attachedPath = landablePathArray[?]; // which one would you select in the array? up to you, I can't tell from your code

                position.Y = footPosition.Y;
            }
        }
    }
    else
    {
        attachedPath = null;
    }
}

```

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


# Question
Title: Is there a SDK for 2D games that will deploy to PC, Flash and Android?
Is there such thing as an SDK or toolset that can produce Windows, Flash, and Android executables from the same source? Something like "write once, run in all three platforms?"

# Answer
unity3d exports to android and will export to flash 11 swf. It can be made to to do 2d, but its not its primary function.

http://haxe.org/ is also a possibility.

If you drop your flash requirement there are lots more :)
> 5 votes

# Answer
Google just released an early version of PlayN that does just what you want (on the paper) : https://developers.google.com/playn/

It's too early to say if it's useful or what.
> 3 votes

# Answer
This is what Adobe AIR is for. Personally I wouldn't really recommend that approach though, because it's not really optimal for each platform (especially not for mobile). I would recommend use Flash to develop for desktop browsers, and then port to a mobile development tool like Corona SDK.
> 2 votes

# Answer
You could try the libgdx library, it supports building games that work on PC and Android, and there are some experiments to get it to work with html5 (using gwt) and to get it to run on iOS (using the avian jvm).

This library has support for buiding 2d and 3d games, you can search in the android market for some examples of games made with the library libgdx on the android market

Some nice examples of games made with libgdx are:

* jumping slime
* tap 'n' crash
* Apparatus
> 1 votes

# Answer
FlashPunk is a nice game framework. It's pretty good - there's also Flixel. Both are pretty great with 2D game drawing; there's many, many games out there made with these two.
> 0 votes

---
Tags: 2d, android, flash
---


# Question
Title: When Should You Revisit Old Web/Mobile Games To Improve Them?
**Note:** I would like this to be specific to mobile and web games, since they have easier distribution methods than other models.

Based on the examples in my interfaces question, it looks like (as expected) there's a lot of work cut out for me; there's a lot of room to improve that old, hoary chemistry game.

But should I?

In fact, when should (and shouldn't) you revisit old games and improve them significantly?

I can definitely think of a couple of reasons not to do this:

* You're going to write a sequel (improve that instead)
* You don't have players howling for your blood (or for improvements)
* It's a one-off type of game you're unlikely to code anything similar to ever again

# Answer
Assuming that you have a title out there, or any title for that matter. Restricting discussion to mobile isn't necessary, the marketing cycles are much faster but the core issues remain the same.

If you're not focused on economic issues then the answer is "Who cares, do whatever you feel like" and you can safely ignore the rest of my talking points. In fact, please ignore the rest if that's the case =)

Pro:

0) Crash fixes or matching to new hardware customers inquire about. 1) Its visibility in the market has gone way down, doing an update refresh its presence. 2) Existing customers appreciate free updates and new customers perceive that it isn't abandoned. 3) Test run a new feature/idea to see if existing users like it enough, before you add it to a brand new title. (ie. market research) 4) Create a tie-in with another, new title of yours, leverage your presence to feel bigger to the customer.

Con:

0) Opportunity cost. Look that up, it's important. 1) If the title is good enough then don't mess with it just because you feel like messing with stuff. Your customers value consistency in their purchases and hate to be jarred out of their complacency. 2) If the title just plain sucks and needs improvement it's better to abandon it (withdraw entirely from the market even), cut your losses and move onto something else less sucky. 3) People love new stuff, they give new stuff a much higher priority than news of version 314 of old stuff that they've already played to death. Adding significant features to old stuff is nowhere near as exciting as something new with that same feature.

Summary:

Like it or not, bury your head in the sand, plug your ears and yell "I can't hear you" over and over but the very second that you mention Distribution and expect other people to use your title (for money or not) everything is about economic choices. There's nothing Evil about money, nothing compromising about wanting to make people happy with your work. Marketing is not beneath you, it's simply a word to describe how you present yourself and your work and who you decide to do that work for.
> 4 votes

# Answer
I take it that you mean, when should you revisit an **unfinished** idea.

I worked on a game for years, refactoring it, recreating it, making it awesome -- until I realized it would make me very little money compared to some other ideas I had. Even though I had spent so much time working on it, I dropped it like a rock after this realization.

The good news was that I had learned a whole lot about game design and programming in general through the experience, so it wasn't a loss by any means. In fact, it put me in the position to be able to analyze it in that way.

I would say that the total complexity of the game also has an impact. It may not be the best idea, but if it's orders of magnitude easier than your best idea, that might be a good reason to carry it.

So, determine your motivation, and figure out the relative complexity of all your ideas. Then weigh them all in this context.
> 1 votes

# Answer
The main issue to consider here is the **cost vs. return**. Cost can be tangible (money) or intangible (time, effort, pain and suffering from a horrible debugger/platform/environment).

So it boils down to this: **do you get more out of the extra effort than what you put in?**

If you have an awesome game, and with some tweaking it'll become much better and attract a higher grade (or quantity) audience -- then by all means, go for it.

If you won't get much out of it, then why are you spending time on it? Go work on another game instead.
> 1 votes

---
Tags: release
---


# Question
Title: What is the maximum width of a Facebook game page?
I read it was going to be changed to 520px, but I keep seeing pages that are new that are the older 760px width. Is it safe to build at the wider width still or should we be building at 520px?

Anyone know if you can still design for 760px width? If not, what's the new width?

# Answer
Based on experience, and according to current Facebook documentation, it is either 760px or fluid width:

> The canvas chrome is 760px width by default but you can set it to be a Fluid Canvas so that it is left aligned and takes up the full width and height of the user browser.

Source: Apps on Facebook.com - Facebook Developers, Getting Started
> 4 votes

---
Tags: facebook
---


title: Java vs Javascript for Web-based games

text:
# Question
Title: Java vs Javascript for Web-based games
With all the recent interest in developing HTML5 apps and games, and I am curious why all the focus is on Javascript, and not on Java.

Minecraft is a great example of what can be accomplished in a browser, and it's written in Java, not JS. I doubt if it is even possible/practical to attempt such a complex project in JS.

Java is clearly a more powerful platform, and it probably runs significantly faster (this is just my guess, though). About the only drawback of Java I can think of is that it runs as a plugin, and with the trend towards plugin-free browsers (e.g. IE10 metro) Java applets may become obsolete in mobile environments. This has already happened with Flash on iOS.

What do you think? Is there a future in developing Java-based Web apps (especially for mobile devices)?

Thanks

# Answer
> 1 votes
Java's main draw currently appears to be as native apps for Android devices. On the web, apps are done primarily using HTML5 and Javascript, while games are primarily for mobile on native (Java/Objective C) and for desktop it is Flash and to a lesser extent HTML5.

Since you limited yourself to only Java or Javascript, I'll say that you choose Javascript. While you might face some issues achieving performance, its future appears more optimistic than Java.

# Answer
> 7 votes
(Ignoring statements like "Java is clearly a more powerful platform") Short version: The focus is on Javascript because that is the whole point of the HTML5 everything. To allow browsers to do things like play video, audio, and render graphics *without* needing a plugin for it.

The biggest problem with Java as a browser game option is simply that there *isn't* any support out there for it. Browser game portals simply don't accept Java games, and pretty much all the money is going to Flash games (and to a lesser extent, Unity, in a few cases, HTML5/Javascript games). With Flash 11 just being released, it's possible to make full 3d games using the Flash plugin, so Java's main advantage there is gone. And with a much higher market penetration of Flash vs Java, it's better overall for people to focus on Flash development. Minecraft is kind of a rare exception, albeit a very well known one.

The main focus for Java-based games right now is actually Android, but for mobile browser games, Javascript or Flash are still the best option (and really, native games are still the best for performance in those cases)

# Answer
> 2 votes
Google web toolkit compiles Java (even with classes and software engineeting as deep as you like) to the javascript. It supports html5 canvas and even webGl.

It is great Java - javascript combo

For example this \- programmed in java, runs in javascript.

---
Tags: java, web, mobile
---


# Question
Title: Is it wrong to transmit information about a user's machine to my own servers without informing the user?
Let's say I ship a game on multiple platforms. My game code detects a few trivialities about the underlying system, like the local settings, the "country," the OS, the kind of graphic cards, etc.

Let's say I ship the game with code inside it that will send this information to a master server where I collect and manage all this data for building charts and such.

In a multiplayer game, it looks pretty reasonable to do this, since connections to that server are totally justified. Still, in a singleplayer game, it may look suspicious if you are informed about this operation.

Is it just wrong to embed this kind of data gathering system in a game? Do you think it absolutely should have a previous authorization from the user before doing any collection and transmission?

If users start to decline that "agreement," I can't really enforce 100% meaningful data. Thoughts?

# Answer
> 26 votes
Get user authorization and tell them exactly why you want that data. You'll get judged harshly in the court of public opinion for sneaking around in a player's machine and uploading information to your private servers.

I am not a lawyer, you may want to ask a real lawyer whether clandestine information gathering is illegal in your jurisdiction.

Whether it's a single or multi-player game has zero relevance on whether it's morally or legally acceptable, it just makes your job of hiding the activity easier, right? If you even have to think of hiding the activity it's a pretty good sign that you already know the answer to your question.

Alternatives? Let them fill in a questionnaire to get some bonus. If they accept, give them a perk in-game. Do a sweepstakes, users who send in their computer info are automatically entered. Just be nice about it, be up front and explain why you want the info instead of just sticking a legal screen in their face.

# Answer
> 2 votes
On the side of the player, I would implore you not to engage in this practice. I have a personal perception that background traffic such as checking for patches or the latest release always siphon my bandwidth; I don't care if it is legitimate. Given the choice, I prefer to initiate the check at my discretion like kicking it off just before I go to bed. I don't want ***any*** extraneous packets that I feel is unnecessary because I think it impacts my game play and I'm not even a professional gamer in any sense of the word.

From the point of view of a developer, the type of information you list (settings/OS/graphics) totally have relevance to debugging/bug fixing in-the-wild. I think it is mandatory to display a prompt at a crash asking the player whether s/he would like to forward the dump to report the error. On the other hand, during a check for updates or newer versions you do want to match compatible platforms and minimum requirements depending on how much a jump the new version may be. So for example, if your game is available on multiple platforms you need to search your available upgrades for OSX as opposed to Windows. You may even be interested in whether they are on broadband before letting them attempt to suck down your 40MB update over a modem line. So there could be good reasons to *detect* the configuration of the player's environment. Still, remember these are situations where you are making life easier for the player. Never take information for no reason. Taking information for your own purposes, without benefit to the player, is wrong and that is why you want the player's permission.

---
Tags: online, statistics
---


# Question
Title: How can one access the depth buffer for Unreal Tournament 2004?
I'm looking for a way of getting depth buffer data for a virtual 3D sensor.

Currently the method used is raycasting (implemented in UnrealScript), but I want to use the depth buffer data instead for faster output of the sensor in FPS.

One complete frame of data takes many seconds to generate currently, which is bad for my application which must parse this 3D depth data and also control a vehicle with it.

I'd like to get the data from D3D but don't know if it's possible.

# Answer
I'm not sure it's possible via the modding APIs exposed by UT2004. If it is, the information is likely on the UnrealWiki or someplace similar -- perhaps ask in the IRC channels listed on that wiki's main page, as well?

Likely the information you will be found under information for framebuffer access or post-processing graphics mods, but I'm not sure if the particular flavor of Unreal Engine used for UT2004 (2, I think?) exposed this kind of thing.

There is another option though. This question about accessing another process's device context deals with API hooking, and has a few answers that may be helpful. With this approach, rather than write a mod, you write an external program that hooks UT2004's `Present()` call (or similar), does the normal presentation work, and rejiggers the scene setup to re-render it with depth pass into a texture you've created and can write out to your sensor.

Unfortunately this is an exceedingly complicated process relative to simply using something in the UT2004 mod arsenal. Perhaps instead you could post another question detailing the requirements and implementation of your raycasting technique, and ask if there's a more efficient way to achieve your ultimate goals?
> 1 votes

# Answer
The simplest option in D3D9 is to use an extra render target (either via MRT or re-rendering the scene) and appropriate pixel shader to output depth to a D3DFMT\_R32F texture.

I'm not sure how easy that would be to integrate with Unreal 2004 though.
> 0 votes

---
Tags: directx, directx9, unreal
---


# Question
Title: Can ARToolkit be used with Unity on the Android platform?
Does anyone know if ARToolkit can be integrated with Unity and work on Android phones? It would be helpful if you could share any examples or resources.

# Answer
> 2 votes
ARToolkit itself supports the Android platform. On the Unity forums, you can find a beta for the UnityAR project, which provides ARToolkit integration with Unity.

Even if the UnityAR project does not meet your needs, you could develop your own integration. It is certainly possible.

---
Tags: android, unity
---


# Question
Title: Does SFML support these specific features that I require?
I've been working on a game in c++ for about a week and a half, and I've been using SDL. However, my current engine only needs the following from whatever library I use:

* enable double buffering
* load an image from path into something that I can apply to the screen
* apply an image to the screen with a certain x,y
* enable transparency on an image
* (possibly) image clipping, for sprite sheets.

I am *fairly sure* that SFML has all of this functionality, I'm just not positive. Will someone confirm my suspicions?

# Answer
I haven't used SDL, and very little SFML, but the consensus I get is SFML is like SDL, but hardware accelerated and object-oriented.

A quick google of your points gave me the following:

> * enable double buffering

> * load an image from path into something that I can apply to the screen
> * apply an image to the screen with a certain x,y

> * enable transparency on an image

> * (possibly) image clipping, for sprite sheets.
> 11 votes

# Answer
I think, SFML is library, which gives you power to use OpenGL. So hardware rendering is self-evidence. And it's fast with blending - you can write your own shader and do blending by yourself.

I also think, double buffering is enabled in default in SFML.

Apply image to screen can be done by drawing a rectangle with texture ;)

Transparency can be also enabled (blending).

I don't have experience with SFML and images, so I don't know nothing about this second. And I don't understand the last point (image clipping).
> 1 votes

# Answer
SFML has all those features you listed I believe. SFML is more object-oriented, while SDL is C-style. SFML does have some extra functions like rotating images, and I think scaling them.

Now, this is just an educated guess, but I've heard of hardware surfaces and hardware accelerated surfaces, but reading this article: http://linuxdevcenter.com/pub/a/linux/2003/08/07/sdl\_anim.html, it seems that if the two terms mean the same thing, then SFML may not really have an advantage over SDL in terms of blitting speed or blending alpha values.
> 0 votes

# Answer
SFML does all of those things, yes. As you are coding in C++, I think you'll find SFML a pleasure to work with as it is very OO and, imho, much tidier to integrate into your code.

I highly recommend going for the switch.

EDIT: SFML is hardware accelerated. SDL is not.
> 0 votes

# Answer
SDL and SFML are both hardware accelerated. I would suggest though to start learning stuff like DirectX or OpenGL and try to use that even for 2D graphics. It will benefit you much more than wasting time with obscure libraries like SDL and SFML.
> -3 votes

---
Tags: sfml
---


# Question
Title: What is a decent polygon count for minimal spherical objects?
I am creating a model pack for a game and I am having a hard time deciding how many sides I should start with for the low poly props made from cylinders and spheres.

Take an apple for example. I want to maintain the apparent roundness of the shape at a glance but keep the polygon count low. The model pack is household clutter so there could easily be 50 such objects to render at any time.

What is a decent polygon count for minimal spherical objects?

# Answer
A decent polygon count is one that combined with other objects in the scene will not reduce your frame-rate beyond acceptable levels. The information you provided is not enough to make a good guess. In fact, you (and your team) is probably the only one who can decide that. It is not just the polygon count of the apples, but the count of all the objects in the particular scene.

If it is a small room let's say, which has very few portals (windows/doors) then the outside world can easily be culled, leaving you with the option to fill that particular room with more detailed objects.

Start with 4 sides for an object that is simply not going to be viewed up close, to 6 sides for an object that *is* going to be viewed up close and take your scene into account as well. Is having 8 sides going to kill the framerate? Yes? Then go lower.
> 3 votes

# Answer
I would consider a "decent polygon count" the smallest number of polygons for which the viewer can't distinguish between your object and a real spherical object. I can't give you a rough number as it varies among viewers, it depends of the type of poly (triangle, quad, etc), it depends on lightning and shading, on numbers of objects on the screen, etc.

Try to vary the number of polygons and find a "sweet spot" were you like most the balance between visual appeal and performance.
> 2 votes

---
Tags: 3d-meshes, efficiency
---


# Question
Title: What is an appropriate OpenGL(ES)-based game engine meeting these criteria?
I want to try my hands on a little shooter on the Android platform, and I'm looking for a full-featured 3D game engine. I can't afford to pay more than 400 € for a license, so expensive engines are excluded from the start.

These are my requirements:

* The engine has to have good level editor (able to place entities, actors and triggers); so "graphics engines" like Irrlicht and Horde 3D aren't what I'm looking for.
* The engine should be based on OpenGL Core and use shaders rather than the fixed function pipeline.
* It shouldn't use octrees and BSP/PVS.
* It needs to have decent occlusion culling because I need good frame rates on not-very-powerful graphics cards.
* It should come with source code.

I like Horde 3D very, very much and I like it's smart design, rendering capabilities and compactness. Sadly, I can't use it due to the lack of tools.

So far I've come across Torque 3D, C4 engine, Shiva 3D, and Unity 3D.

* Torque 3D is really nice, decent design, has good tools, good performance, it's really cheap and comes with source code. Sadly it's only DirectX for now.
* Unity has a lot of features, decent performance and tools, runs on Android but they don't give source code within my price range.
* C4 is good enough, has tools, and source code but there's a catch. While you have source code the source isn't ported to Android and the engine's owner expressly forbids anyone to port source code on other platforms or to release a game on not officially supported platforms.
* Shiva 3D seems nice, too, supports Android, has tools but they don't give you source code license for a decent sum.

That's all I could find. I used the list on devmaster.net, I searched this site, I've searched gamedev.net, gamasutra, polycount.com and of course Google and Bing.

Any suggestions that could help me?

# Answer
> The engine has to be based solely on OpenGL Core and shaders.

Well, that's just not going to happen. Shaders, yes. OpenGL 3.2+ core profile? No.

There is *no* engine on the market that works against the core profile of OpenGL. None. All of them use some of the removed functionality to some degree, even if it's just GL\_QUADS. All of them.

There is no need for the core profile requirement anyway. Especially since you're making a game for *Android*, which does not support OpenGL at all.

It supports OpenGL **ES**, which is not the same thing as desktop OpenGL. ES has no concept of profiles at all, let alone a core profile. Furthermore, you can't just take a desktop-based OpenGL engine and throw it onto OpenGL ES 2.0 and expect it to work. That will involve porting, which (given the significant differences between desktop GL and GL ES) will involve quite a bit of work.

Therefore, you should be looking at engines that have OpenGL ES support.

> No BSP/PVS, octrees. I need some decent frame rates on not very powerful graphic chipsets, so I need some decent occlusion culling.

Quake 1 used BSPs, and it ran just fine on GPUs that are inferior in every way compared to anything that implements OpenGL ES 2.0. Also, what is not "decent occlusion culling" about BSPs or portal systems?

You seem to have some misinformed ideas about what are good ideas and bad ones.
> 4 votes

# Answer
If you are fine with it being 2D, the slick engine can be ported to android. It's not an engine as per say, but still high level. http://slick.cokeandcode.com/. If you don't mind not having the high level stuff, you can code directly using LWJGL and implement into your game. However I'm not to sure how well that would port.
> 1 votes

---
Tags: opengl
---


# Question
Title: Why are my texture coordinates always (0,0) in this shader?
What I'm trying to do is add my depth buffers values to my scene, ie. I'm trying to make objects closer to the camera darker and objects further away lighter. Which should be easy: just render the depth buffer to a texture, and then render the scene, multiplying each pixels colour by the colour value at the same coordinates in my depth-buffer texture...

Yet I don't know how to use coordinates for textures.

Or more like it's just failing. What's happening is that the vertex shader is only using the (0,0) coordinate of my texture, so the entire scene changes colour depending on what's there.

What I'm doing is this (the critical stuff from my render function):

```
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, depthTextureId);   //Binds the texture
box.render();    //Sets the viewing matrix and renders a test VBO

```

I guess that's the right way to bind a texture? Anyhoo, here's the vertex shader's important stuff:

```
out vec4 ShadowCoord;

void main() {
    gl_Position = PMatrix * (VMatrix * MMatrix) * gl_Vertex;  //Projection view and model matrices
    ShadowCoord = gl_MultiTexCoord0;    //something I kept seeing in examples, was hoping it would work.
}

```

It seems gl\_MultiTexCoord0 is the problem? Maybe?

The frag shader sets the colour using this function:

```
vec4(texture2D(ShadowMap, ShadowCoord.st).x * vec3(Color), 1.0);

```

Where the ShadowMap is the sampler2D for the texture, and Color is the vertex's color...

So what am I missing? How come the coordinates are not changing from 0,0?

# Answer
> 5 votes
You don't even have to write the depth buffer to another texture, just convert your current fragment depth to linear space like shown here and multiply your fragment color with the inverse of the depth value obtained.

---
Tags: opengl, textures, shaders, glsl
---


# Question
Title: Why do meshes show up as bones in the Model class?
Right now I'm working on a 3D game and I've come across something very weird. When I created the model in Blender, I added an armature named "MyBone" to the stage and attached a cube ("MyCube") to it, so that when I move the armature, the cube moves with it. I exported this as an FBX and loaded it as a Model object.

What I expected to see was:

But what I got was this:

I'm really confused. Why is the mesh I created showing up in the bone list? And what's Root Node?

Here are the .blend and .fbx files: here or here.

Thanks.

# Answer
> 2 votes
I think your model hierarchy is wrong because you must use bones instead of armatures for animated models that will be imported by XNA (I haven't ever used Blender, but some quick Googling produced these results)

And the Root Node is an automatically generated bone that acts as the parent of all the objects present in the scene.

---
Tags: xna, models
---


# Question
Title: Is my technique for client-side character movement in an MMORPG reasonable?
I started an MMORPG game, and I can already make a character move around the map and see other characters. But I have doubts about my architecture.

I have a loop which, every *x* milliseconds, request from the database the actual position of all characters around the main character. After that, I remove all the objects from the screen and redraw them based on the data retrived from database. Is this reasonable, or is there a better solution?

# Answer
I wouldn't consider that a good, scalable solution, no. The client should not directly query the database on the server, because that will overload the server/database with requests as you increase in scale. You also should not rely entirely on the server for position information as it will create an unpleasant experience for the client.

Multiplayer games in general typically employ **client-side prediction** to cope with the latter situation. This involves having the client maintain a local copy of its simulation state. When a player issues a command to the client, the client transforms that into a request for action which it sends to the server.

While the client waits for the server to confirm that the action is legal, it *assumes* the server will say yes, and updates its local state accordingly. This local state is used to render and subsequently is what a player will base subsequent input on. This allows for a responsive-feeling client (if you are constantly waiting for the server before moving at all, the client will feel sluggish and laggy even under ideal network conditions).

Eventually the server will get the request, process it, and can send a response to the client in the form of updated game state or some such -- the client, when it receives this, simply updates its local state to match, since the server is the authority. You will probably also want to employ smoothing between state updates to help hide unpleasant latency effects this can cause.

You can find lots of resources for client-side prediction and smoothing via Google or your favorite search engine.

As for the former issue... neither the client nor the server in an MMO should read data from the database constantly. It should keep the data and the game state in RAM locally, and push to the DB in intervals so as to avoid flooding it. See this related question for more information.
> 5 votes

---
Tags: architecture, movement, databases
---


title: How to increase update speed of game?

text:
# Question
Title: How to increase update speed of game?
I have a basic game, in which the player moves the environment around the screen, to give the gamer an impression that the player is actually moving. I want this game to be large and have an open world, each piece of scenery is an object and each frame it updates the scenery to make itself move relative to the player. The trouble is with large amounts of objects this causes the game to slow down, but the objects HAVE to be updated otherwise they will become out of synch with the player. So how can I increase the performance of my game without splitting it up into tiny little levels?

Its a 2D top down game. The position of each object is updated each time, but when there are a large number of objects this takes a long time.

# Answer
> 8 votes
The technique you're describing is called Scrolling.

Some suggestions:

* Do not update the position of each object relative to the player (or the viewport). Instead, have your rendering calculate the screen position of each object before it renders it (e.g. subtract the current viewport position). This is known as mapping WORLD coordinates to VIEW coordinates (you might do something else, such as rotation / scaling as well, if the view can rotate or scale)
* The technique to avoid rendering objects which are off the screen is known as "Culling". A simple way of doing it, is to perform the transformation to view-coordinates (as above), and if the object is clearly entirely outside the displayed area, it does not need to be drawn.
* Say you have a world with 1M objects in it. Probably, it will take too long (each frame) to scan all 1M objects, to determine which ones are outside the view (almost all of them). Therefore you need to use some optimisation. The easiest way to do this, is to attach the objects to lists on a uniform grid, and only check the objects on the lists close to the viewport.
* If your objects are not axis-aligned boxes, then you can calculate Axis-Aligned Bounding Boxes (AABBs) for them, which makes culling (and other things, such as collision detection) easier.
* Another idea would be "lazy initialisation" of your world - only actually create parts of the world which are close to the player: split the world into "zones" or "blocks", and initialise the blocks as the player gets close to them. When the player is far away from a "zone" or "block", you can destroy it. This would save memory and mean that the world can be effectively infinite.

# Answer
> 1 votes
You have to decide which objects (or part of objects) are visible and only draw these.

You have to give more details: what kind of game? 3D, 2.5D, 2D? If 2D which kind? Platform, isometric, side-scroller, etc?

---
Tags: performance
---


title: How to use rigid bodies for characters?

text:
# Question
Title: How to use rigid bodies for characters?
First off, I am making a game similar to SSB, which relies heavily on physics, even though it is a sidescroller. I am currently using Unity.

In Unity there are "character controllers" which are used for characters that move, but they don't interact with other physics objects. There are also rigid bodies, which are completely realistic physics components. I can't figure out how to use rigid bodies for human/humanoid characters. Here's some questions I have:

* ***How should I move the character?*** Applying forces is not the way to do it, right? Would you set velocities or pixel-by-pixel movement, perhaps?
* ***What kind of collider should I use?*** I've been using a capsule collider. But is that the best way?
* ***How do you make him not fall down!?*** After some experimenting, I discovered that the character falls over (from applying force/velocity and from the capsule collider tipping it over). Would you constrain the rotation in the Z-axis?
* ***What do you do when he gets hit?*** If you've ever played SSBB you'll be familiar with this topic. I'm thinking that applying a force would be best in this condition? If you did constrain the rotation, would you un-constrain it?

# Answer
> 3 votes
> How should I move the character? Applying forces is not the way to do it, right? Would you set velocities or pixel-by-pixel movement, perhaps?

Apply linear (and possible angular) *impulse*. The object retains velocity and imparts force to other objects on impact.

> What kind of collider should I use? I've been using a capsule collider. But is that the best way?

The capsule collider is what you get with Unity, because it works well for most sorts of games. You could either continue to use it with adaptation (to the FirstPersonController script), or construct your character entirely out of bounding cylinders or bounding boxes (limbs, body, head etc.). The latter won't be as easy, but for a fighting game you'll have more accurate combat. I'm not sure this is really necessary as your game is actually 2D anyway, so benefits from this will be less than if your game were actual 3D.

> How do you make him not fall down!? After some experimenting, I discovered that the character falls over (from applying force/velocity and from the capsule collider tipping it over). Would you constrain the rotation in the Z-axis?

Considering you're using rigid bodies, you're going to have to find some way to constrain, yes. It's either that or you switch between kinematic and rigid bodies at given times. The problem with the latter is you still need to know when the collision between your fist and the enemy's face occurs. So better to stick with rigid body physics throughout.

> What do you do when he gets hit? If you've ever played SSBB you'll be familiar with this topic. I'm thinking that applying a force would be best in this condition? If you did constrain the rotation, would you un-constrain it?

Yes, apply a force; this could be as you switch the character back to rigid body mode (possibly based on where the character was hit, and for how much). In that case, when the character begins to recover, turn kinematics back on so he can stand up again.

---

NB What I've said above about using a mixture of kinematic forces and dynamic ones is one way to do it, and in some ways the easiest. However you can also purely use impulses with rigid bodies to control things. In my experience, this can be less than simple, so caveat emptor.

---
Tags: unity, physics, character, side-scroller
---


# Question
Title: How do I get an xbox 360 controller to rumble?
I am interfacing with the controller using the windows HID API. It seems that its output report length, as provided by the HID driver, is 0, which means I can't send it anything (e.g. make the rumble work). I've also noticed that the input report doesn't include the state of the big "X" button. Am I wrong about this? Is there a workaround, a better API, a workable filter driver that doesn't involve making .infs, etc...?

As I need to support an arbitrary number of controllers (keyboards, mice, and anything for that matter), xinput isn't an option. Installing drivers is also not an option, unless it can be done silently without breaking the device for every other application.

# Answer
> 2 votes
USB HID driver does not contain any provisions for force feedback, and there is no (not even de facto) standard way for HID-compliant devices to provide it.

The USB *PID*, physical interface device, interface contains such a mechanism. But this is a different device class so if the device doesn't claim to support it, you'll need a non-compliant USB stack. And even if it does, USB PID drivers are not available for most machines (for example, there is no Windows x64 driver, and there is no Windows 7 / Vista driver).

To do this you'll have to use both XInput and another API of your choice.

---
Tags: c++, windows, xbox360
---


# Question
Title: How do I go from a general idea to a specific draft of a design?
Before starting planing your code, the data structures, the class hierarchy, you need to have a clear idea of what you want for your game.
I came across with an idea for a game, but it is too general.

I think every game starts with a general idea, but how did they take that general idea and then the came up with games like Imperium Civitas... I'm refering to the actions you can or can't do, the events, *in-game materials* etc.

I wonder how you should engage a blank paper. Where you should start? Is there a chain of steps that you have to follow? Thanks.

(My idea is much more simpler than Imperium Civitas)

# Answer
> 17 votes
My advice would be not to try to delve into too much details yet.

Get a general feel of what type of game you want, with a core gameplay feature that you really want.

Once you know what the *main* gameplay will feel like, start coding. In my opinion, it's very important that your whole idea at first is *simple*. Don't start and try to make something very complicated with complex gameplay and content. Start out small.

An example of this would be if you wanted a 2D platformer with the core gameplay element being magic spells for the main character. What I would do is I would go progressively through it, like so:

* Create quick and dirty *placeholders* for the level tiles (i.e. don't build too much content yet, avoid spending too much time on art and don't make too many assets). So, say, start out with some very simple blocks.
* Make a level system, which you load in the code at first.
* Allow the level to be loaded from a file (to make it easier to test).
* Add a main character.
* Implement physics for your character (tile collision and gravity).
* Allow the character to move and jump.
* Add *very basic* spells.
* Add enemies, make a level editor, replace placeholders and add content, etc.

You see, you follow a path where you add new small things everytime. Not only does it keep you motivated because you can *feel* your progress but it also prevents you from falling into the trap of wanting to implement so many complex things at once and getting lost.

**TL;DR:** Get a *general feel* of what type of game and core gameplay elements you want (but make sure that they're *not too complex*) and simply **start coding**, by making sure that you don't delve into too much details at first. When you have your working *prototype*, you'll know what you want in your game, since you'll have something to work with. From there on, keep coding!

# Answer
> 2 votes
(I'm an amateur)

For the two games I completed, I started with a simple but fixed idea for the gameplay. This first idea wasn't necessarily good, but it was doable, and not too difficult. Once that was completed, I thought of different directions the gameplay could go that might be better, and started trying them out. In both cases, many of the things I tried proved to detract from what was fun about the game, and I ended up discarding them. This was necessary -- no feasible amount of planning can ensure that the idea is good without actually trying it.

The key for me was to have a working and "complete" game, even if it's simple and/or not fun, and once that's done, to try other things. It didn't matter if the original idea was the best.

This is probably not the way professional studios design games, I imagine that they generally come up with a complete design doc and follow it, and it either proves good or bad. That's not to say they can't reuse their code or experience in another similar game, but I imagine it's less flexible.

---
Tags: game-design
---


# Question
Title: What data structure should I use for a Diablo/WoW-style talent tree?
I'm considering implementing a talent-tree system for an online RPG, similar to that seen in World of Warcraft, where acquiring a skill unlocks the next "tier" beneath it in the tree.

Does anyone know of the best way of implementing this structurally in the database/code?

# Answer
Use a structure like this to represent a tree in a database:

```
#Talent
id  parent  description
1   0       Tackle
2   1       Kick
3   1       Punch
4   3       Fire Punch

```

And another table to represent acquired talents per user

```
#UserTalent
id  user  talent
1   4     1
2   4     3
3   4     4

```

You can check for talent dependencies programatically by querying the complete talent table, and building a linked tree. You can also do that with SQL but it will require either recursive subselects or lots of queries. Better do it in your code.

If there are multiple dependencies, like for example `Fire Punch` depends on `Punch` AND `Immolation` use two tables to represent the dependency graph:

```
#Talent
id  description
1   Tackle
2   Kick
3   Punch
4   Fire Punch
5   Immolation

#Depedency
id  parent  child
1   0       1
2   0       5
3   1       2
4   1       3
5   3       4
6   5       4

```
> 13 votes

# Answer
I would recommend using a tree where each node represents a specific talent/skill. Based on whether or not the player has earned a talent, its child talents can be earned. For example the following data structure

```
class Talent {
    std::vector<Talent*> children;
    bool earned;
};

```

To determine which talents a player has, you take the root talent and walk down the graph until you reach the talent nodes where earned is false. This will also reveal which talents are available for obtaining: the first talent in each branch down from the root talent where earned is false.
> 5 votes

# Answer
In my game I do it like this:

**Database:**

*reference\_talent* : contains an unique ID, name, effect etc

*talent* : id, playerid \<- contains all talents players have "learned".

**Ingame:** (on the server)

I load up all reference\_talents in a 'static' (read only) std::map so I can access them easily by their id.

When a client checks out a player I get all the talents from the database and stocks them in a std::vector so that when I need to calculate characteristics etc. I have them in RAM. I also send away the talents to the client.

That's about it (except saving off new talents of course which is just an 'INSERT' in the table 'talent' + a message to the client).
> 1 votes

# Answer
## Relational approach

You describe it as relation between unlockers and unlocked similar as in this tutorial. I suggest learning more about relational algebra and databases. They are nice way how to model data. If You learn how to query the information from database You can model data quite easily.

I don't know how much You know about modeling relations. That tutorial should help You with it.

## One solution

I assume that WoW work as in reality (ehm), that it is

* talent unlocks several (other) talents
* talent is unlocked by several (other) talents.

It is N:N relation, which implies You need "middle man" a new relation between the two talents:

```
(talent who unlocks id, talent who is unlocked)

```

This way You can have talent A unlocking B, C and D ((A, B), (A,C),(A,D)) and talent Y unlocked by X,Z and W ((X,Y),(Z,Y), (W,Y)). In imperative/procedural/object-oriented language You would do it as list/array of pairs like there:

```
var unlocks_unlocked = [[A, B],[A,C],[A,D],[X,Y],[Z,Y],[W,Y]];

```

So for "real-world" example You can have:

```
... ["running fast", "jumping superhigh"], ["antigravity's child", "jumping superhigh"]

```

and it means that "jumping superhigh" is obtained after You have "running fast" and "antigravity's child" talents.

## Other solution

I have not played Diablo recently but it might be, that it had only:

* talent unlocks several other talents
* talent is unlocked just by one talent.

It is 1:N relation:

```
 You put "is unlocked by this talent's id" variable into talent's structure

```

like:

```
 var Talent[8] = { "name": "superpower", "unlocked by": "being Clark Kent"};

```
> 0 votes

---
Tags: mmo, rpg, data-structure
---


title: How do I use D3DXVec3Normalize()?

text:
# Question
Title: How do I use D3DXVec3Normalize()?
It accepts two parameters, the first is an out parameter - a pointer type, so a referenced variable or a pointer to a variable - the second parameter is an in parameter of the same type but const.

This is strange to me, normalizing is a simple calculation, I would expect the function to have one parameter - the vector to be normalised. Why does it have two? could somebody write an example of how I would use it?

# Answer
> 3 votes
Basically it allows you to have an input vector different from an output vector, like so:

```
D3DXVECTOR3 bulletMovement = /*...*/; // the whole bullet movement
D3DXVECTOR3 bulletDirection = /*...*/; // the DIRECTION of the bullet movement, with a length of 1.
D3DXVec3Normalize(&bulletDirection , &bulletMovement);

```

This way you keep your whole bullet movement intact and simply modify the direction, because that's the only vector that you want with a length of 1.

It may not be always useful, but if gives you **more control over the normalization** (although you could do without it being so flexible by making a copy and normalizing it after).

What you generally want is this:

```
D3DXVECTOR3 mouseDirection = /*...*/;
D3DXVec3Normalize(&mouseDirection, &mouseDirection);

```

But keep in mind that you have the **possibility** to have **different input/output parameters**.

# Answer
> 4 votes
> normalizing is a simple calculation, I would expect the function to have one parameter - the vector to be normalised. Why does it have two? could somebody write an example of how I would use it?

Normalizing is, indeed, relatively simple. It's also an operation that is performed *often* and consequently should be very fast. Performance considerations are especially important when designing math library middleware like D3DX.

The reason there are two parameters is for efficiency, and to some extent robustness. By providing by-reference (via pointer) output and input parameters, the D3DX normalize function can normalize a vector in place or to a new vector without unnecessary by-value copying of the vector object.

By way of contrast, consider the alternatives: If the normalization function took only a single input vector, it would have only two reasonable options to get the result back to the caller:

1. Return it directly.
2. Modify the input value.

Option (1) would perforce require a copy of the vector to be returned on the stack (a vector which is much larger than the size of a pointer in real-world scenarios) and so would be somewhat less efficient, even if it is a slightly more natural or convenient API.

Option (2) is cumbersome, would prevent const variables from being normalized without first making a copy, and similarly would require the caller to create a copy if they did not what the input vector modified. So it's both less convenient and in some cases also less efficient.

---

Update: It's worth noting, as discussed in the comments, that modern C++ compilers can perform a copy elision optimization that would allow them to eliminate the performance overhead of (1) entirely. This optimization was prevalent even back in 2011 when I originally answered this, so I should have pointed it out then.

I can only speculate as to why the designers of the API in question chose to implement it in this fashion; perhaps they were being conservative or had reason to expect that RVO wouldn't or couldn't be performed in some important use cases (by contrast, you can see some API's like Apple's GLKit aggressive expect these sorts of optimizations, even in C, because they return entire objects like matrices on the stack; this may also be informed by knowledge of the underlying platforms calling convention, as well, however).

---
Tags: c++, directx, directx10
---


# Question
Title: Where is the "Scripts Window" menu in Blender 2.59?
I'm trying to import a script into Blender, and I have the script in my directory and I pushed F8 to reload scripts, but the instructions for running this script say:

> In the "Scripts Window" run "Scripts → Export → OGRE Meshes".

I've seen other similar instructions for other scripts. But the toolbar only contains "File/Add/Render/Help." Changing the "screen layout" to Scripting doesn't reveal any additional options, either.

I'm sure I'm just missing something obvious. Please help!

# Answer
Those instructions are for Blender 2.49 and before. Scripting API is completely different (and much better) since 2.5. Import and export is in the file menu. What you are looking for is the add-on list, where you can enable them and see where are they located. File -\> User preferences... -\> Add-ons.

Maybe you need to install the appropiate add-on for blender 2.5x, if it exists.

Edit: it's still in development but here it is: http://www.ogre3d.org/tikiwiki/Blender+2.5+Exporter
> 5 votes

# Answer
I believe it is now called "Python console", do you see this option somewhere?

**Edit**: In **this post** they confirm that, from Blender 2.5x, Script Window is now called Python console
> 0 votes

---
Tags: blender
---


# Question
Title: How to deal with corner collisions in 2D?
I'm writing a top down 2d XNA game. Since its my first I'm trying to write the physics and collision stuff myself to learn it.

Whenever my player sprite character attempts to move into a position where its bounds intersect with the edge of a wall, I figure out a bounce angle (angle of incidence = angle of reflection) and I make the player bounce off the wall and avoid the collision.

I'm having trouble figuring out how to deal with the situation of my sprite intersecting with two wall edges simultaneously though e.g. it hits a corner.

My code currently tells me that two wall edges have been intersected but not which edge it would have hit first and therefore which edge to bounce off.

What is the mathematical test to pick which edge to bounce off? It's plain to see when looking at it but I'm struggling to figure out the math test for it.

# Answer
> 10 votes
If you calculate how far into the `Wall` the `Player Sprite` has moved, you can probably base it on the delta of the x and y coordinates of the corners that are intersecting. I hope that makes sense, I can't think of a better way to word it.

So, for example, if you look at your diagram. Take the `x` value of the top left corner of the `Player Sprite` (after the move), and subtract the `x` value of the bottom right corner of the `Wall`. Do the same thing for the `y` values and then see which one is larger. The key is that if one is larger than the other, the `Player Sprite` probably intersected on that side.

Here's an image example (this is a subsection of your image with my own lines added):

Now, you see here that the blue line is larger than the green line. In this case the blue line is also on the side that the `Player Sprite` would be expected to bounce off of.

If the two values are equal, they hit right on the corner.

Now, there is a slight problem with doing it this way. If the `Player Sprite` is traveling very fast or the collision is very close to the corner, it's possible that the `Player Sprite` may go further into the `Wall` in the wrong direction. In that case you'll probably have to check the velocity of the moving object. (See Nathan Reed's answer.)

Note: I think I'm essentially trying to describe the SAT collision detection that @Blau mentioned, but I've spent a long time writing this so I'm going to post it anyways. Hopefully it'll help you some.

# Answer
> 17 votes
Minimum displacement does *not* always give the right answer for which edge was hit first. Consider this case:

This happens when the velocity is high enough that the block moves rather far during one frame. To correctly detect which edge was hit first, you'll need to set up a linear equation to solve for the time of collision with each edge. In this case described in the OP's diagram, the relevant equations are:

```
timeXCollision = (player.left - wall.right) / -player.velocity.x
timeYCollision = (wall.bottom - player.top) / player.velocity.y

```

(This is assuming an X-right, Y-up coordinate system.) In general, you'd have to use the signs of player.velocity's X and Y components to determine which pair of edges need to be tested. Anyway, once you have the collision times computed, the *earlier* of the two is the collision you need to handle.

# Answer
> 2 votes
You need SAT Collision Detection

Basically you need to look for the minimum displacement vector that substracted to one of the objects let them to no intersect.

In your image the minimum displacement is the orange segment.

# Answer
> 0 votes
Answered a similar question here

You may want to consider checking previous positions-

For example : if your left side was previously to the right of their right side and you're colliding, then a right hand collision has happened.

If you do this, just resolve y axis collisions, check if you're colliding with anything, then resolve x axis collisions.

---
Tags: xna, 2d, collision-detection, physics, collision-resolution
---


# Question
Title: How can I make this style of 2D "glowing" graphics?
I'm comfortable with the basics of building a 2d sprite based game in XNA, where all my objects are simply .png images that I move around.

What things do I need to learn next to be able to develop a 2d game that utilizes an art style similar to Super Laser Racer for example.

Other examples of this style would include Frozen Synapse, Geometry Wars, etc.

I would describe this style "2D abstract glowing geometry" or something like that.

I can see that a lot of the effects in these types of games are achieved via particle systems and also that maybe some things are still just sprites that were maybe drawn in a graphics editor to look all "glowing" etc.

But then the rest is possibly done by making draw calls to DirectX and implementing custom shaders, etc?

Is that right? I'm not really sure of what to learn next to be able to go in this direction or what questions to ask.

# Answer
> 30 votes
The simplest way to achieve the effect is to draw a bunch of particles in Additive mode, so when they are superimposed their color values are added up, becoming brighter.

Some samples:

http://www.youtube.com/watch?v=\_sx0KDO-ZbA

http://www.youtube.com/watch?v=-OZOdQHLiiI

# Answer
> 11 votes
The glowing effect is probably a bloom filter pixel shader

# Answer
> 9 votes
One simple method I know of is to render once, blur the result, then render the original, sharp object again on top.

This can be done by a bloom filter pixel shader.

---
Tags: xna, graphics, graphics-programming, special-effects, graphics-design
---


# Question
Title: How can I spawn multiple monsters in my game?
I made a little iPhone game in which I want to make multiple monsters spawn.

I have one UIImageView called `enemy` that spawns at beginning of the game. But I want it to spawn many more monsters until I say it needs to stop spawning them.

I know how to get random locations. This question is a follow up to this one.

# Answer
> 1 votes
You need to have a collection of monsters and a MAX\_MONSTERS constant. I'm not much of an Objective-C programmer, but this pseudo-code should get you going:

```
.. top of program
MAX_MONSTERS = 5;
MonsterCollection[MAX_MONSTERS] mc;

... game loop
for(int i = 0; i < MAX_MONSTERS; i++)
    if(mc[i] != null && mc[i].IsAlive)
        mc[i].Update();
    else
        mc[i] = // new monster

```

# Answer
> 1 votes
From your question it seems like the `UIImageView` is holding your monster-graphics. The more important thing however is where you located the monster-logic (that will update/move the monster-graphics).

For multiple monsters, you'll need multiple instances of the `UIImageView`. Also you'll need to keep track of position and other properties (like health) for each monster. A reasonable approach to this would be to have a separate class that encapsulates all monster related logic.

Therefore, I suggest you create a special class (that inherits from `NSObject`) for monster and make the `UIImageView` a member of this class. A really basic interface for such a class could look like this:

```
#import <Foundation/Foundation.h>

@interface Monster : NSObject {

}

@property(retain) UIImageView* view;

-(void) update:(double)dt;

@end

```

In the `init` method of your monster-class you would initialize your graphics (and assign it to the `view` property). Creating multiple monsters can be done using something like this:

```
// constant that defines how many monsters should be created
#define NUM_MONSTERS 5

// monsters should be a member of your class, so that you can loop through it
// and perform updates. This is why we "retain" the monsters array here.
// You should use "release" to free the array in the class dealloc method.
NSMutableArray* monsters =
    [[NSMutableArray arrayWithCapacity:NUM_MONSTERS] retain];

for(int i = 0; i < NUM_MONSTERS; ++i){
    Monster* monster = [[Monster alloc] init];
    // store the monster in the monsters array
    [monsters addObject: monster];
    // add the monster view (UIImageView) to the current view
    [self.view addSubview: monster.view];
}

```

# Answer
> -1 votes
Look at initWithNib method, if your views are designed in InterfaceBuilder.

---
Tags: 2d, iphone, game-mechanics, objective-c
---


# Question
Title: How do I handle user input with good class structure/architecture for an Android game?
How do I handle user input having "good" class structure and following normal game architecture\*?(see below). At first I didn't think this question was Android specific, although, after seeing a great response in C++ I would appreciate some insight on this question using Android architecture.

**Current way I handle input for my Android Game:**

* Created controller class that takes X,Y screen events and X,Y character position and returns an int that represents a direction the character should move.
* Call the controller method in the game's update.
* Send that direction value to my character update.
* Character's update calls move (which is also passed this value).
* Basic switch statement determines the direction my character moves.
* Getters and setters for the position of the character.(should I have them for this direction also)

Is there a better way of handling input? This doesn't feel like the best way. Where does input fit in with class structure and game architecture?

I'm going to accept the C++ answer but I would really like to see a Java answer for Android in the future. :D

# Answer
> 1 votes
If i'm not mistaken that Idea is generally considered and Anti-Pattern named Anemic Domain Model, but if you use it wisely it can be beneficial. I Prefer one big function if you are not going to implement many controllers with different behaviors, but if you are going to have more than one controller and decide in runtime what that controller should do, it's not a very bad idea to use them but you have to be very careful to prevent possible errors (like controllers call order).

**--EDIT--**

I guess if change your function to this way there won't be any problem, and you'll get smaller functions:

```
class workerA
{
    static point nextPos(point currentPos, ...)
    {
    }
};

class workerB
{
    .
    .
    .
};

class player
{
    void move()
    {
        pos = workerA.nextPos(pos,...);

    }
}

```

I'm not sure if this is a valid design pattern or not but at least classes doesn't have bidirectional pointers, and player class can always guaranty its members, since it's *move* that calls other methods.

**--EDIT2--** This is the best way I could describe my architecture. It's a complete code, with all the thing available in every game. I'm not sure if this is like your previous style or not or if you can convert your code (or even if you are willing to). if you still think there is anything unclear or want to discuss about this code, I think I'll be available in chatroom in 12 hours meaning something around 1:00 GMT.

```
#include <iostream>
#include <vector>

class Keyboard;
class RenderTarget;

struct Point
{
    int x,y;
}

class Rendereable
{
protected :
    RenderTarget* mRenderTarget
public:
    virtual void draw() = 0;
    void setRenderTarget(RenderTarget* pRenderTarget);
}

class world;

class Entity
{
protected:
    Point mPosition;
    Point mRadius;
public:
    virtual void update(world* pWorld) = 0;
    void setPosition(Point pPosition);
    Point getPosition() const;
    bool isColliding(const Entity* pOther) const;
    bool isColliding(Point pOther) const;
};

class world
{
protected:
    vector<entity*> mEntitys;
    int mWidth,mHeight;
public:
    void update();
    void draw();
    void addEntity(const Entity* pEntity);
    void removeEntity(const Entity* pEntity);
    bool isFree(const Entity* pEntity);
    bool isFree(Point* pPoint);
};

class KeyboardController
{
protected:
    Keyboard* mKeyboard;
public:
    Point getNextPosition(const pEntity* pTarget,World* pWorld);
    void setKeyboard(KeyBoard* pKeyboard);
};

class Player : public Entity
{
protected:
    KeyboardController* mController;
public:
    void setController(KeyBoardController* pController);
    virtual void update(World* pWorld);
    virtual void draw();
};

class Game
{
    World* mWorld;
    RenderTarget* mRenderTarget;
    Keyboard* mKeyboard;
public:
    bool init();
    bool update();
    void draw();
    void shut();
};

int main()
{
    Game* game = new Game;
    if (game->init())
    {
        while (game->update())
            game->draw();
        game->shut();
        return 0;
    }
    return 1; //this means error! only useful when your program is going to be used in batch files!
}

void Renderable::setRenderTarget(RenderTarget* pRenderTarget)
{
    mRenderTarget = pRenderTarget;
}

void Entity::setPosition(Point pPosition)
{
    mPosition = pPosition;
}

Point Entity::getPosition() const
{
    return mPosition;
}

bool Entity::isColliding(const Entity* pOther) const
{
    int deltaX = mPosition.x - pOther->mPosition.x;
    int deltaY = mPosition.y - pOther->mPosition.y;
    int sumRadius = mRadius + pOther->mRadius;
    if (sumRadius * sumRadius < deltaX * deltaX + deltaY * deltaY)
        return true;
    else
        return false;
}

bool Entity::isColliding(Point pOther) const
{
    int deltaX = mPosition.x - pOther.x;
    int deltaY = mPosition.y - pOther.y;
    if (mRadius * mRadius < deltaX * deltaX + deltaY * deltaY)
        return true;
    else
        return false;
}

void World::Update()
{
    for (auto i = mEntitys.begin();i != mEntity.end();i++)
        i->update(this);
}

void World::draw()
{
    for (auto i = mEntitys.begin();i != mEntity.end();i++)
        i->draw();
}

void World::addEntity(const Entity* pEntity)
{
    for (auto i = mEntitys.begin();i != mEntity.end();i++)
        if(*i == pEntity)
            throw Exception("Entity is already in world");
    mEntitys.push_back(pEntity);
}

void World::removeEntity(const Entity* pEntity)
{
    for(auto i = mEntitys.begin();i != mEntitys.end();i++)
        if(*i == pEntity)
        {
            mEntitys.erase(i);
            return;
        }
    throw Exception("Entity is not in world");
}

bool World::isFree(const Entity* pEntity)
{
    if (pEntity->x < pEntity->radius || pEntity->x > width - pEntity->radius)
        return true;
    if (pEntity->y < pEntity->radius || pEntity->y > height - pEntity->radius)
        return true;
    for(auto i = mEntitys.begin();i != mEntitys.end();i++)
        if(*i != pEntity)
            if(i->isColliding(pEntity))
                return true;
    return false;
}

bool World::isFree(Point* pPoint)
{
    if (pPoint.x < 0 || pPoint.x > mWidth)
        return true;
    if (pPoint.y < 0 || pPointy > mHeight)
        return true;
    for(auto i = mEntitys.begin();i != mEntitys.end();i++)
        if(i->isColliding(pPoint))
            return true;
    return false;
}

Point KeyboardController::getNextPosition(const pEntity* pTarget,World* pWorld)
{
    Entity x(*pTarget);
    if (mKeyboard->isKeyDown(K_UP))
    {
        y --;
        if (pWorld->isFree (x))
            return x.getPosition();
        y ++;
    }
    // same function goes for other directions
}
void KeyboardController::setKeyboard(KeyBoard* pKeyboard)
{
    mKeyBoard = pKeyBoard;
}

void Player::setController(KeyBoardController* pController)
{
    mController = pController;
}

virtual void Player::update(World* pWorld)
{
    mPosition = pController->getNextPosition(this, pWorld);
}

virtual void Player::draw()
{
    mRenderTarget->Circle(mPosition.x, mPosition.y, mRadius); // a simple drawing function
}

bool Game::init()
{
    mWorld = new World;
    mKeyboard = new KeyBoard;
    mRenderTarget = new RenderTarget;
    Player* player = new Player;
    KeyBoardController* controller = new KeyBoardController;
    player->setController(controller);
    player->setRenderTarget(RenderTarget);
    mWorld->addEntity(player);
}
bool Game::update()
{
    mWorld->update();
}
void Game::draw()
{
    mRenderTarget->clearDevice();
    mWorld->draw();
}
void Game::shut()
{

}

```

# Answer
> 0 votes
What I found to work best is to have

* Android's UI thread subscribe to `onTouch` events on the Game's `SurfaceView` (either OpenGL or Canvas)
* Setup a global `InputSystem` singleton.
* Have the UI thread's onTouch call the `InputSystem`'s onTouch passing the MotionEvent.
* `InputSystem` then saves this event (optionally in a cyclic queue - although using a single event works best for us). On the same occasion InputSystem can do all sorts of short calculations such as the last move distance, and various "was X event triggered in the last X ms"
    + `InputSystem` provides a `peek` and `consume` methods.
    + Various game logic components running on the Game Thread consult the inputsystem for the event, and potentially act upon it, and consume it.

---
Tags: android, input, movement, control
---


# Question
Title: What tool should I use to make this game?
A little background info: I'm just about to graduate university with a software engineering degree. I have a fair amount of experience with more "serious" programming languages (C++/Java/C#), plenty of theoretical background, and good learning ability. I have minimal experience in web development as a whole (some JSP/JavaScript), and only very little with game engines (used Slick2D once to make a simple platformer, and had a brief introduction to 2D XNA).

I was recently approached by some people who have a game idea, and are looking for implementors. The game is a 2D turn-based strategy web game with a persistent world (meaning a DB backend would likely be required to store world state, user info, etc), and several UI interfaces.

I know this is a rather vague description, but based on this, which **free** game engine/framework/toolkit should I be looking at? Or at least, which technology (Flash/HTML5/JavaScript) would make it the easiest for me to develop this game?

# Answer
If you have knowledge with C#, and wish to work with a strongly typed library that supports C# and .NET, try Unity3D

Pros:

* Free for indie developers
* Has a web plugin and ability to communicate with JavaScript
* Can use C# and .NET libraries
* Robust set of helper libraries - mathematical structures and functions, input helpers, shaders, camera, round-robin process execution

Cons:

* native 2D support is spotty, has to use a third-party library (such as EZ-Sprites) for efficient 2D rendering (or roll your own using textured quads)
* Requires a plugin for web deployment and is definitely not as widespread as Flash
* scene files are stored in binary format, cannot be merged through source control (will be fixed in 3.5)
* Lack of good source control for indie version (pro versions require assets server, which is a separate purchase...though 3.5 may provide better support)
* Uses a Mono library which is about one step behind .NET 4, so it is lacking in many bells and whistles such as default variables and anonymous types (if you do use them)
> 2 votes

# Answer
One example, which is free and has a lot of documentation, is the 'ol Apache/PHP/MySQL combo.

A linux box with Apache, Mysql and PHP is almost a standard itself. I made a persistent turnbased RPG game with it and I learned a lot from it (specially database stuff but also a lot of do's and don'ts when it comes to the WEB).

Check it out Here if you want (it's in French but click 'S'enregistrer à Métamorphes !' to register). No one plays it any more and it is like 6-7 years old but it might give you the feeling of what you can build when you don't know very much about Web/DB etc.
> 2 votes

# Answer
I'd suggest Flash for the front-end, perhaps with a library such as Flixel or Flashpunk to facilitate the graphics. However you will need to get more specifications on the graphical style they want, as well as to clarify what "several UI interfaces" means. You can use FlashDevelop to work with Flash for free, and although you don't get all the vector graphic editing capability that the full Flash program gives you, it's perfectly adequate for ActionScript coding.

For the back end, something like Django would work if you wanted to use Python, or Ruby on Rails if you wanted to use Ruby. Personally I don't recommend PHP because it's a bit of an abomination of a language, but it's certainly up to the task. You can also stick with Java if you like, if you know how to access databases that way. All you need here is the ability to handle a variety of HTTP requests and to have them retrieve or store data accordingly. You probably would want to look at getting the data to and from the client in JSON format, as it's fairly compact and yet still human-readable, which means you can test features in a browser before hooking up your main client.
> 1 votes

# Answer
If you're doing this in your spare time, I would suggest trying to write the game using several different engines. That way, you will get a good feel for what each engine can / can't do.

As this is a turn based game, I would definitely start out with something having very simple graphics and probably done as static web pages and then put all your game code on the server, using .Net MVC perhaps. This means that you only have one application to worry about, the server code, and a local DB connection to manage.

Once you've got that working, you can then look into doing some client side processing - animations, fancier UI, etc. You can try out the various client systems you mention to see what works best for you.
> 0 votes

---
Tags: 2d, web
---


# Question
Title: How do I organize my game into multiple classes in C#?
I've made two simple 2D games while following tutorials for the XNA libraries, and I wanted to make something myself, with only the knowledge I gained from these tutorials.

This will be my first serious attempt at game development, as well as my first C#/XNA project. I migrated from Java a week ago. Now, both of the tutorials I've followed made the whole game using only one class. And while it's possible, it isn't organized enough for me, and I want most of the functions to be organized in separate classes. So, I started with Input so I can have an easy way of exiting the game during testing right away.

Here's the important bits, I think:

From my `Game1.cs`:

```
protected override void Update(GameTime gameTime)
{
    Input input = new Input();
    input.PollInput();

    // TODO: Add your update logic here

    base.Update(gameTime);
}

```

From my `Input.cs`:

```
namespace MyFirst2DGame
{
    class Input
    {
        Game1 game = new Game1();

        public void PollInput()
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                game.Exit();
        }
    }
}

```

However, when I run the project, the Back button on the XBox 360 controller does nothing. My question, is am I missing something? I have no idea how to do anything with multiple classes, as all of my Java projects were quite small and had need for only one class.

# Answer
> 8 votes
You are creating a new `game1` object in your `PollInput` command, since that's not your original game object, calling `exit` on it does nothing.

Usual practice would be to pass in your existing game object in the constructor of your `Input` class.

I'd also avoid creating a new `Input` object every loop of `Update`. Create it once and re-use it. This particularly matters when developing on the xbox (i guess you are since you're using a gamepad, not keyboard) since the garbage collection engine isn't as good as the PC, so you want to reuse objects as much as possible.

---

You could make your `Input` class inherit from `GameComponent`, calling it something like `InputHandler`, or `InputComponent` if you like. You'd then pass in the Game into the base constructor, and override the `Update` method.

If you do this, you can add to your game's Components in your game's constructor, which would make its update method get called automatically.

You don't have to use that part of the framework though, so really it's up to you.

---

Also, it's bad practice to depend on PlayerIndex.One, better is to use a loop:

```
for(var PI = PlayerIndex.One;PI <= PlayerIndex.Four; PI++)
{
    if (GamePad.GetState(PI).Buttons.Back == ButtonState.Pressed)
        game.Exit();
}

```

Although normally you'd have a 'Press Start' screen and only use that player's index. The code for that could look like the above.

---

It's probably worth going to the Creators App Hub.

Take a look at their samples for standard ways to lay code out. Particularly the Game State Management sample.

# Answer
> 4 votes
I think the problem is in your `PollInput()`. You instantiate a new `Game1` object in your `Input` class. When you press the button on your controller, you exit the game object of the newly generated game class, not the game class which generated your `Input`.

One solution would be to pass the game object to the constructor of the `Input` like this:

```
public Input(Game game)
{
    this.game = game;
}

```

# Answer
> 0 votes
One problem you'll run into very quickly is putting too much game logic into your input class. You're better off creating an intermediate class that handles game logic and input. Your input classes should be just wrappers around the various devices and provide some utility functions.

Something like this:

```
class MyGame : Game
{
    Input _input;                // Utility class that provides helpers for input
    UnitManager _units;          // Tracker for units
    InputHandler _inputHandler;  // Connects game units with input

    protected override void Initialize()
    {
        _input = new Input();
        _units = new UnitManager(this);

        // InputHandler will probably want the game, units, and the input helper.
        // (Or it internally manages the input util class)
        _inputHandler = new InputHandler(this, _input, _units);

        base.Initialize();
    }

    protected override void Update(GameTime time)
    {
        _input.Update(time);  // Update input states - new clicks, presses, etc...
        _units.Update(time);  // AI moves
        _inputHandler(time);  // Check input for clicks, button presses, etc...

        base.Initialize();
    }
}

```

Edit: Further examples...

The Input class I use is just a wrapper and some utility functions.

InputManager \- Just holds three helpers for keyboard, mouse, and controller. I make this relatively global by creating it in my Game instance and passing it down into the various screens and components.

Helpers:

ControllerHelper, KeyboardHelper, MouseHelper \- These all get updated and store the last and current state so you can have easier helpers like `Input.Keyboard.IsNewKeyPress(Keys.W)` and `Input.Keyboard.IsKeyHeld(Keys.Space)`. Makes checking and storing that information much easier - your logic class doesn't have to concern itself with handling input states, just checking for state changes.

I use an entity system which is a whole other topic, but it gives me the InputHandler class mentioned above. Here's some roughcode for it:

```
public class InputHandler
{
     MyGame _game;   // Assuming Input is a property here
     Player _player;

     // Constructor - pass any dependencies here
     public InputHandler(MyGame game, Player player)
     {
         _game = game;
         _player = player;
     }

     // Update, as usual
     public void Update(GameTime time)
     {
         if (_game.Input.IsKeyDown(Keys.W))
         {
             _player.Position.X += 1;
         }

         if (_game.Input.IsKeyDown(Keys.S))
         {
             _player.Position.X -= 1;
         }

         // And so on...
         // You probably wouldn't be using 1 as a speed, factor in
         // the elapsed time since the last update for smoother movement
         // in case of slow-downs and add in a speed variable to
         // control that.

         // XBox controller input is pretty much the same, just you can
         // get 0.0 - 1.0 Vector2's from the thumbsticks.

         // Not all your input has to go here either.  If you use a game
         // state system, each game state might have it's own InputHandler
         // class (ie, a menu state would handle up/down differently than
         // in game.

         // Elsewhere would be a camera class that takes the player as
         // a dependency and updates the view matrix from player position
         // and rotation.
     }
}

```

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


# Question
Title: How can I create a smooth simulation for a fast-paced, multiplayer table hockey game?
I'm adding multiplayer to an iPhone game that we have in our company. It's a sort of 'table hockey' game, with a puck and two mallets.

It's a pretty fast game, so I need a smooth experience at both ends. What I'm doing right now is using Game Center, and setting up the iPhone that starts the game as the "server."

So, the client runs its physics the same as the server, but the server adjusts the speed of the puck on the client and adjust its position when they are going on the same direction. The problem that it has some glitches, when the physics simulations differs a bit between then and the server sends the command to correct and the client kind of jumps around.

Does anyone has a suggestion how should I can handle this? Or should I try a different way?

# Answer
> 4 votes
The general technique is for the the server to maintain authority, and send the game state updates to the client as rapidly as needed. The client maintains a local copy of the game state which it simulates itself, predicting that most of the time the server will confirm the input it sends. When the server game state and client game state differ, you adjust towards the server state, usually interpolating to hide sudden transitions or rubber-banding effects.

It's not clear from your post what the underlying transmission medium is (TCP versus UDP). Because you have a fast-paced game, you probably want to use UDP and simply send the client state updates as fast as possible. This is what is usually done in other fast-paced games, like first-person shooters.

You can look up client-side prediction resources on Google.

---
Tags: iphone, networking, client-server, game-center
---


title: What is a "cue" in the XACT API?

text:
# Question
Title: What is a "cue" in the XACT API?
I understand that a wave bank is a collection of .wav data files and that a sound bank is a collection of tracks, each having a .wav with properties. But what is a cue?

# Answer
> 4 votes
A cue is a like a trigger used to invoke a sound. A cue has multiple sounds associated with it that all play back once the cue is activated.

---
Tags: xna
---


# Question
Title: How can I implement a renderer that can draw many kinds of primitives?
This is somewhat linked to a question I previously asked concerning the drawing of indexed primitives.

My problem was that I was only drawing one cube when I wanted to draw many. I was told that the problem was that I was overwriting the vertex and index buffers with each new instantiation of `Cube` and that instead I should create one at the origin and then draw many, passing through a transformation matrix to the shader that makes it appear in different places. This worked beautifully.

I now have a new problem though: how would I draw many different types of primitives?

Here is my code from the previous question:

```
Cube::Cube(D3DXCOLOR colour, D3DXVECTOR3 min, D3DXVECTOR3 max)
{
// create eight vertices to represent the corners of the cube
VERTEX OurVertices[] =
{
    {D3DXVECTOR3(min.x, max.y, max.z), colour},
    {D3DXVECTOR3(min.x, max.y, min.z), colour},
    {D3DXVECTOR3(min.x, min.y, max.z), colour},
    {min, colour},
    {max, colour},
    {D3DXVECTOR3(max.x, max.y, min.z), colour},
    {D3DXVECTOR3(max.x, min.y, max.z), colour},
    {D3DXVECTOR3(max.x, min.y, min.z), colour},
};

// create the vertex buffer
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(VERTEX) * 8;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &pBuffer);

void* pVoid;    // the void pointer

pBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the vertex buffer
memcpy(pVoid, OurVertices, sizeof(OurVertices));    // copy the vertices to the buffer
pBuffer->Unmap();

// create the index buffer out of DWORDs
DWORD OurIndices[] =
{
    0, 1, 2,    // side 1
    2, 1, 3,
    4, 0, 6,    // side 2
    6, 0, 2,
    7, 5, 6,    // side 3
    6, 5, 4,
    3, 1, 7,    // side 4
    7, 1, 5,
    4, 5, 0,    // side 5
    0, 5, 1,
    3, 7, 2,    // side 6
    2, 7, 6,
};

// create the index buffer
// D3D10_BUFFER_DESC bd;    // redefinition
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(DWORD) * 36;
bd.BindFlags = D3D10_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &iBuffer);

iBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the index buffer
memcpy(pVoid, OurIndices, sizeof(OurIndices));    // copy the indices to the buffer
iBuffer->Unmap();

//this is simply a single call to the update method that sets up the scale, rotation
//and translation matrices, in case the cubes are static and you don't want to have to
//call update every frame
Update(D3DXVECTOR3(1, 1, 1), D3DXVECTOR3(0, 0, 0), D3DXVECTOR3(0, 0, 0));
}

```

Clearly if I duplicated and modified the code to be a different object or shape, the last shape to be initialized would overwrite the vertex buffer, wouldn't it?

Do I use multiple vertex buffers? Do I append the new vertex buffer to the old one and use the appropriate indices to draw them? Can I do either? Both?

# Answer
> 12 votes
It's probably a bad idea to create new classes for each type of geometry you're going to support. It's not very scalable or maintainable. Additionally, the class design you appear to want now seems to conflate the tasks of managing the geometry itself and the instance data for that geometry.

Here's an approach you can take:

Create two classes, `Mesh` and `MeshInstance`. A `Mesh` contains all the properties of the shared geometry -- basically a vertex buffer and an index buffer. If you want, you can create helper functions that create meshes containing cube vertex data (or sphere vertex data, or whatever else you like). You should tailor the public interface of the `Mesh` class to allow such helper functions to be implemented as non-member, non-friend functions.

`MeshInstance`, on the other hand, must be constructed with a reference to a `Mesh`. The `MeshInstance` contains the properties of an individual object -- it's world transformation, and shader overrides used to render it, and so on.

This way, when you want to create a new cube, you first obtain the `Mesh` object representing a cube from some shared library of primitive mesh objects you created at startup. Then you create a new `MeshInstance`, assigning it that cube `Mesh`.

When you render, you build up a list of all the `MeshInstance`s you want to draw, and submit them. If you group them by `Mesh` or texture, you can optimize for state change overhead (i.e., you draw all the mesh instances corresponding to the cube mesh at once, and then all the mesh instances corresponding to the sphere mesh, so you have fewer `SetVertexBuffer` calls on the D3D device). You can also group by other state, like texture and shader.

In this fashion, you avoid wasting memory duplicating vertex data, and you ensure that your rendering system can scale to any arbitrary set of primitives simply by implementing new (a) functions to create meshes programmatically or (b) functions to load meshes from files of a particular format.

Once your render pipeline works in terms of generalized `Mesh` objects, it's much easier to adapt it in a global fashion to new techniques or optimizations.

Specific comments:

> Clearly if I duplicated and modified the code to be a different object or shape, the last shape to be initialised would overwrite the vertex buffer. wouldn't it?

No. In the code you posted, the only way `pBuffer` and the like would be overwritten was if it was a static member variable. If you copied the class wholesale to create (for example) a `Sphere` class, that would be a new static variable. This is still a bad idea.

> Do I use multiple vertex buffers? Do I append the new vertex buffer to the old one and use the appropriate indices to draw them? Can I do either? Both?

The naive implementation of the technique I describe above involves multiple buffers (one for each set of shared geometry). If that geometry is static it is possible to store it all into one (or multiple, as there is a practical optimal limit to buffer size) buffer to minimize buffer state changes even further. That should be considered an optimization and is left as an exercise for the reader; first get it working, then worry about making it fast.

---
Tags: c++, directx, graphics-programming, directx10
---


# Question
Title: Is it possible to write a game that doesn't require a GPU?
I already know many computers today have a GPU that supports DirectX and OpenGL. But what about computers that don't? Can I write a simple 2D game that does not rely on the GPU, so that it works even on older machines?

Is there a cross-platform C or C++ game library that will let me do this? Ideally, such a library would let me toggle hardware acceleration with very few lines of code.

# Answer
> 6 votes
Certainly- you can use SDL and I believe it does everything on the CPU by default. You can actually get some pretty good performance if you manage your code well.

# Answer
> 2 votes
Do you think Pong used a GPU?

The Flash games you play on the web all the time, do you think they use a GPU?

(It's only these last few weeks that Flash games can at last be developed to use GPU support. And Flash has been around for considerably more than a decade.)

Of course it's possible. I'd been playing games for a decade before there was even such a thing as an accelerated graphics card for the consumer market, let alone entire Turing-complete processors dedicated to graphics (and more specifically, for games graphics).

# Answer
> 1 votes
It's absolutely possible: The first computer games existed before GPUs--which as you point out, are hardware designed to accelerate 3D math. Anything that's being done on the GPU can also be done on the CPU, although usually at a slower overall speed. (The initial release of Quake, for instance, only used software rendering\[1\])

Mesa3D is an OpenGL implementation that claims to support full-software rendering. (I haven't used it other than as a reference implementation, though).

# Answer
> 1 votes
Don't forget, first-generation video games were written for an oscilloscope! And by first-generation video games I mean pong. A GPU remember, is a math processor, which is also what a CPU is. It's just more specialized.

# Answer
> 1 votes
if it's only about 2d games, I suggest you use either `flash 10` or `SDL`, but if you think your game might contain 3d assets and rendering you can also use Irrlicht. it's basicaly an open-source cross-platform 3d engine with support for both hardware and software rendering:

from wiki:

> Irrlicht supports 3D rendering via OpenGL, DirectX 8 and 9, OpenGL ES, and internal software rasterizers.

# Answer
> -1 votes
While what you ask is possible it is worth noting that there is usually practically no advantage in discarding 3D acceleration. All modern PCs have built in 3D acceleration. The few old machines without this feature constitute an extremely small games market, and you'd probably have other compatibility issues with those as well.

I fear that you are asking this question for the wrong reason.

---
Tags: c++, 2d, c, cross-platform, hardware-acceleration
---