text:
Optimising the modelview transformation in GLSL for 2D
So, the standard way to transform vertices and then pass to the fragment shader in GLSL is something like this:
uniform mat4 u_modelview;
attribute vec4 a_position;

void main() {
    gl_Position = u_modelview * a_position;
}

However, I am working in 2D so there is redundancy in the 4x4 matrix. Would it be more efficient for me to do this?
uniform mat3 u_modelview;
attribute vec3 a_position;

void main() {
    gl_Position = vec4(u_modelview * a_position, 1.0);
}

gl_Position requires a 4 component vector so an extra operation is required at output. However the matrix multiplication is for 9 elements instead of 16. Can I do any better?

I think that this question was really valid because it prevents people (like me) from making the exact same performance mistake.

This is correct way how to save few bits. As it is correct it is also little bit useless. GPU is highly optimized for 3D algebra and can do matrix-vector multiplication pretty fast. Same fast in 2D or 3D. This would be slightly faster on CPU, but not on GPU.
But it is ok and smart also. Just try to keep your eye on real problems like correct memory usage (textures, vertex buffers) and algorithms. Not on "micro optimizations".
And no, you can't make it better.

The GPU in an Xbox 360 is 240 billion flops, and it's a joke compared to modern desktop GPUs. You're not going to make any significant difference at all by spending 7 less flops in a shader. This is especially true if the GPU implements SIMD for 4 floats, which it almost certainly will because 4x4 matrices are by far and away the most common, which would make it nothing. This is not the right place to be spending time looking for optimizations.


text:
OpenGL ES 1.1 strange slow drawing by zooming on iPhone
I have created a view (derived from UIScrollView) where the cells are drawn and zoom occurs. Everything is drawn with OpenGL ES 1.1. Zoom is specified by adding of a calculated new distance which is passed by fingers (sliding apart or moving together), which is multiplied by a constant coefficient:
fNewZoom += fDistance * fCoef;

fDistance may have negative value at minimization
There are 4 arrays of cells, each array contains cells with definite size. At zooming the most optimal cells by size are chosen for drawing and are drawn with the OpenGL ES 1.1. The initialization of all four textures takes place at the start while initialization of the drawing view.
Initialization of the view:
+ (Class) layerClass
{
    return [CAEAGLLayer class];
}

- (id)initWithCoder:(NSCoder*)coder
{
    if((self = [super initWithCoder:coder]))
    {
        CAEAGLLayer *eaglLayer = (CAEAGLLayer*) self.layer;

        eaglLayer.opaque = NO;
        eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                        [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];

        m_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
        if(!m_context || ![EAGLContext setCurrentContext:m_context] || ![self createFramebuffer])
        {
            [self release];
            return nil;
        }

        [self InitGLTextures];
    }

    return self;
}

Drawing specifically in function "- (void)drawView":

- (void)layoutSubviews
{
    [self InvalidateView];
}

- (void)InvalidateView
{
    [EAGLContext setCurrentContext:m_context];
    [self destroyFramebuffer];
    [self createFramebuffer];
    [self drawView];             //drawing view
}

- (BOOL)createFramebuffer
{
    glGenFramebuffersOES(1, &m_viewFramebuffer);
    glGenRenderbuffersOES(1, &m_viewRenderbuffer);

    glBindFramebufferOES(GL_FRAMEBUFFER_OES, m_viewFramebuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, m_viewRenderbuffer);
    [m_context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(id<EAGLDrawable>)self.layer];
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, m_viewRenderbuffer);

    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &m_nBackingWidth);
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &m_nBackingHeight);

    if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES)
    {
        NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
        return NO;
    }

    return YES;
}

- (void)destroyFramebuffer
{
    glDeleteFramebuffersOES(1, &m_viewFramebuffer);
    m_viewFramebuffer = nil;
    glDeleteRenderbuffersOES(1, &m_viewRenderbuffer);
    m_viewRenderbuffer = nil;
}

//TEST DRAWING VIEW !!!!
- (void)drawView
{
    const int       nClues = 3; // = 900
    const ImgElDimensionsF  cellDimensions = _skinMgr.GetCellInfo();
    const CGPoint       offset = [self contentOffset];

    float   fDrawX = 0;
    float   fDrawY = 0;
    int nCount1 = 1;

    [self BeginDrawing];
    //
    for (int nRow = 0; nRow < nClues; nRow++)
    {
        for (int nColl = 0; nColl < nClues; nColl++)
        {
            [self AddNewCellType:imgCellTypeSelectedEmpty PosX:fDrawX PosY:fDrawY];
            fDrawX += cellDimensions.fWidth;
        }

        fDrawX = 0;
        fDrawY += cellDimensions.fHeight;
    }
    //
    [self EndDrawing];
}

functions used for drawing:
- (void)BeginDrawing
{
    m_pCellTextureArr = _skinMgr.GL_GetProperlyCellTextInfo();

    glViewport(0, 0, m_nBackingWidth, m_nBackingHeight);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrthof(0.0f, (GLfloat)m_nBackingWidth, 0.0f, (GLfloat)m_nBackingHeight, 0.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    // Clears the view with black
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    // Make sure that you are drawing to the current context
    [EAGLContext setCurrentContext:m_context];
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, m_viewFramebuffer);
    glClear(GL_COLOR_BUFFER_BIT);
    //correct matrix pos
    glTranslatef(0, (CGFloat)m_nBackingHeight, 0);

}

- (void)EndDrawing
{
    ImgSize curImgSize = _skinMgr.GetCurrentImgSize();

    glBindTexture(GL_TEXTURE_2D, m_cellsTextureArr[curImgSize]);
    glEnable(GL_TEXTURE_2D);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);

    //if back cells was added
    if (m_nCurAddBackCell > 0)
    {
        glVertexPointer(2, GL_FLOAT, 0, m_spriteVerticesBack);
        glEnableClientState(GL_VERTEX_ARRAY);
        glTexCoordPointer(2, GL_FLOAT, 0, m_spriteTexcoordsBack);
        glEnable(GL_TEXTURE_2D);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glDrawArrays(GL_TRIANGLES, 0, POINTS_PER_CELL * m_nCurAddBackCell);
        glDisableClientState(GL_VERTEX_ARRAY);
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        //
        m_nCurAddBackCell = 0;
    }
}

With the help of this function the coordinate array of texture vertices for drawing is formed where m_spriteVerticesBack and m_spriteTexcoordsBack are dynamic arrays, seleсted by means of "new" function (m_spriteVerticesBack = new float[MAX_COUNT_CELLS * 12] )
- (BOOL)AddNewCellType:(ImgCellType)cellType PosX:(float)posX PosY:(float)posY
{
    ImgElDimensionsF    cellDimensions = _skinMgr.GL_GetCurrerntCellDimensions(cellType);
    ImgTextureInfoF     imgCellInfo = m_pCellTextureArr[cellType];

    if (m_nCurAddBackCell >= m_nMaxCountBackCell)
        return FALSE;

    const int idx = m_nCurAddBackCell * ELEMENTS_PER_CELL;
    //////////
    //*-------
    //|  3--4
    //|  |  |
    //|  1--2
    //*
    // 1X
    m_spriteVerticesBack[idx + 0] = posX;
    // 1Y
    m_spriteVerticesBack[idx + 1] =  -posY - cellDimensions.fHeight;
    // 2X
    m_spriteVerticesBack[idx + 2] = posX + cellDimensions.fWidth;
    // 3Y
    m_spriteVerticesBack[idx + 3] = -posY - cellDimensions.fHeight;
    // 3X
    m_spriteVerticesBack[idx + 4] = posX;
    // 3Y
    m_spriteVerticesBack[idx + 5] = -posY;
    // 2X
    m_spriteVerticesBack[idx + 6] = posX + cellDimensions.fWidth;
    // 3Y
    m_spriteVerticesBack[idx + 7] = -posY - cellDimensions.fHeight;
    // 3X
    m_spriteVerticesBack[idx + 8] = posX;
    // 3Y
    m_spriteVerticesBack[idx + 9] = -posY;
    // 4X
    m_spriteVerticesBack[idx + 10] = posX + cellDimensions.fWidth;
    // 4Y
    m_spriteVerticesBack[idx + 11] = -posY;

    //////////
    //1--2
    //|  |
    //3--4
    //
    // 1X
    m_spriteTexcoordsBack[idx + 0] = imgCellInfo.fX;
    // 1Y
    m_spriteTexcoordsBack[idx + 1] = imgCellInfo.fY + imgCellInfo.fHeight;
    // 2X
    m_spriteTexcoordsBack[idx + 2] = imgCellInfo.fX + imgCellInfo.fWidth;
    // 2Y
    m_spriteTexcoordsBack[idx + 3] = imgCellInfo.fY + imgCellInfo.fHeight;
    // 3X
    m_spriteTexcoordsBack[idx + 4] = imgCellInfo.fX;
    // 3Y
    m_spriteTexcoordsBack[idx + 5] = imgCellInfo.fY;
    // 2X
    m_spriteTexcoordsBack[idx + 6] = imgCellInfo.fX + imgCellInfo.fWidth;
    // 2Y
    m_spriteTexcoordsBack[idx + 7] = imgCellInfo.fY + imgCellInfo.fHeight;
    // 3X
    m_spriteTexcoordsBack[idx + 8] = imgCellInfo.fX;
    // 3Y
    m_spriteTexcoordsBack[idx + 9] = imgCellInfo.fY;
    // 4X
    m_spriteTexcoordsBack[idx + 10] = imgCellInfo.fX + imgCellInfo.fWidth;
    // 4Y
    m_spriteTexcoordsBack[idx + 11] = imgCellInfo.fY;
    //
    m_nCurAddBackCell++;
    return TRUE;
}

