# Question
Title: Reasons to disable game save during combat (e.g. Mass Effect 2)
So I've been playing Mass Effect 2 (PC) and one of the things I've noticed is that you can only save your game when you're not engaged in combat. As soon as the first enemy shows up on your radar, the save button is disabled. Once combat is over, save functionality reappears.

It seems reasonable to assume that Mass Effect 2 is a state machine, and therefore, the internal state of the program at any moment can be captured and reloaded later. This is basically a solved problem - games have been designed this way since the Half-Life era. It also seems reasonable to assume that BioWare knew what they were doing when they made the decision not to follow this model - it's a tried and true system; BioWare wouldn't have done it the way they did without some good reason.

**What reasons are there to disable game save functionality during combat?**

# Answer
There are a number of reasons that I can think of why designers would do it this way.

The first and probably the most important reason is to prevent really, really annoying the player. E.g. You're in a middle of a tense firefight, you save the game, leave it for a few weeks, load it back up and you're under fire from all angles without any room to breathe.

Another reason is that saving the states of the enemies at that particular time could potentially be problematic. Saving the game state is fairly simple since everything is fairly static (objects in the game world, position of the player, etc). You could save the enemies, but depending on how their AI was implemented it could cause some serialization issues.

Finally saving in other times apart from combat is by design. Again, if the fight you're in is a particularly tense firefight, the developers would want you to experience that tension every time (or something to that effect).

Personally, I believe it's the first and second reason more than anything.

Ray
> 21 votes

# Answer
If you save in combat, you run the risk of saving just before something is going to kill you. Reloading that saved game just puts you right back into the game moments before that event, and it can sometimes be impossible to recover.

As an example, I have a saved game right now in Dead Space where my health is incredibly low, and not 1 second after the save, a big boss monster attacks. I've tried loading and fighting it numerous times, and basically have given up on ever doing so. My only solution is to go back to a VERY old save, and frankly I'm not sure if I want to do that.

So basically, you never want to have the player save the game just before something is going to give them a serious setback. And being in combat greatly increases the odds of this.
> 30 votes

# Answer
I think the existing answers are very good but I want to posit another possible reason. Disabling save prevents the user from using as a cheap crutch, saving right before taking a serious risk and then reloading their save if they fail. I used to do that all the time in RTS games and it eventually sucked all the challenge out of it. Similarly in console emulators with "save state" functions, you can practically tune your game to be perfect. By disabling save, you preserve the sense of risk vs reward, and make the player think rationally before trying something stupid.
> 15 votes

# Answer
The only reasons I can think of are that:

1. It's difficult to save the state of the AI for the enemies and such.
2. You wish to force a certain method of playing upon the players.

I don't think you should use arguments about being able to save right before you die as a reason why you shouldn't be able to save anywhere or in-combat. As the developer, you can implement auto-saves that kick in around areas where combat is about to break out. That way the player can always go back to before the combat started. You can also let the player have multiple saves, then they can go back to any point that they want if they're using that feature.
> 1 votes

# Answer
It gives the players a reason to really think about their tactics. With quick save you could just try it the same way over and over (slowly progressing forward) until you have "beaten" it. Without they have to rethink on how to approach the problem. (be it to be less aggressive, to make better use of the abilities or whatever)
> 1 votes

---
Tags: game-mechanics, state
---


# Question
Title: Intersecting Ray with Extruded 2D Shapes (e.g. Extruded Text)
I'm looking for a way to find intersection between a ray and an extruded 2D shape or text (defied by a Bézier curve). Any ideas?

# Answer
> 2 votes
The procedure is pretty straightforward; it breaks down into a small set of tests:

* Transform your space (ray and text) so that the text lies in the XY plane and has been extruded along the Z axis; in fact, by judicious application of scaling matrices, you can set it up so that the Z-extrusion is from 0 to 1.
* Figure out the values of t along your (transformed) ray (I'm presuming that your ray is of the form P=Po+Dt, where Po is the origin of the ray and D is its direction) that correspond to the values of z=0 and z=1; for instance, at z=1 we have 1=Po\_z+D\_z\*t1, or in other words t1=(1-Po\_z)/D\_z. (Note that if D\_z=0 - in other words, if the ray is in a plane perpendicular to the extrusion axis - you may have to special-case here).
* If t0 and t1 are both less than zero, then the extrusion zone is 'behind' your ray and you can't have an intersection (I'm presuming your ray is one-sided here and that you don't care about intersections behind the camera).
* Otherwise, set t0 = max(t0, 0) - this means that you won't start looking for intersections before the head of your ray or before the 'extrusion zone'.
* Compute the two positions along your ray corresponding to (the new) t0 and t1, say P0 and P1. These are the endpoints of the line segment you'll check; they correspond to the part of your ray that lies within the extrusion zone.
* Now, 'project down' to the plane of your extruded 2d shape by just throwing away the Z-component of your points P0 and P1 (this is the reason behind the transformation back in the first step). All the work from here will be done in two dimensions.
* Perform a point-in-shape test on P0 (I'll explain how to do this in a few moments). If this test comes back positive, then your intersection time is at t0 (with the end-cap of the shape) - note that if t0=0, this can mean that your ray started within the shape, which is another thing that you may want to special-case.
* Finally, find the first intersection (if any) of your line segment with the 2d shape; that t value will be the time along your ray that you intersect the extruded shape.

Of course, that last step is where all the details lie. It's not too hard to do segment-Bezier intersection and you can find most of the details with a bit of hunting around the web, but there are a lot of complications, and little tricks that you can do to speed things up and do as few tests as possible:

* For starters, if your 2d shape is particularly complex then you may want to build a (2d) bounding volume hierarchy for it and use that to cull out pieces of your shape that can't possibly intersect the ray. Once you do this, you should be left with a (hopefully-short) list of individual Bezier curve segments (defined by their four control points C0, C1, C2, C3) that you need to test your line segment against.
* You can shorten your line segment after every 'hit' that you find; for instance, if you find a segment-Bezier intersection at t2, then record t2 as the currently-closest hit point, and reset your segment's endpoints to be (t0, t2) for testing against the rest of the curves (since for the most part you no longer care about intersections after that point).
* The most straightforward way to do the segment-Bezier intersection is by recursively subdividing the Bezier curve: keep a stack of curve chunks to test, and then at each step pop the current curve chunk off the stack. If it's 'short enough' (that is, the total distance between its control points is less than some threshold), then approximate it by a line segment between its two endpoints and test the intersection of your line segment with the approximating segment. Otherwise, check the intersection of your line segment with the bounding box of the current chunk (you can just use the bounding volume of the chunk's four control points for this bounding box, since the curve is guaranteed to lie between them); if there's no intersection, then you can discard the chunk entirely. If there is an intersection, subdivide the chunk into two subchunks C0, C4, C5, C6 and C6, C7, C8, C3 (this is the usual Bezier subdivision - I can point you to details on this if you need them) and push both of those subchunks onto your 'chunk stack'. Repeat until the stack is empty.

Finally, one detail to clean up: I mentioned doing a point-in-shape test up above. The most straightforward way of doing that is casting a (2d) ray from your point off to 'infinity' in any direction - or at least to a point beyond the overall bounding box of your shape - and count the number of intersections that you hit along the way; if this number is odd then your point is inside the shape, otherwise it's outside. There are a few subtle details to be careful of here - for instance, if your ray runs tangent to some curve segment - but the basic approach works quite well.

---
Tags: raytracing
---


title: How to handle dynamic unit color?

text:
# Question
Title: How to handle dynamic unit color?
I'm working on a 3D real time tactics wargame and a primary feature is military customisation. As part of the customisation, I would like to have the player be able to change some of the colors of the unit's texture, similar to how Dawn of War has their color changer. How did they do this?

# Answer
You can either:

* Use the player chosen color when drawing specific polygons on the units. Simple as it sounds, there are certain polygons in the unit model that aren't textured and instead are colored entirely with the color the player chooses. This could be a little flag they're carrying or arm bands or whatever you like.
* Use a base color under the texture for the units that will change the overall hue of the texture to that of the chosen color. When drawing a surface you can set its color and put a texture on top of that, with the proper settings for whatever you're using (OpenGL or DirectX), you can have the texture blend with the base color. For the white or transparent portions of your texture, the base color will take over completely.
* Use a combination of the above.
> 4 votes

# Answer
Many games use the alpha channel of the texture for that. That's a simple composition, first the player color and than the texture on top of it.
> 0 votes

---
Tags: graphics, textures, models
---


# Question
Title: Correct way to handle path-finding collision matrix
Here is an example of me utilizing path finding. The red grid represents the grid utilized by my A\* library to locate a distance. This picture is only an example, currently it is all calculated on the 1x1 pixel level (pretty darn laggy).

I want to make it so that the farther I click, the less accurate it will be (split the map into larger grid pieces). ***Edit: as mentioned by Eric, this is not a required game mechanic. I am perfectly fine with any method that allows me to make this accurate while still fast. This isn't the really the topic of this question though.*** The problem I have is, my current library uses a two dimensional grid of integers. The higher the number in a cell, the more resistance for that grid tile. Currently I'm setting all unwalkable spots to `Integer Max`.

Here is an example of what I want:

I'm just not sure how I should set up the arrays of integers of the grid. Every time an element is added/removed to/from the game, it's collision details are updated in the table.

Here is a picture of what the map looks like on my collision layer:

I probably shouldn't be creating new arrays every time I have to do a path find because my game needs to support tons of PF at the same time.

Should I have multiple arrays that are all updated when the dynamic elements are updated (a building is built/a building is destroyed).

**The problem I see with this is that it will probably make the creation and destruction of buildings a little more laggy than I would want because it would be setting the collision grid for each built in accuracy level. I would also have to add more/remove some arrays if I ever in the future changed the map size.**

Should I generate the new array based on an accuracy value every time I need to PF?

**The problem I see with this is that it will probably make any form of PF just as laggy because it will have to search through a `MapWidth x MapHeight` number of cells to shrink it all down.**

Or is there a better way? I'm certainly not the best at optimizing really anything. I've just started dealing with XNA so I'm not used to having optimization code really doing much of an affect until now... :(

If you need code examples, please ask. I'll add it as an edit.

**EDIT:**

While this doesn't directly relate to the question, I figure the more information I provide, the better. To keep your *units* from moving as accurately to the players desired position, I've decided that once the unit PFs over to the less accurate *grid piece*, it will then PF on a more accurate level to the exact position requested.

# Answer
> 7 votes
Not sure if I properly understand your question, but I will take a stab at it. I would try using a quadtree (similar to a sparse voxel octree, but just 2D). You could represent the entire world as 4 quadrants, and then split each quadrant recursively where you want to achieve higher accuracy. See http://en.wikipedia.org/wiki/Quadtree

Edit: to elaborate...

I would build a quadtree with each node valued between 0.0 and 1.0. To build a node, add up all collidable units inside it, and divide by total number of units. So, if a given quadrant had 16 collidable units, and 48 empty units, its value would be 0.25. If a given quadrant is 1.0 or 0.0, you don't need to build children nodes for it (completely empty or full). You could then select paths by recursively drilling down. Have a start quadrant, and and end quadtrant, then build a path between them by probabilistically selecting nodes that are the least full.

# Answer
> 1 votes
You can make the grid size of each array twice as big as the last one, and let each tile in the lower-resolution grids equal to the maximum value of the smaller tiles it covers, see the figure below.

That way they would be very easy and fast to update. For each lower-res array you get the wanted indices by simply dividing by 2. When a tile's value is changed it will be pretty straight forward to update all the arrays.

If a tile's value is increased, set the value of all the covering tiles to max(newValue,currentValue).

When a tile's value is decreased, refresh the covering tiles to make sure they have the correct value. You can be clever about this and compare the previous value with the new one and only update if neccessary, or just check all the tiles in the most detailed array and use the highest. This update is really fast anyways since you aren't rebuilding the whole array but just updating the affected tiles, so it shouldn't matter much for performance.

If you use this method, you will have to be careful not to make any passages narrower than double the dimension of the tiles in the lowest-resolution array, or the PF might not find the optimal path.

You might also find this article interesting, if you haven't already read it: http://www.gamasutra.com/view/feature/3096/toward\_more\_realistic\_pathfinding.php

---
Tags: xna, path-finding, optimization, lag
---


# Question
Title: Collision detection in multiplayer games
This a followup to my previous question: How to implement physics and AoE spells in an MMO game?.

There, we concluded that all physics have to be done on the server, and that I should use cylinders for calculations.

Now, how can I check for collision detection on a ground-to-player basis on the server? It's fairly easy if the ground is a flat space, I just check if the player's z coordinate is lower than some value and voila, but, what if the map/ground itself is a model? How do I know where hills are on the server-side? How do I know when object collisions happen?

I'm using node.js and socket.io.

# Answer
> 1 votes
Does the exact height of the player have an influence in the outcome? If it has not, there's no need to do it (precisely) on the server, you can use a simplified model of the terrain (simple triangles for instance) for a quick cheat check, but ultimately let the client handle the exact height that will be displayed to the player. Small visual discrepancies might appear, it's up to you to decide if that a tradeoff (accuracy vs performance) is acceptable or not in you case.

Whatever solution you use (full or simplified terrain), some model of the terrain must exist on the server side, there's no way around that. If you're not using a physics engine, and plan to do the calculations yourself, this question might be a good starting point (you can assume the player/object position is a single point - the bottom center of its bounding cylinder - and to detect whether or not it collided with the floor between two frames, check if the point remains in the same "side" of the plane right below it).

---
Tags: collision-detection, javascript, multiplayer, server
---


title: Position sprite at center of screen

text:
# Question
Title: Position sprite at center of screen
I am trying to get a sprite to position itself at the center of the screen but nothing seems to be working for me. I'm trying

```
Viewport viewport = graphics.GraphicsDevice.Viewport;
logoPosition = new Vector2((viewport.Width - towerImage.Width) / 2,
                           (viewport.Height - towerImage.Height) / 2);

```

and

```
spriteBatch.Draw(towerImage, centre, null, Color.White, 0, baseOrigin, 1.0f, SpriteEffects.None, 0);

```

This is my first time using XNA and I don't really have a clue what I'm doing.

# Answer
> 4 votes
Unless you pasted your example wrong, you're not even using the `logoPosition` you calculated when drawing, and you're not showing what the contents of `centre`and `baseOrigin`are, so it's hard to tell you where the problem is.

But anyway I'd use the `position` and `origin` parameters of `SpriteBatch.Draw` in order to draw the image centered. In two steps, although you could inline:

1. Calculate the center of the screen and the center of the image:

```
Vector2 screenCenter = new Vector2(viewport.Width / 2f, viewport.Height / 2f);
Vector2 imageCenter = new Vector2(towerImage.Width / 2f, towerImage.Height / 2f);

```
2. Use the center of the screen as the `position` and the center of the image as the `origin`:

```
                             // position                          // origin
spriteBatch.Draw(towerImage, screenCenter, null, Color.White, 0f, imageCenter, 1f, SpriteEffects.None, 0f);

```

# Answer
> 1 votes
I've never used XNA for a windows phone but I already can tell what your problem is. You aren't following order of operations. Try this:

```
Viewport viewport = graphics.GraphicsDevice.Viewport;
logoPosition = new Vector2(viewport.Width - towerImage.Width / 2,
                           viewport.Height - towerImage.Height / 2);

```

You must divide the second height/width before you subtract if from the original. Otherwise it just negates itself and then divides 0 by 2.

---
Tags: xna, windows-phone-7
---


# Question
Title: Handling different screen densities in Android Devices?
Well, i know there are plenty of different-sized screens in devices that run Android.

The SDK I code with deploys to all major desktop platforms and android. I am aware i must have special cares to handle the different screen sizes and densities, but i just had an idea that would work in theory, and my question is exactly about that method, How could it FAIL ?

So, what I do is to have an ortho camera of the same size for all devices, with possible tweaks, but anyway that would grant the proper positioning of all elements in all devices, right? We can assume everything is drawn in OpenGLES and input handling is converted to the proper camera coordinates.

If you need me to improve the question, please tell me.

# Answer
Your ortho camera handles the viewing frustum. Everything in the frustum will be projected to the viewport. What you are wanting to do is keep the frustum at a constant size, and change the size of the viewport (which is the correct way to do this).

\[edit: The frustum is a 3D representation of space that defines the visible portion of your scene. Effectively a large rectangular prism, things inside get projected to the viewport, things outside do not.\]

**So, just make your viewport represent the size of your screen, and OpenGL ES will stretch the frustum however it needs to. Define all of your screen elements relative to the inside of the frustum.**

On the note of duplicate art though, you really should try to provide one for each density; ldpi, mdpi, hdpi. Otherwise your game may look excessively stretched or shrunk. The extra assets can diminish this effect a bit.
> 1 votes

---
Tags: android, opengl-es
---


# Question
Title: How to shoot a triangle out of an asteroid which floats all of the way up to the screen?
I currently have an asteroid texture loaded as my "test player" for the game I'm writing. What I'm trying to figure out how to do is get a triangle to shoot from the center of the asteroid, and keep going until it hits the top of the screen. What happens in my case (as you'll see from the code I've posted), is that the triangle will show, however it will either be a long line, or it will just be a single triangle which stays in the same location as the asteroid moving around (that disappears when I stop pressing the space bar), or it simply won't appear at all. I've tried many different methods, but I could use a formula here.

All I'm trying to do is write a space invaders clone for my final in C#. I know how to code fairly well, my formulas just need work is all.

So far, this is what I have:

**Main Logic Code**

```
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 1, 1);

            mAsteroid.Draw(mSpriteBatch);

            if (mIsFired)
            {
                mPositions.Add(mAsteroid.LastPosition);
                mRay.Fire(mPositions);
                mIsFired = false;
                mRay.Bullets.Clear();
                mPositions.Clear();
            }

            base.Draw(gameTime);
        }

```

**Draw Code**

```
            public void Draw()
            {
                VertexPositionColor[] vertices = new VertexPositionColor[3];

                int stopDrawing = mGraphicsDevice.Viewport.Width / mGraphicsDevice.Viewport.Height;

                for (int i = 0; i < mRayPos.Length(); ++i)
                {
                    vertices[0].Position = new Vector3(mRayPos.X, mRayPos.Y + 5f, 10);
                    vertices[0].Color = Color.Blue;
                    vertices[1].Position = new Vector3(mRayPos.X - 5f, mRayPos.Y - 5f, 10);
                    vertices[1].Color = Color.White;
                    vertices[2].Position = new Vector3(mRayPos.X + 5f, mRayPos.Y - 5f, 10);
                    vertices[2].Color = Color.Red;

                    mShader.CurrentTechnique.Passes[0].Apply();
                    mGraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, vertices, 0, 1);

                    mRayPos += new Vector2(0, 1f);

                    mGraphicsDevice.ReferenceStencil = 1;
                }
            }

```

# Answer
So you want to shoot a triangle bullet from an asteriod player at the bottom of the screen?

Firstly, why is your logic code in the Game.Draw() function?

You should maintain a list of triangles in your game:

```
//WARNING: psuedo code
// In Game.cpp

List<Triangle> _mTriangles = new List<Triangles>();

public override void Update()
{
    if(Keyboard.GetState() == SPACE_DOWN)
    {
       var triangle = new Triangle(mAsteroid.pos);
       _mTriangles.add(triangle);
    }

    if(Keyboard.GetState() == LEFT_RIGHT)
        mAsteroid.pos.x += Keyboard.GetState().X_OFFSET

    foreach(var t in mTriangles) t.y -= Triangle.Speed * elapsedTime;

    // TODO: another loop to remove triangles outside of screen.
}

public override void Draw()
{
   mAsteriod.Draw();
   foreach(var t in mTriangles) t.Draw();
}

```
> 0 votes

---
Tags: xna, c#, spaces
---


# Question
Title: Is client-side prediction supposed to cause lag?
I found this general question, but I'd like clarification on a specific point.

Consider this simple scenario:

1. Client A sends input to move at `T0`.
2. Server receives input at `T1`.
3. All clients receive the change at `T2`.

With client-side prediction, client A would start moving at `T0`, client-side. All other clients receive the change at `T2`, so to them, client A only started moving at `T2`.

If I understand correctly, client B will always see client A's *past position* and not his *current position*! Is that supposed to happen? How can I sync those clients' world views?

# Answer
> 3 votes
A better, and more direct, answer would be: They don't ever sync. When placed side-by-side, Client A will always move first, before client B sees him move.

"Tricks" are then used to resolve this difference. E.g. If one player shoots at another, resolve the shots based on what the shooting player saw, by checking for past positions on the server (Counterstrike etc).

Or, once client A starts moving on client B's machine, it is forward extrapolated in time, to show an "approximation" of where the player will be. New commands are still lagged though. (Tribes etc)

# Answer
> 4 votes
All clients are initialized to the server time when they log in or the game starts, they get updated on this occasionally.

The server uses the "keep alive" ping of the authentication service and lets the clients know what kind of delay they're working with, this delay will change over time and so needs updating occasionally. If you're not using a proper authentication service then the server manages the ping.

All clients know that they are acting "server time + delay" ahead.

Clients then can use this delay and their duplication of server time to properly interpolate forwards proxies from other clients' time and data from the far past so that other clients appear locally in the present on the player's Client, which is actually operating in the near future relative to the Server and that Server is itself in the near past relative to the remote Clients.

tl;dr Sync to server time, keep track of ping, interpolate all proxy clients.

Clear enough? =)

