title: rotate player based off of joystick

text:
# Question
Title: rotate player based off of joystick
Hey everyone I have this game that i am making in android and I have a touch screen joystick that moves the player around based on the joysticks position. I cant figure out how to also get the player to rotate at the same angle of the joystick. so when the joystick is to the left the players bitmap is rotated to the left as well. Maybe someone here has some sample code I could look at here is the joysticks class that I am using. \`public class GameControls implements OnTouchListener {

```
public float initx =  DroidzActivity.screenWidth - 45;   //255; // 320 og 425
public float inity = DroidzActivity.screenHeight - 45;//425; // 480 og 267
public Point _touchingPoint = new Point( DroidzActivity.screenWidth - 45, DroidzActivity.screenHeight - 45);
public Point _pointerPosition = new Point(DroidzActivity.screenWidth - 100, DroidzActivity.screenHeight - 100); // ogx 220 ogy 150
private Boolean _dragging = false;
private boolean attackMode = false;

@Override
public boolean onTouch(View v, MotionEvent event) {

    update(event);
    return true;
}

private MotionEvent lastEvent;
public boolean ControlDragged;
private static double angle;

public void update(MotionEvent event) {
    if (event == null && lastEvent == null) {
        return;
    } else if (event == null && lastEvent != null) {
        event = lastEvent;
    } else {
        lastEvent = event;
    }
    // drag drop
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        if ((int) event.getX() > 0 && (int) event.getX() < 50
                && (int) event.getY() > DroidzActivity.screenHeight - 160
                && (int) event.getY() < DroidzActivity.screenHeight - 0) {
            setAttackMode(true);
        } else {
            _dragging = true;
        }
    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        if(isAttackMode()){
            setAttackMode(false);
        }
        _dragging = false;
    }

    if (_dragging) {
        ControlDragged = true;
        // get the pos
        _touchingPoint.x = (int) event.getX();
        _touchingPoint.y = (int) event.getY();
    //  Log.d("GameControls", "x = " + _touchingPoint.x + " y = "
                //+ _touchingPoint.y);
        // bound to a box
        if (_touchingPoint.x < DroidzActivity.screenWidth - 75) { // og 400
            _touchingPoint.x = DroidzActivity.screenWidth - 75;
        }
        if (_touchingPoint.x > DroidzActivity.screenWidth - 15) {// og 450
            _touchingPoint.x = DroidzActivity.screenWidth - 15;
        }
        if (_touchingPoint.y < DroidzActivity.screenHeight - 75) {// og 240
            _touchingPoint.y = DroidzActivity.screenHeight - 75;
        }
        if (_touchingPoint.y > DroidzActivity.screenHeight - 15) {// og 290
            _touchingPoint.y = DroidzActivity.screenHeight - 15;
        }

        // get the angle
         setAngle(Math.atan2(_touchingPoint.y - inity,
                _touchingPoint.x - initx) / (Math.PI / 180));

        // Move the ninja in proportion to how far
        // the joystick is dragged from its center
        _pointerPosition.y += Math.sin(getAngle() * (Math.PI / 180))
                * (_touchingPoint.x / 70); // og 180 70
        _pointerPosition.x += Math.cos(getAngle() * (Math.PI / 180))
                * (_touchingPoint.x / 70);
        // make the pointer go thru
        if (_pointerPosition.x > DroidzActivity.screenWidth) {
            _pointerPosition.x = 0;
        }

        if (_pointerPosition.x < 0) {
            _pointerPosition.x = DroidzActivity.screenWidth;
        }

        if (_pointerPosition.y > DroidzActivity.screenHeight) {
            _pointerPosition.y = 0;
        }
        if (_pointerPosition.y < 0) {
            _pointerPosition.y = DroidzActivity.screenHeight;
        }

    } else if (!_dragging) {
        ControlDragged = false;
        // Snap back to center when the joystick is released
        _touchingPoint.x = (int) initx;
        _touchingPoint.y = (int) inity;
        // shaft.alpha = 0;
    }
}

public void setAttackMode(boolean attackMode) {
    this.attackMode = attackMode;
}

public boolean isAttackMode() {
    return attackMode;
}

public void setAngle(double angle) {
    this.angle = angle;
}

public static double getAngle() {
    return angle;
}

```

}\` I should also note that the player has animations based on when he is moving or attacking.

EDIT:

I got the angle and am rotating the sprite around in the correct angle however it rotates on the wrong spot. My sprite is one giant bitmap that gets cut into four pieces and only one shown at a time to animate walking. here is the code I am using to rotate him right now. \` public void draw(Canvas canvas,int pointerX, int pointerY) { Matrix m;

```
    if (setRotation){
    //  canvas.save();
     m = new Matrix();
     m.reset();
            // spriteWidth and spriteHeight are for just the current frame showed
    //m.setTranslate(spriteWidth / 2, spriteHeight / 2);
     //get and set rotation for ninja based off of joystick
     m.preRotate((float) GameControls.getRotation());

    //create the rotated bitmap
      flipedSprite = Bitmap.createBitmap(bitmap , 0, 0,bitmap.getWidth(),bitmap.getHeight() , m, true);
      //set new bitmap to rotated ninja
    setBitmap(flipedSprite);

    setRotation = false;
//  canvas.restore();
    Log.d("Ninja View", "angle of rotation= " +(float) GameControls.getRotation());
    }

```

\`
And then the draw method

```
// create the destination rectangle for the ninjas current animation frame
// pointerX and pointerY are from the joystick moving the ninja around
destRect = new Rect(pointerX, pointerY, pointerX + spriteWidth, pointerY + spriteHeight);

 canvas.drawBitmap(bitmap, getSourceRect(), destRect, null);