The problem is that indifferently how many cells I draw - 9 (field size 3 х 3) or 900 (field size 30 х 30), the speed of drawing at zoom on (iPhone 2G) is the same!!! What decelerates drawing? Drawing is performed like jerking. What was my mistake? What have I omited? I want the increment or minimization to become gradually, how can I achieve that?

Just as an FYI -- you should make your call to EAGLContext setCurrentContext: before any of your GL calls.  You are currently doing in the middle of your BeginDrawing method.  Also, if you are only using one EAGLContext for the app, you can simply set it once after it is created and never call it again as long as it remains valid.

One more FYI -- glBindFramebufferOES() only needs to be called once per context, so you shouldn't be calling it once per frame.

I don't see in your code where you are calling drawRect: (also related, you have it in your example as drawView: -- the method is drawRect:) explicitly, which leads me to believe that you are letting the OS call you when it thinks it is needed.  By default, UIViews will keep the contents of the backing CALayer in memory, so when the OS needs to scroll your view around, it simply blits the contents of the CALayer again instead of calling drawView:.  What you should be doing is calling setNeedsDisplay anytime you have determined that you need to zoom or change the contents.  This tells the OS that it should be call drawRect: at the next chance it gets.
Also, you should not extend UIScrollView for this.  You should extend UIView and then place that view inside of a UIScrollView.  That is how the API was intended to work.  You are basically mucking around the innards of the UIScrollView and replacing it's CALayer with a CAEAGLLayer, which is not what it is expecting.  Even if it works now, it may be broken with a future SDK release.
My recommendation for now would be to get it working properly without the UIScrollView, just to make sure you have everything in order.  Once you get that working, drop it back inside a UIScrollView and make sure it still works.

I'm going to go out on a limb and say that the problem might be related to your view deriving from UIScrollView that you're rendering into.  You should be handling scrolling yourself inside a stationary EAGLView.

Depending on what version of iOS he is running on, the UIScrollView probably isn't having an effect.  For simple scenes like this (looks like about 18 triangles), it's not going to matter.

I'm going to go out on a limb and say
  that the problem might be related to
  your view deriving from UIScrollView
  that you're rendering into.  You
  should be handling scrolling yourself
  inside a stationary EAGLView.

I have written earlier that the same situation appears when I use zoom in EAGLView which is derived from UIView (like is shown in many examples of iPhone Developer SDK documentation). Zoom speed is identical, it is very low and it does not depend on how many squares i draw, 9 or 900!!! So what can I do to make zoom bumpless and quick? Can you give any code example or any of such examples in the Internet?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Android collision detection of a 3d object based on a 2d projection
I am writing a game for android. We have an orthographic view setup, but the characters (ships, projectiles, etc). The enemies / characters will be able to rotate about the x axis. The problem is that I want to do the collision detection as if it were in 2d using sprites, meaning that if i have a ship with a top down view of
---------
--------------
-----------------
--------------
---------

it might rotate to look like
-----
--------------
---

and i want to do all of the collisions based off of the appearance of a top down view. I was originally thinking of using glReadPixels, until I read that was unbelievably slow. Then I was thinking about using pre-rendered bitmaps, but that seems like a pain and not very great since some of our ships won't be 'normal' enough to just say "Have a bitmap for every 45 degrees of rotation about the X". Does anyone have any suggestions?

How would you do it for normal sprites? Have you considered offscreen rendering of "collision map" every frame?

If you just did the collision in 3D this would be trivial, but I'm assuming you don't have a framework that's set up for that.

What Tetrad said, just do it the 3D way, there is nothing wrong with that.

Posting an answer in case anyone comes searching for this topic.
Since this is on Android, I believe the assumption is that CPU is scarce, and so the collision algorithms need to be cheap. Based on that assumption, we will construct a system and then discuss optimizations:
1) [Offline] Simplify the 3D models into a collision mesh. This is a very typical procedure in any 3D game, and is done in the Content Creation Pipeline.
2) [Offline] Calculate a bounding sphere for every 3D collision mesh.
3) [Run-time] Project the 3D bounding sphere of each object to a 2D bounding circle.
4) [Run-time] Do cheap, simple circle-circle collision checks.
5) [Conditional Run-time] If a circle-circle collision occurs, project the full 3D collision meshes for both objects into 2D. This is trivial if you know your Linear Algebra.
6) [Conditional Run-time] Now do 2D triangle mesh intersection tests. If this returns True, you have a 2D collision.
Steps 1 and 2 are cheap, because you do them offline or at startup.
Step 3 is fairly cheap. For extra speed, only re-project a sphere if its projected size will change. This depends on your Projection matrix. In a top-down view, for example, this will only occur if the camera changes height, the objects change height, or the camera zooms in/out.
Step 4 is dirt cheap. Calculate the distance between the objects:
float total_radius = a.bounding_radius + b.bounding_radius;
if(DotProduct(a.2D_position - b.2D_position) < total_radius*total_radius)
    // Possible Intersection Detected!

Step 5 may be expensive, depending on your collision mesh complexity, matrix library speed, and the Android device. Luckily its hidden behind the circle-circle test.
Step 5 can be optimized by caching the 3D projections. So, after you've projected a 3D model into 2D triangles, store that in the object's data. Only re-do that projection if the object has rotated, or moved closer/further to the camera.
Also, don't forget back-face culling!
Step 6 is, again, expensive, but hidden behind the circle-circle test. At the cost of intersection quality, you can simplify the triangle-triangle intersection test to ignore triangle-within-triangle tests. This depends on your game, but I think most games would be fine without that test.
Both step 5 and step 6 can be optimized by sacrificing collision quality with respect to time. While the game may be rendering at 30 or 60fps, you can perform collision checks at 10fps, or at a rate adjustable based on current rendering performance.
Other optimizations depend entirely on your specific game. Collision meshes can be made quite simple, and thanks to back-face culling your final mesh-mesh collision check shouldn't be too complex. You can even do bounding circle-circle intersection tests on the triangles to cull them further (i.e., if a triangle isn't inside the other object's bounding circle, don't test it).
The FPS optimization suggested above can be taken half-way. You can re-project 2D meshes at 10FPS, but do the mesh-mesh intersections at a full 30fps.

That's indeed the only way I was able to figure for our game Synchrom. Everything is done with Three.js
And indeed as exposed steps 5-6 are expensive with quite complexe meshes : / (around 10ms). So definitelly go for simplified models

I've since decided to go 2d, however, @ Tetrad and @Robert, there is something very wrong with that. The problem is that I want to do collisions based off of how it appeared to be in 2d. I would basically need to flatten all of my poly data so that it would lie on a single plane. In the simplest of terms, I needed to get rid of 1 dimension. If I have 2 ships that look like they collide, looking at them from above, I need to make sure they collide.
The overhead projection
      __________
______|_        |
|     | |       |
|     |_|_______|
|       |
|       |
---------

The same ships from a different perspective.
         _____________
_________ \           |
|        | |          |
|________| |          |
          /___________|

I want this to be a collision because it looks like it would be from a top down perspective. Bounding box collision detection would also not be sufficient in this case. The best I could come up with was rendering and using glReadPixels, but I heard that was unbearably slow.
Like I said, I've since decided to go 2d. I was only doing this in 3d so a friend who has a hard-on for OpenGL would work on this with me, but he bolted. Still, it's an interesting problem.
Thanks for your suggestions.

Why was this posted as an answer? It doesn't answer the question... it should be an edit of the question.

@bummzack The user is unregistered, and due to circumstances he has two separate accounts. So he is unable to edit his answer.

Well, you went with 2D eventually so this is purely theoretical at this point :) This is how I'd go about, as you put it, getting rid of one dimension :)
First, you need to project 3d mesh onto a 2d plane. I see two ways of doing that:

if your projection is exactly aligned with either angle you just ignore that coordinate
if it's not you can set up a projection matrix and use it to 'project to screen', ignoring the depth coordinate (this of course would work for the above case as well)

Then, you'd need to build a shape outline while going through all the faces. Working with faces allows you to have a concave outline by constructing a CSG sum of all projected triangles (this would be slow but then you'd be doing that on startu or it can even be preprocessed offline). If a convex outline would be OK then you need to build a convex hull. Last, optional step, would be to simplify the silhouette to make the collision detection faster.
Once you have your outline it's a simple matter of seeing if any of the edges intersect or one object is contained within the other.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/


text:
Took one major now want to be in different industryssT
How different is Programmer Analyst from Game Programmer?
I took the first one as my major but want to go with game development industry.
Is it possible to transition from one to another?
EDIT: There is a single class about game development in this major

What school are you going to with degrees like that?  I point you to my answer on a relevant question about eduction: http://gamedev.stackexchange.com/questions/1611/game-development-degree-vs-computer-science-degree/1612#1612

Unfortunately, job titles vary from company to company, so a "programmer/analyst" at one place might just be a fancy term for "programmer" while at another place it might involve the creation of software specs and design docs, and in another it might involve budgeting and scheduling. So "Programmer analyst" is vague - you really need to list your skill set.
That said, can one transition from "programming" to "game programming"? Sure. Game programming can be thought of as a superset of programming: it's standard programming stuff plus the game-specific stuff (realtime input, graphics, networking, etc.). So, you've already got a foundation.
Keep in mind:
The game industry is insanely competitive. About half of the people in your class probably got into programming in the first place because of an interest in video games. Finding someone to pay you to make games is going to be an uphill battle. Especially if you have no field experience as a programmer, just a degree. (Real-world experience counts for a lot.)
There's no rule that says you can't be a programmer by day and make games on your own time at night, as a hobby.
In either case, take the time to learn how to do game programming (i.e. make some games on your own to teach yourself these skills). If you don't want to because it's too intimidating or just not fun for you, what do you think it'll be like when you have to do this stuff every day because it's your job?
If you are determined to find a game programming job, there are a few paths from here:

Seek entry-level positions directly, right now. In the mean time, while you're waiting to hear back, bring yourself up to speed on game programming as best you can, and keep learning. If you are an outstanding, superstar programmer you might be able to pull this off; if not, realize you are competing against people who are, so it might take awhile.
Seek an entry-level position at a non-game software company. Get some experience. When you feel ready to leave, start looking for game industry work.
You can split the difference here: there are a fair number of "serious games" companies, gamification sites and similar companies that aren't "entertainment games" but are kinda sorta on the periphery and might be "close enough"... and the jobs there are usually less competitive.)
Find a new school that offers a game-programming-specific degree, either as a graduate degree or a second bachelor's. This will probably be expensive and is certainly no guarantee, but if you learn best in a classroom environment this might be a way to push yourself in that direction. Some of these programs also offer part-time classes so that you can go there while also keeping a day job to support yourself. WARNING: there are some good schools out there and a lot of bad ones, and mistakes are very costly in time and money here, so make sure you're getting the value you want before you start if you go this route.

"game-programming-specific degree",  I think attending to one of those school is really shooting yourself in the foot.  Many people in the industry see people coming out of those school as sub programmers.  And if you ever want to change to non-game programming that resume of yours is going to look kinda weird to the people reading it.  Especially if they are HR people with no technical knowledge of programming.


text:
What NPC gets attacked first when attacking an NPC party in an RPG?
Let's say I am in a battle with four trolls, and I have the highest initiative, so I attack first. Should I randomly choose a troll to attack? Proximity to each troll does not matter (it is not a factor in the algorithm). I remember playing an older RPG (I think one of the Final Fantasy games on N64), and the attacks appeared random. You might have one troll that never gets hit, or you might have one that always gets hit. Is there an acceptable standard?

What's wrong with letting the user select which one to attack?

Nothing. That is an option as well :)

There were no Final Fantasy games on the N64... but for the most part, most of the early Nintendo ones (outside of the first) resolved to random choice. Enemies didn't really have a row or priority system like the party had, so random choice just went to any old target.

It might have been Super Nintendo (that was so long ago :)... all I remember is my friend being so pissed that it appeared so random after he made an attack. That might be an indicator that if a player can choose, then that would make it more fun.

If you don't have a good reason for otherwise, then the player always chooses.

Let the players choose, its a game not a cutscene :)

-1 That's a gameplay design matter, that doesn't answer the OP's question, just tells him not to make a decision he probably has already thought of and concluded that it's best for his specific game. Maybe he needs some sort of an "aggressive" mode where the player character automatically attacks enemies in sight?

The biggest troll or the most dangerous one.

... which is true since RPG is the best game genre; all others are so unrealistic.

You could solve an equation to see which strategy is the best.
There are 4 trolls and they all are different. Each one does N damage per second and takes T time to kill. In said example you have 24 possible killing sequences (1-2-3-4, 1-2-4-3, 1-3-4-2, etc..) you can estimate/compute all of them in under 1ms and choose/suggest the best strategy for the player.
Of course it would be nice if player could choose any one he likes to be killed first instead :)

From a realistic-y type PoV:
The heroes aren't really going to know 'oh look, this troll is the most damaged' or 'this one is the largest threat' too much. Mostly since they'll be avoiding getting hit. They're going to attack whatever is closest to them. As such, I would say in  the situation like this (H for Hero, E for Enemy)

  E1

H1   E2
H2   E3
       E4 H3
  E5

H1 will go for E2, H2 for E3, H3 for E4.
The other option is totally random, or let the player choose. It's probably easiest to let the player choose to avoid 'whoops, accidentally didn't kill the boss who had 3hp left oh look I am dead'.

There are a bunch of different ways to solve this problem, as others have said. This ranges from a completely random choice to completely player chosen.
One game that has the style of semi-randomness that you were talking about was Ogre Battle 64. All attacks were done without player choice, but you could direct how you wanted your squad to act. The options were autonomous (pretty much completely random), target weakest (try to kill the enemy with the weakest health), target strongest (slowly weaken the opposing squad), or target leader (without a leader, the squad tries to run back to their base).
The kind of system you want depends on the kind of game you are making. The typical Final Fantasy game is not based around large scale strategy, but are more based on the individual tactics of a single fight; allowing for almost complete player choice tends to be the best bet for this style. In a squad based game, like Ogre Battle, you may want to make the player focus more on the strategy, such as where the squads are placed on the map, or which enemies to kill or weaken first.

