# Question
Title: OpenGL ES 2.0: Calculated Cube Vertex Normals Verification
Could I kindly ask to **confirm**, that the **calculated normals are correct**, please? I have calculated them on my own, but my testcube is still strangely lighted within OpenGLES 2.0.

* The **vertices** were exported from 3D authoring application.
* The **vertex normals** were calculated using matrix cross product.
* The **vertex and fragment shaders** I were exact copies from the book, so there should not be a bug.

The output in OpenGL looks like the sphere is lighted from its bottom. Moreover, it looks, like the box is visible from inside, as the top part is always transparent. Any idea, where can be a problem?

## Added:

The vertex normals are calculated based on **triangulated** quad-polygons. The triangulation is performed internally, by the 3d application. Vertices/ indices are generated by calling API calls of that application.

---

```
#begin 8 vertices
vs 24
v -25.000000 -25.000000 -25.000000
v 25.000000 -25.000000 -25.000000
v -25.000000 25.000000 -25.000000
v 25.000000 25.000000 -25.000000
v -25.000000 -25.000000 25.000000
v 25.000000 -25.000000 25.000000
v -25.000000 25.000000 25.000000
v 25.000000 25.000000 25.000000
#end 8 vertices

#begin 12 faces
fs 36
f 0 2 3
f 0 3 1
f 0 1 5
f 0 5 4
f 0 4 6
f 0 6 2
f 1 3 7
f 1 7 5
f 2 6 7
f 2 7 3
f 4 5 7
f 4 7 6
#end 12 faces

#begin 8 calculated normals
ns 24
n -0.577350 -0.577350 -0.577350
n 0.816497 -0.408248 -0.408248
n -0.408248 0.816497 -0.408248
n 0.408248 0.408248 -0.816497
n -0.408248 -0.408248 0.816497
n 0.408248 -0.816497 0.408248
n -0.816497 0.408248 0.408248
n 0.577350 0.577350 0.577350
#end 8 calculated normals

```

*I use OpenGL ES 2.0, but that should not be relevant at this moment.*

---

## Update:

I can confirm now, that the **calculated vertex normals are correct**, and can therefore be used by others, to verify correctness of their triangulated cube vertex normals calculations.

However, I still have a problem that all the **vertices, which are in positive z axis, are not rendered**. Not sure if they are culled, but I have pretty large frustum. Vertices in the -z axis are kept, so the rendered mesh looks like cut in half, as it is position in 0 z-axis.

This lines below show that I should not concsicously setup small render area:

```
mProjection = glm::perspective (45.0f, (float)WINDOW_WIDTH / (float)WINDOW_HEIGHT, 1130.0f, -1130.0f);

mViewTransformation = glm::lookAt(glm::vec3(vIntCamera.x, vIntCamera.y, 1130.0f), glm::vec3(vIntCamera.x, vIntCamera.y, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));

```

**Any ideas, please, what else should I check?**

## Solved:

Eye position of the camera (in glm::lookAt() function) should be above the top of the perspective frustum, defined by glm::perspective().

Thanks for your support guys, especially with the upper part of my question.

# Answer
Without a picture I'll have a rough guess on some of your problems.

Normals: If this is a cube, I'd expect all the normal component values to be +/- 0.577350 in different combinations depending on the vertex. Where you have other values the normal is no longer being properly averaged from the three faces that share it and it'll be tending more in one direction. Because you're using shared vertices for the faces then despite it being a cube, it's trying to be lit as if it's a sphere. If you wanted it to look like an actual cube you'll need to duplicate up the vertices and have unique normals for them.

"visible from inside": This sounds like a winding order issue. Graphics hardware tends to have Backface Culling enabled as a speed optimisation, depending on the order of the vertices given to the hardware it makes a decision as to whether it thinks a polygon faces towards or away from the viewer. It's possible you can fix this problem by changing the order of the vertices in your faces, so the first face would become "0 3 2" instead of "0 2 3".

A picture of the output would help to be more specific, as would a more accurate description of what problems you actually have, for example, you say it's lit from below, is this a problem or was that just stating how it looks?

Quick update:

You can display the normals manually by drawing some simple lines, just use the vertex position as the start point, then add the normal value (scaled by some constant factor to ensure it's the length you want) and add this to the original vertex position to generate an end point.
> 4 votes

# Answer
I doubt GL ES has geometry shaders but just in case it does (or if you can test your data on something with a full OpenGL 3 and above), my answer to this question on SO provides a geometry shader to visualize your normals.
> 0 votes

---
Tags: opengl, opengl-es, shaders
---


# Question
Title: What time to display in text messages in multiplayer game?
Say I'm having a multiplayer RTS game. There's a main server for each individual game and several clients connected to it. All packets are sent to server first and then server retransmits them back to clients.

Say Server is located in one time-zone and all of the clients are in different time-zones. ClientA send a text message in chat at 12:03, what times should be stamped for other clients? Should his message be uniformely timestamped by Server (12:02) or each client should timestamp the message whenever it is recieved (12:04, 16:04, 03:03, etc..). Bear in mind, that all the messages are to be in the same order on all clients, server takes care of that.

So thats the question - use local time for each client or use global server time to timestamp chat messages?

# Answer
Since you use a central server, the server will keep track of game events and clients will sync their state with the server state. When a message is received by the server at 12:02, the message should show up at the client as being sent at 12:02. However, when dealing with different timezones, you want the client to display local times. This is more convenient and natural to read for the user, as he does not need to think about all the time differences.

The approach I would recommend is timestamping each message in UTC (a method for creating an UTC timestamp is present in almost every class or system library). When the client has to display the message time, the time is converted to the local time zone before being rendered to the screen.
> 13 votes

---
Tags: multiplayer, client-server, timing
---


# Question
Title: Best/Efficient way to implement a 3d Collision
I've already programmed a 2d based collision system for a previous game. It was my first collision system and it was ugly. I was looking for collision between objects by checking all objects with all objects. I've already heard about a grid system with cells where an object will only look the collision with other objects from its current cell(s). Is it really a good way to check collision?

I'd like to have a good technique to loop trough all my items in a 3d world.

# Answer
> 10 votes
You're going to need a good space-partitioning algorithm, commonly used in 3D are octrees.

After that you could surround models etc with bounding spheres in which they fit neatly because a collision between bounding spheres is very easy to calculate. After you know that two bounding spheres collide you can either iteratively make the bounding spheres smaller and adding bounding spheres to keep the object covered in them, or us another smart algorithm to calculate collisions between two complex objects.

See this image:

# Answer
> 12 votes
Ultimately I think the answer to your question is going to depend upon the needs of your particular application, as there isn't a one-size-fits all solution. Although there are a number of decent resources on the web, you'll save yourself a lot of time and frustration by picking up Christer Ericson's Real-time Collision Detection, which lays out in great detail a wide variety of techniques and algorithms, with example C++ code.

It helped me to take baby steps before jumping into trying to build a grand system. Writing a function to determine if a point is in a plane, then if a point is in a triangle, if a ray is in a triangle, etc. Then moving onto static tests of various convex solids: AABB vs. Triangle, etc. With time things that seemed impenetrable (forgive the pun) at first became less daunting. Here is a listing of a good number of tests, with example code:

http://www.realtimerendering.com/intersections.html

In the meantime, since I know not everyone can just fork out 70-80$ for a book at will, here are some terms you might want to look into:

* Spatial Partitioning, Octrees, Quadtrees, BSP trees
* BIH Trees
* Bounding Volumes and Bounding Volume Hierarchies
* Discrete vs. Continuous Collision Detection
* Separating Axis Theorem
* GJK Algorithm

---
Tags: collision-detection
---


# Question
Title: Copyrights and Usage of 3rd Party Intellectual Property
I develop a **game for a mobile platform**. I would like to implement a movie figure/creature/character/vehicle into the game.

*I wish to ask about Copyrights:*

Is it acceptable, if **I implement famous movie-like creatures** (ex: Alien, Predator, Star Ship vehicle) into my game? Occasionally, I see games based on movies: "Star Trek, Star Wars, James Bond, etc..". If I wish to create a game based on successful movie, do I have to obtain approval?

What about **songs**? If I legaly purchase a CD in the store, can I use the song into my game?

Are there any conditions, under which I can use movie-like characters in my game? For example, if the game is going to be shareware/freeware, if the reneues does not exceed certain amount, or if some percentage of the original character look is modified?

# Answer
> 5 votes
I am not a lawyer. This is not legal advice. What follows is a basic overview of the issues that may surround the material you've brought up.

**Music:** Read the license on your music. You've purchased it for personal use on personal devices, not for distribution. Movies featuring a popular song didn't buy a CD from a store and copy it into their movie; they sought a license from the publisher and you'll need to do that too.

**Characters:** In most cases, the kind of characters/races/etc you mentioned will be the intellectual property of some person, company, etc. You will probably not have any permission whatsoever to use it in any way. The exception is anything covered by fair use: for instance, by creating a character who is completely original, but also a parody or reference to someone else covered by IP.

Bear in mind there is public domain material, which is material for which intellectual property rights were forfeited or expired (e.g. a lot of music before the 1930s is no longer covered by copyright). You can use public domain material without restriction.

Ultimately, it is up to you to determine whether the thing you want to use is the intellectual property of someone, and if so, what permissions they extend to you (assume none until proven otherwise). For instance, Blizzard will often permit third parties use of their content so long as it is beneficial to Blizzard (e.g. webcomics, machinimas - it's all just publicity for them).

If there are more specifics I'll leave someone else to address them.

---
Tags: copyright, intellectual-property
---


# Question
Title: Moving an Object along a Curve while Rotating it
I woud like to **move an object along a curve**. At particular points on the curve, I wish the object to change speed and rotate itself along its axis.

Imagine an airplane flying to a destination. It has its path it must follow, plus, it adjusts its speed and orientation all the way (heading, pith, bank).

*Could I kindly ask for a **startup information** on the following:*

* What **kind of curves** to use to smoothly interpolate an object
* What **formulas** to use for reliable interpolation, where I could control the speed of moving oject, and the transition between curve knots would be seamless
* What **information** should be **exported** from a 3D authoring application
* Should I use quaternions **slerp()** for this?

If you know about a **book that covers this topic efficiently**, that would hlep the most. Thank you.

# Answer
For the motion curve, I'd suggest using Hermite curves. You simply give a starting point/velocity and an ending point/velocity, and it creates a nice and smooth curve between those two. Use the ending point/velocity of the first pair of points as the starting point/velocity of the next pair of points and you have a nice long and winding curve that is seamless.

This perfectly handles the requirement to manage the speed: you give a list of points in time with velocities you choose, and it gives you the seamlessly interpolated position and velocity values. If you want to go with this, all you need to extract from the 3D authoring application is points and velocities in the path that you desire. You can also generate them in runtime, perhaps based on user input.

To adjust the orientation, you have a number of options. If the airplane will always point towards where it's going (which is the case that makes sense) you can use the interpolated velocity vector from the Hermite curve to find where your ship should point towards. If you know the up vector (it's moving in a plane, or you know which direction should be up) you can calculate the third axis by cross(front, up) and there you have your orientation.

If you want a somehow "wobbly" orientation so that the plane sometimes deviates from the front direction in the path, you can use the front direction as the desired direction, and successively do one-step slerp between the current orientation and the desired orientation.

If you want custom orientations that have nothing to do with the path, you can of course supply a list of orientation quaternions to this. Then your points become (point, velocity, quaternion). Then you can use slerp between two successive quaternions to set your orientations along the way. Don't forget that slerp is a *linear* interpolation method. However, it should usually be fine. If you find that the rotations are not smooth enough in the seams, you can try interpolating the list of quaternions with a Bezier curve, as explained here on section 7.

Here is some source code that can help you get started. It has a number of smooth interpolation techniques for a list of quaternions (squad, bezier, etc).

Let me know if you have any questions!
> 7 votes

---
Tags: mathematics, game-mechanics, animation, quaternion
---


# Question
Title: Job title for a roleplaying event gamemaster in an online RPG?
I'm considering creating a position in an online RPG where the responsibilities would mainly involve conceiving roleplaying-oriented events and plotlines and executing on them using developer tools such as the ability to create instances of NPCs/items and the ability to control NPCs. Examples of events/plotlines might be "ancient god of evil breaks loose from his prison and attacks the realm" or "upcoming marriage between offspring of powerful dynasties has political opponents trying to disrupt it".

What is the best job title for this sort of position?

The first thing that popped into my head was "customer experience associate", but this appears to have an established meaning in retail where it's a way of dressing up "salesperson". "Game master" positions in MMOs are generally helpdesk positions with no creative duties or authority. I want to select something that neither exaggerates nor undersells this person's level of responsibility.

# Answer
If you're going to pay them as a GM/CSR, the title needs to reflect that. Community Event Manager.

On the other hand, if you're expecting them to use the developer tools to design new content, you're probably not going to find anyone willing to take that kind of pay for that responsibility (and do a good job of it).
> 3 votes

# Answer
Something to do with controlling would work, since it shows they are actually doing something.

Perhaps a Quest Controller?
> 1 votes

# Answer
The best thing I've come up with since I wrote this question is Dynamic Content Coordinator.
> 1 votes

# Answer
How about Dungeon Master (DM) to borrow from games like D&D here the DM is the one driving the story and inserting interesting events.
> 0 votes

---
Tags: mmo, rpg, online
---


# Question
Title: Programmatically set color of Box2D body's sprite or image
In my basic Cocos2D + Box2D iPhone app I have a bunch of circular Box2D bodies. I'd like to change the color of the circles programatically. **What's the easiest way to do this?**

So far I'm just assigning a CCSprite\* to the b2body-\>userData. So perhaps I can change the colors in my sprite sheet programmatically? Seems like there's an easier way. I'm just not sure what it is.

Cheers!

# Answer
> 5 votes
cocos2d CCSprites have a three byte color property. You can use it like `sprite.color = ccc3(r, g, b)`.

---
Tags: box2d, cocos2d, color, ccsprite
---


# Question
Title: More smaller maps among which player can travel
I am developing 2d game, where maps are tile based, small about 20x20 tiles and player can travel between a lot of maps (in my game rooms) like this. The maps are connected sometimes verticaly and sometimes horizontaly and together they make one big cave.

Should I create a class where one 2d array holds all the maps (another 2d arrays), or is there any other way? Whats the most efficient way to create them in this class? Thank you for your help.

# Answer
> 7 votes
Use a 2D array that links a set of coordinates to a map object. When you get down to it, the only operation you'll be performing here is "get me the map at coordinates (X,Y)" and a 2D array is in a very literal sense *made* for that.

Each map should also know its own coordinates so that when the player exits right, you can say "get me the map at coordinates (X+1, Y)".

To make it easy to move maps around, map objects should not know their own coordinates until the first time they're requested from that 2D world array. At that point, the 2D world array tells it its coordinates.

### A space concern

Since you seem to be making a winding cave network, you may become concerned once you run into a situation like this:

Lots of wasted space in the array, right? Only a *fraction* of coordinates are used. At this point, you're only wasting, maybe, a few kilobytes of data on unused coordinates. At this scale you shouldn't even be remotely concerned. If, however, the space wastage somehow becomes an issue, you can potentially trim a tremendous amount of fat by splitting your world into regions:

*All the black space: Some saved kilobytes.*

Each region is a small world in itself. To pass between regions, a region transition would say "go to region X, coordinates (X,Y)." Since your regions have no particular arrangement in space, put them in a 1D array.

---
Tags: java, tiles, maps
---


# Question
Title: What are the most suitable 3D sound engines out there for a FPS?
We are looking for a good 3D sound engine for a game written in C#. We know of irrKlang, which looks great but isn't free for commercial uses, nor is it open source. XNA has an alright one, but it binds us to DirectX and therefore, windows. Are there any other good free ones out there?

# Answer
FMOD and OpenAL are two very powerful alternatives to using DirectX directly. The Tao libraries include OpenAL .NET implementations (as well as OpenGL and other game libraries), but FMOD will need to be used via P/Invoke.

Additionally, OpenAL is free, and FMOD is only free as long as your application is free (see FMOD Non-Commercial License here).
> 4 votes

# Answer
If you want to sell your game but not pay for a 3d audio library, you're pretty much stuck with OpenAL.

It may cost money, but FMOD has an extremely well thought out API. Something else to consider is the added value of their EventSystem. It's not as robust as Wwise, but being able to define high-level sound events in an external authoring tool makes achieving high quality audio a lot easier. Stuff you would have to spend time coding is easily defined in terms of parameters and sound instances in FMOD.

If only they allowed you to add events as well as sound instances to event layers.

BASS from Un4Seen is another free-to-try, pay-to-sell library that supports Windows and OS X.
> 2 votes

---
Tags: c#, sound
---


title: Semi-fixed or Fully-fixed timestep?

text:
# Question
Title: Semi-fixed or Fully-fixed timestep?
I am making an iphone shmup and am trying to decide what type of game loop to use. I want to use either semi-fixed timestep or fully-fixed timestep.

With semi-fixed timestep I will make zero or more update(FIXED\_INTERVAL) calls followed by one update(dt) call where dt \<= FIXED\_INTERVAL per game loop. As I understand it the drawbacks with this method are that my physics update(dt) logic is going to be more difficult to program because I basically have to assume a variable dt for every update. And then I've also heard that each run of my game will be slightly different due to floating point values not being the same every time.

Then with fully-fixed timestep I am making zero or more update(FIXED\_INTERVAL) calls followed by one interpolation(dt/FIXED\_INTERVAL) call where dt \< FIXED\_INTERVAL per game loop.

So it seems like the big decision I really have to make is: do I want to tackle the challenge of implementing an update(dt) with a variable dt or do I want to tackle the challenge of implementing interpolation?

Now from what I've read the majority of people are saying to use fully-fixed and do the interpolation. But when I think about implementing interpolation it seems like I'd be a lot more complex than an update(dt) with variable dt. This is because if I use interpolation I have to remember both the previous state and the current state. So if I want to use interpolation I have to come up with an additional layer of indirection that abstracts out entire individual game states. Whereas with semi-fixed timestep where I don't have to use interpolation I don't have to come up with a game state abstraction because there's always only one game state and it's simply the "global arrays" that represent my enemies, and enemy bullets etc.

So what's the more practical choice: do I implement it semi-fixed knowing that my physics updates could get complicated with the variable dt. Or do I use fully-fixed and try to come up with a game state abstraction so that I can keep track of previous state and current state in order to perform interpolation?

# Answer
**Fully Fixed**

You loose most of the benefits of a fixed timestep when you throw in a variable step once each frame.

Noel Lopis has a great write up on how he implemented a fixed time step in his game Casey's Contraptions. As bonus to you he is an iphone developer, though his technique is not iphone specific.

Some highlights from the article

* Use a time accumulator.
* Use 120Hz physics rate for a 60Hz frame rate.
* Simulate one fixed step into future and use left over time accumulation to lerp drawing code between current physics state and future physics state.
* various gotchas
> 12 votes

# Answer
What you refer to as "semi-fixed" and "fully-fixed" timestep are, in my mind, *both* fixed timestep -- the *dt* that you are passing to your `update` call doesn't change between frames.

So, your question is actually "do I want to implement interpolation for the purposes of rendering?" The answer is: *probably not*.

Interpolation is something you would only want to do if your fixed `update` timestep is markedly different to your target `render` timestep. It's not uncommon for games that have a strenuous `update` phase to only call `update` at, say, 10Hz, but render at full framerate.

Since you're writing an iPhone shmup, neither your `update` nor your `render` need be particularly CPU intensive; you can easily lock your framerate to 30Hz or 60Hz, not bother with implementation, and still have a smooth-looking game.
> 2 votes

---
Tags: game-loop
---


# Question
Title: How do you determine which object/surface the user's pointing at with lwjgl?
Title pretty much says it all. I'm working on a simple 'lets get used to lwjgl' project involving manipulation of a rubik's cube, and I can't figure out how to tell which side/square the user's pointing at.

# Answer
You'll want to use 3D picking. Here's some code I use in my game.

First I cast a ray from my camera. I'm using the mouse, but if you're just using where the user is looking, you can just use the center of the window. This is that code from my camera class:

```
public Ray GetPickRay() {
    int mouseX = Mouse.getX();
    int mouseY = WORLD.Byte56Game.getHeight() - Mouse.getY();

    float windowWidth = WORLD.Byte56Game.getWidth();
    float windowHeight = WORLD.Byte56Game.getHeight();

    //get the mouse position in screenSpace coords
    double screenSpaceX = ((float) mouseX / (windowWidth / 2) - 1.0f) * aspectRatio;
    double screenSpaceY = (1.0f - (float) mouseY / (windowHeight / 2));

    double viewRatio = Math.tan(((float) Math.PI / (180.f/ViewAngle) / 2.00f)) * zoomFactor;

    screenSpaceX = screenSpaceX * viewRatio;
    screenSpaceY = screenSpaceY * viewRatio;

    //Find the far and near camera spaces
    Vector4f cameraSpaceNear = new Vector4f((float) (screenSpaceX * NearPlane), (float) (screenSpaceY * NearPlane), (float) (-NearPlane), 1);
    Vector4f cameraSpaceFar = new Vector4f((float) (screenSpaceX * FarPlane), (float) (screenSpaceY * FarPlane), (float) (-FarPlane), 1);

    //Unproject the 2D window into 3D to see where in 3D we're actually clicking
    Matrix4f tmpView = Matrix4f(view);
    Matrix4f invView = (Matrix4f) tmpView.invert();
    Vector4f worldSpaceNear = new Vector4f();
    Matrix4f.transform(invView, cameraSpaceNear, worldSpaceNear);

    Vector4f worldSpaceFar = new Vector4f();

    Matrix4f.transform(invView, cameraSpaceFar, worldSpaceFar);

    //calculate the ray position and direction
    Vector3f rayPosition = new Vector3f(worldSpaceNear.x, worldSpaceNear.y, worldSpaceNear.z);
    Vector3f rayDirection = new Vector3f(worldSpaceFar.x - worldSpaceNear.x, worldSpaceFar.y - worldSpaceNear.y, worldSpaceFar.z - worldSpaceNear.z);

    rayDirection.normalise();

    return new Ray(rayPosition, rayDirection);
}

```

Then I follow out the ray until it intersects with an object, you can do this with bounding boxes or something similar, since this is specific to your game, I'll let you handle that. Generally this is done by following the ray out (adding the direction of the ray to it's starting point over and over 'till you bump into something).

Next you want to see which face is being picked, you can do that by iterating over the triangles in your cube to see if the ray intersects them. The following function does that and returns the distance to the picked face, then I just use the intersected face that's closest to the camera (so you're not picking the back face).

