# Question
Title: How would I go about implementing a globe-like "ballish" map?
I am new to 3D development and I have this idea of having the game world like our globe is - a ball. So, there would be no corners in the map and the game is top-down RTS game. I would like the camera to go on and on and never stop even though you are moving the camera to the same direction all the time.

I am not sure if this is even possible, but I would really like to build a globe-like map without borders. Can this be done, and how exactly? I am using XNA, C#, and DirectX. Any tutorials or links or help is greatly appreciated!

# Answer
At the GGJ '11 in Berlin one team developed a game using a globus that was freely rotateable.

They made the game and the entire source available. It was made in C# and even XNA if I am not mistaken, so this might be a good reference for you.

Check it out here. The download link is beneath the group's picture.
> 5 votes

# Answer
Yes, it's very possible. I found though that making a true orbital camera was rather confusing. It was better to leave the Y (Up) axis locked and stop the camera at the poles. Otherwise it was easy to get disoriented. Google around for orbit cameras. Back when I was working on something like this, dhpoware's sample was useful. This old one might be useful too.

For the 3d Mesh, look into subdividing icosahedrons (sometimes called a geosphere). They give you a relatively uniform triangle size for texturing.
> 2 votes

# Answer
Whether you go with the torus option or not, you will need to do some wrap around, which will be the root of all the problems you will need to solve. However, they’ll be easier to address on a torus.

The idea is that your world is a grid that repeats itself along both the X and Y axes.

### Position wrap around

When an object’s X or Y position goes over 1.0f (or whatever the world size is), it wraps around to 0.0f. Where you generally do computations such as:

```
position += velocity * time;

```

You add wrap around logic:

```
position += velocity * time;
if (position.x >= 1.0f) position.x -= 1.0f;
else if (position.x < 0.0f) position.x += 1.0f;
if (position.y >= 1.0f) position.y -= 1.0f;
else if (position.y < 0.0f) position.y += 1.0f;

```

Or, avoiding tests and securely handling the large velocity cases:

```
position += velocity * time;
position.x -= floorf(position.x);
position.y -= floorf(position.y);

```

Having `1.0f` as the world size allows you to use `floorf()`, `roundf()` etc. immediately. Otherwise, you will need to use constructs such as `WORLD_SIZE * floorf(value * (1.0f / WORLD_SIZE))` instead.

### Distance computation

Computing distances changes, too. If you have two objects and one of them has `position.x = 0.1f` and the other has `position.y = 0.9f` then the distance is `0.2f`, not `0.8f`. So instead of the following distance function:

```
float distance(vec2 p1, vec2 p2)
{
    vec2 d = p2 - p1;
    return sqrtf(d.x * d.x + d.y * d.y);
}

```

You need to account for wrap around:

```
float distance(vec2 p1, vec2 p2)
{
    vec2 d = p2 - p1;
    d.x -= roundf(d.x);
    d.y -= roundf(d.y);
    return sqrtf(d.x * d.x + d.y * d.y);
}

```

### Rendering

Rendering will be tricky, too. You have several possibilities:

* when the camera reaches `0.0f` or `1.0f`, render the necessary parts from the other side of the map translated by combinations of `(1.0f, 0.0f)` or `(0.0f, 1.0f)`.
* always leave the camera at `(0.5f, 0.5f)` and move the whole world instead of the camera at each frame

These are fundamentally the same, but the way you see it will dictate your data structures. The best strategy here will probably depend on the culling mechanism you have.

**Edit**: sorry, I didn’t realise this was XNA. You will need to replace `roundf` and others with the equivalent `Math.Round()` etc.
> 2 votes

# Answer
Might I ask, do you really need a globe? Is your world small enough that the curvature would be visible? Why not approximate the globe with a bunch of rectangles? It will make your life easier, and presuming your world is large enough and if implemented well, can give the illusion of a fully connected world to boot.

Think of some games which have large open worlds, for the most part, they consist of "zones" where each "zone" borders other "zones." There is typically ocean surrounding groups of these "zones" which the player cannot manually cross, but the player is free to walk from zone to zone without restriction. For example, think of WoW's two continents and the dividing ocean.
> 1 votes

---
Tags: xna, c#, graphics-programming, maps, heightmap
---


# Question
Title: Xna - How do you use large animations for a menu
In the main menu of my game I have several animations that pause in specific frames.

I made the sprite sheets for the different layers, but then I found out that the sprite sheet has to be smaller than 2048 pixels. My sprite sheet is 14400 pixels with 18 frames...

How can I play these large animations? I tried video playback but I couldn't find a way to do this...

# Answer
**Don't make a sprite sheet.**

You are going to want to just create a

```
List<Texture2D>

```

with each frame of animation inside. It will be much more efficient on video memory usage, as you are only passing each frame of animation when the video card needs it, instead of loading everything in at once when you at most will be displaying one frame at a time.

Save all the animation as a png sequence inside a folder of the same name. (bigBG/bigBG0001,bigBG/bigBG0002.....)

Create a method that all you have to pass is the name of the folder, and have it make a sprite and add it to a

```
List<Texture2D>

```

for each file in the folder.

To get how many files are in the folder, use:

```
int count = Directory.GetFiles("Content/"+path,"*",SearchOption.TopDirectoryOnly).

```

That line references System.IO so on the top of the file in which you use this add

```
using System.IO;

```

Create a loop that goes through all the files with the *count* as the max.

You are going to need to make your method aware of how many spaces for the numbers there are and **pass that and the increment number of the loop** to a method like this.

```
internal static string fillZeroes(int num, int spaces)
    {
        string str = num.ToString();
        for (int i = str.Count(); i < spaces; i++)
        {
            str = "0" + str;
        }
        return str;
    }

```

Then you can use:

```
texture = rr.g.Content.Load<Texture2D>(path + name+ num);

```

Add it to your List and the loop restarts, after the loop is done, you are going to want to return the finished list.

You can can now draw any frame of the animation by using:

```
Texture2D texture = spriteListMenu[frameNumber];

```

and pass that texture to your spritebatch.draw
> 4 votes

# Answer
You could always put each frame on a separate texture, and change the texture on your sprite to animate it.
> 4 votes

---
Tags: xna, animation, spritesheet
---


title: Animation file format

text:
# Question
Title: Animation file format
I'm trying to make a simple 2D animation file format. It'll be very rudimentary: only an XML file containing some parameters (such as frame duration) and metadata, and some images, each representing a frame.

I'd like to have the whole animation (frames and XML document) packed in a single file. How do you suggest I do that? What libraries are there that would allow easy access to the files inside the animation file itself?

The language I'm using is C++ and the platform is Windows, but I'd rather not use a platform dependent library, if possible.

# Answer
I'd suggest packing them into a simple .zip archive; there are several libraries out there (a good one using the minizip function of ZLib is discussed here). That way, you'll have an XML file uncluttered with other embedded information, and then all the graphics resources out in their own files inside the archive. This might also allow for better compression of the binary data (very unsure about this).
> 3 votes

---
Tags: c++, animation, file-format
---


title: networking without port forwarding

text:
# Question
Title: networking without port forwarding
I'm trying to add networking functionality to my game. I want any user to be able to host the game, and anyone to be able to connect as a client. The client sends info to the host about their player's position, etc. When the host receives a message, it validates it and then broadcasts it to its other clients. I will primarily be dealing with UDP, but will also need TCP for chat & lobby stuff.

The problem is that I can't seem to get a packet sent from the client to the host or the other way around without enabling port forwarding on my router. But I don't think this is necessary. I believe the reason I need port forwarding is because I want to send a packet from 1 computer on a LAN to another computer on a different LAN, but neither of them have a global ip address since they're in a LAN. So really, I can only send packets targeting the other network's router, which must forward it on to the machine I want to reach. So how can I do this without port forwarding? Somehow a web server can communicate with my computer, which doesn't have a global ip, without port forwarding. And I've played plenty of multi-player games that don't require me to enable port forwarding. So it must be possible.

Btw, I'm using SDL\_Net. I don't think this will change anything though.

# Answer
> 13 votes
Many to one NAT (many computers with private addresses behind one public address) works like this: The router keeps track of outbound packets and when an answer is received it can send it to the internal computer which sent the original request. So this works fine, if you visit a website with a public ip-address.

It is, however, not possible to send an initial packet from the outside to one specific computer on the inside, unless a forwarding rule is defined on the router: There is no way to address a specific computer and the router does not have information in his connection table because it is not an reply.

Skype made a technique popular that is called firewall hole punching: A server with a public address is contacted by the clients. Then it sends an answer back to client A telling it to send udp packages to the router of client B on a port it expect the router of client B to use as source port for the next outbound packet. And it tells client B to send a packet to the router to client A on a port it expects the router of A to use as source port for its next outbound packet. If the prediction is correct, A and B can now talk directly which each other.

Firewall hole punching requires a server with a public ip address to act as a moderator. And it requires a lot of knowledge about the implementations of common NAT router to predict the outbound source ports correctly. Although there are open source implementations available, you should try to avoid this technique because it is unreliable and causes lots of headache. Skye falls back to using the server with the public ip address to relay all packets if the predictions fail.

# Answer
> 4 votes
> Somehow a web server can communicate with my computer, which doesn't have a global ip, without port forwarding

Importantly, the web server itself has a global IP/port pair, that uniquely identifies it. Your computer connects to the web server, which sends the information back along the same channel.

This technique is obviously not available if both sides are behind some kind of NAT, as is the common case for peer-to-peer games. So instead, you need to trick the NAT.

The technique you are looking for is called hole punching or punch-through, in particular UDP hole punching or TCP hole punching. In this case both clients connect to a global server, which in turn tells them how to connect to each other, through the "hole punched" in the firewall by the existing connection.