Depends on how smart you want the decision to be, which is a gameplay design decision - do i want a fluid gameplay where your AI party members automatically pick the correct things to hit on the head so that the player can just do his thing and keep hacking and slashing without being interrupted, or do i want "dumb" party members so that the player has to use his head and make all strategical decisions (maybe even after pausing the game)?
In Dragon Age (might have been done before so don't kill me) for example they've let the player pre-script the behavior of his party members and tell them how to "automatically" make that decision (and others as well).
About the AI picking which one to start striking first - are they all identical and distance doesn't matter? In that case i don't see why not pick a random one. Otherwise some things to take into consideration are which one would be the fastest to kill (least armored, smallest health buffer, already damaged)? Which one deals the most damage? Which one has an ability to heal it's allies? Which one has misc abilities that might be a threat - such as temporary disabling your friendly characters and debuffing them. Based on those and other factors you should make some sort of a score system, you check which troll gets the highest score, and this one gets attacked first.


text:
Are there any implemented game controls like a screen (thumb) joystick? - iOS
I'm looking for some open source game controls.
Especially I'm looking for a thumb screen joystick to move a character on the screen, something like a touch circle.
Are there any open source implementation of what I'm looking for?

There's a button and virtual joystick implementation for cocos2d called "SneakyInput". Here's a tutorial that might help you use it.


text:
Do you think it's Possible to go from C++ Straight to 3D (skipping 2D)
Do you think it's possible to go straight from Experienced C++ programming (5 or so years) straight into learning DirectX 3d?
I mean....i'd be starting with the basics, im more interested in setting up Demos (like getting a good water demo and such) than actually doing a full fledged game.
Do you think this is possible?

Possible, yes. Easy? No way.

Absolutely it's possible.  A great starting point Introduction to 3D Game Programming with DirectX 10 by Frank D. Luna.  It is very easy to read, allows you to quickly implement a lot of common functions, and serves as a great base to learn more about DirectX and game programming.

Thats the exact book I was gonna start with lol.

Another +1 for that book, very good read. From there I would recommend books by Wolfgang F. Engel. his Shader X books especially have been very useful over the years.

This is an excellent book which I have also recommended.

Of course, though I recommend starting with a very, very simple 2D app since the initial learning curve (just getting a DX app running can be a chore) can be quite steep, and it's helpful to know whether the problems you're seeing are 3D-specific, or if you're just missing something very basic.
Implement Pong - you'll learn basics such as getting a DX app up and running, input processing, basic collision detection and, most importantly, how to draw stuff on the screen.
If it's your first app, it should take you less than a week to get that running. At that point, you should understand the basics of the DX framework, and be ready to start another project where you can focus on the 3D aspects - transformation matrices, object/state management, culling, lighting, etc. Maybe implement 3D pong, or racquetball.

Of course it's possible. It's also possible to learn C++ as your first programming language. But it's probably not the fastest way to get there.
Going from "programming" to "game programming" requires learning a few things regardless of graphics: game loops, realtime input, and so on. Those are MUCH easier to learn if you don't have to deal with learning a new graphics library at the same time. Learn one thing at a time and you'll probably have a much easier time of it. (And if you're an experienced programmer, learning the 2D stuff should really not take that long anyway.)

What does 2D have in common with 3D?  Not much.  2D is either a flat world or a faked 3D that, while having a visual appearance somewhat resembling 3D, has very different code from true 3D.
Even for the stuff that they have in common, such as collision detection, how hard is it to extend the code into 3D?  Pretty easy.
Simply put, learning 2D won't help you as much as you might think in your journey to learn 3D game or engine design.  They have little in common, and for what they do have in common, 2D isn't really an easy "stepping stone" to get you up to 3D.
As David Lively suggested, you might want to start out with a very basic 2D game such as Pong, but don't think that you'll have to recreate Final Fantasy, Super Mario Brothers, Zelda, etc. before you can move on to tackling 3D.  Even introductory work such as this is not for the purpose of acquiring lots of 2D experience, but rather for the purpose of making everything as simple as possible so that you can see basic concepts & methods (collision detection, getting the graphics library initialized, etc.,) which have as much to do with 3D as they do with 2D, as quickly as possible so that you can move on to the next step.  The next step might be creating a "New/Save/Load/Exit" menu, which you'll once again make as simple as possible, and then you just keep adding stuff (+1 dimension to movement, models, and collision detection, then jumping, anti-aliasing, mipmapping, shadows, reflections, particles, liquids, etc.) until there's nothing more to add, and then you go back and make it fancy, filling it with content.
Let's just put it this way, though.  After learning some theory in a college course about game design, we were tasked with making a 3D engine.  I made it in about a week.  It drew 3D objects, cast shadows, drew textures, did mipmapping, detected collisions, allowed you to jump, and brought up a menu if you right-clicked or hit {ENTER} or {ESC}.
The time-consuming part is making it fancy... whether it be fine-tuning the engine or making models/textures/animations, game content, etc.

Yes. Since you already know C++, now you just have to learn an API and theory.
The main hurdle in learning 3D specifically is probably the math involved. While 2D math is pretty easy to understand at a minimum level, 3D requires a more complex understanding. There's also a ton of stuff like shaders that are definitely more relevant to 3D as opposed to 2D. If you do plan on making a game though, I would take a quick 2D route just to get the feel for making a game from start to finish (and maybe get a working GUI system that you can port over!) before going into 3D.

IME, the biggest hurdle in learning a 3d api is getting to the point where you qctually have something to look at. I spent a bit of time trying to figure out why i couldn't see anything in early opengl; it's hard to debug a blank screen.


text:
Python Performance vs Game Maker
I was originally thinking of creating a game with Python and SFML. I understand Python is slow compared to C++, but how is it compared to Game Maker?
The main reason I ask is I recently played a Game Maker game (The Iconoclasts) which ran at a fairly bad frame-rate on my computer (GMA 950). I'm worried I would have similar performance issues with Python/SFML.

There's been massive developments in Game Maker that you may want to look into

To say "Python is slow compared to C++" is a generalization that ignores a lot of real-world practicalities and is usually a poor kind of judgement to rely on. What you really want to do is look at what a particular language or technology can bring to the table in terms of your needs and, similarly, evaluate any potential downfalls of that technology against your needs.
If you are having to ask this kind of a question, there is a very good chance that the limiting factor in terms of performance of any game you make will be you and not the technology choices themselves. Consequently the optimal choice is the one that empowers you the most, in other words, the technology or language you already know best.
As for the poor performance of the Game Maker game you played, that could be attributable to a number of factors, some of which are specific to that game, such as specific poor code that may have been written via Game Maker's tools or scripting languages. It isn't necessarily a fault of Game Maker itself.

@Nevermind, you can - google for sockpuppets. :) Just kidding - I'll add a vote for you. 5001 - cool, he can now vote on tag-wiki edits...

On a GMA 950 I wouldn't be at all surprised if the game was GPU bound rather than CPU bound.

If I had to guess the biggest reason that the game you played runs so slow is not that it's a game maker game, but that game maker markets itself specifically to non-programmers. Because you have non programmers making games it's highly likely that the game in question uses some very inefficient algorithms that cause it to run slow.
As in most cases, the speed of the language will only lightly affect the overall performance of the program. When people say "omg this language is 50% slower than this other language" and the speed is still stupid fast in both cases then you'll find little to no discernible difference to the end user.

Game Maker is a good beginner's tool. But I recommend moving upward to bigger and better programs if you have any previous programming experience. I used GameMaker for a college 2D game development course, it has a nice, easy to use drag and drop system. The problem, however, is that the program's drag and drop doesn't use the most efficient (or logical) commands. Plus the drag and drop doesn't support a lot of the advanced commands that the  program is capable of executing, so the programmer has to get creative with it, or learn to code. If you learn to use GameMaker code, however, then you would be able to get around that with relative ease.
But, it can be hard to learn a code for one single program with the busy schedules we all have, which is most likely why you experienced the slow performance.
But as Kort Pleco previously stated, most language speeds are not noticably different.. It all depends on how the code is written and executed. A lot of redundancies can make it considerably slower, which is normally due to a lack of experience in coding.

For the game I am working on, I use a diamond-square algorithm to randomly create terrain upon starting a new game.
To decide between using python with pygame for the project or GameMaker, I implemented the terrain generator in both. Pygame performed slightly faster, but the difference was negligible.
Ultimately I chose GameMaker as I can work much faster in it.

The accepted answer is dead on but I just wanted to add my 2 cents as a GM user for nearly 8 years.
GM did have many issues with optimizations so there is some legitimate concern. There are a group of deprecated methods *_variable_exists? that used to exist in Gamemaker pre-studio. Because of this convenience method it was leveraged in almost every imaginable library and extension that was written for GM.
Turns out these methods were horribly expensive and were causing major issue when running large scale games.
So there are many cases where GM can be really bad but with proper knowledge and careful use it is no less legitimate than any other method (unity2d,pygame,etc.). Just make games and have fun.


text:
For 2D tiled maps is all object and NPC data loaded into memory when the map is loaded?
I'm creating a text RPG in Java, but I think this applies for a GUI as well with regard to the data structure. Each Level is a tiled map. Each Tile object has an (X,Y) coordinate, and references to adjacent tiles, but my question is with regard to storing object and NPC data on that Tile object. Depending on the size of the map I'm loading, this seems like a lot to load, but if that is the commonly accepted practice then I'll go with it.

I'm not sure where the problem is that you're asking about. If you need the data, you have to load it. I would personally keep NPCs in a separate list, and track them separately from all the actual tile data. That's how I make these kinds of games.
Because you only need to draw the tiles on-screen; but entities (NPCs) may have collision logic, events, etc. and should always be tracked, regardless of their position.
If you're worried about performance, then I say, don't; just code it, and if problems arise, you have working code to profile and optimize.
Edit: The way that I would code it would be to have a 2D array of tiles; each tile has the XY coordinates of the image that it displays, a "walkable" attribute, etc. NPCs/entities would be kept in a separate list, and they would either hold a tile XY coordinates for the tile they're stepping on, or hold a reference to a Tile object with an X and Y.

When you say "keep them in a separate list", how do you store your reference between an NPC and a tile? For instance, a battle with a certain group of NPCs only occurs when a player enters a tile?

I'm guessing that this question is about managing large-scale maps with tons of stuff on them. In that case, I would keep one ADT with the tile data (tile image coordinates, walkable or not, etc.) and one with a list of all the NPCs. To give a C# reference, I would probably have a 2D array of some Tile class with ImageX, ImageY, etc. properties and a List of some sort of Entity/NPC class that would have Tile XY coordinates.

How do you store the reference between the Tile class and the NPCs in the Entity/NPC class? Is your tile coordinates your "key"?

I think I've used two approaches: the Entity has (TileX, TileY) coordinates, and (more recently) the Entity has a Tile reference, which in turn, has a (TileX, TileY) coordinate. As for the tiles, I would store them in an array, not a hashmap.


text:
UDK - problem packaging/publishing the game
I have set up all the config files to my game classes and am able to launch the game to test everything.
Although when I package the game, it still runs the UT deathmatch game?
What other lines in the config files should be changed to make it default to my game and default map once published/packaged?

It might help to show which configuration files you have already edited, and to what values.

This is documented here on the UDN:
http://udn.epicgames.com/Three/DevelopmentKitProgramming.html#Configuring,%20Compiling%20and%20Testing

You can also change the default game type to use when none is
  specified in UDKGame.ini in the [Engine.GameInfo] section. Change
  DefaultGame and DefaultServerGame to =MyMod.SuperFunGame. Make sure
  your gametype implements SetGameType() so it can prevent the gametype
  from being overridden.

I should mention there's a bit more info here:
http://udn.epicgames.com/Three/DevelopmentKitDeployment.html

To propagate this change or any other ini change into your packaged
  mod, you'll need to also modify the defaults in DefaultGame.ini.


text:
UDK - Packaging the Game
I have set up all the config files to my game classes and am able to launch the game to test everything.
Although when I package the game, it still runs the UT deathmatch game??
What other lines in the config files should be changed to make it default to my game and default map once published?


text:
What should "own" the battle state in combat between the player and NPCs?
I have a Map, a Tile, NPCs and the Player. When a player enters a tile in the map, a moveTo event is fired, which calls for any NPCs associated with that tile to be "activated". Those NPCs may be antagonists, and wish to start a battle. The battle state (rounds, initiative, alive/dead, add and removing combatants) seems like it should all belong to the Tile, but that seems too tightly coupled... maybe it should belong to the Map? Thoughts on that?

Battles are entirely separate things from any of the objects you mentioned. Yes, they take place on a Tile (and, naturally, within the Map), and happen between NPCs and the Player, but none of these object is the Battle.
I would suggest creating a new object, Battle, to maintain battle state. Hand it the participants and any terrain info it might need (e.g. maybe some NPCs/Players have bonuses on swamp Tiles, or maybe ranged attacks are penalized in forest Tiles), then encapsulate all your battle state logic within the Battle object.
Another approach I've seen (but that I don't like as much; YMMV) is to make the battle a method within either the Player or NPC objects. Hand this object the opponents (if you always only have one Player in a fight, put this method in the Player object and hand it the antagonistic NPCs; this gets really tricky to figure out, though, if you can have multiple participants on both sides), and then let it handle the battle state logic. This feels too tightly coupled to me, though, and personally I much prefer the battle logic living in its own Battle object. This also scales better if you add complexities like different tactics to your battle rules -- you can quickly find yourself maintaining a massive amount of code to represent your complex fights, and having that in its own separate object makes that a lot easier to manage.

I concur. I created a BatleManager object to manage the interaction between battles. This allows one-on-one battles (one player vs. one monster), but also can scale to complex battles (4 party members vs. 40 monsters).