---
Tags: networking, multiplayer, movement-prediction
---


title: Text based game in XNA

text:
# Question
Title: Text based game in XNA
I want to create a text based game, where the player will type up,down, left or right and the sprite will move in that direction. I created the game and at the moment the player moves with the up,left,down and right keys. I would like to change the movement of the sprite from keypresses to text commands, Ive googled a lot on creating text based games in XNA but have had no luck. Could you please help me or guide me in the right direction of how to do this in XNA.

# Answer
> 2 votes
If your goal is a text based game your better off making it with regular Form based program, or my favourite WPF. XNA has no built in support for handling typing, that is, quick presses of keys in sequence. It focuses entirely on detecting keys being held over time (which is more likely the case in an action style game). If you really need XNA to display the results as sprites you need to hook into the keyboard events, I would consider WPF some more however if you want a text adventure.

# Answer
> 2 votes
If you really want to use XNA and graphics along with your text adventure, you should build your own interface; this should be the least of your challenges since you already seem to know how to display and manipulate graphics with XNA.

The question is, do you want to write a text adventure, or a text adventure *engine*?

If what you really want is to write a text adventure, you probably should not start by writing a whole new engine. That would be like building your own car if all you want is *driving* a car.

Writing your own text adventure engine first would not be trivial,I imagine. I would recommend you first try whether an existing engine suits your needs. At least one of those seems to support at least still images for illustration, so they are not text only, which you seem to go for. If you have gathered enough experience with existing systems, you could still write your own engine.

Also highly relevant: this Q&A on Stack Overflow

# Answer
> 1 votes
I haven't used XNA, but I have done this at a game jam.

I extended a text box class from an open source GUI library. Whenever the user pressed enter, it cleared the box, checked for a certain keyword/command, and did stuff.

It seems like you can either wrap a XNA game in a WinForm or WPF. If not, there are a few open source GUIs out there.

Possibly helpful question:
https://stackoverflow.com/questions/1561541/xna-and-gui-controls-eg-xaml-and-xna

---
Tags: xna, c#, text-based
---


# Question
Title: Changing location after CommitAnimations
I'm using the following code to move a `UIImageView`:

```
shootImg.image = [UIImage imageNamed:@"Projectile Left 1.png"];
[UIView beginAnimations:nil context:nil];
shootImg.center = CGPointMake(shootImg.center.x+1000, shootImg.center.y);
[UIView commitAnimations];

```

This works but what I want to do is after `[UIView CommitAnimations];` I want to set the location of `shootImg` using `CGPointMake`. If I just put it after `commitAnimations` then the animation doesn't fully complete. Any suggestions? I'm not using any frameworks like cocos2d and if you need to see any more code just ask.

# Answer
> 1 votes
You could add inside the `[UIView beginAnimations:nil context:nil];` and `[UIView commitAnimations];` add the following line: `[UIView setAnimationDelegate:self];` and create this methods on your class: `setAnimationWillStartSelector:` and `setAnimationDidStopSelector:`

so your code will be like this:

```
shootImg.image = [UIImage imageNamed:@"Projectile Left 1.png"];
[UIView beginAnimations:nil context:nil];
shootImg.center = CGPointMake(shootImg.center.x+1000, shootImg.center.y);
[UIView setAnimationDelegate:self];
[UIView commitAnimations];

```

and on your class this methods:

```
+ (void)setAnimationDidStopSelector:(SEL)selector
+ (void)setAnimationWillStartSelector:(SEL)selector

```

if you like to see more i recommend the documentation for UIView here

---
Tags: iphone, objective-c
---


# Question
Title: Triangles in a C++ STL Vector as an Objective-C member sometimes draws incorrectly in OpenGL ES
The polygons draw correctly 80% of the time. When it fails, a vertex is dislocated. The polygon is consistently drawn with the wrong vertex. I checked that the vector is correct during initialization, even when it's wrongly drawn.

I'm using Cocos2d.

The class member:

```
@interface Polygon : CCSprite {
  std::vector<float> triangleVertices;
}

```

The draw function called in \[Polygon draw\]:

```
+ (void)drawTrianglesWithVertices:(const std::vector<float> &)v
{
    //glEnableClientState(GL_VERTEX_ARRAY);
    glDisable(GL_TEXTURE_2D);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);

    glVertexPointer(2, GL_FLOAT, 0, &v[0]);
    glDrawArrays(GL_TRIANGLES, 0, v.size());

    //glDisableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnable(GL_TEXTURE_2D);
}

```

Any ideas?

# Answer
If your vector is a vector of floats, where each consecutive pair of floats represents a single vertex, as suggested by your `glVertexPointer` call, then it should surely be `v.size()/2` in `glDrawArrays`, but I'm not that sure this would cause your error, otherwise some more information and code would be required.
> 2 votes

---
Tags: opengl-es, cocos2d-iphone, objective-c
---


# Question
Title: What are milestones for a game developer to gauge their progress?
I know actually **completing a game** is a massive milestone, a complete polished, holistic experience. Something that I've not yet been able to commit to.

There are of course classes and degrees to earn in several fields that will help gain experience, but how would one judge their own progress and strive to progress further?

The yellow brick road to "Rock Star Game Programmer" is very cloudy. At this point I think it may be closer to an ocean, drifting along until you wake up one day at your destination.

# Answer
This of course is dependent on the individual developer and what goals they want to accomplish. But I think the only real measure is the development of games! In my opinion, the path of a game developer closely follows the development of their first game. But then what are the milestones for a game? There are simple enough games that they could be created in a single day and there are those that take years (into mine over a year already!). Clearly the span of creation is a large factor for milestones. If you're not going much further than a mile, you don't pass that many stones :). That being said, there are probably some generic milestones for the medium sized game. I believe you can use the milestones below to gauge your progress towards that rock-developer status. Anyone who can make it through the points listed below certainly deserves that recognition.

(damn this auto numbering! I want to start at 0 like any good programmer would!)

1. **Get an idea for a game**. Easy, who doesn't have a list of those somewhere?
2. **Choose your platform and language**. You'll always see this question on this site. It's a big one for new developers. (But don't ask here because it's off topic! This is one challenge you need to overcome on your own)
3. **Write the first line of code for your game.** As simple as it sounds, this is a fairly big one. I bet there's 100 people who have an idea for a game they want to make but never start for each 1 person who completes this first milestone. They get stuck during a tutorial or they get so caught up in thinking about how to do it, they never do it.
4. **Get something basic going**. This could be as simple as getting a triangle to render on screen or using the keyboard to move a little sprite around. At this point you have a bare bones game. It starts, displays some graphics, responds to the player and then ends.
5. **A million smaller milestones** These range from getting your art assets loading correctly, to *fixing that damn bug*, to reading and writing to disk, to that premature optimization that was bugging you just too much to leave it. Getting past this collection of milestones is a pretty big milestone. Plenty of people will give up at this point or start working on something else and never come back. The majority of the milestones in this milestone involve code change-\>play-\>repeat. It's important to play test often!
6. **A playable prototype.** This should represent your finished product fairly well. Now things are starting to come together. You're 90% there right?
7. **A million million smaller milestones.** Oh the grind. You're deep in your second 90% with lots of little changes, fixes, re-optimizing your premature optimizations, brain meltdowns and code re-factoring. This is a major stopping point as well. This part is deceptively difficult. Broad strokes are easy in comparison to the fine art of polish.
8. **A complete game**. Now you have 3 grey hairs and a finished product to show for it. Congratulations! Now you just have to publish, promote and maintain.

But really the milestones are a lot like this list. Made up on the spot and totally up to you.
> 30 votes

# Answer
The best article I have found on the subject is How do I make games? A Path to Game Development.

You really should read the whole article, but let me sum it up:

> When I talk to people looking to get into game development some of the first things I often hear fall along the lines of, "How do I make games?" or "I want to make a game like Quake/Everquest/Starcraft and…". The first is just way out of the realm of answerability, as there are too many aspects to possibly go into, and each of those components can be infinitely complex.
>
> The second, however, falls into just being unrealistic in expectations...
>
> So where do I start?...
>
> Tetris has all the individual components that ALL games share in common. It has a game loop (the process of repeating over and over until the game is quit). The game loop reads in input, processes the input, updates the elements of the game (the falling tetraminos), and checks for victory/loss conditions.

He then goes on to cover more and more advanced games and topics

* advanced collision detection
* simple deflection physics
* level layout
* artificial intelligence
* sound
* art
* advanced game state

and wraps up with this wisdom:

> Finishing a game does not merely mean you get it to a point where it is playable, and then move on, this is not a finished game. A finished game will have an opening screen, a closing screen, menu options (if applicable, at least instructions on how to play and start), introduction screens to playing, reward screens and a score board (where applicable)...
>
> This isn't a world you can't join though, it just takes a good deal of time and experience and track record of making quality games...

So, to judge your progress as a game developer, you cannot simply "\[drift\] along until you wake up one day at your destination", you must actually **develop games**. Anything short of that is simply deluding yourself.\*

\*The author of this post is **not** a game developer.
> 8 votes

---
Tags: career
---


# Question
Title: GLSL compile error when accessing an array with compile-time constant index
I have this shader that works well on my computer (using an ATI HD 5700). I have a loop iterating between two constant values, which is, afaik, acceptable in a glsl shader. I write stuff in two arrays in this loop.