```
public static float RayIntersectsTriangle(Ray R, Vector3f vertex1, Vector3f vertex2, Vector3f vertex3) {
    // Compute vectors along two edges of the triangle.
    Vector3f edge1 = null, edge2 = null;

    edge1 = Vector3f.sub(vertex2, vertex1, edge1);
    edge2 = Vector3f.sub(vertex3, vertex1, edge2);

    // Compute the determinant.
    Vector3f directionCrossEdge2 = null;
    directionCrossEdge2 = Vector3f.cross(R.Direction, edge2, directionCrossEdge2);

    float determinant = Vector3f.dot(directionCrossEdge2, edge1);
    // If the ray and triangle are parallel, there is no collision.
    if (determinant > -.0000001f && determinant < .0000001f) {
        return Float.MAX_VALUE;
    }

    float inverseDeterminant = 1.0f / determinant;

    // Calculate the U parameter of the intersection point.
    Vector3f distanceVector = null;
    distanceVector = Vector3f.sub(R.Position, vertex1, distanceVector);

    float triangleU = Vector3f.dot(directionCrossEdge2, distanceVector);
    triangleU *= inverseDeterminant;

    // Make sure the U is inside the triangle.
    if (triangleU < 0 || triangleU > 1) {
        return Float.MAX_VALUE;
    }

    // Calculate the V parameter of the intersection point.
    Vector3f distanceCrossEdge1 = null;
    distanceCrossEdge1 = Vector3f.cross(distanceVector, edge1, distanceCrossEdge1);

    float triangleV = Vector3f.dot(R.Direction, distanceCrossEdge1);
    triangleV *= inverseDeterminant;

    // Make sure the V is inside the triangle.
    if (triangleV < 0 || triangleU + triangleV > 1) {
        return Float.MAX_VALUE;
    }

    // Get the distance to the face from our ray origin
    float rayDistance = Vector3f.dot(distanceCrossEdge1, edge2);
    rayDistance *= inverseDeterminant;

    // Is the triangle behind us?
    if (rayDistance < 0) {
        rayDistance *= -1;
        return Float.MAX_VALUE;
    }
    return rayDistance;
}

```

The triangle with the shortest distance is the picked triangle. Also, shameless plug for my game, you should check it out, follow it and vote in the polls I put out occasionally. Thanks! http://byte56.com
> 8 votes

# Answer
The technique you're looking for is called "picking" or "3D picking." There are several ways to do it; one of the more common ones is to transform a 2D point on the screen into eye space by using the inverse of the projection transformation. This will allow you to generate a ray in view space, which you can use to test for collision with the physical representation of your various bits of scene geometry to determine which object the user 'hit.'

You can also use a "picking buffer" (or "selection buffer") which GL has support for. This basically involves writing some unique object identifier into a buffer for every pixel and then simply testing that buffer.