Hole punching does require a public server with a global IP/port to handle the initial connection and hand-off, but the bandwidth / processing requirements are minuscule. If you have a global lobby server, it should be able to handle it easily.

# Answer
> 4 votes
Google Talk uses libjingle to achieve the same thing.

Other libraries for ICE/STUN/TURN include PJNATH and libnice

---
Tags: networking, multiplayer
---


# Question
Title: Should I be using Lua for game logic on mobile devices?
As above really,

I'm writing an android based game in my spare time (android because it's free and I've no real aspirations to do anything commercial).

The game logic comes from a very typical component based model whereby entities exist and have components attached to them and messages are sent to and fro in order to make things happen.

Obviously the layer for actually performing that is thin, and if I were to write an iPhone version of this app, I'd have to re-write the renderer and core driver (of this component based system) in Objective C.

The entities are just flat files determining the names of the components to be added, and the components themselves are simple, single-purpose objects containing the logic for the entity.

Now, if I write all the logic for those components in Java, then I'd have to re-write them on Objective C if I decided to do an iPhone port. As the bulk of the application logic is contained within these components, they would, in an ideal world, be written in some platform-agnostic language/script/DSL which could then just be loaded into the app on whatever platform.

I've been led to believe however that this is not an ideal world though, and that Lua performance etc on mobile devices still isn't up to scratch, that the overhead is too much and that I'd run into troubles later if I went down that route?