```
#define NB_POINT_LIGHT 2

...

varying vec3 vVertToLight[NB_POINT_LIGHT];
varying vec3 vVertToLightWS[NB_POINT_LIGHT];

...

void main()
{
    ...
    for (int i = 0; i < NB_POINT_LIGHT; ++i)
    {
        if (bPointLightUse[i])
        {
            vVertToLight[i] = ConvertToTangentSpace(ShPointLightData[i].Position - WorldPos.xyz);
            vVertToLightWS[i] = ShPointLightData[i].Position - WorldPos.xyz;
        }
    }
    ...
}

```

I tried my program on another computer equipped with an nVidia GTX 560 Ti, and it fails to compile my shader. I get the following errors (94 and 95 are the lines of the two affectations) when calling glLinkProgram:

```
Vertex info
-----------
0(94) : error C5025: lvalue in assignment too complex
0(95) : error C5025: lvalue in assignment too complex

```

I think my code is valid, I don't know if this comes from a compiler bug, a conversion of my shader to another format from the compiler (nvidia looks to convert it to CG), or if I just missed something.

I already tried to remove the `if (bPointLightUse[i])` statement and I still have the same error. However, if I just write this:

```
vVertToLight[0] = ConvertToTangentSpace(ShPointLightData[0].Position - WorldPos.xyz);
vVertToLightWS[0] = ShPointLightData[0].Position - WorldPos.xyz;
vVertToLight[1] = ConvertToTangentSpace(ShPointLightData[1].Position - WorldPos.xyz);
vVertToLightWS[1] = ShPointLightData[1].Position - WorldPos.xyz;

```

Then I don't have the error anymore, but it's really unconvenient so I would prefer to keep something loop-based.

Here is the more detailled config that **works**:

```
Vendor: ATI Technologies Inc.
Renderer: ATI Radeon HD 5700 Series
Version: 4.1.10750 Compatibility Profile Context
Shading Language version: 4.10

```

And here is the more detailed config that **doesn't work** (should also be compatibility profile, although not indicated):

```
Vendor: NVIDIA Corporation
Renderer: GeForce GTX 560 Ti/PCI/SSE2
Version: 4.1.0
Shading Language version: 4.10 NVIDIA via Cg compiler

```

# Answer
Doing some searching for "error C5025: lvalue in assignment too complex" suggests that GPUs don't like writing to scattered memory addresses that aren't determined til runtime.

Your shader compiling on one card, and not on the other may or may not be the result of different number of available registers.

Unrolling the loop manually, like you did, eliminates the problem. Ideally, the compiler should unroll small loops by itself, as this answer suggests the compiler may be unable to unroll the loop on it's own though. (which is strange, since NB\_POINT\_LIGHT is not a variable but a preprocessor definition, so at compile time the loop's extent should be known)

As Sam suggested, `#pragma unroll` might help to get the compiler to unroll the loop, however these directives can be different for nvidia and amd specific compilers, maybe also try `#pragma optionNV(unroll all)`.

If that also doesn't help, maybe try replacing `NB_POINT_LIGHT` in your loop with 2, and if necessary combine with the unroll directives, again.
> 2 votes

---
Tags: shaders, glsl, nvidia
---


# Question
Title: XNA: Networking gone totally out of sync
I'm creating a multiplayer interface for a game in 2D some of my friends made, and I'm stuck with a huge latency or sync problem.

I started by adapting my game to the msdn xna network tutorial and right now when I join a SystemLink network session (1 host on PC and 1 client on Xbox) I can move two players, everything is ok, but few minutes later the two machines start being totally out of synchronization. When I move one player it takes 10 or 20 seconds (increasing with TIME) to take effect on the second machine.

I've tried to :

Create a thread which calls NetworkSession.Update() continuously as suggested on this forum, didn't worked.

Call the Send() method one frame on 10, and the receive() method at each frame, didn't worked either.

I've cleaned my code, flushed all buffers at each call and switched the host and client but the problem still remain...

I hope you have a solution because I'm running out of ideas...

Thanks

SendPackets() code :

```
    protected override void SendPackets()
    {
        if ((NetworkSessionState)m_networkSession.SessionState == NetworkSessionState.Playing) //Only while playing
        {
            //Write in the packet manager
            m_packetWriter.Write(m_packetManager.PacketToSend.ToArray(), 0, (int)m_packetManager.PacketToSend.Position);
            m_packetManager.ResetPacket(); //flush

            //Sends the packets to all remote gamers
            foreach (NetworkGamer l_netGamer in m_networkSession.RemoteGamers)
            {
                if (m_packetWriter.Length != 0)
                {
                    FirstLocalNetGamer.SendData(m_packetWriter, SendDataOptions.None, l_netGamer);
                }
                }
            m_packetWriter.Flush();//m
            m_packetWriter.Seek(0, 0);
        }
    }

```

ReceivePackets() code :

```
    public override void ReceivePackets()
    {
        base.ReceivePackets();

        if ((NetworkSessionState)m_networkSession.SessionState == NetworkSessionState.Playing) //Only while playing
        {
            if (m_networkSession.LocalGamers.Count > 0) //Verify that there's at least one local gamer
            {
                foreach (LocalNetworkGamer l_localGamer in m_networkSession.LocalGamers)
                { //every LocalNetworkGamer must read to flush their stream
                    // Keep reading while packets are available.
                    NetworkGamer l_oldSender = null;
                    while (l_localGamer.IsDataAvailable)
                    {
                        // Read a single packet, even if we are the host, we must read to clear the queue
                        NetworkGamer l_newSender;
                        l_localGamer.ReceiveData(m_packetReader, out l_newSender);
                        if (l_newSender != l_oldSender)
                        {
                            if ((!l_newSender.IsLocal) && (l_localGamer == FirstLocalNetGamer))
                            {
                                //Parsing PacketReader to MemoryStream

                                m_packetManager.Receive(new MemoryStream(m_packetReader.ReadBytes(m_packetReader.Length)));
                            }
                        }
                        l_oldSender = l_newSender;
                        m_packetReader.BaseStream.Flush();
                        m_packetReader.BaseStream.Seek(0, SeekOrigin.Begin);
                    }
                }
                m_packetManager.ParsePackets();
            }
        }
    }

```

# Answer
I have a few suggestions :

* Shouldn't you handle network updates on **every** frame ?
* What's your status of GameTime.IsRunningSlowly ?
* Did you try to profile your application ?

Here are some links for you :

The Indiefreaks Game Profiler for Xna is here! **this one might be of interest**

What Are Some Good .NET Profilers?

Plus, on Visual Studio you have *Menu Analyze -\> Launch Performance Wizard*
> 1 votes

---
Tags: xna, c#, networking, synchronization, latency
---


# Question
Title: From simple physics with a ball, to a more complicated shape
Hello fellow game devs and stack overflowers...

I recently made a transition from OpenGL ES 1.1 to 2.0 (on Android via NDK) and things are going well so far. I'm working on doing a dice rolling application (gaming dice up to 20 sided, not just regular 6 sided die) as a way to learn more about how physics is implemented in a gaming environment.

I've explored implementing existing engine options (such as Bullet) and I don't think I need to implement something quite so sophisticated. I've found several tutorials that handle a lot of the general physics involved with initial trajectory, velocity, angle of contact and reflection angle, etc. I'm confident that I'd be able to implement ball-like behavior without much trouble.

My question lies in when I attempt to make the interaction of the die shape with another surface more "realistic," for example... the die strikes the floor surface at such an angle where only one corner makes contact with the floor. In my mind, the center of gravity of the object would play a part in determining how the die bounces away, possibly even spinning it it faster, etc... but I am not sure what the actual math involved is.

Are there any recommended resources for getting into this level of detail? Initial searches haven't turned up much...

Thanks to everyone in the community, -Jeremiah

# Answer
I suppose you want to make a game somewhere down the road, else you wouldn't post here. My advice: Fake it. Fake it as much as you can, and make it more realistic only if it's overall easier and/or looks decidedly better than when faking it. The ultimate goal in games is to make a fun game, not to implement physics at the quantum level. Leave that to the scientists.

As for your actual question: A D20 is, for all intents and purposes, a ball, so you fake it by treating it as a ball. Maybe add some random bounces up or to the side while rolling if you have a very flat, rigid surface on which you roll the die, but otherwise, it's a ball.

Edit: I've just noticed your "Android" tag, so you are working with inherently limited hardware. Another reason to fake it, because it's cheaper in CPU cycles.
> 2 votes

---
Tags: android, physics, opengl-es
---


title: Organize a game set