text:
Realistic damage
I'm looking for a good way to simulate damage, for example a weapon firing at a ship it would calculate the damage depending on layer type, weapon type, angle and similar what i need is a way to to represent the damage to a certain layer. I'm thinking of using matrices for keeping track of damage and also the appearance of the model.
What the problem is for flat surfaces its not a problem but for curved surfaces calculating the angle, at least no way that i know of.
For example its a curved hull with 3 armor layers, so we have 4 matrices 3 for the integrity of the armor and a 4th for the height map there is also a density variable(increasing the armor matrix size and then assigning more values in the heightmap/location map to the coresponding layer surface.
Is there a better way to do this?

I'm sorry, I do not completely understand the question. Is your problem calculating the damage or showing the damage?

If your mesh is made of polygons, can't you just approximate the normal using the cross product of two edges in the polygon hit? Or are you doing something clever?

If you have the equation of the curve in question - or even just an approximation - then you can work out the tangent of the curve at the point where the projectile contacts it. You can then treat that tangent as if it was a flat surface that has been hit and work out the angle of incidence accordingly.


text:
Need help with rally point and spawning in StarCraft 2 map editor
I want to make a Tower Defense game using the StarCraft 2 editor.
How can I make a rally point to control AI appear at one point and go to specific point? How do I make creep spawn properly at specific times?

You need both Locations and periodic events for the functionality you've described. Using locations, you can create a trigger to order all enemy units in location A to move to location B.
Likewise, you can make another trigger to generate enemies in location A every x seconds (which can then be ordered by the first trigger to move towards the goal area).

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
What are the basics in game architecture? How do you create your game skeleton such that it doesn't stay in your way?
There must be some best practices on how you create your game architecture/skeleton.
One of the best resources that I found is:
http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
My primely focus is for iOS games using cocos2d.
What is your know how on this topic?

In addition to MVC pattern as the other reader suggested, I would suggest you learn a little bit about discrete event simulation - because your game engine heart is basically that.
In brief, that means:
Your game is described by a model. A model is composed of game objects. In a real time strategy, this would be terrain, units, static objects (trees), buildings, players, etc. As time progresses, the model is repeatedly changed.
Model your game elements as simulation entities which are scheduled to do actions at a given point in time. When selected at some point in time, each game element produces an action based on the current state of the game (the model). An action changes the game state, produces an event and schedules the game object that produced the action again at some time in the future.
You can also have triggers - whenever a matching event (that an action created) is detected, a trigger is triggered (e.g. an action that moves a player character around produces a MoveEvent which can be detected by a CharacterEnteredRegion trigger, that then does something with the game state again - for instance, creates more monsters).
I found this approach quite extensible and adaptable. In fact, it can be used both for real-time and turn-based games.

First off, study MVC architecture. I've done a lot of UI design and this has really helped me to understand these roles well.
If you can, explain your code to someone -- even if they don't understand what you're talking about. I explain things to my wife all the time, and even though she's probably not even listening, it helps to clarify things for me simply by organizing my thoughts into words.
Lastly, don't be afraid to rip the guts out of your code. If you find that something doesn't seem to work right, come up with a better way to do it and re-implement it, even if you have to tear half of it out to do so. A good revision management system can help here.

I worked in ASP.Net MVC for a period of time + other MVC frameworks. Is the Web MVC approach a similar one to Game MVC?
M = Ship Model, Enemy Model;
V = View Layer where that ship will be;
C = Handles User Inputs, Input Layer;
Does this looks right?

I'd say so. Just make sure that (1) the view works on nothing but the model and that (2) the controller affects nothing but the model. Also, if you have view-specific model (texture ID's, for example) try to keep them out of your base game objects (model).

Agreed, most game experiments I've had were based on the MVC.

I wouldn't say MVC is the most logical approach to game architecture by far.

MVC is not really used in game architectures. In fact, I've never met a professional game engine even remotely using MVC. I've encountered some MVP in production code, and then promptly helped gut it because it was holding back development. I'd encourage you to read this: http://www.amazon.com/Game-Engine-Architecture-Jason-Gregory/dp/1568814135 as a means of helping out


text:
How are profiling- and tracing -techniques used in Game Development?
I feel that in order to create realistic real-life games, game developers need some ways to monitor the system itself i.e. players' moves, other events and the state of the system itself. I know that creation of profiling/tracing -systems is not that easy, look how many people have tried to do better coverage -program in Python and fell far away from the original coverage.py.

I may be associating profiling/tracing wrongly to this game-development phase of dynamic monitoring but I am interested to know where/how profiling and tracing -techniques such as pythonic sys.settrace() are used in game development?
What is their purpose and what are the dynamic event monitoring systems really called? Game engines?
Are there some ready systems to advance/investigate profiling/tracing -areas in game development?

There are two kinds of data we can profile, at the high level:

We can profile the execution of the program itself -- what functions are called when and where, how long they take, and what impact they have on the environment (allocations, locks, threads spawned, et cetera).
We can profile what the user is actually doing with the program -- where they are in the game when they die, where they are when they earn the most experience, what they spend the most money on, which skills they use most often.

These aren't fundamentally different operations, really, although the type of data collected by each operation is pretty significant. The type of data collected by the first technique is generally reusable across many programs, whereas the second type of data tends to be more program/game specific (experience may not even exist in a particular game, for example).
You have the right terminology for this kind of technology -- "profiling," "tracing," "user monitoring" and such are all appropriate terms. The technology itself is fairly straightforward to implement as well. The most basic approach just involves instrumenting code by calling a function that collects the desired data. You can then write that data to a log file or (most usefully) send it to a database for later querying and report generation.
Code coverage, which you mention at one point, is a little more complex and difficult to get right (especially in more dynamic languages). It is more akin to the first technique, that is examining the state of your code rather than how users use your program.

in order to make this kind of systems, what kind of commands/privileges are a prerequisite? Suppose we have 99.99% CPU-consuming game using a huge amount of memory, a real bottleneck. To monitor such program sounds a challenge in itself, because the monitoring it may overheat the system. I am not sure but this problem may require zero 0 level privileges on some systems such as W.XP (maybe associating to unrelated topic, not sure) to prioritize the kill over the bottlenecked software's commands. So by which technique you can address this problem, not making monitoring a problem?

@hhh In order to discover the bottleneck in any game, simply reduce usage of a single system resource such as memory bandwidth, or texture bandwidth, or pixel shader usage, and if the framerate increases, you've found your bottleneck. Profiling tools that track the duration of time spent in various sections of code CPU side, only use 0.01% of the CPU anyway, so the problem you mention isn't really an issue.

For inline'd profiling I have always loved the code sample from GameDev Magazine's Aug04 edition.. Might be a bit dated by now but is a good piece of code to use and fiddle with. Anywho, can find all the code samples over the years at: http://www.gdmag.com/resources/code.htm (Also just neat to see how the topics have changed over a decade as well)


text:
For games that time stamp a saved game (think Half-Life), is the entire game state really being saved every time?
It seems to me if that were the case that your directory of saved binaries or serialized objects could get massive real quick. Is there some sort of strategy being employed on top of the State pattern that is optimizing each time stamped saved game so that it isn't saving the entire game "context" all the time?

What does the State pattern have to do with this? (Or, what do you think it would have to do with it?) There doesn't necessarily have to be a pattern involved at all.

Most saved game data from what I've researched is from an object in state (using the State pattern). The object maintains its state so that when it is saved it can be serialized without a lot of hassle. It was just an observation.

All games and objects have state, but that's very rarely using the State pattern as such. More often you just have write and read functions to save and restore whatever state the object has.

Remember that all you need to save is the dynamic data generated at runtime. For example, if you have a monster about to attack the player, you need to save its position, its monster type, and its aggressive state, but you don't need to save its textures, model, behavioural scripts, and so on, because they are part of the static state that can be inferred from the monster type.
As long as your system keeps a clear distinction between the dynamic properties of the game state and the static properties of the world, there is usually not all that much data to store.

I think you may be over estimating the size of that data and/or underestimating the size of what is saved. Taking a quick look, I see saves in my folder ranging from about 400kb to 3mb, with one outlier of 8.5mb
What can you fit in 400k? Well, to store the position and orientation of an object in 3d space you would probably use 24 bytes (32 bit floating point numbers for x, y, z, yaw, pitch, roll). That fits into 400k over 17,000 times. Obviously there is more to each object than that, but not much. Keep in mind that you are only storing dynamic objects for the level you are currently on, since you never move backwards to revisit old levels. If you think about it, there are probably no more than a couple hundred objects on each level, most of which are very simple, like physics objects or health/ammo pickups, which probably don't need anything more than the previously mentioned position/orientation and their type.
As example that I'm more intimately familiar with, a ~15mb file can hold all the data you need to recreate an hour of game play in Heroes of Newerth. The exact size/time varies depending on the particulars of the match, but what you have there is the initial state of the entire game, plus the changes between each frame and its previous frame. That is a complete game state (minus unchanged data) every 50 milliseconds!

One other aspect of game saving is that you really don't need to save anything that hasn't changed. Say you've got a room full of objects if the player enters the room but doesn't manipulate anything you don't need to bother saving the positions of those objects. So you when you're saving the game you could compare the object's default and current attributes and only save the delta. Obviously the comparisons would add complexity and overhead to the process but that's a typical CS trade off, storage or CPU.


text:
Game Maker not recognizing variable
Attempting to set up a targeting array for a MMO-style game in GameMaker8 Pro, I have this code in the create event for the player's character, which is and has been running perfectly fine:
j = 0
i = 0
g = 0
for (i=100000; i<1000000; i+=1) if instance_exists(i) {if i.object_index = enemy         {global.ttarget[j] = i j+=1}  if i.object_index = rk or i.object_index = sage    {global.etarget[g] = i g += 1}}
global.rmtargets = j
global.etargets = g

Then running this code in the step event for the player character:
h = 0
g = 0
i = 0
for (i=0; i<global.rmtargets; i+=1) global.target[i] = 0
global.target[0]=101139
for (h = 0; h<global.rmtargets; h+=1){hv = -1
for (g = 0; g<global.rmtargets; g+=1){if global.ttarget[g].range > hv {hv =    global.ttarget[g].range}}
global.target[h] = hv
global.ttarget[h] = -1}

Returns this error message:
ERROR in
action number 1
of  Step Event
for object rk:
Error in code at line 8: for (g = 0; g hv {hv = global.ttarget[g].range}}
at position 61: Unknown variable range
Even though I have this in the create event for the enemy:
range = 0
range = distance_to_object(rk)

And I've used this sort of syntax all over:
global.target[target].threat[s] += damage

Help? Any ideas why Game Maker won't recognize the variable?

for (i=100000; i<1000000; i+=1) if (instance_exists(i)) if (i.object_index == enemy) // ... is a bad way to iterate over all the instances of a type- just use with (enemy) // ...

I think the problem is that variable can not have "under variable", in GM is this possible even with the objects.

But looking at the last section of code I posted, I don't see why that can run but why it won't recognize the variable I'm having trouble with... Or is the threat accumulating syntax I posted not what you're calling an "under variable?"