Is this actually the case? Obviously this is just a hypothetical question, I'm happy writing them all in Java as it's simple and easy get things off the ground, but say I actually enjoy making this game (unlikely, given how much I'm currently disliking having to deal with all those different mobile devices) and I wanted to make a commercially viable game - would I use Lua or would I just take the hit when it came to porting and just re-write all the code?

# Answer
> 17 votes
As far as scripting languages go, Lua is very fast, but like anything it varies depending on the processor. For example, Lua would not be great on a console platform because it tends to be very branchy, and some console platforms branch very slowly. To best answer your question, I would suggest running some benchmarks. See how fast Lua performs some various algorithms on the device. I suspect you'd be fine as long as you're not doing any heavy math or iteration in your script code. (You shouldn't be doing that anyway. They're scripts. Do calculations in the engine.)

That said, scripting isn't a silver bullet for platform independence. You may need to rewrite in Obj-C anyway if you port to iPhone due to Apple's restrictions on executing dynamic code. I don't have a link offhand, but it may be worth reading into. Apple *barely* allows managed code (you have to get special permission to run a special distribution). They most certainly will not allow a Lua implementation into the app store.

\[edit\] Apparently I was mistaken about the Lua on iphone thing. Take a look at the comments below.

# Answer
> 7 votes
Lua's C implementation is specifically designed to run on embedded devices. It's small and fast (for a scripting language). I would have thought it was fine for at least light tasks.

# Answer
> 4 votes
Sure. Scripting logic is highly unlikely to be your bottleneck (you will actually profile with Shark or Instruments, right?). I worked on the iPhone version of Marooned, which used a lot of Lua for game logic. I did a lot of performance tuning, and basically Lua was 0%.

(Lua was a grey area when we released Marooned, but it’s since been officially blessed for iOS development.)

# Answer
> 1 votes
See http://code.google.com/p/android-scripting/ for the recommended way of doing scripting on Android. Lua still doesn't fit very well on the Android platform, since it requires C. Of course, you could use the NDK, but that is no silver bullet.

# Answer
> 1 votes
It does depend a bit *how much* of your game logic is embedded in scripts. In general LUA is used as high level glue but a lot of the grunt work happens through C(++). Yes, LUA is fast as far as scripting languages go - your still looking at a slowdown compared to native languages of about 30 to 50 times, so it really depends how much is happening in LUA.

# Answer
> 0 votes
You can actually write your entire game in Lua and avoid Java/ObjectiveC/C/C++ altogether.

For cross platform development use Corona. Its free to use until you plan to ship to the App Store or Android Marketplace.

If you want to target the iPhone/Pad/Touch take a look at wax.

Just as a side note @Sean Edwards: I've been involved in shipping five titles targeting Nintendo DS, Wii, Sony PSP, and Xbox360, all of which used the same engine and were scripted in Lua. Its widely used on consoles and mobiles.

---
Tags: android, lua, mobile, porting
---


title: Arrays for a heightmap tile-based map

text:
# Question
Title: Arrays for a heightmap tile-based map
I'm making a game using in C# and Javascript that uses a map which has tiles, corners and borders. Here's a graphical representation:

I've managed to store tiles and corners in memory but I'm having trouble getting the borders structured.

For the tiles, I have a `Map Width * Map Height` sized array. For corners I have `(Map Width + 1) * (Map Height + 1)` sized array.

I've already made up the math needed to access corners from a tile, but I can't figure out how to store and access the borders from a single array.

Tiles store their type (and other game logic variables) and via the array index I can get the X and Y coordinates. From this tile position it is possible to get the array index of the corners (which store the Z index).
The borders will store a game object and accessing corners from only border info would be also required.

If someone even has a better way to store these for better memory and performance I would gladly accept that.

# Answer
Look closely at your own illustration. What you've drawn here is a **single two-dimensional array**. Make an array of size `[MapWidth*2+1, MapHeight*2+1]` and store everything there. Elements where both coordinates are even will hold corners, where both coordinates are odd will hold tiles, and the rest will hold borders. You'd have to have a common base class for them, but I don't think that's a problem.

Of course, this is a little unintuitive, but adding a wrapper object around this array will solve it.
> 4 votes

# Answer
> > The borders will store a game object and accessing corners from only border info would be also required.

Keep a pointer/a reference to the corners in the border object? Do the same for tiles and borders?

Maintaining such a linear array of borders is definitely doable - you just need to separate vertical and horizontal borders. Then you can take all the borders of one direction and order them according to their x,y coordinates (it doesn't matter which axis is considered first), then simple integer algebra can be used to find the borders corresponding to a tile at coordinates (x,y). *But still, I think you're on the wrong track. Consider using direct links between corresponding objects, as I noted above.*
> 2 votes

---
Tags: c#, mathematics, tiles, javascript, heightmap
---


title: What does it mean to "bake lights"?

text:
# Question
Title: What does it mean to "bake lights"?
What does it mean to bake lightmap ? I heard this in Unity3d, and again found this LightUp plugin for sketchup that bakes lightmap.

From what I observe, the lightmap baked gives the 3d object a much more realistic feel. Is the purpose of baking light on object to give that cg animation look you see on pre-rendered animations?

# Answer
> 62 votes
When you have a static (non-moving) light in a game, you have two options for rendering this light. You could render it the same as a dynamic light; that is, feed it through the shader pipeline which will calculate its effect on everything around it, every frame, on its way to the screen. This is obviously pretty expensive. Or, an editor can bake the light into the scene.

What I've always thought of baking was perhaps a more simple version: basically the editor just takes the textures of everything around the light, calculates the effect of the light on those textures (brightens them, perhaps colors them, shadows, etc.), and saves them as replacement textures to use. So all the textures around the "light" look like they have a light cast on them, but at runtime there actually isn't a light from a calculation standpoint; it's an optical illusion, essentially.

Unity, however, seems to be generating a lightmap. This is similar to the above notion, but the baked lighting is kept separately instead of modifying the underlying texture, and I assume a shader merges the two at runtime. This would have the advantage of keeping the advantage of tiled textures (i.e. low memory usage), since they wouldn't have the light baked right into them therefore they could remain tiled, and the shader would be very lightweight, especially compared to treating the light as dynamic.

A light obviously needs to be static for this to work; that is, you can't move it during gameplay, because the light has been baked into the textures. Also, any dynamic objects in the room (such as the player character) won't have the light shining on them so there needs to be some sort of exception, where the light is rendered for dynamic objects but not (re-)rendered on the static scenery.

---
Tags: lighting
---


# Question
Title: what making a good soundtrack for social game
there are many successful social games in Facebook and other social sites like brain buddies, who has the biggest brain and word challenge.both of them have a great soundtrack while playing and in the beginning of the game . my question is how to find a good soundtrack or what's i should look for to find a good soundtrack like this that's help to attract the user specially for games that need concentration ?

# Answer
> 1 votes
Well you already listed good examples of casual games with good background soundtracks. So play those games and pay attention to qualities of the music, such as the instruments used, tempo, volume compared to any other sounds in the game, notes/chords (major vs minor), and so on. Really pay attention to the subtleties that set the music apart from other background music; you might want to play other games where the music is distracting or the game is more action-oriented, and compare those qualities to see exactly what makes the social game music better for concentration and calmness.

Then apply these qualities that you have now noticed to your own music composition, or your search for background music, or convey the qualities to the person you are looking to hire to do your music.

# Answer
> 1 votes
Its simply how you make the player feel he/she's inside the game by just listening to the music. The composer should know how to deliver the music depending on the environment and situation the scene offers.

---
Tags: game-design, flash, sound
---


title: Make pygame's frame rate faster

text:
# Question
Title: Make pygame's frame rate faster
By profiling my game, I see that the vast majority of the execution time of my hobby game is between the blit and the flip calls. Currently, it's only running at around 13fps. My video card is fairly decent, so my guess is that pygame is not using it.

Does anyone know of any graphics/display options I need to set in pygame to make this faster? Or is this just something that I have to live with since I've chosen pygame?

# Answer
If you're running in full-screen mode, you can use the `pygame.HWSURFACE` flag when you initialise the display to tell pygame to try to use a hardware surface. I believe that if a hardware surface can't be used, pygame will silently use a software surface.

If you're not using a hardware surface, consider using `pygame.display.update(rectangle)` rather than `pygame.display.flip()`. This will only update the given rectangle rather than the whole display, which can increase your performance quite a bit unless your game actually needs to update the whole display.

If you are using a hardware or OpenGL surface, there's also the `pygame.DOUBLEBUF` which uses hardware double buffering, meaning that your drawing functions will draw to one of the two buffers and `flip()` will swap which buffer is visible.
> 12 votes

# Answer
One bottleneck in pygame is actually font rendering. You should not render the same text (with the same font/color) more than once but rather cache the surfaces once rendered and reuse them. Take this into acount if you're using Font.render() alot.
> 5 votes

# Answer
In addition to talljosh's answer, I'd like to throw in a few more suggestions:

Avoid rotations and scaling wherever you possibly can. Such operations are done purely on the CPU and tend to be very, very slow.

If you're doing direct pixel reads/modifications, use the `Surface.get_buffer()` method and work with that, rather than using the `Surface.set_at()/get_at()` methods.
> 4 votes

# Answer
Comment out any test console output you have. This can drastically reduce framerate, especially if you are outputting between rotation and scaling, as Cody said above.
> 2 votes

# Answer
It's correct that Pygame does not use the 3D acceleration capabilities of your video card. This is because it is based on SDL which has the same limitation. One alternative is to rewrite your game in a system like pyglet which *does* natively support OpenGL accelerated sprites, to find a similar library for graphics only, or to write the OpenGL code yourself for this.
> 2 votes

# Answer
One incredibly simple thing to do is use psyco. I don't know how much it will help, but since all it requires is

```
 import psyco
 psyco.full()

```

to start running, you may as well give it a try.
> 1 votes

---
Tags: graphics, pygame, optimization, frame-rate
---


title: Good, free isometric game engine?

text:
# Question
Title: Good, free isometric game engine?
Any recommendations for a good isometric game engine that is also free?

1. Should be possible to develop entirely using freely available tools (meaning: no Flash, and no I don't want to learn haXe...)
2. Works-in-a-browser is a plus, but not required.
3. Support for 32-bit images is required!
4. Good performance.
5. Excellent documentation.

I have looked at FIFE but it is still too unfinished, and the documentation sucks!

# Answer
> 6 votes
I have created games using as3isolib and it works really great for me. It is library for actionscript 3.0 (flash), and as bummzack said in comment, you can develop flash games using only free tools.

# Answer
> 2 votes
There's always Unity3D for everything. ;D It supports browsers, performs excellently, and has good documentation. You could use the orthographic camera for isometric easily.

---
Tags: isometric
---


title: Unused frame(window) management

text:
# Question
Title: Unused frame(window) management
I'm rewriting my game now using software designing patterns and want to do the code, most correct I can. While implementing MVC(Model View Controller) I got a question which I would like to discuss or to hear some opinions of experts. The question is about management of unused frames... For example next sequence of windows: ResourceLoadingWindow -\> LoginWindow -\> GameWindow Definetly that I don't want to reuse ResourceLoadingWindow , since I'm using Java Applet and I don't see any situation when I will need to reuse it. The different story is about LoginWindow, which can be reused a lot of times, because some player would want to Logout and come back again in few minutes for example. I would like to know, following the MVC structure, should I destroy window, removing it from ContentPane or just hide? Maybe I need to unregister it from controller or I shouldn't do so?

Thanks in adavance.

# Answer
> 1 votes
I'd say hide it. Then it's loaded and you can just call it whenever. If you're changing accounts then why load another copy, right? It's pretty lightweight though, I bet, so use whichever is easiest for now.

---
Tags: java, gui
---


# Question
Title: Understanding MotionEvent to implement a virtual DPad and Buttons on Android (Multitouch)
I'm trying to implement a virtual DPad in android, but I'm still very confused about how do I keep track of each trouch point, from the moment it is pressed, till it is released.

In my code, I test if there is a "DOWN" or "MOVED" event, then if one of this events collides with one of the 4 rectangles of my DPad, I set the pressedDirectin variable to the side of the DPad which the user pressed.

The thing I'm not sure, is how do I get track of the touch points, I want to store the ID of the touch point which collided with the DPad direction, so when this ID is moved I update the direction of the DPad and when it gets released I set the Direction to None.

I don't want my DPad to handle multiple directions, but I still didn't get how to handle the multiple touch points, so I can know exacly which touch point is touching the DPad and store it's ID so I know when it is released.

Is the onTouchEvent called for every touch point, or all touch points comes in a single call? I still don't get it.

Here is the code I wrote so far, it works, but guess that it will only handle one touch point.

```
public boolean onTouchEvent(MotionEvent event)
    {
        if (event.getPointerCount() == 0)
            return true;

        int touchX = -1;
        int touchY = -1;

        pressedDirection = DPadDirection.None;
        int actionCode = event.getAction() & MotionEvent.ACTION_MASK;
            if (actionCode == MotionEvent.ACTION_UP)
            {
                if (event.getPointerId(0) == idDPad)
                {
                    pressedDirection = DPadDirection.None;
                    idDPad = -1;
                }
            }
            else if (actionCode == MotionEvent.ACTION_DOWN || actionCode == MotionEvent.ACTION_MOVE)
            {
                touchX = (int)event.getX();
                touchY = (int)event.getY();

                if (rightRect.contains(touchX, touchY))
                    pressedDirection = DPadDirection.Right;
                else if (leftRect.contains(touchX, touchY))
                    pressedDirection = DPadDirection.Left;
                else if (upRect.contains(touchX, touchY))
                    pressedDirection = DPadDirection.Up;
                else if (downRect.contains(touchX, touchY))
                    pressedDirection = DPadDirection.Down;

                if (pressedDirection != DPadDirection.None)
                    idDPad = event.getPointerId(0);
            }

        return true;
    }

```

# Answer
> 2 votes
Given what you've told me in your comment, you can do something like this:

```
float touchX, touchY;

public boolean onTouchEvent(MotionEvent event)
{
        if (event.getAction() == MotionEvent.ACTION_DOWN ||
            event.getAction() == MotionEvent.ACTION_MOVE)
        {
           // store values
           touchX = event.getX();
           touchY = event.getY();
        } else if(event.getAction() == MotionEvent.ACTION_UP)
        {
           // reset values
           touchX = 0f;
           touchY = 0f;
        }
        // consume motion event
        return true;
}

```

In action\_down or action\_move, you store the event.getX() and event.getY() coordinates in a field outside the onTouchEvent class. Then in your update loop, before you do anything with the pressedDirection, you have your code:

```
           if (rightRect.contains(touchX, touchY))
             pressedDirection = DPadDirection.Right;
            else if (leftRect.contains(touchX, touchY))
                pressedDirection = DPadDirection.Left;
            else if (upRect.contains(touchX, touchY))
                pressedDirection = DPadDirection.Up;
            else if (downRect.contains(touchX, touchY))
                pressedDirection = DPadDirection.Down;

            if (pressedDirection != DPadDirection.None)
                idDPad = event.getPointerId(0);

           // do something based on pressedDirection

```

So in the onTouchEvent you store the values the touch coordinates. In your game loop, you do the checks to see if the coordinates are in the appropriate Rects. Then you run the rest of your game code. You reset the values to zero when the MotionEvent is an ACTION\_UP

# Answer
> 0 votes
All the touch points come in a single call. And most of the accessor functions on the MotionEvent class have an overloaded function that takes in pointer index.

So use MotionEvent.getPointerCount() and loop through your mouse pointers.

http://developer.android.com/reference/android/view/MotionEvent.html

Hope this helps.

# Answer
> 0 votes
Remember that many (most?) Android devices don't allow true multitouch; on those phones, once the user is using one finger on your virtual dpad and press elsewhere on the screen at the same time you're going to get random positions sent to your app from the phone and there's nothing you can do about it.

---
Tags: java, android, input, multitouch
---


title: 3D Paint tool in Maya

text:
# Question
Title: 3D Paint tool in Maya
Hey everyone, could someone help me out on this question? When I am trying to texture objects in maya (for example a barrel) I want to texture it with a brush. When I try to use the 3D painting tool it al gets black even when I have a image file selected. Also the resolution is very very low of the models and textures in maya, though the texture image is very high quality. Can someone please help me? Thanks so much for helping.

# Answer
Trying to help here, but need more info.

This is a typical problem, but causes can be several.

1. Are you sure Uv mapping is done? The size of the texture wont help if the UV mapping is badly set, so it could be just mapping a small piece of the texture, and that is why it shows so big pixels. Check that the UV mapping is good and correct, first of all. A good uvmapping is absolutely key in texturing. 3D Painting is cool, but a good uvmapping and old school 2d painting and editing, will give a lot of control and precission. I use 3D painting mostly for seams, for organic models, etc. IMHo it's usually a combined method.
2. Is not clear to me if you see all black or something at low resolution, reading the question... I don't know in Maya, as I don't use it, (but used other packages for years, 3D is similar in the end...) but often the full black can be no actual UV Mapping done, inverted normals (all 3D packages have fast tools to flip or fix them), the UVs are wrong, and the texture has black lines or areas in it, and it's just covering all model with a black part detail (wrong scaled UVs, often).
3. Some packages will show a black render when you just did not create a material for it. (Again, I only handled Maya in some teams for handling assets, I'm a Max and Blender user, mostly)Or did not asign well the texture, UVs aren't there as I mention, etc. Sometimes simply you have not any lights and for that specific viewing or render, it does not do automatic open gl lighting: needs one light there.
4. In some packages, in viewport, always low resolution textures are shown, per software preferences, so to get best performance. These days I think this habit is dissapearing. If that happens, is a matter of going to preferences, and put viewport texture resolution a bit higher.

So, summarizing solutions:

* Check your UV mapping.
* Check normals.Flip them and/or fix them, to see if it gets fixed.
* Check how you created the material and asigned the texture.
* Check if it's a lighting matter in the way you are wanting to display/render it.
* Related to all this, might be good to see if at preferences are correct in stuff related to these matters.
> 3 votes

---
Tags: tools, textures, objects, maya
---


# Question
Title: Followed the XNA GameStateManagement sln, but my doesn't work. What am I doing wrong?
If someone has the time I wanted to know if you would be willing to check out my solution file here: http://elvis.rowan.edu/~majeko02/AwesomeShip.zip

I followed the XNA GameStateManagement on AppHub, but nothing comes up from me. and I haven't the clue why.

I believe I done everything correctly and verified it as well.

I wanted to know if someone has the time could they check it out?

Download link here: http://elvis.rowan.edu/~majeko02/AwesomeShip.zip

I am racking my brain trying to figure out why it doesn't work.

Any help, is greatly appreciated.

# Answer
You're getting stuck in an infinite loop in your ScreenManager.Update() function.

```
while(screensToUpdate.Count > 0)
{
    GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
    if(screen.ScreenState == ScreenState.TransitionOn || screen.ScreenState == ScreenState.Active)
    {
        if(!otherScreenHasFocus)
        {
            //screen.HandleInput(input);
            otherScreenHasFocus = true;
        }

        if(!screen.IsPopUpMessage)
        {
            coveredByOtherScreen = true;
        }
    }
}

```

You're not reducing the screensToUpdate.Count and therefore it's always greater than 0.

EDIT:
I forgot to mention, if you had just stepped through the code you would have quickly found the issue. Use the debugger often and set lots of breakpoints :)

EDIT 2:
Just noticed the line

```
GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];

```

This will cause you issues as well as it's only ever going to update the last screen in your screensToUpdate collection.
> 2 votes

---
Tags: xna, c#, state, management
---


# Question
Title: How long before realtime 3d graphics reach pre-rendered cg likeness? photorealism?
I am overloaded with all these new terms I have to learn about 3d graphics like lightmaps, bumpmaps, real-time radiosity, luxrender (is there a site where I can learn about all these techniques?).

Realtime gameplay graphics are almost better than prerendered 3d graphic or animation from 10 years ago. At this rate, is photorealistic video games on the horizon? (crysis 2 on pc for ex).

I'm not sure if you can understand this question but for example, when Final Fantasy 7's prerendered backgrounds wowed me, almost 14 years ago, today real-time game graphics are almost better than that.

# Answer
Photorealism is about way more than just 3d graphics, you have to take into account so many things to truly make the player believe they are in the game. Animations, environment, sound/music are just a few of the things to make it believable. I find it really interesting how we keep seeing the great looking graphics games and saying how close they are to photorealism, but there is always something our eyes can pick out to determine that it really isn't. The closer we get to photorealism, the more diminishing returns we will have. For example, when you look at Far Cry at the time most people that it was incredibly close to photorealism, but there were details that the players could always find, the same thing happened when Crysis came out, etc. The technology is obviously increasing at a rapid pace, but to be honest I don't think we'll see anything that we view as 'photorealistic' for another few decades. And even then I firmly believe players will be able to determine small nuances in the graphics that will leave them asking, how long before realtime 3d graphics reach photorealism?
> 2 votes

---
Tags: 3d
---


# Question
Title: Electricity effect using XNA and Shaders
I'm looking for a shader or sample that does an electricity or lines-of-force effect between two points that can be used with XNA 3.1.

# Answer
Download RenderMonkey has samples for image based effects including spark and electricity.
> 1 votes

# Answer
I'm not sure if this fits to your picture of "electricity effect":
video and article about it
> 8 votes

---
Tags: xna, hlsl, effects
---


title: Enemy evolution in shoot-em-ups

text:
# Question
Title: Enemy evolution in shoot-em-ups
Are there any shoot-em-ups in which the enemies actually evolve as a response to their relative success against the player?

By evolve, I mean that each enemy has some genetic information encoding their behaviour. Enemies which last longer or do more damage are allowed to mix their genes to create new enemies. This way the enemies would become better adapted to the particular player.

# Answer
> 7 votes
There is a Japanese freeware PC shoot-em-up called "Warning Forever" that evolves the bosses based on how you approach them, in a way that is more than just switching between presets. It's also pretty fun for being free.

Another game I found is "Evolution Shooter" by Petri Purho, which uses an evolutionary algorithm to combine entire shooter game definitions, as opposed to individual enemies.

# Answer
> 2 votes
Not real-time, nor a shooter, but when developing a car combat game we did use an evolutionary process to build the AI. Enemy cars could see the edges of the track and locations of other vehicles.

However things like how hard to break, when to start, how hard to steer around opponents, when to target opponents vs. focus on driving were all setup as variables. Then the AI was setup to run laps all night long slowly tweaking the variables. Each morning we'd look at the previous nights data, find the ones that had the best lap times/kills and then mutate that again. The end result was an AI that could be dumped into any track and be able to compete.

This was all then baked into the game, so it didn't learn from playing against the player.

There are several sports games that track player tendencies and then work to anticipate those choices, not sure if anyone has shipped adaptive AI in a shooter though.

# Answer
> 1 votes
There is an RTS that is based around this concept. But instead of enemies that evolve, the player trains units which are able to breed, adapt, and evolve.

**NERO**

The technology behind this is a mix between Neural Networks and Genetic Algorithms, called NeuroEvolution.

> Neuro-Evolving Robotic Operatives, or NERO for short, is a unique computer game that lets you play with adapting intelligent agents hands-on. Evolve your own robot army by tuning their artificial brains for challenging tasks, then pit them against your friends' teams in online competitions!

http://nerogame.org/

**Galatic Arms Race**

There is another game that used a similar technology but instead evolved custom weapons based the effectiveness and overall gameplay of the user.

> A key objective of this game is to explore the potential for automated content generation technology to intelligently create content for games. In GAR, all player weapons are generated by the cgNEAT algorithm based on weapon usage statistics. However, cgNEAT does not simply respawn weapons that people like. Rather, it creates new weapons that elaborate on the ones that have been popular in the past.

http://gar.eecs.ucf.edu/

**Note:**

Both of these games were developed as academic pursuits.

# Answer
> 0 votes
Not exactly evolution in the sense you mentioned but still interesting:

In both of the Left 4 Dead games by valve there is an AI director that adapts the level based on how the players behave.

"The Director places enemies and items in varying positions and quantities based upon each player's current situation, status, skill and location" - http://en.wikipedia.org/wiki/Left\_4\_Dead#AI\_Director

# Answer
> -1 votes
Rez changes the difficulty of the level boss based on how well you did in that level.

---
Tags: ai, shoot-em-up, evolution
---


# Question
Title: Graphics module: Am I going the right way?
I'm trying to write the graphics module of my engine. That is, this part of the code only provides an interface through which to load images, fonts, etc and draw them on the screen. It is also a wrapper for the library I'm using (SDL in this case).

Here are the interfaces for my `Image`, `Font` and `GraphicsRenderer` classes. Please tell me if I'm going the right way.

**Image**

```
class Image
{
  public:
    Image();
    Image(const Image& other);
    Image(const char* file);
    ~Image();

    bool load(const char* file);
    void free();
    bool isLoaded() const;

    Image& operator=(const Image& other);

  private:
    friend class GraphicsRenderer;
    void* data_;
};

```

**Font**

```
class Font
{
  public:
    Font();
    Font(const Font& other);
    Font(const char* file, int ptsize);
    ~Font();

    void load(const char* file, int ptsize);
    void free();
    bool isLoaded() const;

    Font& operator=(const Font& other);

  private:
    friend class GraphicsRenderer;
    void* data_;
};

```

**GrapphicsRenderer**

```
class GraphicsRenderer
{
  public:
    static GraphicsRenderer* Instance();

    void blitImage(const Image& img, int x, int y);
    void blitText(const char* string, const Font& font, int x, int y);
    void render();

  protected:
    GraphicsRenderer();
    GraphicsRenderer(const GraphicsRenderer& other);
    GraphicsRenderer& operator=(const GraphicsRenderer& other);
    ~GraphicsRenderer();

  private:
    void* screen_;

    bool initialize();
    void finalize();
};

```

---

**Edit:** Some changes to the code and more details.

Per some of the discussions here I decided to replace my use of `void*` with something like this:

```
class Image
{
  private:
    struct ImageData;
    std::shared_ptr<ImageData> data_;
};

```

(Obviously I'll do the same thing for the `Font` class.)

I should also mention hat these are not my final, complete classes. I only show here the basic functionality (loading and rendering). Instead of telling me what functionality you think I might need to add (rotating images, skewing, scaling, etc) just concentrate on reviewing what I already have. I'll try to defend my choices it I can, or change my approach if I cannot.

# Answer
> 1 votes
The thing that itches most for me is the `void *` 'abuse'.

> Void-pointer: I don't need it. It's a way for me to limit the number of files that include SDL.h (void\* data\_ is just an SDL\_Surface\* cast to void\*)

Well, you could avoid inclusion (which I approve BTW) by forward declarating it somewhere convenient for you.

# Answer
> 6 votes
**On Interfaces (in general)**

So, you asked for us to review your designs for interfaces.

You didn't give us interfaces, you gave us full class declarations. If these were *interfaces*, I would expect to see something like:

```
virtual bool load file(const char* file) = 0;

```

*That*, in C++, is an interface. I can override it in a subclass that implements functionality (in fact, I must!). If you are writing an interface, you are enforcing policy, and the above is how you do this.

Half of the complaints about usage of *void ** in the other answers would've been avoided if you had just exposed the interface functions, and kept the member variables hidden (as they should be, in an *interface* class).

Rawr.

**On Interfaces (yours)**

*Image: Copying*

You've got a copy constructor, and an equals operator. The issue I see here is that there is no good way of preventing the user from making silly extraneous copies of images.

For you, using SDL\_surfaces, **this is a big issue**. Without meaning to be offensive, I'm willing to bet that you haven't considered what happens when you free an Image that is a duplicate of another image. I'm further willing to bet that you hadn't planned on handling full deep copying of the SDL\_surface, and so in the aforementioned case you are likely to free an Image, and then your other copies of it will explode, killing everyone you love.

Solution: NO COPIES. Don't do it, don't allow it. Use a factory or a C-style loader function to create new instances of an Image, and use those instead of allowing copying or equals assignments. Alternately, completely figure out how to deep-copy an SDL\_image (not super hard, but annoying).

*Image: manipulation*

How do I change your images once I've loaded them? According to your interface, I don't. Still, are you sure that is a good idea? How do I find out the bit-depth of an image? Its height? Width? Color space?

*Font*

How do I draw with this font? How do I get its name? How do I prevent the copying issues I complained about above? How do I set its color? Kerning? What about Unicode support?

*Renderer: General*

So, I notice you have a couple of blit\*() functions, and also a render() function. This seems to imply that you want users to be able to queue up a bunch of blitting operations, and then flush them all to screen at once using the render() call.

That's fine; in fact, that's how my group's engine tech handles it too. :)

The use of a singleton here is acceptable, mostly because you seem to want to be letting the renderer have complete control of drawing things. If there is only one instance of it (as there probably should be), this won't hurt anything. Not what we do, but hey, it's a matter of taste.

There are a couple of big issues I see here, though.

**Renderer: Transformations**

You seem to be working only in 2D. That's fine. BUT...

How do you handle things like rotating an image when you draw it? Scaling it? You need full support for something called affine transformations. This allows you to easily rotate, scale, translate, skew, and otherwise frob in a pretty fashion images.

This needs to be supported (somehow) for both text and images.

**Renderer: Coloring and Blending**

I want to be able to blend colors onto my images, and set the colors for my text. You should expose this.

I also want to be able to do things like blend images when blitting, so I can do things like translucent ghosts or smoke or fire.

**How to save yourself the trouble**

Use SFML. It's got better design for, well, pretty much everything over SDL. They've already done what you are trying to do here. At the very least, look at how they've spec'ed their interfaces, and how they've designed their class hierarchy.

Also note that they address the issue of transforms I pointed out earlier in their Drawable class. And coloring. And blending.

They've got good tutorials and documentation, so it might be worth your time to fiddle with it a bit and get a feel for what your code should be able to accomplish.

Good luck!

# Answer
> 0 votes
I'm a bit bothered by the "load" method, which breaks the Single-Responsibilty Principle (by the way, to the Communist Duck, I guess this is why he's using a const char\*, because the SDL loading image function, coded in C, do not take a std::string). It shouldn't be an Image class' job to load itself, for at least two reasons :

* If you intend to optimize your memory use, you'll want to have specialized classes for loading resources.
* You'll handle exceptions more easily with a dedicated class.

# Answer
> -1 votes
Singleton = BAD, remove immediately. Fonts and Images should not have a `free()` function, that should be the job of the destructor. The `GraphicsRenderer` should not offer those `Blit` functions, you should offer object-orientated classes which will provide a position for each end result, and the actual rendering automatically managed by the GraphicsRenderer. Finally, for encapsulation, use inheritance, not PIMPL, and *definitely* do not use a void\*, use a strongly typed opaque pointer.

Here are some excerpts from my own design, although I've used compile-time switching and not run-time inheritance.

```
class D3D9Render
{
public:
    std::shared_ptr<D3D9Font> CreateFont();
};
class D3D9Font
{
public:
    // PUBLIC INTERFACE ---------------------------------------------------
    std::unique_ptr<D3D9Text> CreateText();

    int Height();
    D3D9Font* Height(char newheight);
    D3D9Font(D3D9Render& ref);

    int Width();
    D3D9Font* Width(char newwidth);
    int Weight();
    D3D9Font* Weight(short newweight);
    bool Italic();
    D3D9Font* Italic(bool newitalic);
    string Font();
    D3D9Font* Font(string str);
    D3D9Font* CommitChanges();
};

class D3D9Text
{
public:

    // PUBLIC INTERFACE ---------------------------------------------------
    D3D9Text* Text(string str);
    D3D9Text* PositionSizeX(short newx, short newxsize);
    D3D9Text* PositionSizeY(short newy, short newysize);
    D3D9Text* Font(std::shared_ptr<D3D9Font> ref);
    D3D9Text* Colour(unsigned int newcolour);
    string Text();
    int PositionX();
    int PositionY();
    int SizeX();
    int SizeY();
    std::shared_ptr<D3D9Font> Font();
    unsigned int Colour();
    D3D9Text* CommitChanges();
};

```

Here, the memory is managed for you- all ownership is managed via smart pointing, and the interface is completely object orientated.

# Answer
> -1 votes
First things I can spot:

* Singletons are very very bad, usually. It's not 'Hm, do I only want one of these?' but more 'Hm, will more than one of these break the program?'.
* void\* pointers are also rather risky. Why do you need one? Bad design somewhere.
* `Font` and `Image` seem to be closely related. Maybe you could take some of the functionality up the hierachy to a `Renderable`.
* I think this is me, but any reason why you're using `const char*` over `std::string`?

---
Tags: c++, software-engineering, sdl
---


# Question
Title: Are there any resources for motion-planning puzzle design?
Some background: I'm poking at a set of puzzles along the lines of Rush Hour/Sokoban/etc; for want of a better description, call them 'motion planning' puzzles - the player has to figure out the correct sequence of moves to achieve a particular configuration. (One characteristic of the sort of puzzle I'm thinking of is that they're generically PSPACE-complete; they're not necessarily in NP because the optimal sequence of moves isn't necessarily polynomial in the input size, so we can't guarantee that a solution can be verified in polynomial time).

While I have a few straightforward 'building blocks' that I can use for puzzle crafting and I have a few basic examples put together, I'm trying to figure out how to avoid too much sameness over a large swath of these kinds of puzzles, and I'm also trying to figure out how to make puzzles that have more of a feel of logical solution than trial-and-error. Does anyone know of good resources out there for designing instances of this sort of puzzle once the core puzzle rules are in place? Most of what I've found on puzzle design only covers creating the puzzle rules, not building interesting puzzles out of a set of rules.

# Answer
It seems to me that most of these types of puzzles can be related to solving an over-constrained system of equations that happens to have a solution. I'm not sure if that makes sense, but if you can somehow relate your rules to a system of equations, then build "solutions" from what you know the answer to be, it might lead to interesting problems. It also means that the puzzles are entirely mathematical and not "motion-like" at all. Just a bunch of static equations :-)

Another way of looking at it is considering that the simpler types of these puzzles have direct solutions --- that is, move a piece, then another, then another & then it's solved!, but the more complicated ones can force you down a path that doesn't seem obvious at first. Start from the final solution and applying your rules in reverse to complicate the initial conditions will also help. Looking at each rule application as a branch on a tree or graph, the interesting puzzles are very dense with only one or two paths that lead to solutions instead of many paths that lead to solutions.
> 1 votes

# Answer
For the most part it's easy to generate these puzzles by starting at the solution and iteratively choosing objects to move or mutate until you reach a suitable start point. The player then has to perform the same steps (or equivalent) in reverse order, and the more steps you used, the harder it is likely to be for them to solve it.

I'm not sure it would be practical to have any way of auto-generating puzzles that rely on different classes of sub-problem however; that would probably require a human mind to identify these areas and exploit them.
> 0 votes

---
Tags: game-design, puzzle
---


title: Common light map practices

text:
# Question
Title: Common light map practices
My scene consists of individual meshes. At the moment each mesh has its associated light map texture, I was able to implement the light mapping using these many small textures.

1) Of course, I want to create an atlas, but how do you split atlases to pages, I mean do you group the lm's of objects that are close to each other, and load light maps on the fly if scene is expected to be big.

2) the 3d authoring software provides automatic uv coordinates for each mesh in the scene, but there are empty areas in the texel space, so if I scale the texture polygons the texel density of each face wil not match other meshes, if I create atlas like that there will be varying lm resolution, how do you solve this, just leave it as it is, or ignore resolution ?