```

# Answer
> 1 votes
You can use the atan2 function to get the rotation for your sprite. Just plug in the `x` and `y` offsets of your joystick (from the center of the joystick) and you'll get the angle in radians. The rotation will start at the 3 o'clock position, so if your sprite is normally pointing upwards (12 o'clock), you'll have to subtract 90 degree (or `π/2` radians).

---
Tags: android, rotation, joystick
---


title: exact point on a rotating sphere

text:
# Question
Title: exact point on a rotating sphere
I have a sphere that represents the Earth textured with real pictures. It's rotating around the x axis, and when user click down it has to show me the exact place he clicked on. For example if he clicked on Singapore the system should be able to:

* understand that user clicked on the sphere (OK, I'll do it with unProject)
* understand where user clicked on the sphere (ray-sphere collision?) and take into account the rotation
* transform sphere-coordinate to some coordinate system good for some web-api service
* ask to api (OK, this is the simpler thing for me ;-)

some advice?

# Answer
> 0 votes
Will's answer is perfect until you want to do some displacement (which you want propably if simulating planet).

In my opinion the color picking would be the best solution. It is fast to implement and works with o(log(n)) complexity (+ time to render). Every triangle on the sphere will have unique color. Render planet with only colors, no lighting in same resolution as screen. Get clicked point and at the same position as on the screen, check color. Find object with the color. Objects can be simply ordered (color is number) so binary search with log(n) complexity can be used.

We used this simple and old fashion technique for our game Save Us! for geting areas on planet **with no performance loss**. So i can tell you, that it is suitable for realtime application.

# Answer
> 1 votes
Open simple approach is colour picking.

Create two versions of your world map texture that you texture your sphere with. The first is for the user to see, the second for the selection. On the second, each country is drawn with a unique colour.

When the user clicks, render the scene without lighting or other effects, and using this second colour-coded texture. Don't swap-buffers - don't show this version to the user. But then read the colour value using `glReadPixels` as in the article above.

# Answer
> 0 votes
Your approach looks good. Some links for each step, assuming OpenGL:

1. `gluUnproject` the x,y of the click (flipping the y if necessary; screen coordinates for clicks are typically 0,0 is top-left of screen, whereas OpenGL 0,0 is bottom-left) for near (`0.0`) and far (`1.0`). This gives you a line segment which is the ray projecting from your mouse cursor through the scene. (`gluUnproject` is deprecated, so you might want to copy-n-paste it into your code from here.)
2. find line-sphere intersection code e.g. from this excellent page.
3. inverse the rotation of the nearest intersection point to account for the sphere's rotation e.g. adapt this.

---
Tags: geometry
---


# Question
Title: Ogre3D : seeking advices about game files management
I'm working on a new game, and its related level editor, based on Ogre3D. I was thinking about how i could manage the game files, knowing that Ogre use .mesh files for models, .material for materials/texture information etc... . At first i thought about a common .zip folder decompressed at runtime (the same way Torchlight and Ogre samples do). But this way the game assets become a monolithic archive, loading takes time, and could be difficult to eventually patch them. So, let's say i have a game object named "Cube" i want to load in my program. Going for modularity, what if i create a compressed file (using zlib compression routines) named Cube.extname, containing its sub-files Cube.mesh, Cube.material and so on ? Are there any alternatives or should i stick with compressed objects?

PS: Just to clear things, the answer is unrelated to my program code, at the moment i'm using "resources.cfg" pointing to the OgreSDK media directory.

# Answer
> 5 votes
You can have the assets of the game organized with any structure. Ogre only needs to know a parent directory or more ( this depends if you separate the assets to use on different nivels or to load at different times ), this information is written to the file "resources.cfg".

This is a valid approach, but package the files in a zip archive has some advantages:

1. It's open format.
2. The virtual files within a ZIP archive "remember" their relative path.
3. ZIP archives may be compressed: less space
4. ZIP archives are modular: useful for localization, for example.

Obviously is faster decompress a large chunk of bytes that multiples small chunks. You should use streaming decompression and use a loading bar at first of a level.

You can see more about Resource Managers at the book:

Title: "Game Engine Architecture"
Author: Jason Gregory
Chapter: 6. Resources and the File System

---
Tags: ogre, file, compression
---


# Question
Title: What is the best online game framework for Python?
I want create online game with Python. Is there any framework or library to make it easier? I would like it if the framework provided things like character attributes, such as health.

# Answer
> 3 votes
There is not one. If you are interested in making online games in Python, I encourage you to look at Panda3D, which does have a networking interface. However, it is not nearly as high-level as you want - there is nothing like health or HP built into it.

# Answer
> 2 votes
Have a look at BigWorld (www.bigworldtech.com). It's not free, though, not even particularly cheap.

---
Tags: python
---


# Question
Title: What alternatives exist of how an agent can follow the path calculated by a path-finding algorithm?
What alternatives exist of how an agent can follow the path calculated by a path-finding algorithm?

I've seen that the most easy form is go to one point and when the agent has reached this point, discard it and go to the next point.

I think that this approach has problems when the game has physics with dynamic objects that can block the travel between point A and point B, then the agent is taken from his original trayectory and sometimes go to the last destiny point is not the most natural behavior.

In the literature always I have read that the path is only a suggestion of where the agent has to go, but I don't know how this suggested path must be followed.

Thanks.

# Answer
> 8 votes
*image from http://www.red3d.com/cwr/steer/PathFollow.html*

What you're looking for is actually a path following steering behavior. The AI moves to a future point along the path instead of from one point to another. A gray buffer around the path allows the AI to navigate within this region before the AI must steer to stay on the path.

**Craig Reynold** has an excellent article on how this behavior works and implemented it in the **Open Source OpenSteer** library

**Path Following steering behavior**

# Answer
> 0 votes
A lot depends on how movement is handled in your game. If you want your agent to work at avoiding obstacles and such that may occur in real time separate from the original path finding, you may wish to perform a second layer of obstacle avoidance, using the next path node as the "goal".

Methods for doing this are varied, from doing a short range path search to giving the agent "sensors" and having them react to what they notice in their immediate vicinity.

Any method you use will effect it's behavior of course and the recommendations as to what kind would be largely dependent on obstacle density, distance between nodes, and desired agent behavior.

---
Tags: ai, path-finding
---


# Question
Title: Python or C server hosting for indie development
I've written a lot of the game, but it's singleplayer. Now we want to join up and play together.

I want to host it like an MMO, but haven't got any personal ability to host (no static IPs or direct access to a reasonable router that will allow me to port forward) so I wondered if there were any free / very cheap hosting solutions for people developing games that need to develop their MMO side.

In my case it's a world server for a 2D game where the world map can be changed by the players. So, GAE sounds expensive, as there would be quite a few updates per second (I heard they bill for data updates but not for download, but can't find refernce to billing anywhere on the FAQs)

I'd prefer to be able to write the server in python as that's what the game is written in (with pygame), but C is fine, and maybe even better as it might prompt me to write some more performant world generator code ;)

# Answer
You might want to look into getting an EC2 instance (Micro) -- you can run basically whatever you want on them, so writing python shouldn't be a problem.

The smallest Linux instance is $0.02/hr as I recall, so it shouldn't run you all that much.

However, I would build and test your server code on a LAN, and only once that is working well would I start looking for external hosting options. No need to pay for an Internet server, until you have something to actually test.
> 3 votes

---
Tags: mmo, server, python, hosting
---


title: Achieving certain rendering styles

text:
# Question
Title: Achieving certain rendering styles
I'm trying to assess the difficulty of creating a rendering style that is more like the game Okami and the Quake mods (as shown on this page...search for 'okami','quake npr'). Here's a better page describing the Quake rendering mod.

Can a game engine such as Unity be used and programmed to achieve these kind of rendering styles?

I'm doing research and am totally new to this so any insight into this would help tremendously.

# Answer
> 6 votes
Through the use of Shaders Unity can have a variety of rendering styles.

The Unify Community Wiki has a variety of articles dealing with the subject of shaders, complete with source code.

Creating Post-Processing shaders such as the ones in your example requires a Unity Pro license.

---
Tags: rendering, graphics-programming
---


# Question
Title: Find meeting point of 2 objects in 2D, knowing (constant) speed and slope
I have a gun which fires a projectile that has to hit an enemy. The problem is that the gun has to be automatic, i.e. - choose the angle in which it has to shoot, so that the projectile hits the enemy dead in the center.

It's been a looooong time since school, and my physics skills are a bit rusty, but they're there. I've been thinking to somehow apply the `v = d/t` formula to find the time needed for the projectile or enemy to reach a certain point. But the problem is that I can't find a common point for both the projectile and enemy trajectories. Yes, I can find a certain point for the projectile, and another for the enemy, but I would need lots of tries to find one where the two points coincide, which is stupid. There has to be a way to link them together but I can't figure it out.

I prepared some drawings and samples:

A simple version of my Flash game, dumbed down to the basics, just some shapes:

http://axonnsd.org/W/P001/MathSandBox.swf \- click the mouse anywhere to fire a projectile.

Or, here is an image which describes my problem:

So... who has any ideas about how to find x3/y3, thus leading me to find the angle in which the weapon has to tilt in order to fire a projectile to meet the enemy?

**EDIT**

I think it would be clearer if I also mention that I know: the speed of both Enemy and Projectile and the Enemy travels on a straight vertical line.

# Answer
Searching for "aim at moving target":
Aiming and hitting a moving target

```
/**
* Shoot at a target
*
* @param    t   The target to be shot
* @return       The bullet to be fired (or null if cannot hit)
*/
public function shoot(targ:Target, bulletSpeed:Number = BULLET_SPEED):Bullet
{
    var dx:Number = targ.x - this.x;
    var dy:Number = targ.y - this.y;
    var a:Number = targ.vx * targ.vx + targ.vy * targ.vy - bulletSpeed * bulletSpeed;
    var b:Number = 2 * (targ.vx * dx + targ.vy * dy);
    var c:Number = dx * dx + dy * dy;

    // Check we're not breaking into complex numbers
    var q:Number = b * b - 4 * a * c;
    if (q < 0) return null;

    // The time that we will hit the target
    var t:Number = ((a < 0 ? -1 : 1)*Math.sqrt(q) - b) / (2 * a);

    // Aim for where the target will be after time t
    dx += t * targ.vx;
    dy += t * targ.vy;
    var theta:Number = Math.atan2(dy, dx);

    // Fire the bullet
    var bullet:Bullet = new Bullet();
    bullet.target = targ;
    bullet.hitPoint = new Point(targ.x + targ.vx * t, targ.y + targ.vy * t);

    bullet.x = this.x;
    bullet.y = this.y;
    bullet.vx = bulletSpeed * Math.cos(theta);
    bullet.vy = bulletSpeed * Math.sin(theta);

    return bullet;
}

```
> 1 votes

# Answer
I don't know about Flash technology, nor how the game is updated. Presuming that there can be an `Update()` method like the one encountered in XNA that is called from within the game loop, would it not be possible to simply calculate:

1. the coordinates of your enemy's center, that is, (x2, y2) based on its current location;
2. than the coordinates of the projectile's center (if needed) or only its boundaries;
3. see if these both coordinates meet sometime, and if they do, this means your enemy's dead?

Once again, I do not pretend that this is doable in Flash, I only try to help the best I can with what I know. As far as I know, Flash has a behind script capability. Now, to make sure a method would be called X times per second might be another story in Flash, I unfortunately can't say.

> **EDIT #1**
>
> \[...\] the question is how to shoot so that the weapon hits it.

Here's my guess:

Let's take some arbitrary coordinates:

```
(X1, Y1) = (800, 600)
(X2, Y2) = (1000, 50)
(X3, Y3) = (X3, Y3) // Means these are to be determined.

```

Since this was not mentioned, I extrapolated a constant speed for both the enemy and the projectile.

```
Enemy's speed:
    Ve = d/t = 20 px/s

Projectile's speed:
    Vp = d/t = 10 px/s

```

Then, we have to determine when the projectile could reach the Y3 coordinate:

```
h = Y1 - Y3
h = 600 - 50
h = 550 px // This means that the projectile has to travel 550 px at 10 px/s to reach Y3

```

In how much time will the projectile reach Y3?

```
t = 10 px/s * 550 px
t = 550 px / 10 px
t = 55 s // Then, 55s is required for the projectile to reach Y3

```

Now, where will the enemy be in 55 seconds?

```
Ve = d/t = d/55s
20px/s = d/55s
d = 20px * 55s
d = 1100 px

```

Now, we can determine X3 with the following formula:

```
X3 = X2 - d
X3 = 1000 - 1100
X3 = -100 // Remember, these are arbitrary coordinates

```

`X3` would then be outside the visible area in this example, which doesn't matter here since the Cartesian plan includes negative coordinates. What matters most is that from this (X3,Y3) coordinate, we'll be able to find the required angle.

We can now determine the size of a new right-triangle following these coordinates:

```
(X3, Y3) = (-100, 50)
(X1, Y1) = (800, 600)
(X3, Y1) = (-100, 600)

```

Which allows us to find out the distance on X that the projectile needs to travel:

```
d = X1 - X3
d = 800 - (-100)
d = 800 + 100
d = 900 px

```

And we already know the height that the projectile needs to travel on Y which is 550px. Then, we can calculate the hypotenuse according to pytaghorian theory.

```
sqr(a) + sqr(b) = sqr(c) // Where sqr(c) represents the sqr(hypotenuse)
sqr(c) = sqr(900) + sqr(550)
sqr(c) = 810,000 + 302,500
sqr(c) = 1,112,500
c = sqrt(1,112,500)
c = 1,054.75116 (rounded value)

```

Then, we can now find the cos(A), where A is the angle which we're looking for.

```
cos(A) = adjacent side / hypotenuse
cos(A) = 900 / 1,054.75116
cos(A) = 0.853282 (rounded value)

```

From cos(A) we can now determine angle A:

```
A = cos-1(cos(A))
A = cos-1(0.853282)
A = 31.42956561 (rounded value)

```

> **References**

1. Triangle (Wikipedia);
2. Finding an Angle in a Right Angled Triangle;
3. Trigonometry Calculator - Right Triangles.

I do hope this helped at least a little!
> 2 votes

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


# Question
Title: problems programmatically creating UIView on iPad App
I have been struggling with this problem for a few days.

My iPad app is designed to be a portrait game. To satisfy Apple's expection, I also support landscape mode. When it goes into landscape mode, the game goes into a letterbox format with back borders on the sides.

My problem is I am creating the UIWindow and UIView programmatically. For some unkown reason, the touch controls are "locked" in to think I'm always in landscape mode. And even though visually in portrait mode everything looks correct, the top and bottom of the screen does not respond to touch.

To summarize how I am setting this up, let me provide the skeletal framework of what I'm doing:

in main.cpp:

```
int retVal = UIApplicationMain(argc, argv, nil, @"derbyPoker_ipadAppDelegate");

```

In the delegate, I am doing this:

```
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 CGRect screenBounds = [[UIScreen mainScreen] bounds];
 CGFloat scale = [[ UIScreen mainScreen] scale ];

 m_device_width = screenBounds.size.width;
 m_device_height = screenBounds.size.height;
 m_device_scale = scale;        // Everything is built assuming 640x960

 window = [[ UIWindow alloc ] initWithFrame:[[UIScreen mainScreen] bounds]];
 viewController = [ glView new ];
 [self doStateChange:[blitz class]];

 return YES;
}