The OpenGL FAQ has brief discussions on both (it focuses more on the selection buffer since that's entirely a GL feature; ray picking is API agnostic except perhaps for extracting the active matrices from the pipeline). Here is a more specific example of the ray picking technique (for iOS, but it should translate easily enough). This site has some source code to some of the OpenGL Red Book examples ported to LWJGL, which include a picking demo.

See also this question on SO.
> 3 votes

---
Tags: opengl, java, interface, lwjgl, picking
---


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

```
fNewZoom += fDistance * fCoef;

```

fDistance may have negative value at minimization

There are 4 arrays of cells, each array contains cells with definite size. At zooming the most optimal cells by size are chosen for drawing and are drawn with the OpenGL ES 1.1. The initialization of all four textures takes place at the start while initialization of the drawing view.

Initialization of the view:

```
+ (Class) layerClass
{
    return [CAEAGLLayer class];
}

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

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

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

        [self InitGLTextures];
    }

    return self;
}

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

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

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

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

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

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

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

    return YES;
}

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

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

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

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

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

```

functions used for drawing:

```
- (void)BeginDrawing
{
    m_pCellTextureArr = _skinMgr.GL_GetProperlyCellTextInfo();

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

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

}

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

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

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

```

With the help of this function the coordinate array of texture vertices for drawing is formed where m\_spriteVerticesBack and m\_spriteTexcoordsBack are dynamic arrays, seleсted by means of "new" function (m\_spriteVerticesBack = new float\[MAX\_COUNT\_CELLS * 12\] )

```
- (BOOL)AddNewCellType:(ImgCellType)cellType PosX:(float)posX PosY:(float)posY
{
    ImgElDimensionsF    cellDimensions = _skinMgr.GL_GetCurrerntCellDimensions(cellType);
    ImgTextureInfoF     imgCellInfo = m_pCellTextureArr[cellType];

    if (m_nCurAddBackCell >= m_nMaxCountBackCell)
        return FALSE;

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

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

```

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

# Answer
I don't see in your code where you are calling drawRect: (also related, you have it in your example as drawView: -- the method is drawRect:) explicitly, which leads me to believe that you are letting the OS call you when it thinks it is needed. By default, UIViews will keep the contents of the backing CALayer in memory, so when the OS needs to scroll your view around, it simply blits the contents of the CALayer again instead of calling drawView:. What you should be doing is calling setNeedsDisplay anytime you have determined that you need to zoom or change the contents. This tells the OS that it should be call drawRect: at the next chance it gets.

Also, you should not extend UIScrollView for this. You should extend UIView and then place that view inside of a UIScrollView. That is how the API was intended to work. You are basically mucking around the innards of the UIScrollView and replacing it's CALayer with a CAEAGLLayer, which is not what it is expecting. Even if it works now, it may be broken with a future SDK release.

My recommendation for now would be to get it working properly without the UIScrollView, just to make sure you have everything in order. Once you get that working, drop it back inside a UIScrollView and make sure it still works.
> 1 votes

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

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

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

---
Tags: iphone, opengl-es
---


# Question
Title: Should I package and sell my game on the unity3d asset store?
I'm trying to figure out if I should refurbish and refactor a game I and some friends have made. It's released on kongregate and wasn't a super hit but I feel there's a lot of interesting techniques and solutions going on that new or intermediate developers would like to see. The only thing that's holding me back is that I don't know if people are interested in it at all. Would you be interested in buying the source code and assets for this game?

Check it out and you'll see that there's a lot of things happening in the game. If we packaged it and sold it, we would of course tidy it up a bit which would involve more work so I would really appreciate your honest opinion.

We've looked around and haven't found actual released games in the unity3d asset store. Maybe we just didn't look enough though. We're thinking of setting a price tag of between 150 and 200€. What's your opinion on this price?

And in general, what's your opinion on selling assets and source code? Should I be wary of any legal implications (like my customer licensing my stuff and then forbidding me from selling it)?

I posted this over at UnityAnswers as well but I know I rather go here for gamedev questions so I'm hoping other unity devs will drop by here too.

**Edit:** Reconsidering after getting some great advice we'll probably rip out the assets only and market those as space stuff or something. We'll then market the assets with the help of some free classes of code showing off some of the examples that were hard for us to do when we were (more) beginners. The unify wiki might benefit from having some of the code that we've done and that isn't all that hard but a bit tedious.

If we actually "finish" the game (it is indeed an asteroids spinoff and was never intended to be anything else, apart from some sandbox modes we've been experimenting with) we'll probably sell it with a decent price tag for an indie game like this.

# Answer
> 4 votes
> We've looked around and haven't found actual released games in the unity3d asset store. Maybe we just didn't look enough though. We're thinking of setting a price tag of between 150 and 200€. What's your opinion on this price?

Without actually being able to see the code and source assets, et cetera, it's hard to actually evaluate whether or not the whole package would be worth the price you're asking. From playing the game briefly, however, **my initial opinion is that the product isn't worth the price**.

While it seems like an interesting spin on Asteroids, that's all it is -- a spin on Asteroids. The gameplay you've added to the system isn't terribly unique, and the code to achieve those features shouldn't be all that clever or complex. Examples of such are likely to be found all over the internet already, for free. Perhaps you could argue that there is some value-add in that you're offering an example of the code already packaged up, implemented and integrated, but I personally don't believe that source code (alone) is a very valuable learning resource (certainly not one I'd ever advocate paying for).

The most interesting thing the package contains is the source assets (the art in particular, which is quite good for the price). However, you aren't clear on what the licensing restrictions for that art would be -- or indeed, for the rest of the source material. If you're granting a license to re-use the art/code/etc in whatever manner the purchaser sees fit, without further compensation (except perhaps giving credit to the original artist), then from the perspective of an art pack it might be something you could sell.

> And in general, what's your opinion on selling assets and source code? Should I be wary of any legal implications (like my customer licensing my stuff and then forbidding me from selling it)?

I don't think there is much of a market for selling code, as I alluded to above. Art is another matter. You can draw up a license to restrict the purchaser in whatever manner you see fit, but do note that the licensing is something a potential buyer will consider in determining the value of the product.

Although it's always possible for somebody to purchase your product and then violate your license, so you need to be prepare to defend whatever license you use, which can be costly.

Also you should probably have a real lawyer (which I am not) answer legal questions w.r.t to licensing issues.

# Answer
> 2 votes
> We're thinking of setting a price tag of between 150 and 200€. What's your opinion on this price?

To my opinion, it's easier to sell 5000+ copies of a game sold 10-15 euros than to sell 100 copies of a game sold 150-200 euros even if assets and source code are provided with it.

```
5000 * 10€ = 50k€
5000 * 15€ = 75k€

100 * 150€ = 15k€
100 * 200€ = 20k€

```

As you can see with this example, low price can be really more interesting to make money than high price... And as selling "digital" copies doesn't cost any materials, you can sell an infinite number of copies without any cents more from your pockets.

Finally, if you fix your price at 150 euros, normals players for most of them won't buy your game even if it looks fun (there is plenty of fun games for less than 150 euros), thus you will target the micro market of people searching for sources codes and assets (for THIS kind of assets), and that mean probably very very few persons.

Personally, I prefer having lots of people playing my game even if I earn few money, than having a "cool" game that nobody plays because it's too expensive.

# Answer
> 1 votes
I don't think this is worth 150-200 euros. A competent developer probably can make this kind of game without any outside resources, and incompetent/beginner is unlikely to shell out this much.

I know you want to earn money on your game, but Asset Store is hardly the place to do this. Now, if you offered your game on Asset Store for 5 euros or even free, as an example for less skilled developers.. that certainly won't bring any money, but is good for your karma! (-8

---
Tags: unity, assets, marketing, release
---


title: Skybox textures for our solar system

text:
# Question
Title: Skybox textures for our solar system
For a solar system simulation project I'm looking for a good (semi-accurate) set of textures to texture the skybox.

I've already found these http://paulbourke.net/miscellaneous/starfield/ and we implemented a quick skysphere instead of a skybox. But after testing we found out that the 2048x1024 resolution image was too low-res for our application, and we can't use the higher resolution version because of GPU limitations (we're developing this for a specific platform).

So we came up with using 6 separate 2048x2048 textures on a skybox to have everything look pretty. However I can't seem to find any solar system star textures that are made for a skybox.

So basically what I'm asking:

* Does someone know where to find skybox textures for our solar system?
* Alternatively, does someone know a free program to convert a spherically-mapped texture to 6 box-mapped textures?

# Answer
If you're looking for spherical to cubic projection, this site seems to have an answer. It looks like HDR Shop has some panoramic transformations that will work for this.

Additionally there is at least one Photoshop plugin that will do this.
> 2 votes

# Answer
Not 100% certain this will satisfy your needs, but it sounds similar to what you want:

http://alexcpeterson.com/spacescape
> 3 votes

# Answer
Why don't you use softwares like "Celestia" to capture your own skybox ?

If you don't know it,

> Celestia is a free space simulation in 3D: http://www.shatters.net/celestia/

Using options, you can hide almost all you need (planets, names, constellations etc.) and using the "Render" menu, you can adjust the screen resolution, the stars radiance, the texture quality etc.

It's not "easy" to use, but it's "not difficult" either, and there is some tutorials on how to "navigate" into Celestia if you need some help. You can use scripts to manipulate the camera and capture images.

Finally, here is a forum thread where someone ask some help to make a skybox using Celestia:

> Generating a skybox with Celestia: http://www.shatters.net/forum/viewtopic.php?f=9&t=11079

It is probably not the "easier" way to get what you want, but this way it will be exactly what you want because you can set lots of options. It is maybe not enough realistic tough but I think it could be ok.
> 2 votes

---
Tags: textures, art, sky
---


title: Isometric rendering and picking?

text:
# Question
Title: Isometric rendering and picking?
I've been looking for a formula to plot (world-\>screen) and mouse pick (world-\>screen) isometric tiles in a diamond-shaped world. The ones I've tried always seem to be, well, off. What's the usual/correct way to do this?

# Answer
> 21 votes
Based on your comment, here's the code I'm using to convert tile x,y values to on screen coordinates. Now, it doesn't take into account "3d tiles", everything is considered as being on the same plane, so if you're writing a game where that matters, this code will not work.

```
//this converts a map x/y coordinate into screen coordinates
//public, static method, so can be called outside the Tile object
point Tile::convertToScreen(int x, int y, int offsetX, int offsetY)
{
        point screen;
        //calculate the screen coordinates
        //note: these will then be modified by the camera
        screen.x = offsetX - (y * TILE_WIDTH/2) + (x * TILE_WIDTH/2) - (TILE_WIDTH/2);
        screen.y = offsetY + (y * TILE_DEPTH/2) + (x * TILE_DEPTH/2);
        return screen;
 }

```

point is simply a structure containing x and y ints, TILE\_WIDTH would be 64 in your case, TILE\_DEPTH is kind of badly named (it is actually the height of the tile graphics), but it would be 32 in your case. The offsets are if you want your tile map to "start" at a different x,y location (such as if you want tiles to be above another set of tiles). Typically the offset can be 0,0.

This will generate a map with 0,0 on top, middle, like this:

```
        0,0
    0,1     1,0
0,2     1,1     2,1

```

As for finding the tile x,y of the cursor:

```
point selectedTile;
int x = mX - camera.x;
int y = mY - camera.y;
selectedTile.x = (y + x/2)/TILE_DEPTH;
selectedTile.y = (y - x/2)/TILE_DEPTH;

```

In this bit of code, mX and mY are the mouse screen coordinates, which we're combining with the camera values to find out where we are in "world coordinates". Everything else is the same as the previous code example.

Once again, this assumes a flat 2d isometric tile map. There's some additional work if you want to use a semi-3d view of the map, and this all assumes that you're working in 2d anyway.

---
Tags: rendering, tiles, isometric, mouse
---


title: Need Ideas for Game

text:
# Question
Title: Need Ideas for Game
I've been through a year of programming and have the tools to create a cool, simple 3d game using Java.

The biggest problem I have is ideas. When you have no idea how programming works, you want to create extravagant games and then you realize it doesn't work that way.

I just need a simple game to create. I don't have many models (sphere or block guy) to work with, just a 3d environment my professor created. I can also create a very limited multiplayer aspect (leaderboard, perhaps a 2 player co-op).

So please, throw out some ideas! Or allow me to join your team as an intern. :D

# Answer
> 8 votes
Start small. Clone pong, breakout, or tetris. Or make a simple game where you explore an island (Myst, anyone?) If you want a challenge, make an FPS, or a on rail shooter game. If you want to do something really fun and crazy, make a racing game where you can make the car better not by buying a new engine or upgrading the car, but by adding lightning bolts and flame decals.

Or make a game from your favourite genre (favourite genre may vary, fans of MMOs or Dwarf Fortress may go insane trying to recreate their favourite genre)

# Answer
> 2 votes
Getting an internship is the best what you can do in your case. Enthusiasm (and you have it) is one of the biggest values for getting one. It will help you grow professionally and personally as well. And last thing to say, if there is no company offering internships, just write them and tell them about you and your skills and how much you are interested in game programming and see what happens. It should work.

---
Tags: game-design, 3d, java
---


# Question
Title: Are there any good articles that layout the evolution of game development techniques?
I'm just getting into coding up some 3d rendering apps and I'm considering taking the jump into interactivity. While developing I've learned about Euler angles, gimbal lock, quaternions, frustum, culling, vector matrices, (quad/oc)trees, etc. Haven't touched vertex buffers, textures, mipmapping, peripheral interfaces (other than mouse/keyboard), and general game engine components.

I imagine all of these terms, techniques, have evolved over time from early "Wolfenstein" implementation, to Quake 3 implementation, to modern day id Tech 5 implementation (and everything in between.)

Seems like information like this would be valuable so I can rule out certain implementations of something because they've already been obsoleted by other newer and cooler things. Essentially looking to evolve my own skills, but on a fast track (instead of reading all the material and chronologically keeping track.)

**Are there any good articles that layout the evolution of game development techniques?**

Thanks, Chenz

P.S. I'm not trying to avoid RTFM, just trying to only get the up-to-date information.

# Answer
> 2 votes
The Real Time Rendering authors keep a blog that attempts to track this sort of thing for rendering. The opening notes to the 3rd Edition Real Time Rendering book were also helpful in this regard, for me.

Look where these authors look:

* GDC, SIGGRAPH, and other conference proceedings (including the marvelous GDC Vault; there's both a free section and a paid section -- Llopis recommends watching one session over each lunchbreak, a practice I heartily recommend),
* game industry publications (e.g. Game Developer Magazine),
* various graphics blogs (a subset of the answers to the Game Development Blogs question will be very applicable here), and
* the "collection of articles" books such as the ShaderX series, anything with "Gems" in the title, et cetera.
* (You'll find other non-article books, e.g. Game Engine Architecture, will come up repeatedly; go back and read those as you hear about them multiple times or are specifically recommended to, especially if they have relatively current editions.)

"Game development techniques", especially the combination of rendering and engine design you're specifically calling out here, is a big and constantly (daily!) evolving category. It's also necessarily subjective. You're likely not going to find any one resource that will cover what you want and stay remotely current. This isn't to discourage you from trying to create such a resource, but first...

It may be better for you to try to find the forefront of the industry and attempt to be "swept along" a bit.

Follow the industry greats: influential coders and/or writers (overlapping sets, there). In addition to the aforementioned sources, watching twitter can give you a hint of what they're thinking about and doing *now* -- stuff they're perhaps not ready to write about in detail. Some I've found to be consistently interesting:

There are also very meaningful conversations about what tech and practices people are using, have stopped using, are trying out, et cetera -- see for instance Carmack's recent response regarding the usage of trees in rendering. Terse (as is usual for twitter), but interesting, and there's a lot of other writing about this issue once you start looking.

Watch these people and who they communicate with, and you'll start to feel a sort of pulse of the industry.

Surround yourself, and be willing to branch out. (Immersion learning isn't just for spoken languages.) Don't rely entirely on any one medium. Subscribe to some "push" media (e.g. blogs, twitter, magazines, conferences) in addition to whatever you do to "pull" information.

Develop a sense of who might be interesting and useful to watch or read over time (finding the gafferongames blog was an exemplary moment for me -- a lot of distilled wisdom and technique there).

Don't be too fixated on history or evolution -- it's interesting and useful, but it will come as a byproduct of this immersion in industry sources.

Regarding specific techniques: if you're curious whether they've been replaced with something newer/better, or if there are alternatives, dig a bit on a per-case basis. It often doesn't take more than 10-15 minutes of searching around, especially if you have a decent list of good sources already. It's daunting to hit a million seemingly undifferentiated pages on google regarding e.g. scenegraphs or game loops, half with wrongheaded, obsolete, or incomplete (and yet touted as the be-all-and-end-all) recommendations. But if you happen to know authors or tech from other places, you can assign more value to those results.

It won't be overnight. It may be occasionally overwhelming (don't worry about that too much, learn to trust yourself to pick out the interesting bits). But it will be rewarding. When you've done this for a while, you can share some of the resources you've found and valuations you've made with others.

---
Tags: game-design, game-mechanics, game-industry
---


# Question
Title: What are some good resources for creating a game engine in XNA?
I'm currently a student game programmer working on an indie project. We have a team of eleven people (five programmers, four artists, and two audio designers) aboard, all working hard to help design this game. We've been meeting for months now and so far we have a pretty buffed out Game Design Document as well as much audio/visual concept art. Our programmers are itching to progress on our own end.

Each person in our programming team is well versed in C++, but is very familiar with C#. We have enough experience and skill that we're confident that we will be successful with our game, and we're looking to build our own game engine in XNA as it seems like it would be worth our time and effort in the end.

The game itself will be a 2D beat 'em up style game to be released over xbox live and the PC. It's play style will be similar to that of Castle Crashers or Scott Pilgrim vs The World. We want to design the game engine to allow us to better implement our assets into the game as well as to simplify the creation of design elements/mechanics.

Currently between our programmers, we have books such as "XNA 4.0" and "Game Coding Complete, Third Edition," but we'd still like more information on both XNA and (especially) building a game engine from scratch. What are any other good books, websites, or resources we could use to further map out and program our game engine?

# Answer
### What you need to do is actually start writing your game!

You don't need more resources. It's time to start producing - learn by getting your hands dirty.

Write the lightest-weight engine you can. If you follow this tutorial series until #9 (and since it's written for XNA 2 or 3, translate it in a couple of places to XNA 4.0 using this cheat sheet) you'll have a fully working component framework that gets out of your way. What I just described took me a few hours a day for a week and a half on my own.

Then you can get on with your game. You'll have an engine that takes care of rendering and updating for you so long as you provide an update/draw method on each component you write, so just focus on making your game's content. As you require, go back and hack the engine to bits and make it your own. Among the improvements, I'd recommend replacing its JigLibX physics with Velcro Physics since JigLibX is a dead project.

Reading stuff and writing your game design doc are both helpful but what you need to know is if your game is fun and if it *works* and a hacky prototype built in a week with a minimal feature-set and rectangles for graphics will tell you more about that than even the nicest game design doc.

Ever played Super Meat boy? It never even *had* a design doc! To quote the Super Meat Boy postmortem from Gamasutra:

> Super Meat Boy is Super Mario Bros. if Tommy and I made it. If we had made a design doc, it would have been as simple as that.
> 11 votes

# Answer
I think this post needs to appear.

If you have all your game docs organised, what is stopping you making the game? Why bother with a game engine if you already know exactly what you need to do?

Build the game, and then when you start writing another you'll be able to pull out the reusable bits.

Give it a bit of polish, and you have several decent indie games AND an engine/codebase that **does what you want**, rather than **what you think it should**.
> 9 votes

# Answer
# Write your game, and you will have your engine.

---

I'm in the same position as you and your team, I just bought these with the certain thought that they would help us out in our endeavour:

Check them out, and see if they contain solutions to problems you might meet!

> *(For a complete Table of Contents for the GPG series, look here)*
> 7 votes

# Answer
I'd say the team you have is considerably more than resources that most have setting out to do an indie project. If your programmers are itching to get started, then do so! Start implementing the design plan you have now. The best way to learn more is to start doing! You'll get so many more ideas just by working out the finer details.
> 3 votes

---
Tags: xna, 2d
---


# Question
Title: Where can I download the Doom Classic source code, the iOS port?
Doom classic source code for iOS was released by id software, but there is no working link on their web site where I could get it from.

Do you know an alternative source to download the Doom Game for iOS?

# Answer
You can get it from "http://www.doomworld.com"

> http://www.doomworld.com/idgames/index.php?id=15906

But getting it from idsoftware directly would be better. I hope they will read your mail and fix the problem.
> 4 votes

---
Tags: first-person-shooter, open-source
---


# Question
Title: What criteria should I have met before releasing a game?
I am working on a hobby game that is played in the browser (not flash). It is a sort of civilization simulator. It is a pretty substantial sized game that I hope one day has many players.

My question is what should my game have before I allow the public to play. I have several thoughts and would appreciate suggestions as well as other thoughts.

1. Limit the game to colleagues and friends to test until I effectively finish the game.
2. I open the game up to the public shortly after basic enjoyable functionality is done. I would then release weekly or biweekly updates with new functionality and bug fixes.

So the root question is, is it better to release to the world after everything is "done" (potentially years) or after it is "playable", but lacking?

# Answer
Provided you've got enough of the game finished (core feature are done, no major glaring bugs, enough content to get a feel for the game), then I would suggest releasing it to the public in the "playable but lacking" state. You'll be able to get feedback, and possibly find additional bugs from multiple users playing. The feedback is the most important. Not only does it help you with ideas on what to add to the game, it can help motivate you to keep working on the game.

A something to keep in mind when you open the game up to the public: responding quickly to bug reports and having a level head when responding to criticism will help build a community for the game. Good luck!
> 15 votes

# Answer
I strongly advocate Agile for gaming. It's the best. Based on that, I would say release **now**, and keep continuously improving it. (But the down-side is that people may get upset if you need to do things like resetting points/experience.)

In agile, work is broken down into small pieces that make sense if the game was released right away. So make sure you do it right.

This also gives you crucial early feedback, which may surprise you and provoke you to completely change the direction of your game -- for the better. You won't know until players get their hands on it, though.
> 5 votes

# Answer
I was reading an article about this topic on a blog by somebody who has studied Jesse Schell. Their philosophy concerning game is identify the "core mechanic" or "toy" that is fun to do in the game, and build everything else around that.

Take minecraft for example. The "toy" that is fun to do in the game is making blocks explode and putting new ones in their place.

If your game has its core mechanic down and playable, and most importantly, it's FUN then release and iterate. If not, then don't release until it is FUN.

Again, considering minecraft, it had the bare essentials of the fun "toy" built so Notch released it. It's since sold over 1.8 million copies at 10 euro (or more) each. It's still barely in beta and a significant number of copies were sold in ALPHA. But it was fun.

Keep your eye on the ball. An unfun game is a game that will go nowhere no matter how many years of development you put into it. =)
> 4 votes

# Answer
The above answers are pretty nice and enough for your question.

So, I want to recommand two great books: "Getting Real" and "Rework" which are 37signals great products. I don't know you've heard about these two books or not. But I'm sure these two books will not only solve your problems but will also help in your entire life.

You should read "Getting Real" first. And there, you will learn about "building the real thing" by skipping all "unnecessary" stuff and the method of promoting your app to spread the world. And read "Rework". It is really nice book too. I'm sure, you'll surely love these books. :D
> 1 votes

# Answer
Think about the difference a live game will make.

You say it is a browser game so do they download it or is it run off a server.

Several hundred beta testers are different to a few mates.

Another thing is be realistic. You say about releasing additional content weekly but would it be better to wait a fortnight and release it.

the most important thing is release it when you are confident about it. There is nothing people like more than tearing down your work to make them selves feel better.
> 0 votes

---
Tags: browser-based-games, release
---


title: downsampling algorithm

text:
# Question
Title: downsampling algorithm
what are the steps to perform downsampling on a texture ? I've got as far as rendering the scene to a render target, but I'm not sure as to how to then render that to a smaller texture in order to blur it. I can't seem to find in good explanation or tutorial about this technique.

# Answer
> 2 votes
Render a large quad (with your texture) to a smaller render target, performing whatever blur/downsampling algorithm is appropriate.

I.e. for each target pixel, sample the number of texels from the source you'd want to combine.

The simplest (and thus fastest, but ugliest) is the box filter, which usually uses 4 samples from the large texture and put their average into a single texel/pixel in the target. Repeat this step until destination is 2x2 to get all mip-map levels for a texture.

There are two-pass techniques that are more efficient if you don't need the intermediate textures, and just a result, see this gamasutra article.

---
Tags: c++, directx, hlsl
---


# Question
Title: Is there any scroll algorithm for OpenGL ES?
I was working on J2ME games in the past, when draw a large backgroud, I always use the Carmack 2d scroll algorithm, keep a image buffer a little larger than device screen, draw the changed small tiles to this buffer, then draw the buffer to device screen. This can reduce the number of times to call drawImage().

Now we need to prepare for opengles 2D games for iphone and android. I am new about opengl, but i have try to read some engine code and keep learning opengl. There isn't much problem about 2d graphic system, except the tile buffer, there is no image buffer any more, so what size of the tile should i use? The screen size maybe 800\*480, if i keep the 32\*32 tile, i need to draw about 400 tiles per frame, will this be ok?

# Answer
When you are drawing using raw OpenGL ES, you will be drawing your tiles as pairs of triangles. Imagine one of your tiles, now draw a line from any corner to the opposite -- this is effectively what you will be doing. So for each tile, you will draw 2 triangles each frame. 400 tiles * 2 = 800 per frame, or 800 * 60 = 48,000 per second, which is a very small amount considering most modern phones can handle millions of triangles per second.

There are lots of optimizations you can make as well to avoid changing the current texture binding more often than you need to, and drawing multiple objects in one GL call. I'll be happy to elaborate if you want, but your original question seems concerned with performance, and I don't think you need to worry about that at all.

I have a font rendering system that renders each character in much the same way you would draw your tiles. I look up the coordinates of the particular character in a bitmap font file and draw it as a quad (two triangles in "GL\_TRIANGLE\_STRIP" mode.) For efficiency, I add all of the characters that I will draw into one large array and pass that to the GPU in one single command. I can render thousands of characters per frame, and that's being alpha blended on top of my game. This is all consistently done at 60 FPS. So I think you'll be just fine :)
> 2 votes

# Answer
As stephelton says, OpenGL hardware is pretty fast, so maybe you don't need to worry too much about tiling and scrolling. Just re-draw everything each frame and see if it's fast enough.

Now, if you really want/need to do Carmack-style scrolling/buffering (in case your background is a complex scene with many bells and whistles), I suggest you look into Frame Buffer Objects (google for 'opengl fbo'), which allows you to render to memory (i.e. a texture). That texture (or a portion of it) can then be drawn pretty fast to the screen each frame, with "sprites" added on top.
> 1 votes

---
Tags: opengl-es
---


# Question
Title: What type should you use for keeping game score
Lets say you have a high scoring game like geometry wars, why type would you use for the score and how should you handle overflow?

# Answer
Depending on the scoring system in your game and the type you use you may never need to wrap. For example, an unsigned 64-bit integer can hold a maximum value of 9,223,372,036,854,775,807. Long before games get close to that most would start displaying problems rendering a number that long in the UI. It would also take an awfully long time to rack up a score that big so it's not really worth worrying about.

Depending on how you implement a leaderboard (i.e. use a third-party system for online scoreboards) then the format of the score may already be decided for you on their servers.
> 4 votes

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


# Question
Title: How do I rotate a segment + normal so that the normal is (0,-1) and the segment is now axis aligned
I have an arbitrary line segment, which may or may not be axis aligned along with its normal eg: Segment(Coord(-1,-1), Coord(1,1), Coord(-1, 1).normalize) which represents a line segment with a 45 degree angle.

My desire is to transform that line to Segment(a:Coord, b:Coord, Coord(0,1))

I have a beginners understanding of how transformation matrixes work, in that I know I can get a rotation matrix and apply it to each of the Coords and I'll be left with my segment in the coordinate space I want.

I do not however, know how to calculate that rotation matrix given I know the start normal and the desired end normal.

# Answer
> 1 votes
The classical 2D (row) matrix is:

> R(θ) = \[ cosθ, sinθ \]
> \[-sinθ, cosθ \]

## ----------

Thus, using your example (45°) the (row) matrix would be:

```
R(-45°) = [ 0,7071, -0,7071 ]
          [ 0,7071,  0,7071 ]

```

And if we consider your points \[-1,-1\] and \[1,1\] the result would be:

```
P([-1,-1])R(-45°) = [ -1, -1 ][ 0,7071, -0,7071 ]
                              [ 0,7071,  0,7071 ]

                  = [(-1*0.7071)+(-1*0.7071), (-1*-0.7071)+(-1*0.7071)]
                  = [ -1.41, 0 ]

P([1,1])R(-45°) = [ 1, 1 ][ 0,7071, -0,7071 ]
                          [ 0,7071,  0,7071 ]

                = [(1*0.7071)+(1*0.7071), (1*-0.7071)+(1*0.7071)]
                = [ 1.41, 0 ]

```

---

But I guess you need to calculate the angle too.

You can do it using the dot product of the vector representing the line and an axis (say \[1,0\]).

Let:

* A the ray vector obtained from \[Point2 - Point1\] (take care to avoid zero vector)
* B the base axis used as reference \[1, 0\] or \[0, 1\]

> A·B = ||A|| ||B|| cosθ \<===\> θ = acos( A·B / (||A|| ||B||) )
>
> * ||A|| = square\_root( Ax² + Ay² )
> * ||B|| = square\_root( Bx² + By² )
> * A·B = (Ax\*Bx)+(Ay\*By)

## ----------

Thus, using your example again:

```
A = Point2 - Point1 = [1-(-1), 1-(-1)] = [2, 2]
B = the x axis = [1, 0]

||A|| = square_root( 2² + 2² ) = 2,8284...
||B|| = square_root( 1² + 0² ) = 1
A·B = (2*1)+(2*0) = 2

θ = acos( 2 / (2,8284 * 1) ) = acos( 0.7071 ) = 45°

```

The line was rotated by 45°, so you need to rotate -45° to realign with axis.

---

Edit: hum I used \[0,1\] as normal target, because this is what we can read in your text, but now I see that you specified \[0,-1\] in your title. Anyway the technique should remain OK.

---
Tags: 2d, physics, geometry
---


# Question
Title: How do I draw a portion of a texture onscreen in OpenGL?
I have a sprite sheet loaded as an OpenGL texture, and I'd like to draw a portion of that texture sequentially for animation. Is there an actual OpenGL command to draw part of a texture? I can get it done by modifying the U and V components when drawing the texture, but I'm not sure if there's a more elegant/correct method of doing this.

# Answer
Using a part of the UV space is the "correct" way. It's used for almost every full screen operation (except clear and some resolve ops). Avoid blitting and tex copy as much as you can.

Using UV and geometry gives you a lot of flexibility, you can rotate/zoom images and batch together sprites that share the same atlas. Just be careful about pixel center and filtering so that sprites don't bleed into each other.
> 7 votes

# Answer
Set UI transformation matrices, set U/V/vertex coordinates for quad, draw. Nothing more to it, really.
> 0 votes

---
Tags: opengl, textures
---


# Question
Title: What weight should each frame have in motion blur?
I am working on a game and would like to add motion blur to videos that I export from the engine. Right now, I play back gameplay at 1/16th the original speed, giving me 16x more frames (e.g. instead of 60 frames per second, it's 960 frames per second) and averaging the frames. I am curious though, is this the proper weight or should I give frame samples closer to the middle more alpha? Also, should the frames sampled be sampled uniformly?

# Answer
> 1 votes
You might want to rethink motion blur and only do it for one frame, not blending between several. This will help you avoid a lot of edge cases where your frame rate is stuttering and you have to decide on which frames to blend and how much.

A common way to do this is using motion vectors, where you render your scene again, with extra data for each mesh, and render screen space velocity into a separate buffer. This buffer can then be used as a blur direction control. to compose the final blurred image.

You can also build depth of field information at the same time using this technique.

---
Tags: graphics, video, blur
---


# Question
Title: Data Organization in Custom 3D Mesh File Format
After careful consideration to use middleware, I have decided on creating my own 3d file format format to export meshes from 3D authoring application (Softimage) into my game.

*I will need to export the following:*

* Vertices
* Indices
* Normals
* UVs
* Material Information
* Animation information (no clue, how to import it)
* Collision mesh
* Game Properties defined within 3D authoring tool (object intelligence, aggressivity, etc..)
* ..another assets..

Can I kindly ask for a hint, how to construct my custom file format. How to organize data within my files, please? Does anoybody have a good adivce on exporting animation information, especially when the mesh changes its geometry?

I would be thankful for advices that could point me into right direction. It would be nice to save some time instead of wasting it on incorrect approaches.

*I use Softimage as my 3D authoring tool. Target platform is OpenGL ES 2.0 running on mobile devices (iOS, Android). Programming language: C++.*

# Answer
Because, I haven't received any answer so far, to provide you with some solution, let me tell you how I solved it.

In the beginning, I use text file format. It is easier to read and debug my application. The text format is based on WaveFront .obj file architecture, and I simply add the tags, as needed.

When I have complete text file format, I will create binary format, that will reflect the data stored directly in my application, so I will minimize the need for parsing, to make the format as fast as possible.
> 0 votes

---
Tags: opengl, c++, opengl-es, 3d-meshes
---


title: Mouse location is off due to camera

text:
# Question
Title: Mouse location is off due to camera
I'm building a top down shooter but I have a little issue with my camera and mouse. When I add the camera that I use to my game (see here) my mouse pointer seems to be in the wrong location. When I call my `Mouse.GetState().X` or `Y` the location seems to be about 300 pixels off. I've looked all over the net but I just can't find the solution.

I'm pretty new to coding, so I'll just post my main and my camera class. My objective is to get the green circle on the actual position of my mouse.

### Camera class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace ZombieSurvival
{
    public class Camera2D
    {
            protected float _zoom; // Camera Zoom
            public Matrix _transform; // Matrix Transform
            public Vector2 _pos; // Camera Position
            protected float _rotation; // Camera Rotation

            public Camera2D()
            {
                _zoom = 1.0f;
                _rotation = 0.0f;
                _pos = Vector2.Zero;
            }

            // Sets and gets zoom
            public float Zoom
            {
                get { return _zoom; }
                set { _zoom = value; if (_zoom < 0.1f) _zoom = 0.1f; } // Negative zoom will flip image
            }

            public float Rotation
            {
                get { return _rotation; }
                set { _rotation = value; }
            }

            // Auxiliary function to move the camera
            public void Move(Vector2 amount)
            {
                _pos += amount;
            }
            // Get set position
            public Vector2 Pos
            {
                get { return _pos; }
                set { _pos = value; }
            }

            public Matrix get_transformation(GraphicsDevice graphicsDevice)
            {
                _transform =       // Thanks to o KB o for this solution
                  Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                                             Matrix.CreateRotationZ(Rotation) *
                                             Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                                             Matrix.CreateTranslation(new Vector3(graphicsDevice.Viewport.Width * 0.5f, graphicsDevice.Viewport.Height * 0.5f, 0));
                return _transform;
            }

    }
}

```

### Game:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
//using Microsoft.Xna.Framework.Graphics.GraphicsDevice.SetCursorProperties;

namespace ZombieSurvival
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        int cursorX, cursorY;

        Camera2D camera;

        Player player;
        Texture2D playertex;
        Texture2D bulletTex;
        Texture2D zombieTex;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

        }

        protected override void Initialize()
        {
            this.IsMouseVisible = true;
            graphics.IsFullScreen = true;
            graphics.ApplyChanges();
            Mouse.SetPosition(0, 0);
            cursorX = Window.ClientBounds.X + Mouse.GetState().X;
            cursorY = Window.ClientBounds.Y + Mouse.GetState().Y;

            //graphics.

            base.Initialize();
        }

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            playertex = Content.Load <Texture2D>("player");
            bulletTex = Content.Load<Texture2D>("bullet");
            zombieTex = Content.Load<Texture2D>("zombie");

            player = new Player(new Rectangle(100, 100, 50, 50), playertex, 5, bulletTex);

            // TODO: use this.Content to load your game content here
        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {
            player.Update();

            /*if (IsActive)
            {
                MouseState mouseState = Mouse.GetState();
                int cx = graphics.GraphicsDevice.Viewport.Width / 2;
                int cy = graphics.GraphicsDevice.Viewport.Height / 2;
                int x = mouseState.X - cx;
                int y = mouseState.Y - cy;
                Mouse.SetPosition(cx, cy);
            }*/

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            Camera2D cam = new Camera2D();
            cam.Pos = new Vector2(player.playerPosition.X, player.playerPosition.Y);
            // cam.Zoom = 2.0f // Example of Zoom in
            cam.Zoom = 0.5f; // Example of Zoom out

            //// if using XNA 3.1
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                                    SpriteSortMode.Immediate,
                                    SaveStateMode.SaveState,
                                    cam.get_transformation(graphics.GraphicsDevice));

            player.Draw(spriteBatch);
            spriteBatch.Draw(zombieTex, new Rectangle(Mouse.GetState().X, Mouse.GetState().Y, 50, 50), Color.White);
            // Draw Everything
            // You can draw everything in their positions since the cam matrix has already done the maths for you

            spriteBatch.End();

            //Console.WriteLine(camera.Pos);

            /*if (camera._pos.X - player.PlayerRect.X >= 100)
            {
                camera.Pos = new Vector2(camera.Pos.X - player._PlayerSpeed, camera.Pos.Y);
            }

            if (camera._pos.X - player.PlayerRect.X <= -300)
            {
                camera.Pos = new Vector2(camera.Pos.X + player._PlayerSpeed, camera.Pos.Y);
            }

            if (camera._pos.Y - player.PlayerRect.Y >= 0)
            {
                camera.Pos = new Vector2(camera.Pos.X, camera.Pos.Y - player._PlayerSpeed);
            }

            if (camera._pos.Y - player.PlayerRect.Y <= 250)
            {
                camera.Pos = new Vector2(camera.Pos.X, camera.Pos.Y + player._PlayerSpeed);
            }*/

            /*spriteBatch.Begin();
            player.Draw(spriteBatch);

            spriteBatch.End();*/

            base.Draw(gameTime);
        }
    }
}

```

I realy hope someone has a solution for this, because I'm stuck right now. I'd really appreciate the help.

# Answer
> 11 votes
The positions that you store within *cursorX* and *cursorY* hold the position of the cursor **relative to top left corner of your screen monitor** (since you add the ClientBounds to it). I'd guess that you used that exact position when drawing the circle, and since the *Draw* function takes a position **relative to the top left corner of the game window**, you'd be off by the position of the ClientBounds.

But I have to ask: why are you holding the "real" value of the mouse position? Is there any particular reason why you're storing it instead of the usual positions return by *Mouse.GetState().X* and *Mouse.GetState().Y*?

---

**EDIT**

After looking at your code, I think I found where the main problem is.

When defining the transformation matrix for your camera, you apply a translation to the center of the screen, like so:

```
_transform =       // Thanks to o KB o for this solution
    Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
    Matrix.CreateRotationZ(Rotation) *
    Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)) *
    Matrix.CreateTranslation(new Vector3(graphicsDevice.Viewport.Height * 0.5f,
                                         graphicsDevice.Viewport.Width * 0.5f, 0));

```

the relevant part being:

> **Matrix.CreateTranslation(new Vector3(graphicsDevice.Viewport.Height * 0.5f, graphicsDevice.Viewport.Width * 0.5f, 0));**

From the comment I'm guessing that someone proposed this solution and it probably is perfectly fine but here is how I've changed your code to make it work:

Ok, so I changed a couple of things.

First, I removed the translation to the center, making the camera point at the top left corner, like so (removed the last translation):

```
_transform =       // Thanks to o KB o for this solution
    Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
    Matrix.CreateRotationZ(Rotation) *
    Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)));

```

Then, in your *Game1.cs* file, I put the *player.Draw(spriteBatch)* call within the *spriteBatch.Begin()* call affected by the camera's transformations, since the player should be affected by the camera. Like so:

```
spriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                  SpriteSortMode.Immediate,
                  SaveStateMode.SaveState,
                  cam.get_transformation(GraphicsDevice));

player.Draw(spriteBatch);

spriteBatch.End();

```

Basically, you just have to think differently from usual. It's all about understanding the difference between **screen** positions and **world** positions (well, that's how I call them).

**Screen** positions are those that you use when you call *spriteBatch.Draw()*. They represent positions on your screen monitor.

**World** positions are those within your virtual world. You have to convert these to screen positions before drawing (by using the camera transformation matrix with a *spriteBatch.Draw()* call).

To illustrate the difference, here is an example: Let's say that you have a map with a size of 2500 x 2500. Your game window has a size of 500 x 500. Here is a quick drawing of that game world:

The green rectangle represents your game world (the one with a 2500 x 2500 size). The red rectangle represents the camera view (the size of the game screen). The blue rectangle represents an object within the world.

Now, the **world position** of that object would be (600, 600), because the world position is independent of where the camera is.

The **screen position**, however, is relative to the top left camera position. So its screen position (where it is drawn) would be (100, 100).

I think it's pretty clear with that example that to convert from a screen position to a world position, you must add the camera's position. To convert from world position to screen position, you must subtract the camera's position.

So, anything that is *part* of your world holds a world position (like a player or bullets). Anything that is part of the user interface holds a screen position (like the amount of ammo left or the aim of the player). All you have to do is put all the objects drawn using world positions within the *spriteBatch.Draw()* call using the camera. All objects independent of the camera should be drawn on the next *spriteBatch.Draw()* call.

So, let's go ahead and hide these implementation details within your Camera2D class:

```
public Vector2 GetScreenPosition(Vector2 worldPosition)
{
    return worldPosition - Pos;
}

public Vector2 GetWorldPosition(Vector2 screenPosition)
{
    return screenPosition + Pos;
}

```

I guess that you were using a translation to the center of the screen to keep the player centered. So let's place the player to the center within the *LoadContent()* function:

```
player = new Player(new Rectangle(
                        (int)(GraphicsDevice.Viewport.Width / 2f),
                        (int)(GraphicsDevice.Viewport.Height / 2f), 50, 50),
                    playertex, 5, bulletTex);

```

Next, let's add camera movement support (I changed the code you were using since I'm not applying the center-screen camera translation anymore):

```
Vector2 cameraDirection = Vector2.Zero;
const int TO_MOVE_SIDE_DISTANCE = 150; // the distance to the side required to move.

Vector2 playerScreenPosition = cam.GetScreenPosition(new Vector2(
            player.PlayerRect.X, player.PlayerRect.Y));
Rectangle playerScreenRect = new Rectangle((int)playerScreenPosition.X,
            (int)playerScreenPosition.Y, player.PlayerRect.Width, player.PlayerRect.Height);

//We make the camera follow the player if he goes too close to the sides.
if (playerScreenRect.Left < TO_MOVE_SIDE_DISTANCE) // move to the left
{
    --cameraDirection.X;
}
if (playerScreenRect.Right > GraphicsDevice.Viewport.Width - TO_MOVE_SIDE_DISTANCE) // move to the right
{
    ++cameraDirection.X;
}
if (playerScreenRect.Top < TO_MOVE_SIDE_DISTANCE) // move up
{
    --cameraDirection.Y;
}
if (playerScreenRect.Bottom > GraphicsDevice.Viewport.Height - TO_MOVE_SIDE_DISTANCE) // move down
{
    ++cameraDirection.Y;
}

cam.Pos += cameraDirection * player._PlayerSpeed; // move with the player.

```

So now the camera works. There's a new bug though: bullets start at the player's position, but are not aimed at the right place when the camera has been moved.

This is because we're aiming using the **screen position** (the cursor position, actually), when really we're aiming within the world. So, we have to convert the cursor's position to a world position to be able to aim properly. The shooting happens inside the Player class:

```
Vector2 targetWorldPosition = cam.GetWorldPosition(
    new Vector2(Mouse.GetState().X, Mouse.GetState().Y)); // we're aiming at an object within the world.

BulletList.Add(new Bullet(new Vector2(_PlayerRect.X, _PlayerRect.Y),
    targetWorldPosition, 5, bulletTex,
    new Rectangle(_PlayerRect.X, _PlayerRect.Y, bulletTex.Width,bulletTex.Height), 90));

```

Notice that we're passing the target world position to the Bullet constructor now.

There you go, you have a working camera system.

I'm sure you could go with the centered transformation that you had at first, but I'm not used to that system. If you ever want to change system, just change the GetWorldPosition function, the GetScreenPosition function and the matrix transformation. Since those are hidden within the Camera2D class, changing the implementation details will be easy.

I hope this helped!

---

**EDIT 2**

To remove the problem where the camera transformation is applied twice when drawing the tile map, you must change this part of the code:

```
spriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                  SpriteSortMode.Immediate,
                  SaveStateMode.SaveState,
                  cam.get_transformation(GraphicsDevice));

#region mapDrawing

Vector2 firstSquare = new Vector2(cam.Pos.X / Tile.TileWidth, cam.Pos.Y / Tile.TileHeight);
int firstX = (int)firstSquare.X;
int firstY = (int)firstSquare.Y;

Vector2 squareOffset = new Vector2(cam.Pos.X % Tile.TileWidth, cam.Pos.Y % Tile.TileHeight);
int offsetX = (int)squareOffset.X;
int offsetY = (int)squareOffset.Y;

if (Mouse.GetState().LeftButton == ButtonState.Pressed)
{
    Console.WriteLine(firstSquare + " " + squareOffset);
}

for (int y = 0; y < squaresDown; y++)
{
    for (int x = 0; x < squaresAcross; x++)
    {
        if(firstY >=0 && firstX >=0)
        foreach (int tileID in myMap.Rows[y + firstY].Columns[x + firstX].BaseTiles)
        {
            spriteBatch.Draw(
                Tile.TileSetTexture,
                new Rectangle(
                    (x * Tile.TileWidth) - offsetX, (y * Tile.TileHeight) - offsetY,
                    Tile.TileWidth, Tile.TileHeight),
                Tile.GetSourceRectangle(tileID),
                Color.White);
        }
    }
}

#endregion

player.Draw(spriteBatch, cam);

spriteBatch.End();

```

The whole problem is that you tell the spriteBatch to use your camera's transformation with this statement:

```
spriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                  SpriteSortMode.Immediate,
                  SaveStateMode.SaveState,
                  cam.get_transformation(GraphicsDevice));

```

but then you use the camera's position to find `firstSquare` and `squareOffset` (`cam.Pos.X / Tile.TileWidth`, `cam.Pos.Y % Tile.TileHeight`, etc).

To avoid applying the transformation twice, you must use the camera's transformation only once by either moving that `Draw` call on a different `spriteBatch.Begin` call that doesn't apply the transformation, or by removing all the calculations involving the camera's position. I chose the latter since it makes simpler code:

```
spriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                  SpriteSortMode.Immediate,
                  SaveStateMode.SaveState,
                  cam.get_transformation(GraphicsDevice));

#region mapDrawing

for (int y = 0; y < squaresDown; y++)
{
    for (int x = 0; x < squaresAcross; x++)
    {
        foreach (int tileID in myMap.Rows[y].Columns[x].BaseTiles)
        {
            spriteBatch.Draw(
                Tile.TileSetTexture,
                new Rectangle(
                    (x * Tile.TileWidth), (y * Tile.TileHeight),
                    Tile.TileWidth, Tile.TileHeight),
                Tile.GetSourceRectangle(tileID),
                Color.White);
        }
    }
}

#endregion

player.Draw(spriteBatch, cam);

spriteBatch.End();

```

This should work. If you prefer the other method, just us another `spriteBatch.Begin()` call without the matrix parameter and use the code you already have.

---
Tags: xna, c#, software-engineering, camera, mouse
---