Actually these questions also applies to other non tiled maps.

# Answer
To create an atlas (without scaling the lightmaps), create an image that is, say 2x larger than your lightmap on each edge. Then you've got a 2x2 grid of lightmaps. Dump the lightmaps into it, and adjust the texture coordinates based upon which lightmap they came from. To directly answer your question, yes -- group close objects in the same lightmap. If you reverse the situation (have far away objects in the same lightmap) then you introduce performance problems almost immediately and unnecessarily.

Resolution is actually much less of a problem for lightmaps since it provides only subtle detail rather than the actual high frequency visual information such as bricks/concrete.

Scaling: don't scale things outside of the editor after generating lightmaps. Generally, you only generate lightmaps for static geometry anyways, so I don't know why you'd want to scale it. If it must be scalable, then you need some other \[dynamic\] solution since scaling a model can entirely change where shadows would normally occur in the lightmap generation process. In other words, it will look not just "pixely" or "blurry", but straight up wrong.

Any lightmap generation program that isn't brain dead should use area of the triangle as a way of generation "priority" for texel space. For example, if you had 4 triangles in your scene that had 2500, 300, 500, and 200 units of area, you'd expect the triangle with 2500 area to have more texel space in the lightmap allocated for it compared to the others, since increased resolution will actually be visible in the larger triangle.
> 1 votes