text:
# Question
Title: Organize a game set
I'm developing a endless running game and I'm not really sure on how to make the set. The first approach was to make a BIG set like 10240x3072 pixels so that we have a nice portion of set. After having like 3 or 4 sets that go along with each other I would work on making their elements sequential and repeatable. However this is getting really heavy for the iPad 1 (it's running good in the iPad 2 and the New iPad) even though I'm splitting all the set in slices through Photoshop. For the implementation I'm using Cocos2D. Is there any better approach to make something like this but truly efficient for the iPad memory?

Thank you.

# Answer
Here's how I did it :

I have a camera which is nothing more than a vector, from its position I do find which tiles needs to be drawn; using tile size and viewport size.

In this example less than 10% of the level is drawn :

The whole level is only using 3 textures that are 32x32 pixels, in comparison to your huge texture. However there are some considerations you should care of if using this method : the level generation. Since it's not a huge texture anymore, you can either code a text file that would be the level, each character representing a tile. Or you can use a level editor for this purpose. A quick search for 'mac level editor' brings Tiled.

Here is an excerpt of what I did, that's the part that does find what to draw and draws only that.

The code should be self-explanative, if not, ask.

```
namespace x
{
    public class LevelComponent : DrawableGameComponent
    {
        public List<Texture2D> Textures { get; private set; }
        public List<Sprite> Sprites { get; private set; }

        private readonly List<Bounds> _bounds;
        private Vector2 _camera;

        private Vector2 _screenCenter;

        private Vector2 _screenSize;
        private Vector3 _size; // level size as tiles
        private Vector2 _sizeAsPixels; // level size ...

        private SpriteBatch _spriteBatch;
        private Vector2 _sizeOfTile;
        private Tile[,,] _tiles;
        private int _tilesRendered;

        public override void Update(GameTime gameTime)
        {

            /* We will center on the player just like in Super Mario Bros.
             * Also, we clamp the camera to level bounds. */
            Vector2 newPos = Players[0].Position - _screenCenter;
            Vector2 min = Vector2.Zero;
            Vector2 max = SizeAsPixels - _screenSize;
            _camera = Vector2.Clamp(newPos, min, max);

            /* We get level size as tile units. */
            float w = Game.GraphicsDevice.Viewport.Width/SizeOfTile.X;
            float h = Game.GraphicsDevice.Viewport.Height/SizeOfTile.Y;
            var max1 = new Vector2(SizeOfTile.X, SizeOfTile.Y);

            /* Now we are going to find out which level region
             * we just want to render otherwise it'd be unpractical to render the whole level.
             * Example :
             * - If level is 32 * 32 * 3 layers there are 3072 tiles,
             * - Now if our viewport is say 5*5, we only render 5*5*3 or 75 tiles.
             * - While these numbers are low, on a huge level it is critical.
             * - Say on a 512*512*3 or 786432 tiles, tiles to render is only 75.
             * - Yet it is about 0.0001% of the level we render ...
             * - We can thus keep a 60 fps frame rate with this method. */
            Bounds.Clear();
            var layers = (int) Size.Z;
            for (int layer = 0; layer < layers; layer++)
            {
                /* We divide here to make far layers moving more slowly
                 * than layers that are closer to us OR Parallax Scrolling ! */
                Vector2 topLeft = TilesFromPixels(Camera);
                topLeft /= (layer + 1);

                /* We draw what's visible on the screen. */
                Vector2 bottomRight = topLeft + new Vector2(w, h);
                bottomRight = Vector2.Clamp(bottomRight, Vector2.Zero, max1);

                // Now we have bounds of regions to render for all layers !
                Bounds.Add(new Bounds(topLeft, bottomRight));
            }

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            _spriteBatch.Begin();

            if (Tiles != null)
            {
                /* We're going to draw level from back to front
                 * BUT the most important and a huge CPU saver is that
                 * we're going to draw only what we can see on screen,
                 * thus, we can have gigantic levels and they'll
                 * still at run 60 fps. */

                _tilesRendered = 0;
                var layers = (int) (Size.Z - 1);
                for (int z = layers; z >= 0; z--)
                {
                    Bounds bounds = Bounds[z];
                    Vector2 topLeft = bounds.TopLeft;
                    Vector2 bottomRight = bounds.BottomRight;
                    Vector2 translation = Camera/(z + 1); // Scrolling difference
                    for (var x = (int) topLeft.X;
                         x < bottomRight.X;
                         x++)
                    {
                        for (var y = (int) topLeft.Y;
                             y < bottomRight.Y;
                             y++)
                        {
                            Tile tile = Tiles[x, y, z];
                            if (tile == null) continue;

                            Vector2 position = PixelsFromTiles(new Vector2(x, y));

                            _spriteBatch.Draw(this.GetTexture(tile.Texture), position - translation, tile.Color);
                            _tilesRendered++;
                        }
                    }
                }
            }

            _spriteBatch.End();

            base.Draw(gameTime);
        }

    }

    public static class Helpers
    {
        /// <summary>
        /// Get pixel position from a tile position, according a tile size.
        /// </summary>
        /// <param name="x">Position horizontal value, as tiles.</param>
        /// <param name="y">Position vertical value, as tiles.</param>
        /// <param name="tileWidth">Tile width, as pixels.</param>
        /// <param name="tileHeight">Tile height, as pixels.</param>
        /// <returns>Position, as pixels.</returns>
        public static Vector2 PixelsFromTiles(float x, float y, float tileWidth, float tileHeight)
        {
            return new Vector2(x * tileWidth, y * tileHeight);
        }

        /// <summary>
        /// Get pixel position from a tile position, according a tile size.
        /// </summary>
        /// <param name="position">Position, as tiles.</param>
        /// <param name="tileSize">Tile size, as pixels.</param>
        /// <returns>Position, as pixels.</returns>
        public static Vector2 PixelsFromTiles(Vector2 position, Vector2 tileSize)
        {
            return PixelsFromTiles(position.X, position.Y, tileSize.X, tileSize.Y);
        }

        /// <summary>
        /// Get tile position from a pixel position, according a tile size.
        /// </summary>
        /// <param name="x">Position horizontal value, as pixels.</param>
        /// <param name="y">Position vertical value, as pixels.</param>
        /// <param name="tileWidth">Tile width, as pixels.</param>
        /// <param name="tileHeight">Tile height, as pixels.</param>
        /// <returns>Position, as tiles.</returns>
        public static Vector2 TilesFromPixels(float x, float y, float tileWidth, float tileHeight)
        {
            return new Vector2(x / tileWidth, y / tileHeight);
        }

        /// <summary>
        /// Get tile position from a pixel position, according a tile size.
        /// </summary>
        /// <param name="position">Position, as pixels.</param>
        /// <param name="tileSize">Tile size, as pixels.</param>
        /// <returns>Position, as tiles.</returns>
        public static Vector2 TilesFromPixels(Vector2 position, Vector2 tileSize)
        {
            return TilesFromPixels(position.X, position.Y, tileSize.X, tileSize.Y);
        }
    }
}

```
> 1 votes

---
Tags: iphone, ios, cocos2d, ipad
---


# Question
Title: Serverside memory efficiency and threading for a turn based game
Im programming on a turn based war-game for some years now (along with the engine) and Im having quite a hard time at figuring out what the games server architecture should look like, since most game server architecture articles I found focus either on FPS oder MMOGs, which doesn't really fit since I want many matches with 1- 16 players on my server, with each match being played in turn based mode.

My chief concern is memory usage, since the most basic approach of loading every game that is being played completely into RAM should be quite inefficient, so is there a suitable strategy for selecting only the needed bits and loading them?

Another question I got is how to design the threading on the server, since I think using only a single thread could be a problem due to the fact that the game or part of it might have to be loaded from the database.

I would be very happy if you could share your knowledge or point me to material on this topic.

# Answer
Of course I can't tell how much data there will be for each game as I don't know what you are planning, but in general I'd say that the state of a turn based game should not fill more than 1 MB given a reasonable format. In most cases a lot less will do. See one of my other answers for a bit on the concept of counting memory: https://gamedev.stackexchange.com/a/22305/3505

So you should have the memory for keeping "everything" there, and from a performance perspective it's probably best to do so. If you deem it important you can save players' orders to a database to be able to regenerate the games in case of a crash.

While a database can save you from many worries, performance in general is not one of them. A typical SQL database might give you 100 000 simple queries per second, application memory is more likely to give you 1000 000 000 I/O operations per second. (Note for those who like to argue: The numbers vary wildly between configurations, but the fact that a typical database is a huge drag is a constant.)

As for threading, the easy route is to have one process, with one thread for each game. Depending on language of choice that will give you a few MB of overhead for each game, and a lot of process switching. Depending on exact circumstances this will give you a limit somewhere between a few hundred and some thousand simultaneous games.

If ever this is not good enough for you multiple games per thread/process is the most straight forward improvement.
> 0 votes

# Answer
(Hm, I'll add this as an answer because I can't seem to comment for some reason :()

I think you need to use a database instead of keeping the games in RAM. With a database you don't need to think about memory because it is handled by the os and the db software.

I have worked on a real-time MMO and you are right that you have to worry about memory concerns there because the server has to keep every players info in memory while they are logged in. This is mainly because of position. The users expect the location of their players to be the same on every machine, much like a multiplayer fps game.

However; a turn based game does not need all players info in memory to do operations on it. You have "unlimited" time to process an operation. I have not done any work on a turn based game, but I believe there are two things here you need to worry about: verifying a users move and reacting to that move. As we have unlimited time to process this, we could easily use a database here to directly process every input that we get. With postrgresql we could even put the reaction rules into the database. Then you don't have to worry about memory or threading because it is handled by the database.

In practice you will need an executable in between your database and the input from the users because of security and some things that the database could not do. Even if you have a lot of connections at the same time, I cannot see that memory would be a problem here.

So really the answer is: use a database, you don't really need to worry about memory with a turn-based game if you do.
> 1 votes

---
Tags: server, multithreading, memory-efficiency, turn-based-strategy
---


title: Create edges in Blender

text:
# Question
Title: Create edges in Blender
I've worked with 3DS Max in Uni and am trying to learn Blender.

My problem is I know a lot of simple techniques from 3DS max that I'm having trouble translating into Blender. So my question is:

Say I have a poly in the middle of a mesh and I want to split it in two. Simply adding an edge between two edges. This would cause a two 5gons either side.

It's a simple technique I use every now and then when I want to modify geometry. It's called "Edge connect" in 3DS Max.

In Blender the only edge connect method I can find is to create edge loops, not helpful when aiming at low poly iPhone games.

Is there an equivalent in blender?

# Answer
Luckily, Blender's BMesh support is finally here, as of 2.63. You're looking for the "Knife" tool. See http://wiki.blender.org/index.php/Dev:Ref/Release\_Notes/2.63/BMesh

hit `K` in edit-mode to switch to the knife, and click to set up points to "cut". Spacebar exits knife mode.
> 5 votes

---
Tags: 3d, models, 3d-meshes, blender, 3dsmax
---


# Question
Title: Optimizing graphics for an iOS flash game
A friend of mine and myself are working on a flash developed iOS (and later Android) puzzle board game. He's a developer and I'm a designer/developer so (no surprise) we have different points of view.

* His method: make small tiles (100x100px) in Photoshop join them into the board and then in flash apply effects to the board to avoid repetition (80's not in the good way).
* My method: precompose the whole board (960x640px+bleed) in Photoshop and than mask active and inactive areas in flash.

What do you think?

# Answer
> 4 votes
If both methods give you the same result, and if you're not programming it, let your programmer decide. If it's easier for him to implement this one way, why would you force him the other way?

# Answer
> 1 votes
I would tend to agree with the method of creating the game board in Photoshop. It would probably look better this way, but more importantly, you may run into performance concerns with the tile/effects method.

I'm not sure how your partner planned on adding effects or variations to the tiles, but it sounds like it could come at a CPU cost. If, for example, he was using filters or alpha blending, the rendering cost for those tiles would be far greater than a bitmap. Also, using bitmaps opens up some opportunities for tapping the GPU on iOS devices.

In over 6 years as a Flash developer, I've found that the more pre-rendering you can do, the better your performance will be. I always use bitmaps wherever possible, and the game board (which doesn't change or rotate much, if at all) is the absolute perfect place to use a pre-rendered bitmap.

# Answer
> 0 votes
I'm not sure how iOS deals with its video memory, the old PSP was faster if you rendered small objects rather than big ones.

The only way to know for certain is to benchmark it.

---
Tags: graphics, flash, ios, graphics-programming, graphic-effects
---


# Question
Title: Server Client position information exchanging
I am doing small game in xna client/server, there can be 50f per seconds, but i don't belive that each client has to sent 50 mesagges about only their position, and then get back from server, regular ping is 50ms so even if 20 messages per second then success, so how it is made that everyone see immediately that someone else changed its position?

# Answer
> 2 votes
i recommend to all who want to implement multi player this article http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/

# Answer
> 0 votes
Generally, you don't send 50 movement packet updates a second, normally it should be around 20. Quake 1 had 10 packets/second. What you would do is send say 20 movement packets a second, and have the other clients interpolate between the old position and the new position to stop the jitteryness.

That won't be immediate, but networking never is. Even over fast LAN connections, there would still be about 2-5 frames latency.

The client doesn't sent the position, and then move when the server lets him. That would introduce large amounts of delay that would make it unplayable. (Assuming real time here). What you would do is the client would tell the server that I am moving here, and the server would go off to tell all the other clients.

It would also be possible to have some form of anti-cheat system, where the server watches where the player is moving to, and figures out if it is valid. So it would verify that it is not inside a wall, not teleporting across the map, etc.

---
Tags: xna, client-server
---


title: Pong Collision Help in C# w/ XNA

text:
# Question
Title: Pong Collision Help in C# w/ XNA
Edit: My goal is to have it function like this:

Ball hits 1st Quarter = rebounds higher (aka Y++) Ball hits 2nd Quarter = rebounds higher (using random value) Ball hits 3rd Quarter = rebounds lower (using random value) Ball hits 4th Quarter = rebounds lower (aka Y--)

I'm currently using Rectangle Collision for my collision detection, and it's worked. Now I wish to expand it.

Instead of it simply detecting whether or not the paddle/ball intersect, I want to make it so that it can determine what section of the paddle gets hit. I wanted it in 4 parts, with each having a different reaction to impact.

My first thought is to base it on the Ball's Y position compared to the Paddle's Y position. But since I want it in 4 parts, I don't know how to do that.

So it's essentially be

```
if (ball.Y > Paddle.Y)
{
PaddleSection1 == true;
}

```

Except modified so that instead of being top half/bottom half, it's 1st Quarter, etc.

# Answer
If you want to split the paddle into 4 areas and see which one of the four sections it has hit you could do simple comparisons like your if statement above.. if its above or below the mid point in the X or Y position you will now if its left or right, top or bottom...

Assuming ball.Y and Paddle.Y are in the same coordinate system (I am assuming 0,0 is in the bottom left corner of the screen) and you already know that the two have collided, then

```
if ( ball.Y > Paddle.Y + (Paddle.Width * 0.5))
{
    Top of Paddle
}
else
{
    Bottom of Paddle
}

```

And you could extend this to the X coords for Left and right as well.

Hope this helps
> 1 votes

# Answer
To split a paddle into four sections along its Y-axis, you could measure penetration percentage through the bat. Hitting the top would be `0.0f`, the bottom would be `1.0f`. The second quarter would be between `0.25f` and `0.5f`, etc.

Following is a method to calculate the penetration depth and a method which translates that into the far more important quarter.

```
// Note: This method can return a value > 1.0 or < 0.0 if the paddle and ball are
// not actually colliding.
float PenetrationDepth(Vector2 ballOrigin, Vector2 paddleOrigin, float paddleThickness)
{
    float paddleEdge = paddleOrigin.Y - paddleThickness * 0.5f;
    float ballRelativePos = ballOrigin.Y - paddleEdge;

    float ballDepth = ballRelativePos / paddleThickness;
    return ballDepth;
}

enum PenetrationQuarter { None = 0, First, Second, Third, Fourth }

PenetrationQuarter GetPenetrationQuarter(Vector2 ballOrigin, Vector2 paddleOrigin,
    float paddleThickness)
{
    float depth = PenetrationDepth(ballOrigin, paddleOrigin, paddleThickness);
    if (depth > 1.0f || depth < 0.0f) return PenetrationQuarter.None;

    int quarter = (int)(depth * 4) + 1;
    // Edge case: If depth was 1.0, quarter will be 5, which is within quarter 4
    if (quarter == 5) quarter = 4;

    return (PenetrationQuarter)quarter;
}

```

Edit: Fixed some (fairly terrible) logic errors.
> 1 votes

# Answer
The most efficient way I've found to do this exact thing in my game is by inserting this code:

```
    public void BatHit(int block)
    {
        if (direction > Math.PI * 1.5f || direction < Math.PI * 0.5f)
        {
            switch (block)
            {
                case 1:
                    direction = MathHelper.ToRadians(200);
                    break;
                case 2:
                    direction = MathHelper.ToRadians(195);
                    break;
                case 3:
                    direction = MathHelper.ToRadians(180);
                    break;
                case 4:
                    direction = MathHelper.ToRadians(180);
                    break;
                case 5:
                    direction = MathHelper.ToRadians(165);
                    break;
                case 6:
                    direction = MathHelper.ToRadians(130);
                    break;
            }
        }
        else
        {
            switch (block)
            {
                case 1:
                    direction = MathHelper.ToRadians(310);
                    break;
                case 2:
                    direction = MathHelper.ToRadians(345);
                    break;
                case 3:
                    direction = MathHelper.ToRadians(0);
                    break;
                case 4:
                    direction = MathHelper.ToRadians(0);
                    break;
                case 5:
                    direction = MathHelper.ToRadians(15);
                    break;
                case 6:
                    direction = MathHelper.ToRadians(50);
                    break;
            }
        }

        if (rand.Next(2) == 0)
        {
            direction += MathHelper.ToRadians(rand.Next(3));
        }
            else
        {
            direction -= MathHelper.ToRadians(rand.Next(3));
        }
        AudioManager.Instance.PlaySoundEffect("hit");

    }

```
> 1 votes

# Answer
Johnathan Hobbs is close in his answer. I would suggest ditching corners, and going with a percentage base.

Hitting the paddle on the left-most edge gives an angle of, say, -60 degrees (2pi/3, I think). Hitting the right-most edge is +60 degrees.

So your range is 120 degrees. Calculate the relative Y of where the ball hit, map it from \[0 .. 1\] (a percentage) to \[-60 ... 60\] and that's the angle of reflection.

I used something quite similar in my Flash block-paddle game. The benefit of this approach is:

* simplistic (easy to code)
* "realistic" (users can understand how it works quickly and "aim" where they want the ball to go).
> 0 votes

---
Tags: xna, c#, collision-detection
---


# Question
Title: Loading content (meshes, textures, sounds) in the background
In my game, I am aiming for a continuous world, that is, a world where you can go anywhere without breaking the immersion through load times and "virtual seams".

My world is broken up into regions, which are nodes in a graph. A region is considered adjacent to another if it can be travelled to or seen from that region. In order to keep this continuous, I want to preload the assets needed in the adjacent regions (such as world meshes, textures, and music) before they are actually used.

As for actually loading the content, I use a manager that keeps at most one copy of each asset in memory at a time, accessible by its filename. When I try to access an asset, it loads it (if necessary) and then returns it. I can then unload any asset that is currently loaded to save memory.

Clearly, I want to do this in the background so there are no hiccups. I assume I have to use threads in some way, but I'm not sure how.

# Answer
> 1 votes
I think I have figured it out. I'll process the content using a job queue and send thread-safe messages to the main thread to tell when an asset has loaded. When the assets are needed, the engine will wait (if necessary) for all the required assets to load and then continue with business as usual.

---
Tags: c#, multithreading, loading
---


# Question
Title: What file formats and conventions should I support to make my game engine artist-friendly?
I'm writing a game engine, and I want to know what I should do to make it more artist-friendly. I don't want to be too limiting in terms of what file formats I support, etc.

Are there specific formats artists like to model in, or does it not matter, because the 3D modeler abstracts the data storage away?

Is it okay if I don't support per-vertex coloration in my game engine? If I have to store a diffuse, specular, ambient, and emissive color value for each vertex, it doubles the size of the vertices, in the buffer. Is it reasonable to ask artists to do all these things in the textures or maps?

# Answer
Create or decide on internal data formats for your engine first; you can use custom formats or handle standard ones, however you prefer. Then use this code will eat any format as an intermediate point in your content pipeline to eat your artist's output and un-eat whatever internal formats you decided to use.

When I suggest assimp I'm really just suggesting that you have a pipeline that has an intermediate step so you can be flexible. Source -\> Intermediate Conversion -\> Runtime. Not only can you target different runtime environments more easily, but you can change sources if something really bad happens.

The main point here is that your engine only supports one format, ever, the tools of the content pipeline are responsible for handling multiple incoming formats. This makes your engine easier to maintain and arguably more stable and less prone to bugs.

Next, stop worrying about vertex size. You're putting the "OMG I'm out of memory" cart waaay before the horse on this. Unless you've already built an engine or three before and know what limits you want to hit, but then you'd already know the answer to vertex size =)

The unspoken secondary point here is KISS Don't go adding in features before they are needed, not only will you waste time on many features that never get used but you'll annoy the pig. For example, don't worry about vertex colors until some artist has a good case for why they need them.

3D modelers don't abstract anything away, you will learn to hate their idiosyncrasies but assimp will help hide that.

One very bad point about letting artists use a variety of different modelers... they cannot exchange work without converting, and there you get the idiosyncrasies again. In terms of an ongoing production it's more sane to standardize.
> 12 votes

---
Tags: art
---


# Question
Title: Running one action on multiple sprites simultaneously
I have created a spiraling animation for a football. I want to be able to run it on 2 sprites simultaneously.

This is what I have done:

```
CCAnimation* footballAnim = [CCAnimation animationWithFrame:@"Football" frameCount:60 delay:0.005f];
spiral = [CCAnimate actionWithAnimation:footballAnim];
CCRepeatForever* repeat = [CCRepeatForever actionWithAction:spiral];
[Sprite1 runAction: repeat];
[Sprite2 runAction: repeat];

```

However, the action is only run on the first sprite. What am I doing wrong?

# Answer
> 3 votes
Actions (sadly) can't be re-used or run multiple times. Instead you'll have to instantiate two actions or copy an existing one.

Something like this should work:

```
[Sprite1 runAction: [repeat copy]];
[Sprite2 runAction: repeat];

```

---
Tags: animation, cocos2d-iphone, cocos2d
---


title: Ragdoll continuous movement

text:
# Question
Title: Ragdoll continuous movement
I have created a ragdoll for my game but the problem I found was that the ragdoll joints are not perfectly implemented so they are continuously moving. Ragdoll does not stand at fix place. I here paste my work for that and suggest some guidance about that so that it can stand on fix place.

```
    chest = new Chest(pX, pY, gameObject.getmChestTextureRegion(),
            gameObject);

    head = new Head(pX, pY - 16, gameObject.getmHeadTextureRegion(),
            gameObject);

    leftHand = new Hand(pX - 6, pY + 6, gameObject.getmHandTextureRegion()
            .clone(), gameObject);
    rightHand = new Hand(pX + 12, pY + 6, gameObject
            .getmHandTextureRegion().clone(), gameObject);
    rightHand.setFlippedHorizontal(true);
    leftLeg = new Leg(pX, pY + 18, gameObject.getmLegTextureRegion()
            .clone(), gameObject);
    rightLeg = new Leg(pX + 7, pY + 18, gameObject.getmLegTextureRegion()
            .clone(), gameObject);
    rightLeg.setFlippedHorizontal(true);

    gameObject.getmScene().registerTouchArea(chest);
    gameObject.getmScene().attachChild(chest);

    gameObject.getmScene().registerTouchArea(head);
    gameObject.getmScene().attachChild(head);

    gameObject.getmScene().registerTouchArea(leftHand);
    gameObject.getmScene().attachChild(leftHand);

    gameObject.getmScene().registerTouchArea(rightHand);
    gameObject.getmScene().attachChild(rightHand);

    gameObject.getmScene().registerTouchArea(leftLeg);
    gameObject.getmScene().attachChild(leftLeg);

    gameObject.getmScene().registerTouchArea(rightLeg);
    gameObject.getmScene().attachChild(rightLeg);

    // head revolute joint
    revoluteJointDef = new RevoluteJointDef();
    revoluteJointDef.enableLimit = true;

    revoluteJointDef.initialize(head.getHeadBody(), chest.getChestBody(),
            chest.getChestBody().getWorldCenter());

    revoluteJointDef.localAnchorA.set(0f, 0f);
    revoluteJointDef.localAnchorB.set(0f, -0.5f);

    revoluteJointDef.lowerAngle = (float) (0f / (180 / Math.PI));
    revoluteJointDef.upperAngle = (float) (0f / (180 / Math.PI));
    headRevoluteJoint = (RevoluteJoint) gameObject.getmPhysicsWorld()
            .createJoint(revoluteJointDef);

    //
    // left leg revolute joint

    revoluteJointDef.initialize(leftLeg.getLegBody(), chest.getChestBody(),
            chest.getChestBody().getWorldCenter());
    revoluteJointDef.localAnchorA.set(0f, 0f);
    revoluteJointDef.localAnchorB.set(-0.15f, 0.75f);
    revoluteJointDef.lowerAngle = (float) (0f / (180 / Math.PI));
    revoluteJointDef.upperAngle = (float) (0f / (180 / Math.PI));

    leftLegRevoluteJoint = (RevoluteJoint) gameObject.getmPhysicsWorld()
            .createJoint(revoluteJointDef);

    // right leg revolute joint
    revoluteJointDef.initialize(rightLeg.getLegBody(),
            chest.getChestBody(), chest.getChestBody().getWorldCenter());
    revoluteJointDef.localAnchorA.set(0f, 0f);
    revoluteJointDef.localAnchorB.set(0.15f, 0.75f);
    revoluteJointDef.lowerAngle = (float) (0f / (180 / Math.PI));
    revoluteJointDef.upperAngle = (float) (0f / (180 / Math.PI));
    rightLegRevoluteJoint = (RevoluteJoint) gameObject.getmPhysicsWorld()
            .createJoint(revoluteJointDef);

    // left hand revolute joint
    revoluteJointDef.initialize(leftHand.getHandBody(),
            chest.getChestBody(), chest.getChestBody().getWorldCenter());

    revoluteJointDef.localAnchorA.set(0f, 0f);
    revoluteJointDef.localAnchorB.set(-0.25f, 0.1f);

    revoluteJointDef.lowerAngle = (float) (0f / (180 / Math.PI));
    revoluteJointDef.upperAngle = (float) (0f / (180 / Math.PI));
    leftHandRevoluteJoint = (RevoluteJoint) gameObject.getmPhysicsWorld()
            .createJoint(revoluteJointDef);

    // right hand revolute joint
    revoluteJointDef.initialize(rightHand.getHandBody(),
            chest.getChestBody(), chest.getChestBody().getWorldCenter());

    revoluteJointDef.localAnchorA.set(0f, 0f);
    revoluteJointDef.localAnchorB.set(0.25f, 0.1f);
    revoluteJointDef.lowerAngle = (float) (0f / (180 / Math.PI));
    revoluteJointDef.upperAngle = (float) (0f / (180 / Math.PI));
    rightHandRevoluteJoint = (RevoluteJoint) gameObject.getmPhysicsWorld()
            .createJoint(revoluteJointDef);

```

# Answer
Luckily, I found the solution of my problem and here I post the answer for other community member to help them. I set Mask Bit for each part of the body like leg,hand,chest,head. So that they don't collide with each other. As a result the continuous movement of the ragdoll was stop.
> 4 votes

# Answer
Well i dont think it's the joint implementation,it's just that ragdolls can't help ,but move when running a physics simulation ,because there's say gravity affecting the parts and joints and now counter force applied to keep them straight.If you just want to keep the ragdoll straight you could limit the joint angles or apply some balancing strategy.
> 1 votes

---
Tags: andengine
---


# Question
Title: Where can I pay artists to make models for my game?
Lets say I get some money for my hobby project, and I would like to start filling it up with good models, instead of some cheap placeholder ones. What are some sites where I can pay people to make models for the game? How much would it cost per asset?

**Edit:** I don't want to hire anybody. I just want to pay them for individual assets.

# Answer
> 17 votes
As some one who ventured a bit into the creation of art, I would really advise you to get in touch with one rather than just "buying" models.

Art from different sources rarely work together (unless of course, they are meant to be) and high quality models alone won't make good graphics, everything needs to be put together with a sense of aesthetics to really convey a sense of quality. Just like starting writing a game without really having a idea how it should be structured doesn't really work just putting some graphics together won't really work either. It really requires expertise. Not just expertise in modelling/painting/pixeling but also in style and aesthetics.

So if you already know someone who is adept in digital art approach him, if not you might want to lurk somewhere (for example some IRC-Channel of some online community) with some artists.

If you have someone ask him about your game, ask what he thinks, ask how he would approach it from a art perspective. You might ask him whether he could do some graphics for it. Just make sure he is a part of the project, and not just some work slave.

# Answer
> 7 votes
You can always use oDesk or eLance. The former offers per-hour jobs, the latter offers fixed-price jobs. I've used them before, oDesk for art assets. You just need to be picky and not pay more than X hours a week; but it can backfire.

I recommend eLance, therefore.

# Answer
> 4 votes
While I haven't officially used it yet, I was told that the DeviantArt marketplace is a great place to find artists eager for work:

http://forum.deviantart.com/jobs/offers/

# Answer
> 4 votes
Have you tried to look on sites like turbosquid and such ? They are full of quality assets, some of them game-ready.

You can get models for free, up to a few thousand dollars for the best ones (the ones I was looking was for an entire city).

EDIT: Looks like turbosquid now also does custom 3D models !

# Answer
> 1 votes
Also check out Freelancer: http://www.freelancer.com/jobs/Game-Design/

I haven't advertised there before specifically in the gaming section, but got work from it before for webdesign and it is a big site.

But anyway, I'd recommend just googling around for their communities/forums then hanging out there for a bit (if you get lucky you might find somebody who agrees to partner with you for free? If it is non-commercial?).

---
Tags: models, art
---


title: Simple collision detection for pong

text:
# Question
Title: Simple collision detection for pong
I'm making a simple pong game, and things are great so far, but I have an odd bug which causes my ball (well, it's a box really) to get stuck on occasion when detecting collision against the ceiling or floor. It looks as though it is trying to update too frequently to get out of the collision check.

Basically the box slides against the top or bottom of the screen from one paddle to the other, and quickly bounces on and off the wall while doing so, but only bounces a few pixels from the wall.

What can I do to avoid this problem? It seems to occur at random. Below is my collision detection for the wall, as well as my update method for the ball.

```
public void UpdatePosition()
{
    size.X = (int)position.X;
    size.Y = (int)position.Y;
    position.X += speed * (float)Math.Cos(direction);
    position.Y += speed * (float)Math.Sin(direction);
    CheckWallHit();
}

// Checks for collision with the ceiling or floor.
// 2*Math.pi = 360 degrees
// TODO: Change collision so that ball bounces from wall after getting caught
private void CheckWallHit()
{
    while (direction > 2 * Math.PI)
    {
        direction -= 2 * Math.PI;
    }

    while (direction < 0)
    {
        direction += 2 * Math.PI;
    }

    if (position.Y <= 0 || (position.Y > resetPos.Y * 2 - size.Height))
    {
        direction = 2 * Math.PI - direction;
    }
}

```

# Answer
> 3 votes
Check my comment for some explanations. Here's a hack:

```
 public void UpdatePosition()
{
    size.X = (int)position.X;
    size.Y = (int)position.Y;
    oldPos.X = position.X;
    oldPos.Y = position.Y;
    position.X += speed * (float)Math.Cos(direction);
    position.Y += speed * (float)Math.Sin(direction);
    bool collided = CheckWallHit();
    if (collided)
    {
       position.X = oldPos.X + speed * (float)Math.Cos(direction);
       position.Y = oldPos.Y + speed * (float)Math.Sin(direction);
    }
}

```

Make sure you return a bool for your collision query. That hack should do the trick..

# Answer
> 0 votes
I'm curious about your direction variable.... I see it being used but not how it is being defined. This may not have a thing to do with it but, it just might.

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


# Question
Title: Which K-factor should be used in case players have different K-factor values
I am implementing a ranking system based on the Elo rating and cannot get a point about the K-factor. If two players with different skills and, therefore, different K-factors are playing, which exactly K-factor should be used when changing their ratings?

For example, player A has rating 2500 and K-factor 16 (probability ~75%) while player B has rating 2300 and K-factor 24 (probability ~25%). If player A wins, do I need to use 16 as K-factor for both players or 16 for player A and 24 for player B?

# Answer
> 1 votes
Each player's new ranking is calculated based on their own K factor. It is just a scaling value to ensure that values converge at a reasonable rate, and can be arbitrarily chosen according to whatever suits your game. In particular, if a new player plays against an old player you usually want a large K factor for the new player to make their rating change more significantly, whereas the older player will have a lower K factor since it's unlikely their rating is a significant over or underestimate of their skill.

http://en.wikipedia.org/wiki/Elo\_rating\_system#Most\_accurate\_K-factor

---
Tags: ranking
---


title: Drawing text from update method in XNA

text:
# Question
Title: Drawing text from update method in XNA
I am having a problem drawing the "Game Over!" text once the user is on the last tile.

This is what I have:

The `Update` and `drawText` methods are in a class named `turtle`:

```
public void Update(float scalingFactor, int[,] map, SpriteBatch batch, SpriteFont font)
{
    if (isMovable(mapX, mapY - 1, map))
    {
        position.Y = position.Y - (int)scalingFactor;
        angle = 0.0f;
        Program.form.direction = "";

        if (mapX == 17 && mapY == 1)// This is the last tile(Tested)
        {
            Program.form.BackColor = System.Drawing.Color.Red;
            drawText(batch, font);
        }
    }
}

public void drawText(SpriteBatch spritebatch, SpriteFont spriteFont)
{
    textPosition.X = 200; // a vector2
    textPosition.Y = 200;
    spritebatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
    spritebatch.DrawString(spriteFont, "Game Over!!!", textPosition, Color.Red);
    spritebatch.End();
}

```

This update is in the `Game1` class:

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

    turtle.Update(scalingFactor, map, spriteBatch, font);

    base.Update(gameTime);
}