The enemy at that point in the array has probably been destroyed. Instead of looping through an array full of potentially-gone instance ids, you should use with:
var hv;
hv = -1
with (enemy) {
    if (range > hv)
        hv = range
}

Replace the inner for loop of your step event with that and then you can create and destroy enemies all you like without worrying about updating the now-unnecessary array.


text:
XNA captures mouse clicks when the game doesn't have focus
If I alt-tab and do stuff outside of the game window, the game still captures mouse clicks (both left and right clicks).
The game doesn't "consume" the clicks, since they are also sent to the application that has the focus.
But it's rather annoying to hear a gunshot each time you click in your internet browser...
Also, the problem occurs even if the game is set to fullscreen.

The best solution I have found to this is to stop responding to input (and probably pause your game as well) if it goes inactive.
You can check Game.IsActive or hook the Activated and Deactivated events.
There is one minor drawback - I would just about consider this a bug in the framework - the game always starts in the Active state, even if the game isn't actually active when it starts running. (For example: you click to another window between launching your game and your game actually starting.)
You could work around this by checking what the active window is when your game starts, probably using GetForegroundWindow. Or you could just not worry about it - it occasionally happens as a developer, but I suspect it doesn't really affect end-users.


text:
What is Java missing that might make it difficult to develop fully-featured 2D games?
Without using any external libraries, does Java, including all officially supported APIs give you enough to develop fully-featured 2D games? The reason I ask is that I hear a lot of "bad-mouthing" about Java and game development, but I'm wondering if that is only in regard to intensive 3D games. Also reading up on some Java games there often appears to be external graphics or sound libraries involved that simply have a Java port. This makes me think it isn't possible.

What is wrong with external libraries?

Any language which can do any type of output can be used to make a 2D game... Console output and ASCII Art...

Can you clarify what kind of features you're looking for?

@AttackingHobo: It wasn't necessarily that there is anything wrong with libraries, but I know Java, and if I can stick to the core API for graphics and sound without having to learn an external API as well, then that is always a plus.

There are 2D java game libraries that would make your job much easier than coding it your self. I mean it is possible, but why waste 1000s of man hours that have been put into proven, fast 2D renderers.

In 2011 any language with bindings to OpenGL is more than capable of a "2D game" in the style of Nintendo from the 1990s or so, when running on a desktop PC made in this millennium.
For TV game consoles, the only language available for development across all platforms is C++, so that's what people use for the most complex 3D games and the simplest 2D games. Java would work for simpler games, but C++ is the compromise we live with to avoid the cost of supporting more than one language.
For handheld devices (and to a lesser extent TV game consoles) performance is critical often enough that the overhead imposed by Java et al. can't be tolerated for games with medium or high complexity.
Android phones do run games in Java, but there is a clear trend recently toward "native" C++ games on Android, not primarily for performance, but because ironically Java isn't as "platform-independent" as C++. All non-Android platforms use some kind of C/OpenGL, and porting a game among them is fairly cheap. Porting from any of them to Android/Java is relatively expensive.

Java overhead is nearly zero these days. It even performs dynamic casts faster than C++ because the type information is stored inside the object data header .

In theory, nothing.
In practice, mainly the fact that not a lot of people have done it already.  If you're looking for code samples or documentation you'll more likely find code written in C or C++ instead of Java.

There's nothing missing from Java that is required to make a fully featured 2d game.  There are definitely games written in Java that don't use external libraries, or, use them sparingly.  Most of the complaints people tend to make about Java are either the slowness of games vs C or C++ (valid, but computer speed is fast enough to make the point moot), or personal frustrations with Java (almost everyone has a language they like to hate...).  Java also has a reputation for being a 'business' programming language.
The only issues that might come up from using Java is hardware acceleration.  If Java's native graphics rendering is not hardware accelerated, then you'd be risking performance problems.  External libraries can often solve this problem.

These days, in many cases the standard graphic classess are backed up by hardware acceleration. So in this case, no JNI extensions are needed. Example is my 5 years old PC drawing a hardware accelerated instance of BufferedImage on the screen about 20 000 each iteration at 200 fps. Using JDK 7

Of course you can. But some boring stuff you have to do at your own.
I read a book, 'killer game programming in java', and there was no external library, just Java2D. I also developed an arcade game with it...
Java can be an engine IMO, but you should really prefer another engine, which is built on top of this stuff and OpenGL.
I am currently using libGDX for my android game and I am happy so far. With it you can develop simultaneously for android and PC ;)

Keep in mind you can write boring stuff in any language, and that a lot of exciting stuff "back in the day" got written in assembly language.

For modern high quality 2D graphics you'd often use 3D rendering, meaning you'd need a 3rd part 3D library for most languages anyway.
I think mostly for game development Java just doesn't do a lot that C++ or C# doesn't do, and it might be a little slower than C#.
A lot of people seem to have very strong opinions on what is good for what and what isn't, it's often a sign that they simply don't know what they are talking about.

"For modern high quality 2D graphics you'd almost always be using 3D rendering"
This makes no sense to me.  There are LOTS AND LOTS of 2D games that have nothing to do with 3D rendering or styles.

Of course there are still games that use pure 2D, mostly small stuff. 3D gives easy to use rotation and scaling, if you need just one of those features it's the easy and performing choice. What recent high graphics quality 2D games have been made using pure 2d?

Pokemon heart gold, soul silver, black and white are good examples of 2.5d games. Zenonia 2 (android) is an example for 2d games with good graphics.

". What recent high graphics quality 2D games have been made using pure 2d?" => vector graphics (ie mostly Flash, but also other Macromedia and non Macromedia products), see many experimental Flash games.

Flash is GPU accelerated these days, the Nintendo DS seems to be a platform where pure 2D still lives (does it even have hardware accelerated rotation and scaling?). Of course one could argue that the mobile 2D games does not meet the high quality graphics criterion, but that is a subjective argument. My point was mainly that for 2D games on desktop and consoles one should consider using 3D acceleration.


text:
Movie clip in a button changes on hover
I have a button for my game which has a MovieClip in it. It consists of an image of a lock and an image of an item, representing the item being locked and unlocked. I make the button become slightly smaller when the mouse is over it to create the effect of a button slightly down.
For some reason, however, this makes the MovieClip in the button go to the next frame. I have no Actionscript code in the button or any frame except stop() on the first frame of the MovieClip, so I really don't understand why this would happen. It only goes to the next frame when I hover my mouse over the button and then quickly goes back to the first frame (since there's no stop() in the second frame).
After experimenting with stop() in both frames of the movie clip, it does indeed only happen when my mouse enters the button. Leaving the button doesn't do anything and the button left alone doesn't do anything. It just changes the frame when I hover my cursor over it. There's absolutely no script involved aside from stop() in the first frame of the movie clip in the button. What could be the cause of this problem?

I wonder why you put a MovieClip with two frames inside a Button? From my experience the Flash Button is really broken and scripts won't work inside the button. So if you have a "locked" (frame 1) and "unlocked" (frame 2) image in your MovieClip, you won't be able to access the "unlocked" image, because using a script to get to frame 2 won't work properly in the first place.
Better create two separate Button instances, or script the MovieClip so that it works as a button directly (eg. scale it on mouse-over/mouse-out and use buttonMode and useHandCursor properties to control mouse-pointer behavior).

I wouldn't use a Button object. "Button" is simply a shortcut for some common button functionality like mouseover and click states; you can set mouse event listeners on any MovieClip. You probably also want to set buttonMode=true so that the mouse cursor will turn into the hand to indicate the user can click:
movieClip.addEventListener(MouseEvent.CLICK, onClick);
movieClip.buttonMode = true;

Try putting gotoAndStop(1) in the second frame of the movie clip


text:
How could an XNA game close with no exception being thrown?
I've been messing with my game's network code recently (TCP/UDP sockets) and my game keeps shutting down with no exceptions being thrown at all.
It runs fine until the disconnection of a client, so I already know that it has to be related to the network.
My real problem is that no exception is thrown and the game silently exits on both the client and server sides. How's that even possible? What could end the runtime of an XNA game?

+1 and added the debugging tag as those kind of skills will pay of for any developer.

I just found the answer to my problem:
The reason why the exception wouldn't show off is because it was actually thrown on a different thread. So removing my existing try/catch blocks in the main thread was of no help to show the exception. Adding a try/catch block to the Main method (to catch anything thrown in the entire application) wouldn't help either, since exceptions thrown on different threads don't fall in the catch blocks of the main thread.
My guess was correct: the problem came from the async TCP networking, which automatically generates and uses underlying threads. The exception was thrown whenever the client forcibly closed the TCP socket. Since the exception was on another thread, it silently forced the XNA runtime to stop.
This is the exception that was silently thrown and that stopped the runtime:
// Unable to read data from the transport connection: An existing connection was
// forcibly closed by the remote host.

// at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)

Update: Just to make it perfectly clear for anyone who might encounter this problem in the future, here's how to correct it.
This is the problematic code:
// runs on the main thread
private void ReadAsync()
{
    tcpClient.GetStream().BeginRead(buffer, 0, buffer.Length, readCallback, null);
}

// runs on an hidden underlying thread
// because of the asynchronous operation
private void OnRead(IAsyncResult result)
{
    // dangerous exception thrown here
    // which won't fall in the catch blocks of the main thread
    tcpClient.GetStream().EndRead(result);

    // process the received data
}

A simple try/catch block in the asynchronous thread will fix the problem:
private void OnRead(IAsyncResult result)
{
    try
    {
        // dangerous exception thrown here
        // which won't fall in the catch blocks of the main thread
        tcpClient.GetStream().EndRead(result);

        // process the received data
    }
    catch(Exception ex)
    {
        // handle the exception
    }
}