# Answer
Have you looked at the Q3A source code at all?
I don't know much about it's light map code other than that it is OpenGL so may answer some of your questions?

I would start with `R_LoadLightmaps()` in `tr_bsp.c` of the renderer project as a pointer...

HTH
> 0 votes

# Answer
1. Since lightmaps only apply to geometry that won't move, having objects that are close to each other share atlases is sensible. It limits the number of lightmaps you need to use in any one frame. You can then load the lightmaps in the same way you load the other textures for those objects - reference count textures that are shared between multiple objects.
2. The texel density of lightmaps can often be much lower than other texture maps and stil look good, especially where the lighting doesn't change much over the object. Ideally lightmap texel density would vary based on how much detail is in the texture - a smooth gradient will be approximated quite well by bilinear filtering. As doing that automatically isn't easy I'd suggest just giving the artist / designer control of the texel density for each object.
> 0 votes

---
Tags: opengl, directx, textures, lighting
---


# Question
Title: Is requirements analysis useful in game development?
I'm a software engineering student with a game development focus. How big of a part does requirement analysis play in game development?

I'm asking because I'm trying to decide whether to take a class on requirements analysis. Here is a description:

> An in-depth study of current research and practice in requirements elicitation, requirements, analysis, requirements specification,requirements verification and validation, and requirements management.