```

I have also added the font content to `LoadContent`:

```
font = Content.Load<SpriteFont>("fontType");

```

What am I doing wrong? Why does the text not want to show on game completion? If I call the `turtle.draw()` in the main `Draw` method. The "Game Over" text stays on screen from the beggining. What am I missing?

Thanks

# Answer
You want to keep your drawing and update loops separate. Attempting to draw inside the update loop is likely to cause issues. Additionally, putting logic for drawing a game over message inside the update loop of a game character isn't the best place for it.

You can try using a global variable for setting when your game is over:

```
if (mapX == 17 && mapY == 1)
{
    GameOver = true;
}

```

Then in your draw loop,

```
if (GameOver)
{
    Program.form.BackColor = System.Drawing.Color.Red;
    drawText(batch, font);
}

```

This will allow you to have a bit more control in other aspects as well. For example you can check to see if the game is over before checking for input. That would disallow players from moving around after the game ended.
> 5 votes

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


# Question
Title: Is it possible to billboard a sprite using a transformation matrix?
None of the current topics on billboarding seemed to answer this question.

But, given

* a sprite (or quad) that has it's own 4x4 transformation matrix
* a camera with a view matrix (a standard 4x4 transformation matrix)

is it possible to compute a 4x4 transformation matrix such that when the quad's matrix is multiplied with this matrix it has an orientation of looking at the camera?

# Answer
Yes. Start with the rotation part of the camera-to-world matrix (inverse of the world-to-camera matrix, if that's what you meant by "view matrix"). Set the translation part of the matrix to zero. This will make the quads rotate with the camera. Then, given that the quads have the correct initial orientation, they will face the camera. That is, if the camera setup is such that an identity view matrix results in the camera looking along the +X axis (for example), the quads should be set up to face -X before the camera-facing matrix is applied.

This will make the quads parallel to the image plane. In some cases you might prefer that quads turn to directly face the camera rather than facing the image plane; that approach gives a different look that can be better or worse depending on the situation. Making the quads directly face the camera will require a different matrix for each quad, though, computed like Patrick Hughes suggested in his comment.
> 4 votes

---
Tags: c++, 3d, mathematics, matrix, qt
---


# Question
Title: How do I get the correct values from glReadPixels in OpenGL 3.0?
I'm currently trying to Implement mouse selection into my game editor and I ran into a little problem when I look at the values stored in `&pixel[0],&pixel[1],&pixel[2],&pixel[3];` I get

```
r: 0
g: 0
b: 0
a: 0