Naturally, this pitfall is not limited to TCP networking. You might encounter this problem for any type of .NET asynchronous operation and also in your own custom threads, so be sure to always put some try/catch blocks at these places!

How did you fix it?

From the block of code he just handled attempting to read data from a closed socket. Good find Asmo!

With out knowing more I can not give you more detailed information but here are some things to look for:
Look for critical failures you may be handling in your code silently that could cause this.. and do not rule out that that is what is happening in the XNA code. This could be anything that you would assume would never happen but put in for good code theory.
Areas to look for are where you are access the data of the other user. Maybe a system is still tracking the remote user on a Mini map that is no longer there or the like. Pretty much any sort of data that you are guaranteed is there when not dealing with remote players but might disappear when dealing with remote players.
I will update if you get more specifics.
Hope this helps.

But how could my code be silently handling a critical failure? I commented out all the try/catch blocks.

Are you using any 3rd party libraries?

Unfortunately with out more information I can not tell you how its doing it. If you can add in debugging output messages at key locations to see if it is hitting them on its way out it might help, but we really need more info to give you better answers... Sorry.

@Omnion I'm only using SharpZipLib. Everything else is .NET or XNA built-in. I tried commenting out everything related to SharpZipLib but the problem still occurs. So it must be something else...


text:
Is there a site where people discuss game concepts and questions in general?
I like making game concepts for fun, as a hobby. I don't think that all my game concepts are amazingly awesome and have to be created and would revolutionize the industry. I just want some people to talk to that have the same hobbies as I do. To be able to discuss ideas and point out the pros and cons.

A question this significant surely has more answers - or we game developers have failed to make a real contribution to our community. Take note, those of you who can do something about this: if this question ends up with no good answers, it's your job to do something about it and create a site which would make a spectacular answer. We do what we must because we can.

What are you implying, Jonathan? That the links posted are too few in quantity, or not of the right quality, or that you feel the industry is lacking in good game concepts, or... what?

I'm suggesting that the quantity of discussion is lacking, or this is an important question not receiving enough attention. At the time of posting the bounty, the answers amounted to two subforums and a chat room.

I don't entirely agree, but I've elaborated on this in an answer below.

Hobbyists, independent developers, and prospective developers discuss these things on this site, Gamedev.net, and various forums such as TigSource and Indiegamer. These are pretty much only the places where this sort of discussion happens.
By comparison, professionals tend to carry out their high-level discussion of game design in a similar way to much academia: they publish books, papers, articles, give conference talks, and post blog entries, which are then discussed and cross-referenced. There's no reason why you couldn't start your own blog about your ideas, but you'll have trouble getting any traffic, because the average person's game concept is not going to be of much interest to the wider community. This is why typically you'd go for the first route, of game development forums.
The reason there isn't anything more for this is partly because the professionals do a decent enough job of exchanging and discussing ideas, and partly because the ideas and concepts that a typical prospective developer comes up with are considered nearly worthless in the professional arena. (And as such, only of interest to one's peers on forums and the like.) This perception of worthlessness is because most professional game developers already have more of their own pet ideas than they have time to create (making ideas far too abundant for the average one to be worth much), and because the quality of a game is almost never intrinsic to the concept itself, meaning it can be almost useless in isolation without a full prototype or technical specification behind it - and usually the only people capable of making such a prototype or specification are already either in the industry, or are able to make the game themselves without presenting it to others.

There's a design board on the TIGSource forums. It seems pretty full and diverse.

There are game development communities on http://www.gamedev.net/ and http://www.indiegamer.com/

You might try the GDSE Chat Room.  It's occasionally pretty well-populated, and has proven to be a pretty good sounding-board.

GDNet also has a Game Design forum.

I have a website myself that I am using for game design discussion called Ascension Protocol. You can visit it at: http://www.ascensionprotocol.com, be sure to visit us on facebook as well!

Ascension Protocol seems to be about discussing your potential game and its design. It's an acceptable answer since it still seems to allow people to talk about MMO concepts in general (without necessarily having to discuss your game), but you should have frank and full disclosure or else it's effectively false advertising!


text:
Facebook Game Development - Where can I save my data?
I'd like to develop a small Facebook game with some graphics involved (not that many). Within that game, the users will be able to buy/sell certain items and I wonder WHERE I can save those items/virtual money...? Does Facebook offer me a database I can use?

Depending on what sort of game you are trying to make, you will need some place to put the actual game.
A Facebook App points to external websites for the canvas part of the application. This is your own webserver/webhotel and what ever language your webserver uses ought to provide you with some database connectivity.
So if you eg. use PHP on the server, MySQL might be the datasstorage.
If you have a IIS/ASP/ASP.net server available, SQL-Express could be your answer. But with most server-side languages you can also remotely connect through IP to another database server somewhere else.
You can also use API's to connect to webservices that allows you to put/get data from their storage. Some are SQL, some are Table and some are XML based, but if you have basic CRUDL functionality at them, you dont have to care about how they do it.
Amazon AWS has something called SimpleDB which is a XML kinda storage. It has a great API too, but again, it all depends on your needs, economics and technical skills for implementing this.
If you use Flash for a client, then you have the issue of how to communicate with a server to get the data in and out from the client. For this you also need the server-side "something" that can serve your data as needed and receive "POST" data from the Flash-client.
So once you have a server, you know where you can put your data.
To my knowledge, Facebook does currently NOT support native data-storage, but perhaps others can elaborate on this subject.

Google App Engine and AWS Simple Db would be a good starting point. They include some superb sample client code to get you going.

You need to provide your own server for hosting your database. Google App Engine is free to start using but kind of tricky because the database is Google's Big Table rather than SQL.
So the option I recommend is Kodingen: http://kodingen.com/


text:
Why has it become commonplace for NPCs to have one weapon per class instead of variants?
For instance, in Half-Life 2 you have Civil Protection, Combine Soldier and Combine Elite. Each class has a weapon. Is there a shift away from this at all, where the NPCs are matched with the player in the sense that the weapon they choose to use is based upon their advantage, while still maintaining some sense of competitiveness? Is there a reason this became the norm? Does it have to do with all the variables and complications that can arise from doing that?