Would this type of knowledge be useful for an independent game developer? (The alternatives are artificial intelligence or software architecture.)

# Answer
> 7 votes
Requirements analysis will be incredibly useful, whether you're an independent developer or you work for a big company. Requirements analysis lets you break down your project into manageable chunks. It lets you estimate the time your project will take, and weigh the value of a feature against your desired development schedule and required effort.

If you're in a larger indie game company, it will help you work together with other developers and content producers to make sure everyone's always got something to do and you can meet your development targets. If you're working for a big corporation, learning requirements analysis will make you one of the few developers at the meeting who can actually give a realistic time estimate for a feature instead of just pulling a number out of your ass.

In addition to all that, requirements validation could include things like unit testing and verification of features, which is invaluable for a developer without a large QA department at his back.

# Answer
> 2 votes
I think this class will have between zero and very little relevance to game development. Certainly the semi-formal or formal methods you mention do not get used in my experience.

Games typically have incredibly fluid requirements, and even if it were possible to invest time and best practices into gathering requirements, much of what you'd end up with are meaningless and vague terms referring to fun, addiction, immersion, and so on. Very rarely will you have very clearly defined deliverables because, as much as we like to pretend making software is engineering, it's actually more of a craft, given the variety of different ways that programmers can express themselves. This goes double for games.

# Answer
> 2 votes
Requirements analysis is much more aimed at corporate software, with formal communication channels and that kind of thing, little to none of which will exist for an indie developer. It's not very useful for games because many requirements cannot be formally tested or verified. If you have a toolbar and you say, "Clicking this button should drop down a menu with XYZ on it", then you can pay someone virtually nothing to click the button and see what happens. Is your game fun? That's a whole different kettle of fish.

RA can be useful for determining if the game functions; but when it comes to things like balance, replayability and other factors that determine the ultimate fun factor of the game, then it's difficult or impossible to test them. So ultimately, it depends on whether or not you're going for an excellent implementation of an existing idea; or whether or not you're looking for success in novel gameplay.

# Answer
> 0 votes
Skip it.

What area of Game Development are you interested in going into? I'm assuming Programmer but...

Designer: They write a lot. A whole lot. There is usually a design document which communicates the designers vision but for everyone else except the producer or publisher you'll normally get the information from the designer themselves.

Programmer: The lead determines the technical requirements which will depend hugely on the platform and the asset pipeline. You'll learn how to do this as you work with your lead on the job.

Artist: Again its the lead artist along with the lead programmer who usually set the requirements for art assets. Learn on the job.

Requirements analysis, like the course they will most likely be teaching, is useful for big corporations trying to justify spending money and for outsourcing. And its often done by someone who once coded and has possibly since forgotten. *stab*

If you plan to go indie take a business/accounting/management subject. You'll need it to survive and not get screwed. Good Luck.

---
Tags: education, software-engineering, requirements
---


# Question
Title: Unrealscript tutorials for self-made maps
I've been looking up tutorials for UnrealScript, but I'm very confused by what I find.

All tutorials seem to use Visual Studio and nFringe for the coding, plus the UDK editor for the maps.

Every tutorial I've come across seems to assume I want to either modify UT2004 or edit physics. This is not the case. I plan on making some custom maps in UDK with no textures or anything, and script some events for those maps. Lights turning on and off. Doors opening and closing. Walls shifting. That kind of stuff.

As such, the tutorials I've found are confusing and take up a lot of time and configuration I don't understand. Can someone get me on the right path for what I'm trying to do here?

# Answer
> 1 votes
Level scripting is generally done through Kismet, not through Unrealscript. Kismet is their visual scripting language that ties triggers/entities together and so forth.

http://udn.epicgames.com/Three/KismetUserGuide.html

---
Tags: udk
---


# Question
Title: What are pros and cons of different social gaming networks from developer's point of view?
I am developing a game for a mobile platform and I want to integrate it with either **Scoreloop** or **Openfeint**.

So my question is which of the platforms has better SDK (by that I mean that its has better tools to implement achievements and global leader board and other things) and more features?

Which of those has larger user base?

# Answer
> 1 votes
I don't think anyone can give you a definitive answer to this one.

You need to weigh up a number of factors and rate them based on your projects requirements.

* Licence terms: Are you required to link/mention the provider?
* Features: leader boards weekly/monthly/etc, achievements, matchmaking, etc.
* Platform availability: iOS, Android, WinPhone7, and Web
* Service Performance: Do they place any limit on you that could affect the responsiveness of your game

If you can't choose sign up with both and see how easy it is to work with either of them.

---
Tags: mobile, social
---


title: Draw land for motocross game

text:
# Question
Title: Draw land for motocross game
I would like to draw a land for a motocross game. I've been thinking of Bezier Curves but I am not sure whether this is the best approach. Can you give me some advice? I want to do it in JavaScript, not very good choice but it's personal project so for time being it's OK.

# Answer
I found a couple of links that might be useful for others:

Example script of Bezier implementation in JS
http://jsfromhell.com/math/bezier

It can be used from JavaScript or ActionScript to animate along a bezier path.
http://code.google.com/p/javascript-beziers/

Online drawing script/plot, quite useful if you want to make some tests
http://jsdraw2d.jsfiction.com/demo/curvesbezier.htm

A bit of theory and an implementation example
http://13thparallel.com/archive/bezier-curves/
> 2 votes

# Answer
Instead of beziers, you probably want b-splines or catmull-rom splines.

```
float bspline(float t, float p0, float p1, float p2, float p3)
{
  float it = 1.0f - t;

  float b0 = it*it*it * (1.0f / 6.0f);
  float b1 = (3*t*t*t - 6*t*t +4) * (1.0f / 6.0f);
  float b2 = (-3*t*t*t +3*t*t + 3*t + 1) * (1.0f / 6.0f);
  float b3 =  t*t*t * (1.0f / 6.0f);

  return
    b0*p0 +
    b1*p1 +
    b2*p2 +
    b3*p3;
}

float catmullrom(float t, float p0, float p1, float p2, float p3)
{
  return 0.5f * (
          (2 * p1) +
          (-p0 + p2) * t +
          (2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t +
          (-p0 + 3 * p1 - 3 * p2 + p3) * t * t * t
          );
}

```

Usage: t ranges from 0 to 1, where the value interpolates the spline between two control points, and the floats p0, p1, p2 and p3 are represent the control points (previous, current, next, and the following). To interpolate n-dimensional curves, just call the functions once per axis.

The practical difference between bsplines and catmull-rom is basically that catmull-rom goes through all control points while bsplines are more smooth.
> 4 votes

---
Tags: algorithm, linear-algebra
---


title: per pixel based collision detection

text:
# Question
Title: per pixel based collision detection
I was wondering if anyone had any ideas on how to get per pixel collision detection for the android. I saw that the andEngine has great collision detection on rotation as well but couldn't see where the actual detection happened per pixel. Also noticed a couple solutions for java, could these be replicated for use with the Android SDK?

Maybe someone here has a clean piece of code I could look at to help understand what is going on with per pixel detection and also why when rotating it is a different process.

EDIT: Here is something I am working with right now.

```
public void getBitmapData(Bitmap bitmap1, Bitmap bitmap2){
     int[] bitmap1Pixels;
     int[] bitmap2Pixels;

    int bitmap1Height = bitmap1.getHeight();
    int bitmap1Width = bitmap1.getWidth();
    int bitmap2Height = bitmap2.getHeight();
    int bitmap2Width = bitmap2.getWidth();
    bitmap1Pixels = new int[bitmap1Height * bitmap1Width];
    bitmap2Pixels = new int[bitmap2Height * bitmap2Width];

    bitmap1.getPixels(bitmap1Pixels, 0, bitmap1Width, 1, 1, bitmap1Width - 1, bitmap1Height - 1);
    bitmap2.getPixels(bitmap2Pixels, 0, bitmap2Width, 1, 1, bitmap2Width - 1, bitmap2Height - 1);

```

}

# Answer
> 4 votes
From what I know, pixel perfect collision detection is done this way :

* Convert two checked objects coordinate into world coordinate
* Get their bounding box, check for intersection
* if intersection occurs, check every pixel from both objects inside the intersection
* if both objects have non-alpha pixels in the same location inside the intersection, then collision is confirmed.

Sorry, I have no code to share, since I haven't write one in java.