```

As you can see I'm not able to get the correct values from `glReadPixels();`

My 3D models are red colored using `glColor3f(255,0,0);`

I was hoping someone could help me figure this out.

Here is the source code:

```
  case WM_LBUTTONDOWN:

  {

    GetCursorPos(&pos);
    ScreenToClient(hwnd, &pos);

     GLenum err = glGetError();

     while (glGetError() != GL_NO_ERROR) {cerr << err << endl;}

     glReadPixels(pos.x, SCREEN_HEIGHT - 1 - pos.y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pixel[0] );

    cerr << "r: "<< (int)pixel[0] << endl;
    cerr << "g: "<< (int)pixel[1] << endl;
    cerr << "b: "<< (int)pixel[2] << endl;
    cerr << "a: "<< (int)pixel[3] << endl;

    cout << pos.x << endl;
    cout << pos.y << endl;

  }

break;

```

I use :

```
WIN32 API
OPENGL 3.0
C++

```

# Answer
FBOs shouldn't be relevant in this case as it's happening outside of the main render.

glReadPixels definitely works as advertised in this kind of setup - I just copied and pasted your code into a program and got expected results. That indicates to me that your problem is most likely elsewhere.

You should check the current value of glReadBuffer - if it's not GL\_BACK then you may not get the end result you want. Also check that you're not doing anything weird like creating a single-buffered context.

Check your value of SCREEN\_HEIGHT - is it actually the height of your window's client rect? If not then the read will be off-location. At this point I have to bring up the fact that the size you create your window at is not necessarily the size of your client rect - if you're running in a windowed mode then the size params you pass to CreateWindow(Ex) will be inclusive of title bar, borders, etc. You may already be aware of this - ignore if so.

You're not showing the definition of your "pixel" variable - "unsigned char pixel\[4\]" is what it should be here. Check that too.

Purely cosmetic but you don't need to pass "&pixel\[0\]" as your data parameter. Just "pixel" will do.

Reading as GL\_RGB won't give you a meaningful value in your alpha channel (which you may not have anyway if your pixel format doesn't have destination alpha) - use GL\_RGBA instead.

Also cosmetic, but I'm not certain what you're trying to achieve with that glGetError loop - glGetError doesn't behave like that, and you're not going to get meaningful or helpful info from it.
> 2 votes

---
Tags: c++, opengl
---


# Question
Title: How can I calculate DeltaTime in seconds?
Here is how I've been trying to implement delta time based on different internet resources.

```
var startTime:Number = getTimer();
game.Update(deltaTime);
deltaTime = Number(getTimer() - startTime) * 0.001;