There are two reasons I can see immediately, both to do with simplicity: it's simpler to program the AI, and it's simpler for the player to understand. Now for certain games it may be an advantage if enemy characters can switch weapons for the situation (for starters, it's more realistic) but for most games it can be a significant problem if the player gets confused about what tactics to expect and counter. Players like being able to think "oh there's one of the grenade dudes, I better watch out for grenades."
As for complication in AI, there's just plain less thinking for the enemy to do if it doesn't have to consider which weapon to use. Consider your own thought process when deciding which weapon to use; now try to model that thought process as a set of instructions. You'll be considering damage per shot with how accurate the shots are, weighing effectiveness against different sorts of targets, and balancing all those factors against how much ammo you have. Pretty complicated huh?

It would be quite funny to see the AI screw up though and use a Rocket Launcher in a confined space...

It'd be funny to see a player do that as well, but somehow they always come out fine, not even tinnitus :P

@jhocking spot-on I'd say. Most players don't want truly want intelligent behavior in NPCs, they want the satisfaction of having them figured out. It's truly an art to strike the right balance between NPCs that are braindead, cheaters with robotic precision, or plain unpredictable randomness.


text:
Rudimentary 3D graphics in C++ .NET
I am looking to implement an extremely rudimentary FPS game with extremely rudimentary 3D graphics using C++ .NET and DirectX.
I'm not interested in any third party libraries or anything special like that.
Having never done graphics based programming besides 2D stuff I don't really know where to get started or even how to find the right resources online.
I have a few weeks to build this game so im trying to keep it simple.
Can anyone give me a little guidance on how to get started?

Download the DirectX SDK and fire up the sample code that puts a rainbow colored 3D shape on screen. Try making it draw more shapes. Try making it so that big shapes can shoot little shapes out of them. Try moving the shapes around. Try moving the camera around.
You can have a fully playable (but weird) game up and running in an evening that way. Later, you can worry about getting more sophisticated one step at a time. For example, keep the game playable while replacing the rainbow colored 3D shape with a mesh that looks like a person or a bullet or a tank.
The key point is to keep the thing playable at all times. That's where the fun is, and it will motivate you to go back again and again to fix "one more detail." It's like the folk story of Stone Soup.


text:
Preventing ties
I'm working on a simple game to rate a users' preference among several styles.  There are C classes, and the game consists of R rounds of comparison.  At each round, the user is presented a [pseudorandomly selected] single representative image from each of S classes and chooses exactly one to be the "round winner."  At the end of the R rounds, there cannot be a tie among any classes (i.e., one of the classes must have a higher score than all the others).
For example, say I have 3 classes (traditional, contemporary, alternative), and I want to run a 5 round game, comparing 2 classes per round.
I'm looking for an algorithm to provide as-even-as-possible sampling from each of the classes, but in such a way that it would be impossible to end the 5th round with a tie.

Don't completely understand,Is this played against another playing?

Is the design so rigid that a "tie removal" additional round is impossible?

This is a common issue with voting, in a lot of cases a > b > c does not imply a > c, especially not when a > b is concluded because a was picked out of {a,b,c,d,e}.

Perhaps a different approach will help:
You're basically after a 'winner' so perhaps a 'ladder' approach used in one-on-one sports might be what you're after. Each choice is a rung on a ladder and adjacent choices can compete, the winner swapping places. This does rely on some kind of initial ordering which could be random.
eg for C=3 Classes (a, b, c) with S=2 choices and R=5 rounds
At start: (Top) c-b-c (Bottom)

a vs b. b wins => b-a-c
c vs a. c wins => b-c-a
b vs c. b wins => b-c-a
c vs a. a wins => b-a-c (players can be fickle!)
b vs a. b wins => b-a-c (so b is overall winner!)

Admittedly the player will likely be presented with some of the same choices more than once, but you don't get a tie and in the example above, 5 rounds should be plenty to get allow the randomly placed bottom Class to 'float' to the top.
Anyway, hope this helps!

How Fixed is R? Would the Player notice if after the regular rounds of comparison, you ended the sequence with a series of direct comparisons of the tied classes?
Let's say R is 10. After 10 rounds you have A and B which are tied. Can't you do an A vs B round to force the direct comparison?
This will work better if R varies from time to time normally, so as to hide the occasions when you need a few extra rounds for tie-elimination.

Your first issue is that with your example of 3 classes and 5 rounds you can't make any selection of five comparisons where each of the three classes has an equal chance of winning given random choices by the user. That's because 5 rounds * 2 choices per round isn't a multiple of the number of classes.
Unfortunately fixing that and making it fair means you can almost always end up with a tie. The only exception I can think of is with two classes and and odd number of rounds. Other than that I don't think there's any way to rig it so that ties are impossible without adding unlimited numbers of extra rounds, or biasing the selections you present to the user.
Of course if the classes are significantly different and the number of rounds is high it's very unlikely that you'll actually get a tie. You could always just pick randomly between the tied classes if you need to pick a single winner.


text:
Changing player color without multiple player bitmaps

Possible Duplicate:
How to colorize certain parts of a model - like RTS games have those team colors?

Ok, so here is my current situation. I have a player model, fully UV mapped, and textured. At first I made multiple bitmaps for the character representing multiple colors for each team in the game. (red, blue, green, yellow, etc) Well, as my player count build up, space lowers. So I needed to make a new method of keeping the game effecient, clean, and fast. So I thought of the idea of having a color mask (alpha map covering the areas to be colored). I am using OpenGL, and I just have NO idea on where to begin!
So I ask you, are there any libraries? methods? anything that could help me do this?

Are you doing this in fixed-function OpenGL or in shaders?

I recommend using the same idea that they use in movies - chroma key. Reserve one color that you don't otherwise use in your textures (e.g. green, blue, magenta). Let's call it the "reserved color." In the engine, make a matrix that rotates the "reserved color" onto the "player color" you wish to render at the moment.
Set this matrix as a pixel shader constant. In the pixel shader, compute the chroma of the pixel color and find its angle to the "reserved color's" chroma. Lerp the pixel color to the pixel color transformed by the matrix, according to how close the pixel's chroma is to the reserved color's chroma.
Why do this instead of using an alpha channel? Because when textures are DXT compressed, adding an alpha channel makes your texture 2x bigger. A matrix multiply and a little bit of trig in the pixel shader is a lot cheaper than reading 2x as much memory - and will become even cheaper as the years roll on.

you can make a model with some base color and replace that color with a shader.
color = texture_color(x,y);

if(color == base_color)
    color = team_color;


text:
Client server design question
I'm working on creating a multiplayer game, with the client in ActionScript and the server written in Java. I'm using XMLSocket in the client to connect to the server. The server code looks something like:
ServerSocket server = new ServerSocket(port);

while(true)
{
    Socket client = server.accept();
    ClientHandlingProcess child = new ClientHandlingProcess(client);
    child.start(); // starts new thread for client
}

The client handling process looks something like:
while(true)
{
    byte[] arr = new byte[1024];
    if(socket.getInputStream().read(arr) == -1)
    {
        break;
    }

    handleInputMethod(arr);

    while(!message_queue.isEmpty())
    {
        socket.getOutputStream().write(message_queue.get(0).getBytes());
        message_queue.remove(0);
    }
}

The issue is that the read method is blocking, meaning I can't send any data while I'm waiting for data to come in. What would be a good way to fix this? Have two processes: one for reading and one for writing, have the client send empty requests when it has no proper messages to send, or is there another way I can proceed?

The main takeaway from the below answers is that you should steer away from one (or more) thread per client, for scaleability reasons. Even today's most powerful quad core processors can only technically handle 8 simultaneous threads (four cores, two threads per core via hyperthreading); any more than that and there is an overhead for context switching between threads; essentially the processor juggling more threads than it can physically handle. Instead, look into non-blocking IO e.g. via Java's NIO library, or a 3rd party library.

You have basically these two options:

Use blocking IO with one reading thread per client
Use non blocking IO

The first option has the disadvantage that it does not scale for large number of clients.
While non blocking IO can be done by checking inputstream.available(), it may be a good idea to look at the New I/O API. Wikipedia has a good article on NIO with sample code. You can find additional information in the JavaDoc for the NIO package. And on a quick glance this tutorial seems helpful.
You might get away with doing smart things on the client side, such as sending a dummy message on every "turn". This, however, means that a rouge client can freeze your server. So you should not go into this direction.

He is already using blocking IO with one thread per client.

@Ricket, added the word "reading" before "thread per client".

Never rely on a client to do ANYTHING to make your server run properly. If you do, then malicious users can attack your game simply by refusing to perform whatever is required of them.
Use non-blocking IO or threads for this task. Threads is fine if you have a small number of players (eg, < 10) and you are confident with passing data safely between threads. Otherwise, go for the non-blocking IO route.

A client not sending data will only block that client's thread, not in any way cause the server to run improperly. He is already using threads.

So, someone can log in lots of clients and leave them all dormant, eating up memory. You must never leave your system at the mercy of clients because that's how denial of service attacks happen.

Would that not be the case for any server?

Depends what kind of server it is, but the general theme is that the content of the server's response may depend on the client but the actual response must not - if the client doesn't submit the request in time, or submits an invalid request, the connection is dropped. Servers have to assume clients are malicious and malformed and not base their own control flow around the client.

Java's NIO package (as of Java6), provides support for non-blocking I/O only, via Selectors.

Is that the best option though? What is the advantage of this over sending dummy packets to the server?

Yes, NIO is the best option for a server handling many clients. One thread per client has a huge overhead for context switching. And as a solution to your current code, dummy packets would be very wasteful (a lot more incoming bandwidth that the server has to handle) and inconsistent. Each client's connection would then run at different rates depending on the client's connection speed and quality. Terrible idea. The read call should not block, whether you use the old non-blocking ways or restructure your server for NIO.

@user6924 just to clarify the NIO was introduced in Java1.4 you can check it even in wiki

I agree with the other answers that NIO provides better results. However using NIO isn't that trivial. You will definitely learn something when you code the NIO network code yourself. Or you just use an asynch network package like netty or Apache Mina. I prefer netty, since I find it better documented. However if you understand one of them, you understand the other one as well.
But, if you want to keep the design you have, you can split the sending and receiving code. Create some "PlayerSession" or "PlayerConnection" Object that provides the methods for sending messages to the client and contains one thread that blocks on the read and handles input. Maybe you want to move the sending stuff to an own thread, just try it.


text:
Do you know any 3D engines written in Objective-C for iOS?
In the next few weeks I will start a game for iOS, most of the action will happen in 2D but a 2D engine is not enough for our idea, therefore I'm doing a small research on available 3D engines for iOS written in Objective-C (we already looked on some engines written in C++).

Do you know 3D engines written in Objective-C?

I found this one http://nineveh.gl/ but is not yet ready :(.

later edit (1).......
I did a research on the engines written in C++, they are nice and probably I will go with one of them, but if there is any good engine written in Objective-C, than I will go with it, because its a matter of taste and I like very much the obj-c language.

later edit (2).......
nice presentation/teaser about what I'm looking for http://www.slideshare.net/rsebbe/designing-an-objectivec-framework-about-3d

Why does it have to be in Obj-C?  What was wrong with the C++ engines?

My guess is he wants to program his app in Objective-C, and thus the actual engine language doesn't matter.

Its nothing wrong with C++. But I like more Objective-C, and if I can have an engine which at least has a good objective-c api wrapper than I will go with it.

you might want to select an answer to encourage people answer your questions in future

You might also want to check out iSGL3D (http://isgl3d.com) which is an open source Objective-C iOS scene graph library.
It works with both OpenGL ES 1.1 and ES 2.0 with a number of features such as simple scene and object manipulation, lighting and shading, cameras, multiple views, meshes and particles, tweening, mesh skinning, vertex animation, shadows, object interactivity, etc.
It uses a few C++ hooks for external libraries such as Bullet physics and PowerVR POD importing but these are wrapped in Objective-C classes.

I had to choose between ISGL3D and Cocos3D, I went with latter because there was more response in the official forum.

Cocos3d is an extension for Cocos2d and supports many features. Check out their website -
http://brenwill.com/cocos3d/

This looks to be the best answer to the question, but I'm wondering the same thing as tetrad; why not c++?

I knew about it, I hardly wait for the May release which is said to have touch controls on the models :D.
@Jhocking, check out my edit

Even thought I knew about Cocos3d, until now, it seems to be the only framework to do what I want, but still I have to wait for the May release... that's why I chose this answer :)

Cocos3D is good.. You can easily export models from 3D editors, you have default 2D physics engine. You can easily port bullet 3D physics engine. Looks very good.

Check out both the Unreal Development Kit (http://www.udk.com/) and Unity (http://www.unity3d.com) engines.  Both have Objective-C hooks.
I am assuming that it's not important that the engine itself be written in Objective-C, only that you can program in Objective-C and use the engine.

That would also qualify any C++ engine then..

True.  I listed Unreal and Unity as they are both top notch professional engines that are well supported and accepted.

Galaxy Engine looks pretty solid. It's not just a 3D engine written in Objective-C, but the package also contains scene manager, mesh converter and dozen of other content-creation related tools.
Also check out the Oolong engine, it's mostly written in C++ and maintained by Wolfgang Engel of Rockstar Games fame.

Galaxy Looks nice, but I didn't manage to compile it, watched the youtube video on how to do it, it failed and I didn't bother to go further, I will give it another try this weekend.