But most of the time my game objects doesn't need pixel perfect collision detection. If it is complex enough, I use multiple bounding boxes (circles, usually) to represent the object.

# Answer
> 1 votes
In addition to the other answer, you could speed up the per pixel solution using an octree to have a hierachical approach to being able to quickly reject completely transparent pixels (or regions). It would work best if there were large areas of non-collidable regions of pixels which could be quickly ignored.

You could also have a hierachy of collision primitives, a basic encompassing circle around the whole object, which if colliding you could then drop down to the next level of primitives which could be a number of more accurately placed circles, etc, which more accurately follows the outline of the object. You could in theory allow this to recurse as much as possible, the hierarchy allowing for early outs if a collision isn't detected at a higher level.

# Answer
> 1 votes
The "classic" per pixel collision system assumes that you're not rotating anything, or the rotations of your sprites are fixed.

Next, make bit masks of your sprites. If your sprites are 32x32 pixels, this is pretty simple, as one sprite consts of 32 32-bit words. If the sprites are wider, things get a bit more complicated.

```
...xx...    ...++...
..xxxx..    ...++...
.xxxxxx.    ++++++++
xxx..xxx    ...++...
.x....x.    ...++...

```

To check the collision, first do a aabb collision check, and if the boxes overlap, calculate y difference to know which scanlines to compare, and x difference to calculate the shifts required to make the bitmaps overlap.

The actual check is just an AND operation.

```
...xx...
..xxxx..
.xxxxxx..++...
xxx..xxx.++...
.x....*+++++++
      ...++...
      ...++...

```

If the sprite(s) are bigger than 32x32 pixels, the easiest (but not the most performant) way to solve the collision check is to handle them as groups of 32x32 pixel sprites.

If you're using OpenGL to rotate your sprites, this technique is naturally out. Rasterizing the rotated sprite(s) and doing pixel-by-pixel checking is probably (but not necessarily) prohibitively slow. If you're going that route, no need to hassle with bits, as you'll have to wade through so much data in any case.

# Answer
> 1 votes
You can obviously avoid unnecessary computation by doing rectangle-intersection first.

Say you really want per-pixel intersection, however.

You could create a 1-bit 'hit' mask for all sprites and do an bitwise & op on the overlap. However, for large overlap this can be *very* expensive.

An approach that worked very well back in the platform game era - and which would work equally well on phones today - is to **run-length-encode (RLE)** your hit masks. This may also reduce storage.

If your hit mask is a list of RLE-encoded scan-lines you can cheaply do intersection by walking these encoded lines.

I've seen DOS games that go so far as to special-case right-sided intersections and walk those scan-lines backwards!

---
Tags: android, collision-detection, rotation
---


title: How was sfxr made?

text:
# Question
Title: How was sfxr made?
I figure this is a Game Development question as this is a sound generation tool made specifically for games (in particular, Ludum Dare games).

I have a basic understanding of how sound works, with the changing amplitudes causing changes in pressure to produce sound. What I wonder though is how you go about making sounds through programming, and more specifically how sfxr does it. My approach would be to have an array of values representing each amplitude and then some how send it to the speakers. But how do you do that? Are there libraries that sfxr uses?

# Answer
Well, you usually don't have to go low level and transport the audio data to the speakers. The operating system has an interface for that (be it ALSA, DirectSound, CoreAudio, etc). Using that library, you just have to periodically give it a block of samples of a fixed length (for example, 512 samples). The sound library stores that array in an internal buffer and plays it.