```

My issue with this is it doesn't seem to be giving me accurate timing. The main update shows the frame time at 0.001 and when reinitializing the level it goes to 0.002. I'm using dt else where for a timer and later on time based physics so I would like it to work as expected. I must be missing something silly.

# Answer
I have tried different methods to get the elapsed time and this one has worked best for me so far:

```
private var _t:int;

// initialize _t and add ENTER_FRAME listener
private function init():void {
    _t = getTimer();
    addEventListener(Event.ENTER_FRAME, onEnterFrame);
}

private function onEnterFrame(e:Event):void {
    var t:int = getTimer();
    var dt:Number = (t - _t) * 0.001;
    _t = t;
    game.update(dt);
}

```
> 4 votes

---
Tags: actionscript-3, game-loop
---


# Question
Title: OpenGL: glGetError() returns invalid enum after call to glewInit()
I use GLEW and freeglut. For some reason, after a call to glewInit(), glGetError() returns error code 1280. Reinstalling the drivers didn't help. I tried to disable glewExperimental, it had no effect. Code worked before, but I am not aware of any changes I could possibly make.

Here's my code:

```
int main(int argc, char* argv[])
{
    GLenum GlewInitResult, res;

    InitWindow(argc, argv);

    res = glGetError(); // res = 0

    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();

    res = glGetError(); // res = 1280

    glutMainLoop();

    exit(EXIT_SUCCESS);
}

void InitWindow(int argc, char* argv[])
{
    glutInit(&argc, argv);

    glutInitContextVersion(4, 0);
    glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
    glutInitContextProfile(GLUT_CORE_PROFILE);

    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,
    GLUT_ACTION_GLUTMAINLOOP_RETURNS);

    glutInitWindowPosition(0, 0);
    glutInitWindowSize(CurrentWidth, CurrentHeight);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

    WindowHandle = glutCreateWindow(WINDOW_TITLE);

    GLenum errorCheckValue = glGetError();

    if (WindowHandle < 1)
    {
        fprintf(stderr, "ERROR: Could not create new rendering window.\n");
        exit(EXIT_FAILURE);
    }

    glutReshapeFunc(ResizeFunction);
    glutDisplayFunc(RenderFunction);
    glutIdleFunc(IdleFunction);
    glutTimerFunc(0, TimerFunction, 0);
    glutCloseFunc(Cleanup);
    glutKeyboardFunc(KeyboardFunction);
}

```

Could someone tell me what I am doing wrong? Thanks.

# Answer
Try disabling the `glewExperimental` support, as that may be attempting to call something in OpenGL that isn't supported by your particular driver. That actual error is `GL_INVALID_ENUM` which, unfortunately, can be raised from pretty much anywhere.

Also, what OpenGL driver are you using and in what environment? Some drivers may allow you to enable a debug log or the like. Unfortunately, GLEW itself is not written in a way that makes it easy to add in generic `glGetError()` checks after every extension query or the like, but you might be able to narrow it down by adding it in at strategic locations.
> 2 votes

# Answer
The error code given, 1280, corresponds with GL error 0x0500

GL\_INVALID\_ENUM, 0x0500: Given when an enumeration parameter is not a legal enumeration for that function. This is given only for local problems; if the spec allows the enumeration in certain circumstances, and other parameters or state dictate those circumstances, then GL\_INVALID\_OPERATION is the result instead.

http://www.opengl.org/wiki/GL\_Error\_Codes

Apparently one of the enums you are passing into OpenGL is bad. I've never used GLUT so I have no idea what the possible enum error could be.
> 0 votes

---
Tags: c++, opengl, glut
---