```

The last bit of code sets up the UIView...

```
      - (void) doStateChange: (Class) state{
 viewController.view = [[state alloc] initWithFrame:CGRectMake(0, 0, m_device_width, m_device_height) andManager:self];
 viewController.view.contentMode = UIViewContentModeScaleAspectFit;
 viewController.view.autoresizesSubviews = YES;
 [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}

```

The problem seems to related to the line viewController.view.contentMode = UIViewContentModeScaleAspectFit;

If I remove that line, touch works correctly in portrait mode. But the negative is when I'm landscape mode, the game stretches incorrectly. So That's not a option.

The frustrating thing is, when I originally had this set up with a NIB file, it worked fine. I have read through the docs about UIWindow, UIViewController and UIView and have tried about everything to no avail.

Any help would be greatly appreciated.

# Answer
> 1 votes
Here there is a tutorial of how achieve this:

http://elasticimagesoftware.posterous.com/opengl-on-ipad-how-to-handle-arbitrary-device

I think that this approach uses a MVC approach and is the view which makes the transformation for you ( graphics with animation included and input ).

On the other hand, I remind that if you want do this rotation with programation the view doesn't rotate and you need transform the coordinates that receives from the iOS.

In that book there is an example to do programatically ( with animation also ):

Name: iPhone 3D Programming
Author: Philip Rideout

I have seen the two approaches and I recommend you to use the MVC approach, because when the application starts, it's impossible know the orientation with programmation ( the first accelerometer event doesn't reach ) and the image may be inverted for the first time. With MVC you see the image in correct orientation the first time.

# Answer
> 0 votes
There's no requirement to support both orientations. But if you do, you can change the content mode in the -(void)willAnimateRotationToInterfaceOrientation method. I'm on an ipad at the moment or i would post more specific code, but I'll come back later if someone hasn't posted more.

# Answer
> 0 votes
I submitted this bug to Apple last month and with they sent me an email the other day that said this bug was fixed with the latest release of iOS. I believe its fixed after iOS 4.3

---
Tags: ipad
---


title: Angular Velocity

text:
# Question
Title: Angular Velocity
Hey, I have a particle that is hit with a force `F` at a particular position on the ball `P`. How can I calculate the angular velocity of the X,Y and Z axis? The actual rotating of the object should be fine, but it's the values of the `angular velocity (Vector3)` that I'm not sure of. Sorry I can't show any code, but I'm not really sure where to start. Thanks for any help.

# Answer
I assume you're already calculating the linear momentum change from the collision so I won't cover that. Essentially, angular momentum works in the same way as linear but with Force replaced by Torque and Mass replaced by Inertia.

dv = T / I

where dv is the change in angular velocity, T is the torque from the collision and I is the moment of inertia which for a sphere is

I = (2/5)MR^2 (solid sphere) I = (2/3)MR^2 (shell)

where M is the mass of the sphere and R is the radius.

The torque, T, is calculated from the cross product of the force with the vector from the collision point to the center of the sphere:

T = F x (P - O)

where O is the center of the sphere.

Putting it all together:

dv = (F x (P - O)) / ((2/5)MR^2)
> 6 votes

---
Tags: xna, 3d, physics
---


title: Game Code Design for Rendering

text:
# Question
Title: Game Code Design for Rendering
I first created a game on the iPhone and I'm now porting it to Android. I wrote most of the code in C++, but when it came to porting it wasn't so easy. The Android's way is to have two threads, one for rendering and one for updating - this due to some devices blocking when updating the hardware - while the iPhone's way is to have one thread to do it all.

My problem is that I am coming from the iPhone. When I transition, say from the Menu to the Game, I would stop the Animation (Rendering) and load up the next Manager (the Menu has a Manager and so has the Game). I could implement the same thing on Android, but I have noticed on game ports like Quake, don't do this - as far as I can tell.

What I want is someone to explain how a game like Quake can transition from the menu to the game? Does it stop rendering, load the game stuff and then start rendering again, like what I did on the iPhone? Does it load the game stuff while still rendering the menu?

Interestingly, when I did try to load a Renderer class while renderering I would get a dequeuing buffer error - which I believe to be OpenGL ES. Was I just doing something wrong or is it possible to load textures and buffers, while it's rendering?

Examples would be appreciated.

# Answer
> 7 votes
Rendering on a separate thread is a common idiom.

To quickly and directly answer your question about "*Was I just doing something wrong or is it possible to load textures and buffers, while it's rendering?*" - OpenGL ES has a rendering context bound to one thread and calling any OpenGL ES functions from any other thread is illegal. More on that in a bit.

Quake is a single threaded program, and written for DOS originally. Its code is fairly specific to the game, but basically the menus are built-in and simple rendered on top of the 3D graphics (if any). It has been a while since I've read through the source, but conceptually, the game loop is this:

```
loop {

update_game();

if(menu_up)
    draw_menu();

draw_world();

}

```

I think rendering on a different thread is generally good because it forces you to separate the app's logic from the presentation layer from the actual rendering code, and even on the iPhone, I suggest you use it (new iPad is dual core!). Additionally, you abstract the drawing interface from rendering API.

It presents some challenges and in your case, the challenge is synchronizing the logic with the presentation. If you aren't writing a full-out game engine that is meant to be reused by both, then sharing the menu state with the renderer thread would be the most direct way. Basically something like this:

```
renderer_thread_loop() {

lock( sharedState.mutex )
if(sharedState.menuUp == true) {
   draw_menu(sharedState.menuState);
}
unlock( sharedState.mutex )

render_game();
}

```

There are a lot of synchronization issues here, tread carefully! You can't update information the renderer is rendering!

A less direct but more elegant way would be to submit stuff to the renderer to do. Each frame, some presentation layer code would queue up tasks for the renderer to do. At the end of the queue might be a "swap buffers" message that tells the renderer to swap buffers. In this way, the renderer runs on a separate thread but acts similar to directly calling functions like glDrawArrays(). Normally, the logic updates stuff, the presentation layer decides what to draw, and the renderer draws it.

A more full example would be this:

```
logic() {
  respond_to_input(); //move character, interact with menus
  update_game(); //physics, AI, etc.
}

presentation() {

    queueBeginFrame();

    if(inMenu) {
        queueDraw(menu);
    }

    queueEndFrame();
}

renderer() {

    while(game_not_exited) {
    if(queue.empty() == false)
    {
       work = queue.fetch();

       doWork(work); //do something with the request
    }

}

```

---
Tags: c++, android, opengl-es, rendering
---


# Question
Title: Including Microsoft.XNA.Framework.Input.Touch in a project?
So after running through tutorials by both Microsoft and www.xnadevelopment.com I feel very confident in my ability to get to work on my first game using the XNA Framework. I've manipulated sprites, added audio, changed game states, and even went a step further to apply the knowledge I had and figure out how to make animations and basic 2-dimensional physics (including impulses, force, acceleration, and speed calculations)

But then shortly into the project I hit a curious bump that I've been unable to figure out.

In wanting to implement menus, pause screens, and several different aspects of play (a "pre-level" prep screen, the level itself, and a screen after the level to review how well you did) I took a look at Microsoft's Game State Management sample. I understood the concept, although it was admittedly quite a lot to take in. Not wanting to recreate the entire concept by scratch (after all- what purpose would that serve?) I tried copying and pasting the sample code into my own `ScreenManager` class (as well as `InputState` and `GameScreen` classes) to try and borrow their ingenuity. When I did this, however, my project stopped compiling. I was getting the following error:

> The type or namespace name 'Touch' does not exist in the namespace 'Microsoft.Xna.Framework.Input' (are you missing an assembly reference?)

Having read through their sample code already, I realized that this namespace and every function and class within it could be safely ripped from the code without losing functionality. It's a namespace simply for integrating with touchscreen devices (presumably Windows Phone 7, but maybe also tablets).

But then I began to wonder- how come Microsoft's sample compiled but mine didn't? I copied their code exactly so there must be a setting somewhere that I need to change in Visual Studio in order to correct this. I tried creating a new project as a Windows Phone 7 game rather than a Windows game, however that only forced it to compile to a Windows Phone emulator and denied me the ability to change the resolution and other features which I clearly had the power to do in the sample code.

So my question is simple - how do I properly use the namespace Microsoft.XNA.Framework.Input.Touch?

# Answer
Input.Touch is only available in WinPhone7 projects. You can't use it on Win7. I don't know why the XNA team decided to do this. In the beta, Input.Touch worked on Win7 just fine.
> 5 votes

---
Tags: xna, c#, xna-4.0, microsoft
---


title: Game ideas for a platformer

text:
# Question
Title: Game ideas for a platformer
I have created a platformer which currently has the features listed below. I would greatly appreciate any further ideas which I could implement! (I don't play a lot of games which is why I require help)

* Walking/jumping/movement
* player can shoot lasers
* enemies also walk, fly, and shoot lasers
* water (you can swim in this)
* mud (slows you down on contact, and stops you from jumping)
* ladders
* damage when falling from a large height, unless falling into water
* moving platforms
* springboards (jumping on them shoot you into the air)
* growing platforms (allow you to reach new places)
* key and door system
* gem and coin collection system
* teleporting
* turrets

# Answer
Interesting and strategic AI behavior.

At all costs avoid the syndrome of enemies that run in a line toward the player weapon fire. Games where the player walking backward and firing is the winning strategy undermine any other cool things you might have put in.

Enemies should show some sense of self-preservation by means of: taking cover, keeping distance, holding back until sufficient numbers of team mates are available for an assault, coordinated use of different weapons systems, character support roles to heal the injured.

Some degree of AI unpredictability is also helpful to keep things interesting.
> 2 votes

# Answer
Wow, that's already a huge list of features!

Personally I'd probably invest the time to build some interesting levels instead of adding more features to the game. When designing the levels you could highlight the features of your game by making some of them a key-part of the level.. so you might have a level that introduces water or moving platforms etc.

So instead of using all your features from level 1, you can introduce new features with upcoming levels which keeps the player motivated to discover new stuff as he moves on.
> 9 votes

# Answer
Power-ups like:
\- invisibility
\- run faster
\- teletransporting
\- invulnerability

Weapons:
\- grenades
\- turrets
\- pistols

Atmospheric effects:
\- Rain ( the laser doesn't work )
\- Wind ( you walk slowly )

Vehicles:
\- cars
\- tanks
> 2 votes

# Answer
Is this a commercial game?

I would say a really cool game idea would be a platformer where you battle other players, as magicians or something, and can add to the map and destroy objects on the map to hinder your opponent.

Other than that, just make an rpg, they are the good ol' fallback with lot's of features =)
> 0 votes

---
Tags: game-design
---


title: Physics timestep questions

text:
# Question
Title: Physics timestep questions
I've got a projectile working perfectly using the code below:

`//initialised in loading screen
 60 is the FPS - projectilEposition and velocity are Vector3 types`

```
gravity = new Vector3(0, -(float)9.81 / 60, 0);
//called every frame
projectilePosition += projectileVelocity;

```

This seems to work fine but I've noticed in various projectile examples I've seen that the elapsedtime per update is taken into account. What's the difference between the two and how can I convert the above to take into account the elapsedtime? (I'm using XNA - do I use ElapsedTime.TotalSeconds or TotalMilliseconds)?

Edit: Forgot to add my attempt at using elapsedtime, which seemed to break the physics:

```
projectileVelocity.Y += -(float)((9.81 * gameTime.ElapsedGameTime.TotalSeconds * gameTime.ElapsedGameTime.TotalSeconds) * 0.5f);

```

Thanks for the help

# Answer
If you assume a constant frame rate of 60, your game doesn't work with the same speed with any other frame rate. If your rendering is too slow, the physics will also slow down. Sometimes this is desirable, but usually games are running the physics with constant speed independent of the rendering frame rate.

You can change your formulas to use elapsed time instead of 60, but it is very hard to do that in a way that the physics will behave the same with different time differences. For linear movement it is not a problem, but already for a parabolic trajectory or collisions this becomes hard and for more complex trajectories there is no closed form formula.

The best solution usually is to use frame skipping. In this approach you take the elapsed time into account, but instead of updating the formulas you calculate how many times you need to update the physics in a row. This means that if the rendering is lagging, the physics will be updated several times per rendering frame. If the rendering is running faster than the physics should be updated, then frame skipping will skip the physics update as needed. The following code snippet does frame skpping. It assumes that the time units are in milliseconds, but it is easily adaptable to other units as well.

```
int TIMESTEP = 1000 / 60; // 1000 milliseconds in second, 60 Hz physics update
long previousTime = getTime();
long deltaTime = 0;

while (gameRunning) {
    long currentTime = getTime();
    deltaTime += currentTime - previousTime;
    while (deltaTime >= TIMESTEP) {
        updatePhysics();
        deltaTime -= TIMESTEP;
    }

    render();
}

```
> 5 votes

# Answer
Your formula is wrong, as 0.5\*accel\*t^2 gives a change in position, not a change in velocity. What you probably want to do is this:

```
gravity = new Vector3(0, -9.81f, 0);
projectileVelocity += gravity * gameTime.ElapsedGameTime.TotalSeconds;
projectilePosition += projectileVelocity * gameTime.ElapsedGameTime.TotalSeconds;

```

Note that the framerate of 60 is not needed, this will work for any framerate which is the main reason to use elapsed time in the first place.
> 2 votes

# Answer
What you are doing is actually the starting point of what quite a few physics packages do, and that is used a fixed time step for your updates. By dividing the value by 60 you are using a fixed time step.

What using the elapsed time would do is allow that to happen even when you are Not running at 60fps. You would use the actual elapsed time instead of 1/60.

As for the error to why your switching didn't work as expected is I believe because you are using TotalSeconds.. Which is probably the number of seconds your game has been running instead of the number of seconds since the last frame update. Aside from that it looks like
> 0 votes

# Answer
You could try to do more accurate integration. What you have is called the Euler method, and you have to use really small times steps to make it accurate. The next best method is to evaluate the acceleration at the beginning and end of the time step, i.e. compute the acceration at time t0, then advance at that velocity and acceleration by delta T. Then recalculate velocity/acceleration at that time step. Now take the average of the two, to advance from to to t0+dt. This is second order accurate rather than first, so errors won't accumulate nearly as fast.
> 0 votes

---
Tags: xna, 3d, physics, mathematics, fixed-timestep
---


title: Real Time Cloud Algorithm

text:
# Question
Title: Real Time Cloud Algorithm
I want to know how the algorithm works in this game: http://www.gametrailers.com/user-movie/cloud-the-game/45068

Especially how the game generates the real time cloud, and be able to merge with other clouds dynamically.

I tried to google some info, but was unable to find the useful information. Probably because I used to wrong keywords

# Answer
> 13 votes
Cloud rendering is hard task. But those clouds in video are just couple of "cloudy" particles. I don't think that that is something nice :)

For nice clouds problem is not the cloud simulation, but the cloud rendering, which is impossible to handle to be photo realistic in realtime for scene with dynamic lighting. What happens in participating media like cloud is:

Light emission exist only when participating media emits light (like hot gas or fire) or when they are lighted (this is simalar part to normal rendering), absorption mean that light is absorbed and scattering is the biggest computational problem. Light is scattered inside the volume. Then you want to have self shadowing and shadow emmiting to the ground and opaque scene. How to do it?

**Where to obtain cloud?** Clouds can be simulated by perlin noise. It is very common and looks nice. Perlin noise can be 4D, where 4th dimension is time to create nice dynamic clouds. If you want to specify cloud shapes: you have to do volumetrization over the desired shapes, save it as density 3D grid and multiply it with perlin.

## How to render it

**By rendering particles?**. Particle clouds are possible. It is most simple method. However, simulation of any light propagation between particles is pretty hard. It is very typical that you have to sort particles in the view direction of camera ( or in so called half-axis between camera-dir and light-dir). This **is impossible in realtime application** unless your target platform doesn't support shader model 4 or better shader model 5 - and gpgpu computing (like cuda, openCl or direct compute) - so you could write Parallel radix sort and sort particles every frame (that will be realtime). Sorting is needed for alpha blending and also for smart shadow mapping.

I'll guide you to some articles:

**By volumetric raycasting**. Volumetric raycasting means, that you have grid where you did fluid simulation (typicaly Navier-Strokes, but voxelized cloud shape is ok too). And shoot ray for every pixel through volume and integrate radiance across the ray. **This is suprisingly OK for realtime applications**. Raycasting on wiki. You don't have to have gpgpu computing. Volumetric raycasting can be done on pixel shader, because it doesn't need any synchronization between threads (rays). Having grid in 3D texture is perfect on graphics hardware, because you can benefit from native tri-linear interpolation of the texture unit. Self shadowing can be done by shooting ray from every sample to light and counting the density of light shadowing volume. This is slow. You could use some shadow mapping with transitions (like deep shadow maps). The light scattering is also not possible in realtime (with gpgpu it is).

Volumetric raycasting is fast and it is easier to implement than particle sorting and work fast even on older HW.

Something to study:

# Answer
> 5 votes
I can't speak to the details of Cloud, but clouds are usually implemented using three dimensional Perlin noise. From the video and my recollection, Cloud "merges" the clouds by just making your cloud bigger and removing the other one.

Ken Perlin's original noise presentation uses clouds as an example.

---
Tags: point-cloud
---


title: Java graphic objects as in flashgames

text:
# Question
Title: Java graphic objects as in flashgames
How is it possible (with the standard Java2D engine) to use small sprites like graphic objects?

For those who don't know what I mean, in all those Flash-games like on Facebook they put small sprites on the screen which react to mouse-over and clicks. I tried to do the same in Java but can't find a good method. Swing components always spread over the whole bitmap, but I only want to get a reaction from the object when the mouse is over a pixel that's *not* transparent.

So basically checking every time if the object below the mouse contains a non-transparent pixel (which i believe could be pretty intense in a gameloop or repaint loop). I have no idea how to implement such a thing efficiently.

# Answer
Is it really that expensive to check one pixel for transparency every frame? Of course, you only check if the cursor is within the sprites bounding box.

Assuming you use BufferedImage to hold your image data, you can dom something along this (sorry, code is really not exact, look up how BufferedImage work):

```
image.getRaster().getPixel(x, y, array);
alpha = array[4]
if (alpha > 0.5f) { ...

```

Area can be used for operations between shapes (such as add and subtract). It's fairly easy to make a algorithm that cover an area with as few rectangles as possible (if you don't want it to have the guaranteed best solution). Cover all opaque pixels with rects and leave out the transparent ones. Use the Area class for unifying them into a single path. BUT, I think that checking the sprite for transparency is more efficient.
> 2 votes

# Answer
You could try a reduced bounding box. Let's say you have a 20x20 px sprite, with 2 px of transparency around the borders. Set up a 18x18 px bounding box, and check at the end of every buffer update if the mouse pointer coordinates are included in the bounding box coordinates.
> 0 votes

# Answer
You could use PulpCore, a lightwight 2D framework, which will let you use sprites really easily:

http://www.interactivepulp.com/pulpcore/
> 0 votes

---
Tags: java
---


# Question
Title: Rotation of bitmap using a frame by frame animation
I have one large bitmap that has four frames drawn on it and I only draw one at a time by looping through the bitmap by increments to animate walking. I can get the bitmap to rotate correctly when it is not moving but once the animation starts it starts to cut off alot of the image and sometimes becomes very fuzzy. I have tried

```
public void draw(Canvas canvas,int pointerX, int pointerY) {
    Matrix m;

    if (setRotation){
    //  canvas.save();
    m = new Matrix();
    m.reset();

    // spriteWidth and spriteHeight are for just the current frame showed
    m.setTranslate(spriteWidth / 2, spriteHeight / 2);

    //get and set rotation for ninja based off of joystick
    m.preRotate((float) GameControls.getRotation());

    //create the rotated bitmap
    flipedSprite = Bitmap.createBitmap(bitmap , 0, 0,bitmap.getWidth(),bitmap.getHeight() , m, true);
    //set new bitmap to rotated ninja
    setBitmap(flipedSprite);    //  canvas.restore();
    Log.d("Ninja View", "angle of rotation= " +(float) GameControls.getRotation());
    setRotation = false;
}

```

And then the Draw Method here

```
// create the destination rectangle for the ninjas current animation frame
// pointerX and pointerY are from the joystick moving the ninja around
destRect = new Rect(pointerX, pointerY, pointerX + spriteWidth, pointerY + spriteHeight);

canvas.drawBitmap(bitmap, getSourceRect(), destRect, null);

```

The animation is four frames long and gets incremented by 66 (the size of one of the frames on the bitmap) for every frame and then back to 0 at the end of the loop.

# Answer
Disclaimer: I have not programmed for the android.

There might be two things going on here.. When rotating pretty much anything you want to do it around the center point of the object in question.. So where you are calculating the center for the current sprite shown (width and height divided by two) you may also need to include the current frame offset. The m.preRotate() may be handling this but I am not sure, and this would skew the frames aside from the initial one.

Second is if you are using all 66 texels (pixels of a texture) of the frame, then when you start rotating and it does the sampling of the texture through rotation to screen pixel coordinates you will start noticing fuzzy or jagged edges. You may want to put a little padding on your animation frames or 1-2 pixels per edge so your animations are 68 or 70 texels wide. This hides the fuzzy or jagged edges by making it blend together completely transparent texels into a screen pixel.

Hope this might give you some things to look into, but again, I have not programmed for an android before so I have no way to test this.. Just issues I have run into on the PSP and Zunes over the years.
> 3 votes

---
Tags: android, animation, rotation
---


title: Team brainstorming

text:
# Question
Title: Team brainstorming
I want to ask developers who work in small teams, like 5-6 people, how can brainstorming accomplish as much as possible? What does brainstorming look like on your team ? I ask, because I remember my previous brainstorming meeting, and I know is very hard to co-ordinate it :/ We want to brainstorm about game design, game architecture and etc.

# Answer
Brainstorming is sort of *supposed* to be loose and unstructured in order to facilitate a free flow of ideas. That said, it's usually possible to have an agreed-upon, firm guideline for what you're brainstorming about (game ideas, solutions to a technical problem, et cetera). Everybody should be aware of this guideline and do their part to ensure the meeting doesn't drift too far into the territory of brainstorming about things that are not germane to that guideline.

During the meeting you should encourage people to both propose new ideas and to build upon ideas others have proposed. Usually you'll want to avoid criticizing ideas too much, though. One way I've seen to do this (although I've never done it myself) is to do things in two phases, where people first propose ideas by writing them on sticky notes and quietly sticking them to a whiteboard and afterwards all the ideas are discussed and built upon.

Tools like whiteboards and sticky notes can be invaluable as means of expression in these sorts of sessions.

Almost as important as how you run the meeting is what you do afterwards: even the most haphazard meeting will probably produce at least one reasonably actionable idea, so it's important that you have somebody dedicated to capturing all of the decent ideas and recording them in some notes somewhere.

If you search Google for "brainstorming meetings" you get a lot of results. These two seem potentially interesting:
> 7 votes

# Answer
I think that the most important aspect of brainstorming is that someone write stuff down (type it, perhaps even digital-voice-record it, for later transcription/summarization), otherwise it's easy to forget intricacies of ideas that make them good.

I've had great success in using an online todo list (via http://basecamphq.com basecamp) for a continuous brainstorm. When I come up with an idea (e.g. when I'm out at a restaurant), I write it down, stick it in my pocket, and add it to the online todo list later. Then, when it comes time to actually code, I pick stuff from the todo list that I actually want to do and are high priority.
> 4 votes

# Answer
Here are a few things that help:

* Brainstorming inherently goes slightly off topic so try to make each session about a fairly narrow topic area. Otherwise the sessions can drift into full tangent land, which is fun but not particularly productive.
* Use a whiteboard, post-it notes or a projector to put the ideas up in front of everyone. Often a earlier idea can trigger a later one if you can see them all up in one place. Also this cuts down on the discussion recycling concepts since you can see they were already suggested.
* When writing the ideas down try to give them a rough visual grouping. Doesn't have to be good but it will help later.
* When you get towards the end of the session do basic pairing down. There are a few simple steps to help with this.

1. Quickly attempt to group ideas in categories, either drawing circles around them on the whiteboard or moving the post-it notes. You should have been doing a bit of this while writing them down but now you can use the help of the group to collect them into more thoughtful categories.
    2. Have everyone indicate their top three ideas. You'll tend to get a clustering of the more popular ideas that will have more potential than others. It's important to limit the number of votes people have in this stage as it focuses them to the stuff they think will work, not just find amusing.
> 1 votes

---
Tags: game-design
---


title: Calculating and detecting curves

text:
# Question
Title: Calculating and detecting curves
How can I detect the 'steepness' of a curve? For example, if the user swipes their finger across the screen in a curve, what's the best way of detecting whether the curve is almost a semi-circle, or whether it's straight?

Is it also possible to extend this to possibly recognise multiple curves (e.g. a sigmoidal shape)?

Thanks for any advice

# Answer
I suggest using an orientation histogram. First, collect sample points on your curve, ensuring they're far enough apart to be meaningful. Choose a minimum distance of 10 pixels, for instance.

Then iterate on point triplets \[A,B,C\] and compute the orientation change:

```
v1 = (B - A).normalize();
v2 = C - B;
f = atan2(-v2.x * v1.x -v2.y * v1.y,
          v2.x * v1.y - v2.y * v1.x);

```

Now `f` contains the orientation difference between `BC` and `AB`. The `atan2()` here is important to avoid any division by zero.

Now you can compare successive orientation changes like \[Jesse Emond\] suggested. However, computing a histogram will be more robust:

```
float histo[32];
memset(histo, 0, sizeof(histo));

/* ... */

histo[31 - (int)((M_PI - f) * (32.0 / 2.0 / M_PI))] += weight(A, B, C);

```

(I use `M_PI - f` instead of `f + M_PI` because the `M_PI` value is inclusive and could lead to an integer overflow).

`float weight(A, B, C)` is a method that computes the weight of the stroke. A simple weight function would return the length of `AC`, but you could decide to give long strokes a smaller weight.

Finally, analyse the histogram. If you get most of the values around `histo[15]` and `histo[16]` it means the user did a straight line. If they are around `histo[13]` it means a large counterclockwise circle arc, `histo[18]` means a clockwise circle, `histo[11]` means a smaller circle, anything below `histo[8]` or above `histo[24]` means there was a brutal change in direction...
> 4 votes

# Answer
For the curve or straight line problem, I think I'd keep a list of the positions of old input. Then, I'd check the slope between every point (delta Y / delta X). If the slope does not change a lot, then it's probably a line. If it varies a lot, it's probably a curve. You could use a limit representing the slope difference that determines if the input is a line or a curve.

So, if I had to implement such a functionality, I think I'd go like this:

```
List<Vector2> inputPositions = new List<Vector2>();//the old input positions

```

then I'd find the slopes between every position:

```
float deltaY = 0f;
float deltaX = 0f;
List<float> slopes = new List<float>();
for (int i = 0; i < inputPositions.Count - 1; ++i)//check all the positions except the last one
{
    deltaY = inputPositions[i + 1].Y - inputPositions[i].Y;//next pos.Y - current.Y
    deltaX = inputPositions[i + 1].X - inputPositions[i].X;//next pos.X - current.X

    if (deltaX != 0.0f)//prevent division by 0
    {
        slopes.Add(deltaY / deltaX);
    }
    else
    {
        //I'm not really sure about using these values, but basically it
        //means that the movement was vertical
        slopes.Add(deltaY > 0.0f ? float.MaxValue : float.MinValue);
    }
}

```

then you can analyse the results to see if the slope difference was too huge.

```
bool IsLine(List<float> slopes)
{
    const float IS_NOT_LINE_SLOPE_DIFF = 0.05f;//find an appropriate constant for your program

    float slopeVariation = 0f;
    for (int i = 0; i < slopes.Count - 1; ++i)//check all but the last element
    {
        slopeVariation = slopes[i] - slopes[i + 1];
        if (Math.Abs(slopeVariation) >= IS_NOT_LINE_SLOPE_DIFF)
             return false;
    }

    return true;
}

```

You could even get the median of the slope variations to get a more general result.

Sure, this isn't the cleanest and certainly not the best way to solve your problem, but that's the way I would go to do it.
> 3 votes

---
Tags: xna, mathematics, algorithm, touch
---


title: Create shadow for SkinnedEffect model

text:
# Question
Title: Create shadow for SkinnedEffect model
I've followed a tutorial that uses the XNA 4 SkinnedEffect for my animation on that model . How can i also make a shadow for my SkinnedEffect model ?

Thanks !

# Answer
Shadows can be a thorny subject. There are many ways to create shadows in games, broadly split in to 3 techniques: Stencil shadows Texture space shadow maps/light maps Shadow buffers

Stencil shadows give hard, sharp shadow edges and use the stencil buffer and geometry extruded from every triangle (or the silhouette edges, if you can find it quick enough) of a mesh. http://www.gamedev.net/page/resources/\_//183/403/the-theory-of-stencil-shadow-volumes-r1873 here's a good page describing the technique in more detail.

Texture space shadow maps or light maps are typically created off-line and stored as a static texture. Generally speaking, these are not dynamic although there are some interesting techniques that can generate light maps in real-time.

Finally, real-time shadow buffers are the most commonly used techniques. These methods all render the scene again in an off-screen buffer from the light's point of view, storing depth values instead of colours. This is called the 'shadow buffer'.

When rendering the scene from the camera's point of view, every pixel is reverse transformed (in your shader code) into the shadow buffer's space and checked to see if the depth of the pixel being written is deeper than the depth stored in the shadow buffer. So far, so good. It gets more complicated when you realise that there isn't enough resolution in the shadow buffer to give good shadows in most cases. There are many techniques to try and increase the effective resolution of your shadow buffer. These are either view space distortion techniques (Perspective, Light space perspective, Trapezoidal) or multi-shadow buffer techniques such as cascaded shadow maps http://msdn.microsoft.com/en-us/library/ee416307%28v=vs.85%29.aspx

From bitter, bitter experience, I would avoid distortion techniques -they just don't work for all situations and introduce nasty biasing problems when sampling from the shadow map. You will spend months trying to sort out the fiddly edge cases whilst your boss (if you have one) becomes ever less patient. Use cascaded or split buffer shadow maps where the view frustum is split into smaller chunks which have their own shadow map. Then use simple bounding volumes to zoom in on shadow casters and receivers. This is the technique that 90% of games I see use.

Good luck, the devil is in the details but there's lots of help out there. Hopefully this will give you the pointers you need.
> 5 votes

---
Tags: xna, xna-4.0, shadows
---


# Question
Title: Are there any Java based libraries that provide game mapping features?
I'm working on a Java web based game in my spare time (springMVC / JSPs etc), and I'm wondering what are my options for dealing with the "game world" or mapping element.

My game will be 2d / text based, so I have no need for any OpenGL / Flash etc.

My initial idea was to use Google maps and provide a custom overlay, but I want to know if there are any alternatives?

For example, if I create a 2d map with all my zones, are there any libraries that will help me plot players, work out distances and so forth?

Regards

# Answer
I'm not sure if this is what you're looking for but heres a 2d map editor built in java available for free http://www.mapeditor.org/
> 1 votes

---
Tags: java, maps
---


# Question
Title: Current state of the art for holographic displays?
In another thread I was asking about independent arcade system development, and partly it was because I'm interested in using available 3D holographic technology for the displays.

I saw one which involved a rotating mirror at very high speeds, so that's probably not going to be too feasible (I'd hate to think of what happens when something goes wrong).

However, I looked around for videos from trade shows, and I found this:

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

But information is scarce, and I'm led to believe it's just using mirrors and reflections, and does not convey true 3D depth like the one using rotating mirrors at high speed:

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

So yeah, does anyone know if there's something better available today?

# Answer
> 1 votes
Feel free to ignore the hyperbolic commentary. This is a new display technology that uses lasers to ignite the very air into a little ball of plasma, creating an amazing dot matrix free floating 3D display. http://www.youtube.com/watch?v=KfVS-npfVuY

---
Tags: hardware
---


# Question
Title: How should I configure firewall for online game server?
I'm complete newbie on game server work. As I know, online (massively multiplay) game server should keep some TCP or UDP connection from the user. As I (=newbie) guess, maybe huge count of socket port should be opened. So how should I configure firewall for game server? Or should I use some other special method to security? Any advise will be appreciated.

# Answer
From the way your question is worded, I get the impression that you think there needs to be one incoming port per player connection; this is not at all the case. Each client connects to one public port, whichever that port may be, and all communication comes in through that single listening port, even if there are thousands of players.

There can of course be several ports open, but the main point is that each port can handle more than one simultaneous connection to or from it, so you need only open ports on your firewall corresponding to any ports that the game server listens on; this may be one or a few, but it should not be thousands of ports.

On a low level, a "port" is just a number tacked onto a packet. The firewall can read it and drop the packet if it's out of your specified ranges, and the operating system obviously obeys it and hands the packet to the application listening for that port, but the network system doesn't care if two or more people send and receive packets over the same port. They're just packets, they don't somehow "collide" if they are of the same port.
> 6 votes

# Answer
In terms of configuring your firewall for maximum security: block EVERYTHING except that which you absolutely cannot live without.

In his post @Ricket makes several great points , I'd like to add a bit more background for you. You mention TCP and UDP "Connections" -- TCP has connections and has handshakes built into the protocol, UDP does not. For both protocols, a port must be "allowed" and an application must be listening on that port. Think of an IP address like a physical address, and think of the port as the apartment number -- take a web server for example, it has an IP address and listens on TCP port 80, even though the website can be viewed by hundreds or thousands of clients they all send their requests to "port 80" and the operating system sends those to the web server which is listening on that port.

The reason some games use both UDP and TCP is because in-game, there are a variety of services being communicated with from client --\> server and also server --\> client.

**GameState** is a great candidate for a UDP type of transmission, because speed is more important than getting every packet in order, loss of packets is made up for by client-side prediction.

**In-Game-Chat** is a great candidate for TCP, since performance is not critical, and order of data is important.

So a game might use UDP 5678 for GameState transfer, and might use TCP 5679 for chat -- in this case, you'd add these two (and only these two) exceptions in the firewall.
> 3 votes

# Answer
For maximum security when configuring the firewall you want to leave open any ports that people will need to play the game, and close all others. You may also want to allow ping (ICMP) through.

At the very least this will mean blocking the first 1024 ports.

That should leave the only security issues that can be remotely exploited to be those in the game server itself, so that will need to be coded with security in mind.

http://en.wikipedia.org/wiki/List\_of\_TCP\_and\_UDP\_port\_numbers
> 1 votes

---
Tags: server, security
---


title: Frenet frame and application

text:
# Question
Title: Frenet frame and application
I have just been reviewing Frenet Frame math. It is an interesting geometrical issue.

I know that common applications are:

* camera movement along a curve
* tube and ribbons surface

Can someone suggest other interesting applications?

# Answer
Very interesting. Roller Coaster rides is what came to my mind. You can manipulate a 3D object riding a path in three dimensions.
> 1 votes

---
Tags: mathematics, geometry
---


title: Drawing territories border in 2d map

text:
# Question
Title: Drawing territories border in 2d map
I'm programming a little web strategy game. In the country map I pretend to display each country with a national color. The issue is how to render the borders in a simple and efficient way. Right now I'm planning to set a field to each tile called "border" with values from 0 to 8. The algorithm would check for EVERY tile is its adjacent has a different "owner". If the tile is inside the territory, the border value would be 0, because would not have adjacent any tile with different owner, if not, would vary between 1 (north) clockwise to 9 (north-west) and then draw the border.

I find this simple but too processor-intensive. Are there any other "pro" choices to render territories borders?

# Answer
> I'm programming a little web strategy game.

Computing which edges to draw where and storing that info rather than finding out during drawing by looking at neighbouring cells is a good strategy.

Remember, a cell can likely have borders on many sides, so use bitwise operators to store all the adjacency information in a single integer.

> I find this simple but too processor-intensive.

What are you using? HTML tables? A canvas?

If HTML5 canvas, the key is to use fillRect instead of paths for the edges.

Finally, ensure you are doing partial updates - drawing only those cells that have changed ownership or other state, and those adjacent to them, rather than redrawing the whole map for each update.
> 5 votes

# Answer
In your map, why not just have an attribute on each tile indicating if it is a border (and if so, what edge and what color)? The benefit is that it will use less processor cycles, the drawback is that you must know at design time where the borders are.

Unless you are procedurally generating your maps, this should be an easy thing to setup. Even if you are generating the map procedurally, you only need to run the processor intensive step of calculating borders one time, at design time, not every frame.

If knowing at design time is not an option, you could similarly add the attributes to your tiles; and only calculate them once, upon loading the map data. That doesn't resolve the processor intensive task, but it does keep it to a minimum.

In terms of the algorithm you are using, there may be more optimized way to do it, but if you can avoid making those optimizations by moving when/where the algorithm is run, I'd do that first.
> 0 votes

---
Tags: 2d, rendering, maps
---


title: Sprites are sometimes blurry in Flash

text:
# Question
Title: Sprites are sometimes blurry in Flash
I am playing around with drawing an SVG sprite (imported in through `[Embed]`). Depending on the coordinates of the image, sometimes it appears more crisp than others.

The following image shows how at different locations is it rendered differently:

(Image link \- You may have to download and zoom in with an image editor to see it)

You'll notice that the middle sprite is more blurry than the ones on the sides. Does anyone know why this is? Any help would be appreciated.

# Answer
> 2 votes
That's your sub pixel accuracy. It's a feature, rather than a bug but it's annoying in the wrong context. What's happening is that somewhere in the pipeline the x coordinates of your sprite are being rasterized to the screen a little off the pixel boundaries. This causes the flash renderer to interpolate between one pixel and the next, resulting in the blur you see. This actually aids animation as objects can smoothly transition from one pixel to the next but you don't want it here.

You can try two things - either look at the source svg and ensure that every coordinate is integer (i.e. no fractional part) or if that doesn't work, try offsetting everything by half a texel - that'll be 0.5 * the\_width\_of\_your\_drawing\_surface.

# Answer
> 4 votes
As Luther already wrote, it's how the flash renderer works. One thing that will guarantee pixel-accuracy is to turn your sprites into bitmaps and then set the pixelSnapping property to `PixelSnapping.ALWAYS`.

Or try `cacheAsBitmap = true` on your vector sprites (see here).

---
Tags: flash, rendering, sprites, blur
---


# Question
Title: Good book or tutorial for learning how to apply integration methods
I'm looking to animate a graph layout using edges as springs and nodes as weights (a node with more links will have a bigger weight).

I'm not capable of wrapping my head around the usage of mathematical and physics relations in my application.

As far as I've read, Runge Kutta 4 (preferably) or Verlet will be a good choice, but I have problems with understanding how they really work, and what physics equations I should apply.

If I can't understand them, I can't use them. I'm looking for a book or a tutorial which describes the things that I need.

# Answer
Here is an awesome introduction to the Runge Kutta 4 integration:

http://gafferongames.com/game-physics/integration-basics/

It starts with a brief introduction to the Euler integration basics (and why you shouldn't use it).

Moreover, there are more tutorials on this page about game-physics: How to fix your timestep, physics in 3D, spring physics, and networked physics

Hope it helps!
> 4 votes

---
Tags: 2d, graphics, physics
---


title: Creating the “game space” for a 2D game

text:
# Question
Title: Creating the “game space” for a 2D game
How does one setup the game space for a game so that obstacles can be spawned?

Examples would be ice climber or the iphone doodle jump. Tile maps are limited in size and would need to change often if the user jumps a lot.

How would this be done in another way than tile maps.

How or what is used to create the notion of a game world where these spawned ledges/obstacles are placed as the user progresses through the stage?

What is actually moving if the user jumps from ledge to ledge, what are the ledges based on in terms of the game world/space. What data structure or representation could the game use to reference and manage the spawning of these obstacles/ledges?

How is a continuous environment created which creates collision objects as the user progresses?

# Answer
As far as my experience goes, there are two ways to implement a world space.

note: *feature* means an object with which your player may collide with. A feature can be a wall, a monster, a bullet...

**Per unit of space** Usually the choice for 2D games. You make a grid out of your world, where each square (or triangle, hexagon, or whatever you wish) can be as large as a tile, down to a single pixel (or even less if you want). A value in the grid determines how to act when the player collides with a given location (commonly 0 for no-collision and 1 for collision). Collision detection is O(1), and memory usage is O(w\*h) where w and h are the width and height of your space respectively; regardless of whether or not there are features in it. Data structure is as simple as a 2-dimensional array.

**Per feature** Usually the choice for 3D games. You have a set of features, and collision detection is performed per-feature. There are interesting data structures, such as KD-trees, that help you determine which features are likely to be in a collision with the player, so you don't have to check it for every single object. Collision detection is non-trivial, and is O(n), for n features, and memory usage is O(n) as well. Data structure is a list, tree or dictionary that lets you do lookup by x,y,z location.

However, per-feature is also used in 2D (or pseudo 3D). Take for instance old shooters. Walls can be implemented as lists of line segments, which is a simple variant of the per-feature technique.

Dynamic feature placement is possible with both techniques. In the first technique, you simply modify your array during execution. Set an element in the grid from 0 to 1, and bam! you have a wall where you didn't before. In the second technique, just add a feature to your features list, and you're ready to go.
> 6 votes

---
Tags: collision-detection, parallax-scrolling
---


title: Frame Independent Movement

text:
# Question
Title: Frame Independent Movement
I've read two other threads here on movement: Time based movement Vs Frame rate based movement?, and When should I use a fixed or variable time step?

but I think I'm lacking a basic understanding of frame independent movement because I don't understand what either of those threads are talking about.

I'm following along with lazyfoo's SDL tutorials and came upon the frame independent lesson. http://lazyfoo.net/SDL\_tutorials/lesson32/index.php

I'm not sure what the movement part of the code is trying to say but I think it's this (please correct me if I'm wrong): In order to have frame independent movement, we need to find out how far an object (ex. sprite) moves within a certain time frame, for example 1 second. If the dot moves at 200 pixels per second, then I need to calculate how much it moves within that second by multiplying 200 pps by 1/1000 of a second.

Is that right? The lesson says:

"velocity in pixels per second * time since last frame in seconds. So if the program runs at 200 frames per second: 200 pps * 1/200 seconds = 1 pixel"

But...I thought we were multiplying 200 pps by 1/1000th of a second. What is this business with frames per second?

I'd appreciate if someone could give me a little bit more detailed explanation as to how frame independent movement works.

Thank you.

ADDITION:

```
SDL_Rect posRect;
posRect.x = 0;
posRect.y = 0;

float y, yVel;
y = 0;
yVel = 0;

Uint32 startTicks = SDL_GetTicks();

bool quit = false;
SDL_Event gEvent;

while ( quit == false )
{
    while ( SDL_PollEvent( &gEvent ) )
    {
        if ( gEvent.type == SDL_QUIT )
            quit = true;
    }

    if ( y <= 580 )
    {
        yVel += DOT_VEL;
        y += (yVel * (SDL_GetTicks() - startTicks)/1000.f);
        posRect.y = (int)y;
    }

    startTicks = SDL_GetTicks();
    SDL_BlitSurface( bg, NULL, screen, NULL );
    SDL_BlitSurface( dot, NULL, screen, &posRect );
    SDL_Flip( screen );
}

```

That's code that moves a dot down the screen. I think I have everything correct so far. It moves down the screen but there is a bit of an odd thing that happens that I can't explain. The dot is supposed to stay at the y=580 when it gets to greater than that y-value. However, every time I run the program, the dot will end up in a different location, meaning a little bit to a lot more than 580, so the dot is halfway or more than halfway off the screen (the dot is 20 pixels, screen dimensions 800x600). If I do something like click and hold the title-bar of the program, and then release, the dot disappears off the screen. How come it's variable each time? As for the titlebar problem I think it's because when I hold on to the titlebar, the timer is still running, and the time elapsed gets larger, resulting in a larger distance the dot moves in the next frame. Is that right?

# Answer
> 11 votes
NOTE: All fractions are meant to be floats.

Frame independent movement works by basing movement off of time. You get the amount of time that is spend since the last frame (so if there are 60 frames in one second, each frame takes 1.0/60.0 seconds, if all the frames took the same amount of time) and find out how much movement that translates into.

If you want your entity to move a certain amount of space for a specified unit of time (we will say 100 pixels for every second of time) then you can find out how many pixels you should move per frame by multiplying the amount of movement per second (100 pixels) by the amount of time passed in seconds (1.0/60.0) in order to figure out how much movement should take place in the current frame.

It works by figuring out how much movement you should perform per frame by using the amount of time elapsed and a speed that is defined with some unit of time (seconds or milliseconds are preferable). So your calculation might look like: `movementPerSecond * (timeElapsedInMilliseconds / 1000.0)`

I hope that made some kind of sense to you.

I want to move my guy 200 pixels to the right every second. If the current frame is run 50 milliseconds after the previous frame, then I should move my guy a fraction of the speed previously specified (which was 200 pixels). I should move him 50/1000th of the distance because only a 1/20th (50/1000 = 1/20) of time has passed. Therefore it would make sense to only move him 10 pixels (if 19 more frames occurred, 50 milliseconds apart from each other, then the total amount of movement in that second would be 200 pixels, the amount we wanted).

The way frame independent movement works is that frames usually occur at variable time steps (there is a different amount of time that takes place between subsequent frames). If we constantly move an entity a constant distance every frame, then the movement is based on the frame rate. If there is a lot of time between frames, the game will seem to move too slow and if there is not a lot of time between frames, the game will seem to be going to fast. (too little time between frames = a lot of frames = more movement) To overcome this, we use a speed in terms of time and keep track of the time between frames. That way we know how long it's been since we last updated the position and how much further we should move the entity. By using time we can eliminate the dependence on the frame rate and our game will look more or less the same on different frame rates.

Frames per second : This is the amount of frames that take place per second. Usually a frame rate is either how many times the game is drawn/rendered a second or how many times the game loop is completed a second.

Fixed Verse Variable Time Step : This refers to the amount of time between frames. Usually, the time between frames will not be constant. Certain systems/cores like physics will need some unit of time in order to simulate/run something. Usually, physics systems are more stable/scalable if the time step is fixed. The difference between fixed/variable time steps are in the names. Fixed time steps are what they sound like: time steps that occur at a fixed rate of time. Variable time steps are time steps that occur at varying/different rates of time.

# Answer
> 7 votes
In frame dynamics your code for (for instance) moving an entity would look like this:

```
x = x + speedPerFrame

```

If you want to be frame-independent, it could look like this:

```
x = x + speedPerSecond * secondsElapsedSinceLastFrame

```

# Answer
> 1 votes
Regarding the additional question.

Your point stops at different locations each time because you don't check for the boundary (y \> 580) when you move it. You only stop updating it further once its past 580.

On the last frame before you cross 580 you could be starting from 579 or you could be at 570 or you could be at 100. You also could be stepping 1 pixel forward or 1000, depending on how long the last frame took to execute.

Just change your IF condition to something like this and you should be fine.

```
if ( y <= 580 )
{
    yVel += DOT_VEL;
    y += (yVel * (SDL_GetTicks() - startTicks)/1000.f);
    if( y > 580 )
    {
        y = 580;
    }
    posRect.y = (int)y;
}

```

---
Tags: frame-rate
---


# Question
Title: How to procedurally (create) grow an artistic (2D) tree in real-time (L-System?)
Recently I programmed an L-system module, It got me interested further. I am a Plants vs Zombies junkie as well, really liked the concept of Tree of Wisdom. Would love to create similar procedural art just for fun and learn more.

Question: How should I approach the process of creating an artistic tree (2d perhaps with fixed camera/perspective) dynamically?

Ideally I would like to start with a plant (only a stem with a leaf) and grow it dynamically using some influence (input/user action) over its structure. These influences may result in different type of branching, curves in branches, its spread, location of fruits, color of flowers, etc. Want it to be really full of life/spirit. :)

Plants vs Zombies: Tree of wisdom It would be great to dynamically grow a similar tree, but with lot more variation and animations happening.

My Background: Programmer, have used few game engines (Ogre3d, cocos2d, unity). Haven't really programmed directly using openGL, trying to fix that :).

I am ready to spend considerable time, Please let me know about the APIs? and how would an expert like you would take on this problem?

Why 2D? I think it's easier to solve the problem only considering 2 dimensions.

Artistic inspirations:

Only the tree, with fruits and leaves, without the shrubs at the bottom

The large tree (visible branches, green leaves, flowers, fruits, etc) on the left, behind monkey.

PixelJunk's Eden (Art style inspiration).

Procedurally Generated Apple Tree using Fractals

Please let me know if it was easy for you to understand the question, I may elaborate further.

I hope a discussion of various approach would be helpful for everyone. You guys are awesome.

# Answer
Do take a look at ABOP (Algorithmic Beauty of Plants):

http://algorithmicbotany.org/papers/#abop

Its free online now, and has a very in-depth view of L-systems and plants.
> 11 votes

# Answer
Some ideas for your "game":

* Promt the user for a name for his tree first. Use that name to generate a seed for the algorithm. So every name will have it's unique tree. The seed could also influence the type of foliage and fruit of the tree.
* You could implement some sort of "tree tamagotchi" where the tree grows bigger and nicer the more the user cares about it (fertilize, water, etc.)
* Create a highscore list of the highest trees. Another idea would be to show heights and names of other users next to your tree. So you can compare your tree height directly to other users. See this video as an example. The clouds indicate the height other users have accomplished.

There are lots of algorithms and papers for procedural tree generation out there (this thread might be interesting). A difficult task is to nicely blend the branches. 2D is definitely going to be easier in that regard, since you can solve that with alpha-blending.

Since you're experienced with Ogre3D, Unitiy and cocos2d you can go right ahead and implement that thing (no need to start learning OpenGL now IMHO). Personally I'd choose cocos2d and release for iPad and/or iPhone, so that everybody can carry his tree around with his mobile device.
> 8 votes

# Answer
Context-Free and it's 3D counterpart StructureSynth could be an excellent basis or inspiration.

Examples:

etc...

These days you could write an online visualiser in WebGL!
> 5 votes

---
Tags: 2d, art, procedural-generation, procedural, tree
---


title: Can I release Kinect based games?

text:
# Question
Title: Can I release Kinect based games?
I've been reading up some hacks on Kinect development to work around the fact that there is no official SDK from Microsoft. Even if we do manage to create a game, can we distribute it through the XBox marketplace? Or will it cause any issues?

# Answer
No. Without official support they won't let you release it. The problem would be if they changed the way something worked (behind the scenes in their libraries) and you weren't going through official channels to access the Kinect, then it could break your Kinect support and it would make both of you look bad. Full blown (paid up development kit) game developers aren't allowed to access hardware by hacking around the official libraries for the same reasons. Hardware changes over time for cost-reduction and other reasons.

Have you managed to find hacks to get it working with XNA for the 360? I thought most of them were PC specific and non-portable. I can't imagine it'll be that long before they release an official SDK, they've already said the PC is getting one very soon, hopefully XNA support will follow closely.
> 5 votes

# Answer
Microsoft have plans to release the Kinect SDK for Windows for free this Spring (link). The point to notice here though is 'Windows'. That wording suggests to me that there'll be some additional fee to realease games onto the Indie Channel on the XBLA; though they might just absorb the charge into the current one for distributing a game to the service.
> 1 votes

---
Tags: xna, xbox, kinect
---


# Question
Title: How do I use depth testing and texture transparency together in my 2.5D world?
***Note:*** *I've already found an answer (which I will post after this question) - I was just wondering if I was doing it right, or if there is a better way.*

I'm making a "2.5D" isometric game using OpenGL ES (JOGL). By "2.5D", I mean that the world is 3D, but it is rendered using 2D isometric tiles.

The original problem I had to solve was that my textures had to be rendered in order (from back to front), so that the tiles overlapped properly to create the proper effect. After some reading, I quickly realised that this is the "old hat" 2D approach. This became difficult to do efficiently, since the 3D world can be modified by the player (so stuff can appear anywhere in 3D space) - so it seemed logical that I take advantage of the depth buffer. This meant that I didn't have to worry about rendering stuff in the correct order.

However, I faced a problem. If you use `GL_DEPTH_TEST` and `GL_BLEND` together, it creates an effect where objects are blended with the background before they are "sorted" by z order (meaning that you get a weird kind of overlap where the transparency should be).

Here's some pseudo code that should illustrate the problem (incidentally, I'm using libgdx for Android).

```
create() {
    // ...
    // some other code here
    // ...

    Gdx.gl.glEnable(GL10.GL_DEPTH_TEST);
    Gdx.gl.glEnable(GL10.GL_BLEND);
}

render() {
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    // ...
    // bind texture and create vertices
    // ...
}

```

So the question is: How do I solve the transparency overlap problem?

# Answer
*OK, so here's my solution (please comment if it can be done better)...*

Turns out that I should in fact be using alpha testing (though, I discovered this by accident, so I'm not entirely sure why it works).

```
create() {
    // ...
    // some other code here
    // ...

    Gdx.gl.glEnable(GL10.GL_DEPTH_TEST);
    Gdx.gl.glEnable(GL10.GL_ALPHA_TEST);
}

render() {
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    Gdx.gl10.glAlphaFunc(GL10.GL_GREATER, 0);

    // ...
    // bind texture and create vertices
    // ...
}

```

Note the use of `GL_ALPHA_TEST`, and `glAlphaFunc`.
> 7 votes

# Answer
Alpha testing is used to stop the renderer drawing pixels to any buffer, including the z buffer. Alpha blending is just a visual thing - values are still written to the zbuffer, which can result in problems like this - invisible pixels are infront of subsequently rendered pixels which means they'll fail the ztest when you draw the new pixels. This is what you can see in the image you gave, a ztest fail.

Switching off z writing will also achieve the same ends but you have to ensure you draw everything int back to front order. This should be easy enough to do in your isometric game.
> 2 votes

---
Tags: 2d, opengl, opengl-es, depth-buffer, blending
---


# Question
Title: Can one draw a cube using different method/drawing mode?
I've just started learning gamedev (in particular android EGL based) and have ran over a code from Pro Android Games 2 that looks as follows:

> /\* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. \*/
>
> package opengl.scenes.cubes;
>
> import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer;
>
> import javax.microedition.khronos.opengles.GL10;
>
> public class Cube {
>
> ```
> public Cube(){
>
>     int one = 0x10000;
>     int vertices[] = {
>             -one, -one, -one,
>             one, -one, -one,
>             one,  one, -one,
>             -one,  one, -one,
>             -one, -one,  one,
>             one, -one,  one,
>             one,  one,  one,
>             -one,  one,  one,
>     };
>
>     int colors[] = {
>             0,    0,    0,  one,
>             one,    0,    0,  one,
>             one,  one,    0,  one,
>             0,  one,    0,  one,
>             0,    0,  one,  one,
>             one,    0,  one,  one,
>             one,  one,  one,  one,
>             0,  one,  one,  one,
>     };
>
>     byte indices[] = {
>             0, 4, 5,    0, 5, 1,
>             1, 5, 6,    1, 6, 2,
>             2, 6, 7,    2, 7, 3,
>             3, 7, 4,    3, 4, 0,
>             4, 7, 6,    4, 6, 5,
>             3, 0, 1,    3, 1, 2
>     };
>
>     // Buffers to be passed to gl*Pointer() functions
>     // must be direct, i.e., they must be placed on the
>     // native heap where the garbage collector cannot vbb.asIntBuffer()
>     // move them.
>     //
>     // Buffers with multi-byte datatypes (e.g., short, int, float)
>     // must have their byte order set to native order
>
>     ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
>     vbb.order(ByteOrder.nativeOrder());
>     mVertexBuffer = vbb.asIntBuffer();
>     mVertexBuffer.put(vertices);
>     mVertexBuffer.position(0);
>
>     ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);
>     cbb.order(ByteOrder.nativeOrder());
>     mColorBuffer = cbb.asIntBuffer();
>     mColorBuffer.put(colors);
>     mColorBuffer.position(0);
>
>     mIndexBuffer = ByteBuffer.allocateDirect(indices.length);
>     mIndexBuffer.put(indices);
>     mIndexBuffer.position(0);
> }
>
> public void draw(GL10 gl)
> {
>     gl.glFrontFace(GL10.GL_CW);
>     gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer);
>     gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer);
>     gl.glDrawElements(GL10.GL_TRIANGLES, 36, GL10.GL_UNSIGNED_BYTE, mIndexBuffer);
> }
>
> private IntBuffer   mVertexBuffer;
> private IntBuffer   mColorBuffer;
> private ByteBuffer  mIndexBuffer;}
>
> ```

So it suggests to draw a cube using triangles. My question is: can I draw the same cube using GL\_TPOLYGON? If so, isn't that an easier/more understandable way to do things?

# Answer
It is indeed possible to draw polygons using OpenGL by passing GL\_POLYGON instead of GL\_TRIANGLES as the first parameter of glDrawElements(). Unfortunately, this is not supported in OpenGL ES, which is the subset of OpenGL that's available for your platform.

In addition to GL\_POLYGON, the GL\_QUADS and GL\_QUAD\_STRIP primitives are not supported either.

Fortunately, there's nothing you can do with quads that you can't do with triangles.
> 3 votes

# Answer
As mentioned in this thread: Why do game engines convert models to triangles compared to keeping it as four side polygon triangles are what we generally use.

If you want to work in quads, add some higher level code to add quads to an index buffer that then adds two triangles.
> 1 votes

---
Tags: 3d, java, android, opengl-es, cubemap
---


# Question
Title: Should I keep login server apart from game server?
I'm thinking of making a MMO server, and I've been looking at how other games structure their network. One of the things I've noticed is that there's always a Login server and then the game server(s).

I'm still deciding if I should do this, but I would like to hear some opinions first. What are the advantages of this, and how does the login server communicates with game server to handle logins?

# Answer
I believe this is mostly caused by the fact that login and game handling are logically more or less independent, so they're typically kept separate for better decoupling, easier maintenance and scalability. They needn't necessarily reside on different physical servers, they can run just as well as independent services on the same machine. If the traffic grows too large, the login server can easily be moved to another machine.

Also, login servers are a likely attack vector so it's good to have them separate from a security point of view.

Internally, different server-side services can use regular sockets to communicate with each other, be they on the same machine or on another machine in the cluster. Alternatively, a database server could be used to maintain an 'is logged in' flag for each user.
> 15 votes

# Answer
One very important aspect in MMOs development is achieving scalability and allowing for load balancing.

Authentication users by checking credentials, ban status, counting recent failed logins, etc. is a task that can be done without knowing anything of the game logic or game data. So it is very easy to move that to its own server cluster.

Furthermore the login servers are a well known "entrance" for the client to contact. After successful authentication they can dispatch the client to the appropriate server in the game server cluster. This dispatching can be done by forwarding the network connection to the right game server or telling the client to open a new connection to a right game server.

You should think about cuts of your system for distribution early on. It is very easy to run several pieces on one server. But it is quite difficult to split things that have been developed as one unit.
> 10 votes

# Answer
As a former WoW player, my experience was that the login server was always the weakest link in the chain.

The world servers were usually impressively stable, even handling exceptional load (e.g. new expansion pack releases) quite well.

But the login server(s) just never seemed to cope so well, and would frequently be down whilst the world servers were fine. (meaning that if you lose connection in a raid/dungeon, you can't get back in, but the other players are waiting for you!)

And now that the WoW login system is merged into Battle.Net, Starcraft 2 can become unavailable when WoW is under heavy load (as happened for a couple of hours when Cataclysm launched)

So if you're building a game that will have very large numbers of users, scalability and performance of the login system is very important, too.
> 3 votes

---
Tags: mmo, networking, server, scalability
---


# Question
Title: How do you test xbox (via PC) input without an xbox on XNA Game Studio?
Is it safe to just hookup a wired Xbox controller to my PC via USB? Do I need to buy a special PC Xbox controller? I've read conflicting reports. Any help is appreciated.

# Answer
You can use an Xbox wired controller, or you can pick up the wireless receiver which plugs into your USB port and lets you use the wireless controllers with windows.

Here is a link to the wireless receiver.
> 8 votes

# Answer
Any wired Xbox 360 will work when plugged in to a computers USB slot. Windows XP SP 3, Vista, and 7 will automatically install the drivers for you.

There are some wired controllers that specifically say "For PC" on them, but other than the packaging they are identically.

It is a standard USB device, and you will not hurt the controller, or a computer you plug it into.
> 2 votes

---
Tags: xna, input, xbox, controllers
---


# Question
Title: Broad topics needed for teaching game development
I am going to be doing a presentation on game development to an iPhone user group in the near(ish) future. My audience are iPhone developers, but not necessarily very experienced ones, and this is meant to be an introduction.

My question is, what broad topics are needed to understand game development? I acknowledge that this is fairly subjective, but I really am hoping for a comprehensive list of high-level topics that apply to a broad enough swath of games that anyone interested in the topic SHOULD know about them. I would be ecstatic with some pointers to any resources that attempt to make a list such as this this. (I have looked, but my google-fu is failing me tonight.)

Here's what I have so far:

* The Game Loop
    + a sub-note about event driven games
* 2D Animation
    + sprites/texture maps
* 3D Animation
    + importance of frameworks
    + modeling software
* Particles and particle effects
* hit detection
* AI

Obviously I will not be covering all these topics with any depth, more like simply defining them so that after my talk, the audience will (hopefully) be able to wrap their heads around how any given game might be developed.

What am I missing?

# Answer
> 4 votes
It really depends on your target audience and what you want them to learn or take-away from the presentation, but I'd consider these:

* Asset pipeline
    + command line tools vs plugins
* Audio
* Profiles / saves
    + autosave vs slots
* Physics
* Network play
    + online play
    + leaderboards
* Source control
    + importance of being able to roll back
* Input
    + polled vs event
    + handling available input methods between devices
* Degradation vs denial
    + handling graphical differences between devices
* Testing

Possibly also:

* Legal issues (music / name clashes)
* When to make the choice to not support a device

---
Tags: architecture
---