If your block is, for example, 512 samples long, and the sampling frequency is 44.1Khz, this means that you have 512/44100 = 11 milliseconds to generate the next block of 512 samples. If you take longer to update, usually the old block is replayed again (the sound doesn't stop). That sounds like a broken CD, very annoying. You don't want that. I guess what sfxr does is store the whole wave and just copy the relevant chunk to memory, that operation takes virtually nothing.

On top of that, there are other libraries that provide an abstracted API and "talk" to the operating system's sound architecture. This way you can easily write multiplatform applications without having to adapt your sound code to each system. Examples of them are fmod, OpenAL, SDL, PortAudio, and a long etcetera.

**Update**:

**sfxr** uses **PortAudio** for its Windows version and **SDL** for the other platforms. If you look at the very end of *main.cpp*, you will see how these engines are initialized. PortAudio is passed pointer to a function called *AudioCallback*, and SDL is passed a pointer to *SDLAudioCallback*. You can see that what these functions do is to process a block of 512 samples and copy it to the output buffer. The processing itself is done in a rather complex function called *SynthSample*, which is the one that produces the desired output samples for a block given all the internal parameters of sfxr's synthesiser.
> 7 votes

# Answer
I started writing this answer, and it just got longer and longer, so this will be the verbose answer, so take from it what you will. Like CeeJay said though, you don't need to worry about this stuff typically. Especially so if you can use an API like FMOD, Wwise, or XACT that lets your sound designer hook everything up themselves so that you're not saying "play this.wav" but instead "trigger the 'PlayExplosionSound' event" you'll have a much easier time integrating sound into your game.

---

SFXR works by building some fundamental sound generators and offers the parameters you see in the GUI. Both XNA and ActionScript 3 have recently provided a way to directly pass samples to the underlying mixing engine on-the-fly. XNA could already define static sample buffers (looks like XNASfxrSynth uses this), but now you can have a DynamicSoundEffectInstance fire an event requesting you to feed it a sample buffer. This greatly reduces your memory footprint for continuously generated audio signals. You could technically write your own mixing engine as well, just have a single master sound instance to which all your sample buffers are sent for mixing.

A general example of making a sine wave generator can be found in Adobe's documentation for their new sampleDataEvent event in the Sound class. It's really just about knowing how digital audio works and constructing the correct sample buffers to get the sound you want. Also, look at Andre Michelle's site for more awesome advanced audio processing in Flash.

Like CeeJay said, audio data typically has an associated sampling frequency (usually 44.1kHz or 48kHz--Battlefield Bad Company uses 48 to achieve high fidelity playback when you've got a good 5.1 system hooked up). When working with digital audio, you have to worry about something called the Nyquist frequency. Basically, the highest frequency you can represent in an audio signal is half of your sampling frequency. The reason why 44.1kHz and 48kHz are the most common sampling frequencies is that the range of human hearing is roughly 0 to 20kHz. Thus 44.1kHz and 48kHz do a pretty good job at reconstructing a high fidelity sound on most consumer's systems.

It also has a bit depth, which is typically 16 for the final mix. This means that you have 16 bits to represent the amplitude of each sample, -32768 to 32767. This translates roughly to having a volume range of 96 dB to work with. The standard intensity limit for sound in a movie theater is 85 dB SPL (the SPL bit is a way to standardize the loudness, since the decibel system is relative), so 16 bits work really well for a final mix on most consumer's systems.

Often a game will do some internal mixing using 32 bit floating point values and then convert to 16 bit before pushing to the sound card. The reason for this is the same reason you will record in 24 bit with a 96kHz sampling frequency. When you start manipulating sound, you want as much headroom as you can get. Digital audio effects can sometimes introduce cool new high frequency signals that then get manipulated further down the signal chain and have an affect on the final output. These may get cut off when you mix down to 16 bit, 48/44.1k, but you will have preserved all the data along the way. It's like keeping a copy of your high-res .PSD file that just gets re-exported every time you need to alter an art asset. Except this is all happening in real-time in the audio engine.

If you want to read more about the lower level concepts of audio programming, I recommend looking at The Audio Programming Book by Richard Boulanger & Victor Lazzarini. I just received my copy a few weeks ago, and it does a great job at easing you into the concepts of audio programming (the introductory C chapter's kind of a tedious though since there's important concepts in it you can't miss, but you also have to sit through explanations of pointer arithmetic).

Another good book is Who Is Fourier?. It assumes little math background and covers the basics of the Fourier transform and general wave theory in the context of language researchers trying to study speech patterns. Kind of has the kiddie introductory Japanese language textbook feel with cute hand-drawn characters, but at the same time it's talking about Riemann sums by the second chapter.
> 5 votes

---
Tags: audio, sound, sound-effects
---


title: achieve transparent object

text:
# Question
Title: achieve transparent object
How can i achieve transparency and shadowing for a model in XNA ? Do you have a good tutorial ?

For the shadow i can manage the effect but how can i implement the transparency also ? Do i have to use the pass in effects ? And if so, how can i make an object transparent ?

# Answer
For transparenty objects you have to define alpha to you color or texture and enable alpha blending in you render state: link to msdn

Transparent objects have to be always rendered after opaque scene. If you have only one object, than you dont have problem.

If you have more objects, than there is problem to solve. Alpha blending is not comutative, so objects have to be sorted in a distance from actual camera position. Order independent methods exists. Original Depth peeling or dual depth peeling is mostly use on HW without sm5 (shader model 5 - dx11).

Shadows for transparent object are really not trivial task. First study shadow mapping. And once you be solid rock in it, than start investigate transparent shadows (take it only as recomandation). Wikipedia has surprisingly good article about it. Riemer's XNA tutorial series contaons also very good shadow map tutorial.
> 2 votes

---
Tags: xna, effects
---


# Question
Title: Am I allowed to sell a XNA game by myself?
I've just started the development of an XNA game, and I'm asking myself if it wouldn't be better to use an open-source alternative since I absolutely want to keep the complete control over my game. I need to be able to sell it to whoever I want, using the media I want.

Based on the XNA license and all that sort of legal stuff, am I allowed to sell an XNA game on my own, or am I forced to sell it through the Xbox Live Marketplace?

I'd like to see some reliable reference with your answer.

# Answer
> 17 votes
Check out this answer here. The simple answer is: **Yes**.

The networking stuff that uses "Games for Windows Live" does not work on Windows without Microsoft's blessing. But you can always just use the plain ol' networking stuff in the .NET Framework.

You cannot distribute XNA Game Studio (the Visual Studio bit) - this affects the Content Pipeline APIs for building content. This means, if you have a level editor for example, your users will have to manually install XNA GS.

The XNA Framework runtime, on the other hand, *is* redistributable.

# Answer
> 2 votes
Yes you can sell it by yourself, XNA inhibits no restrictions like that whatsoever. However you can't package the XNA framework installer into your installer, you will have to ask people to download it separately.

Edit: on the PC that is, there is no way to bypass the Xbox and WP7 stores.

# Answer
> 1 votes
I couldn't find easy 'official' reference on the subject, but I can provide indirect evidence.

There are currently several XNA games on sale on Steam, which is not related to Microsoft in any way, see for instance Beat Hazard: on Steam store and on XBox Live Indy Games.

There are parts of XNA that are off-limits though. You can't use most of the online functionality on the PC, as it is related to XBox Live and using MS's dedicated servers.

---
Tags: xna, legal
---


# Question
Title: C# Pathing algorithm for moving a object from point(X, Y) to point(X, Y)
Given a object which may move forward, backward, left and right at a given X,Y point. How to efficiently direct the object to a X,Y point using the given movement mechanics in the most efficient and human natural way.

The object is available for movement in real time, you may tell them to "startMoving|Direction|()" and "stopMoving|Direction|()" to any heading of 360 degrees. Though as a additional twist and the part I am having trouble with, is the facing of the object is never known, only its current location is known, so the algorithm must "detect" direction. The location of the object is updated in a separate thread in 500-1second intervals. A "Request" to update the location within the algorithm made be made at any point, but it is not immediately available and the algorithm must keep that in consideration. Doing something like requestAndWaitForCoordUpdate() is perfectly acceptable, however likely not needed.

In addition, no obstacles appear, it can be assumed you are on a MOSTLY open plane, stray to far from the direct straight line between the paths and you may run into obstacles. It is safe to assume that 1/4th the distance between a target and source, should be available in width on a given direct path.

I would also mention I am not sure A\* applys in this scenario, if it does I am unsure how to implement it given the constraints. The only real variable here is the facing of the object.

Here is some example code:

```
public int[] currentCoords;
public void movement() {
  currentCoords[0] = 1005; // starting y coord
  currentCoords[1] = 1007; // starting x coord
  moveTo(1050, 1025);
}

public void moveTo(int x, int y) {
  ... how?
}

public void threadUpdatingCoords() {
   ... periodically check for source coord updates
   ... between 200ms and 1000ms apart.
}

```

# Answer
I suggest the first thing you do is move the object straight ahead for a short duration. Now you will know the original position as well as it's new position. From the knowledge of these you will be able to calculate the rotation of the object.

```
originalPosition = (3 ; 2)
newPosition = (3.5 ; 1.7)
offset = (newPosition - originalPosition) = (0.5 ; -0.3)
offsetLength = sqrt(0.5^2-0.3^2) = 0.583
currentDirection = Normalize(offset) = (0.5 / 0.583 ; -0.3 / 0.583) =(0.857 ; -0.515)

```

Once the current direction is known, all you have to do is to offset the direction so it points towards the goal location and start moving until you reach it.

For additional information such as ETA you could compute the speed of object while it's moving.
> 1 votes

---
Tags: c#, algorithm
---


# Question
Title: Traffic estimation for a multiplayer flash game
hey, i want to know if my rough traffic estimations are right, it would be for a pretty simple realtime flashgame in the style of haxball (but not as a soccer game) heres a video of it http://www.youtube.com/watch?v=z\_xBdFg1RcI

So here comes my estimation, i dont know if they are realistic! i hope someone can help me.

consider the packet attached as a typical one sent every 200ms, its 148bytes + 64 bytes of header will make around a 200bytes packet. The server will receive 200bytes x 6 players x 5 times a sec=6000bytes/s=5.85Kbytes/s=46.9kbit/s plus he has to send all back to the players, so at this point are 94Kbit/s.The server received all the information, perform the definitive calculation and send the new position to all players, in a bigger packet of around 900bytes that have to be delivered to the others 6, which makes 900bytes x 6 players x 5 times a sec=27000bytes/s=26Kbytes/s=210kbit/s. overall that would be 26kbyte per second. thats like 130mb traffic per hour for a 6player room. but somehow i think the numbers are too high? that would be really much traffic for such a simple game.

did i calculate something wrong?

# Answer
> That would be really much traffic for such a simple game.

The problem, your type of game faces, is that it needs to be extremely responsive. On first glance World of Warcraft may look like a highly complex game, but there is far less information that needs to be transferred to the client and status updates can be a lot less frequent.

The math look correct to me, but Kibibytes (1024) are only used for RAM, network traffic is described using normal Kilobytes (1000).

You said that the server has to sent the package from the clients back to each one. That's probably the first thing you can optimize by just removing this step. The client should know what he told the server so there is no need to sent this information back to it.

48,000b/s upstream + 216,000b/s downstream = 264,000b/s in sum. That is 120 MB/h.

Another optimization is to only sent information from the client to the server, when the user does some action such as pressing or releasing an arrow key.

900 bytes per status update seems large. Without knowing details, I'd expect

```
package_header + message_type + 7 * (position + vector)
64             + 1            + 7 * (2*4      + 2*4) = 177 bytes

```
> 5 votes

# Answer
Actually there may be very little data transfer, it depends on the protocol you use. A TCP based protocol will ensure reliability and consistency amongst the data transfer but will have high latency and cost bandwidth charges. But using UDP the 2 players will exchange data primarily amongst themselves and the server will most likely be the super group handling ip allocation, In which case the packets aren't costing you money. If you want to make a realtime game, use UDP (but you need to program in game logic to best prevent hacking or cheating since the packets sent is amongst users)
> 0 votes

---
Tags: flash, game-mechanics, server
---


# Question
Title: What should I expect from volunteer playtesting?
I have recently been invited to do some volunteer playtesting for a pretty well known developer. They made it very clear that it was on a volunteer basis only. It's not a job and I won't be getting paid. What should I expect? What kind of input are they going to be looking for from me? What tips do you have for doing the playtesting well? What should I do to ensure I'll be invited back? Have you or anyone you know done something similar to this before?

Also, although this is unlikely (at best) to turn into a job, what tips do you have for possibly getting my foot in the door at the company? I am happy to just be able to participate, but I would love to be able to make some good connections since I plan on building a career in the game industry. Thanks in advance.

Update:
I've been invited back to be part of a regular test group for the same game. We went over some UI designs and filled out a survey on what we thought of them and how well we understood them. Then we had a video taped Q&A session with the QA supervisor and some of the developers. We discussed the designs we critiqued in the survey and elaborated more on what we thought of them. Finally, before leaving, we played a few rounds of one of the test builds of the game, just for fun. It was a great experience and from what I observed about the offices and the general work atmosphere, I'm even more sure I've made the right career choice for myself, personally.
I've accepted an answer to this question, but I'm still open to hearing about experiences from other people who have been involved in volunteer playtesting!

# Answer
Volunteer playtesting is usually just a few hours of watching you over your shoulder (or at the really fancy places, through cameras and one way mirrors) to see what you do when you're exposed to something you haven't seen before so they can see where frustrations lie or what you're inclined to do given a certain situation. They might ask you to fill out a questionnaire afterwards, but it isn't as useful as just watching you go through the game. Or at least that's what it should be. Related question from the opposite angle: How do you get useful data from playtesters?

At the larger companies you probably won't be meeting anybody that has any say in hiring or any hand in development; they usually have dedicated focus testing people taking notes. Smaller companies have the designers and leads there to watch.

It's like anything else, you might make a contact if you come across as somebody who knows their stuff and aren't a complete idiot. But don't go into a company and say "I have a great idea for a game" because they're not going to listen to you.
> 10 votes

# Answer
```
"What should I do to ensure I'll be invited back?"

```

Nothing special, really, but this depends of the company. This might be "napkin testing", where they only rate initial reactions, and after you've seen the game once, you're useless as a tester.

Since it really does depend on the company and their methods, they may interview you afterwards (or even during), so give useful feedback. Don't be a fanboy, or over-critical; just try to be honest.

Or well, there's one way to *ensure* you'll be invited back. Just bring a couple million dollars.. =)
> 1 votes

---
Tags: career, playtesting
---


# Question
Title: How to write reuseable components for pygame
Is there a recommended way to write reuseable components for pygame? Simple example would be a FPS counter. Should I write a class which has an init, update and draw method and call them from inside a game loop?

# Answer
> 1 votes
That would be pretty normal, pass the frame delta to update and pass in a destination surface to draw (which will normally be the screen).

# Answer
> 1 votes
I'm not sure if there's a recommended way, as such, for writing components but I often reuse buttons and other stuff for the game and pause menu which are initialized with Surfaces for mouse-states (hover, mouse-down, etc) and a function for click-events.

And of course, I have a vector class that I reuse all the time.

You definitely don't really need a module for basic timing and fps calculation though. Pygame's Clock-class is ideal for that. You just create a clock-object, call tick() once per frame and it returns the delta-time and keeps track of fps for you:

```
def main_loop():
    clock = pygame.time.Clock()
    counter = 0

    while game_is_running:
        handle_events()

        lapse = clock.tick()
        update_physics_and_stuff(lapse * BASE_SPEED_FACTOR)
        render()

        # once every second, display the fps
        counter += lapse
        if counter > 1000:
            pygame.display.set_caption('fps: %1.2f' % clock.get_fps())
            counter = 0

```

---
Tags: python, component-based, pygame
---