title: Function for sun movement?

text:
# Question
Title: Function for sun movement?
So, given a sun sprite set at the horizon (x = 0, y = worldheight/2) I'm trying to devise a function to make the sun rise, then fall.

The best way to do this would be the sin function, but I have no idea how to use it.

if using y = sin(x), then x would have to range between 0 and pi for a full curve, while having a constant velocity for X.

Any thoughts or suggestions?

Edit: Thanks guys!

# Answer
> 6 votes
Regarding the 0 to pi issue, in general all you have to do is scale the X by a multiplier. Example:

```
y = sin(x * pi / worldWidth)

```

http://www.wolframalpha.com/input/?i=Plot%5BSin%5Bx%5D%2C+%7Bx%2C+0%2C+Pi%7D%5D

However, this doesn't get quite the curve you're probably looking for. You should use the parametric form:

```
t = 0 -> pi over the course of a day
y = sin(t)   -> goes from 0 up to 1 at noon, then down to 0 again
x = (1-cos(t))/2 -> starts at 0 goes up to 1 by sundown.

```

http://www.wolframalpha.com/input/?i=ParametricPlot%5B%7B1+-+Cos%5Bt%5D%2C+Sin%5Bt%5D%7D%2C+%7Bt%2C+0%2C+Pi%7D%5D

This combination of sin for Y and cos for X will trace out an ellipse.

# Answer
> 12 votes
Like Jimmy said an ellipse is probably a better fit for this motion. Here's some ideas on how to actually implement it with a bit more detail for those interested.

**Taking Time**

For starters, you need a variable to keep track of time in the game world. You can implement it any way you like, but here's an example. I'll use a variable called `hours` that varies from 0 to 24 (although when it reaches 24 it wraps back to 0).

Unlike real life though, I'll just consider that day starts at 0 hours, and night starts at 12 hours. This will make some of the calculations easier.

I'll also define the rate at which game time changes in relation to real time. In this example, every two minutes of real time will correspond to one hour in game.

```
float hours = 0.0f;                       // From 0 to 24 wrapping around
const float HoursPerSecond = 1f / 120f;   // E.g. 2 minutes = 1 hour ingame

public void Update(float elapsed)
{
    hours += elapsed * HoursPerSecond;    // Advance clock
    if(hours >= 24f) hours -= 24f;        // Wrap around 24 hours
}

```

**Configuration**

Now before setting our sun's movement we need to specify a few of its parameters. In particular, at what X value does it raise from the horizon, and at what X value does it fall into the horizon. Also, what Y corresponds to the horizon, and how high is he supposed to rise above that line.

```
float startX = 0;
float endX = 1000;
float horizonY = worldHeight/2;
float amplitudeY = 200;

```

**Calculating the Sun's Coordinates**

Now it's time to calculate the position of our sun for a given time of the day. I'll use the same parametric function used by Jimmy but with the domain ranging from \[0..2PI\] instead (in order to bring the sun back to its original position by daybreak):

> x = (1-cos(t)) / 2
>
> y = sin(t)

This is a good function because the X value varies from 0 to 1 and then back to 0 again (which we'll be mapping to our sun's start and end X values) and the Y value starts at 0 and moves up to 1 and back to 0 again (which would be our *day* portion) and then repeats the exact same thing on the negative side before coming back to the original position (which would be our *night* although the sun will not be drawn at this point).

The first step is scaling the hours from the \[0..24) range to the range of our function which is \[0..2PI):

```
float t = (hours / 24f) * MathHelper.TwoPi;          // Scale: [0..24) to [0..2PI)

```

Next we apply the functions to get back the values between 0 and 1 I talked above:

```
float horizontal = (float)((1-Math.Cos(t)) / 2f);    // Changes: 0 1 0
float vertical = (float)(Math.Sin(t));               // Changes: 0 1 0 -1 0

```

And finally we scale those values using the sun's parameters:

```
float sunX = startX + (endX - startX) * horizontal;    // From startX to endX and back
float sunY = horizonY + amplitydeY * vertical;         // Up and down around horizonY

```

---
Tags: xna, 2d, mathematics, algorithm
---


# Question
Title: How do I rotate a sprite around a pivot point using SDL_gfx's rotozoomSurface?
Using SDL\_gfx's rotozoomSurface function to rotate a 38x58 sprite....naturally when it rotates it creates a new surface with a new size, and the rotation isn't going around the center point. I am actually having issues trying to figure out how to make it seem like its spinning around an axis...

Here is the image that I am using:

And here is the code that I have thus far:

```
  #define ANGLE_STEPS 32
  #define ANGLE_STEP  (360 / ANGLE_STEPS)
  ...
  int angle = 0;
  SDL_Rect cpos;
  cpos.x = cpos.y = 100;
  ...
  // create chopper angled surfaces
  for (int i = 0; i < ANGLE_STEPS; i++)
  {
    choppers[i] = rotozoomSurface(chopper, i * ANGLE_STEP, 1, 0);
  }
  ...

  // blit the currently requested angle
  SDL_BlitSurface(choppers[angle], NULL, screen, &cpos);
  ...

  // handle rotating the chopper
  if (keystate[keys[LEFTKEY]])
  {
    angle = (angle + 1) & (ANGLE_STEPS - 1);
    cpos.x = ?
    cpos.y = ?
  }
  if (keystate[keys[RIGHTKEY]])
  {
    angle = (angle - 1) & (ANGLE_STEPS - 1);
    cpos.x = ?
    cpos.y = ?
  }

```

# Answer
Never mind, figured it out after simply sketching it out.

I calculated the center point of both the old and new sprite to be drawn, and simply subtracted that offset from the x and y points to be drawn.
> 1 votes

---
Tags: rotation, sdl, sdl-gfx
---


# Question
Title: Is libgdx fit for 2D game development on Android or are there simpler alternatives?
I'm looking for a Java framework to develop 2D games on desktop and Android. I've looked at Slick and I really like the API, however the developer himself says if you want a framework for Android and desktop best go with libgdx atm.

Now I'm reading up on libgdx, but I'm wondering if there are simpler alternatives for just doing 2D sprite stuff on Android and desktop. I'm only interested in creating NES like graphics, nothing too fancy. Something like this.

Because on the wiki of libgdx it says you can't use the OrtographicCamera with OpenGL ES 2.0 (http://code.google.com/p/libgdx/wiki/OrthographicCamera), but I read (http://www.badlogicgames.com/wordpress/?p=504) when your device supports OpenGL ES 2.0 it doesn't support 1.0, so you can't effectively use OrtographicCamera on OpenGL ES 2.0 devices?

I'm confused, should I go with libgdx? Are there simpler alternatives?

# Answer
As a new android game developer myself, I understand what you are trying to look for. I've researched on this for a while and I chose libgdx as a game dev framework.

There can be several reasons.

1. The developer of libgdx is also the author of "beginning android games". For some reason the author does rarely mention about libgdx in that book and I liked it because I could fully understand basic game development before getting into libgdx. And then when you looked at libgdx, I could understand many of its APIs without much effort.
2. The library (or framework) is pretty awesome in a sense that you can quickly develop a game once you understand all right components of it. For me, first week of learning the framework was really hard but it has been better ever since. its demo games are pretty good to understand its APIs too. And its community is active.
3. You are not going to stick with android. Once you are used to it, you might want to move to iOS development. In that case, you might want to use OpenGL ES anyway. Getting into game development is big investment for anybody and you don't waste what you have learned and done.
> 7 votes

---
Tags: android, java, libgdx
---


# Question
Title: How to fix odd artifacts at the edges of textures in DirectX 11?
In my DirectX 11 project, when I have textures they have odd artifacts at the edges. I've seen it before and searched online, but I can't find any DirectX examples that I can get to work.

You can see it on the skybox too. I'm assuming this is caused because the texture is too small and it's being expanded. I'm using the sampler state filter D3D11\_FILTER\_MIN\_MAG\_MIP\_LINEAR. How can I fix this?

# Answer
> 8 votes
I'm pretty certain this has to do with Texture addressing. If you could post the sampler state part of your shader then I'd could rule that out. Also is this a texture atlas (many used images stored in 1 texture)?

Texture addressing handles regions outside of the 0.0 to 1.0 range. When filtering other than point is applied the rendered texture will use nearby texture addresses. In the case of edges this means using a texture coordinate outside of the 0.0 to 1.0 range.

To change it simply set the addressing mode in your sampler state. Microsoft states that the default is Clamp which should eliminate this problem but I would set it in your hlsl sampler state and test it.

Edit: Here I was able to replicate your issue in Direct3d 9 simply commenting two lines out

```
sampler2D colorMap = sampler_state
{
    Texture = <texture0>;
    //AddressU = Clamp;
    //AddressV = Clamp;
    MagFilter = Linear;
    MinFilter = Anisotropic;
    MipFilter = Linear;
    MaxAnisotropy = 16;
};

```

Here is a comparison image. Code commented out on left (thus AddressU and V set to default state) and AddressU and V set in sampler2d to Clamp in right. Sorry if the image is slightly off. This is a skybox in the background and I had to zoom it 2.5x nearest neighbor after printscreen to make it easier to see the white line.

See: D3D11\_TEXTURE\_ADDRESS\_MODE enumeration

---
Tags: 3d, textures, directx11
---


title: Latency benchmarks for WebSocket games?

text:
# Question
Title: Latency benchmarks for WebSocket games?
I'm trying to find some actual latency benchmarks for using WebSockets in HTML5 games. If I were to go down this route, I'd probably end up using (as you might expect) Node.js and Socket.IO.

However, most search results I find tend to discuss what is possible or how it would be done. I'm more concerned about what kind of performance you can get out of this platform.

These are the only demos that I've found that include a latency meter for the user:

http://rawkets.com/

http://o.smus.com/client/

Most of the time it stays around 100-200ms.. Not sure how reasonable that number is for other games out there, although I have come across people using long-polling on top of Node.js, which gets you some pretty bad lag..

# Answer
> 3 votes
SockJS has a test suite which includes some smoke tests that report latency. For example, here's a test that does cursor tracking. Select 'websockets' from the drop down and click 'connect'.

Mind that it's hosted in Europe; I get about 30ms. Also note that it polls at 5Hz, so the cursor movement is not an indication of latency, only the 'latency' field is.

It's also interesting to see latency on the other transports. Most are indeed slightly worse than websockets, though I never get more than 90ms.

If you want to *require* users' browsers to have websocket support, you can also use something like faye-websocket to implement only a websocket server. It's what backs SockJS, but spares you all of the fallback mechanisms.

---
Tags: websocket, node.js
---


# Question
Title: How to create a very specific kind of joint in Farseer?
**Edit**

Problem solved (see Drackir's answer). Here's a demo of what I was trying to achieve with this joint. More info about the scenario on this other question.

---

**Problem**

I'm trying to create a very specific type of joint in Farseer that behaves like this:

* Objects should always keep the *same* distance between them in **both** the X and Y axes.
* Translation - A collision with one of the objects should move the entire group together, but the *group must not rotate* \- only the individual objects may rotate around their centers as a result of torque.
* Rotation - Objects should always have the same rotation. A collision with one of the objects should make all others rotate the exact same amount.

Here's a picture:

If there's no way to achieve this with Farseer out of the box, how would I go about extending it to create a new type of join that works like this? Basically I want every body to behave like a "clone" of the others, but with a fixed offset between them.

# Answer
Ok, after about two hours of tinkering I managed to do this but it requires adding some extra bodies. You'll probably want to extract this stuff into a method/class but the basic idea is this:

1. Create what I call "holder" bodies for your objects. These bodies share the size and position of your "objects" but don't participate in collisions. Essentially, they are clones.

```
//Create "Main" (center) body
_bodyMain = BodyFactory.CreateRectangle(World, 5f, 5f, 1f);
_bodyMain.BodyType = BodyType.Dynamic;
_bodyMain.Position = new Vector2(2, 2);
//Create "MainHolder"
_bodyMainHolder = BodyFactory.CreateRectangle(World, 5f, 5f, 1f);
_bodyMainHolder.BodyType = BodyType.Dynamic;
_bodyMainHolder.CollisionCategories = Category.None; //Prevents collisions
_bodyMainHolder.Position = new Vector2(2, 2);
_bodyMainHolder.IsSensor = true;
//See http://farseerphysics.codeplex.com/discussions/222524 for why they're sensors
_bodyMainHolder.FixedRotation = true;
//Note: Only add FixedRotation for the main one, leave it off of the other
//      holders. I'll explain later.

```
2. Attach each holder to the "mainHolder" using a `WeldJoint`. This will prevent them from moving away from one another. The `FixedRotation` on the mainHolder prevents them from rotating. I don't know if there's a bug in farseer but if you add a `WeldJoint` and both bodies have `FixedRotation == true`, the joint doesn't work properly. This is why only the main holder has `.FixedRotation = true`.

```
//Weld the holders together so they don't move. Assumes another holder is defined
//  for the object on the right side (bodyRightHolder).
JointFactory.CreateWeldJoint(World, _bodyMainHolder, _bodyRightHolder,
_bodyRightHolder.Position - _bodyMainHolder.Position, Vector2.Zero);

```
3. Attach your "object" bodies to their respective holders using `RevoluteJoint`s. This locks your objects to the holders but allows them to rotate freely.

```
//Lock the actual bodies to the holders
JointFactory.CreateRevoluteJoint(World, _bodyMainHolder, _bodyMain, Vector2.Zero);
JointFactory.CreateRevoluteJoint(World, _bodyRightHolder, _bodyRight, Vector2.Zero);

```
4. Make your real objects rotations match each other by attaching an angle joint. Note: you don't have to attach an angle joint to each and every pair of objects. Just add an angle joint to the main body and the other body and the rotations will translate across all objects.

```
//Make them rotate the same as each other
JointFactory.CreateAngleJoint(World, _bodyMain, _bodyRight);

```

---

That's it! Just add the extra code for each other object/object holder you want and it will handle the rest. Here's an image to illustrate my test:

Here you will see the green bodies are the holders. They do not rotate or collide and are welded together. The yellow and red bodies are your "objects" (yellow is the main). You can see that they are rotated by the same amount and are rotating around their respective holders. Also, only the red and yellow bodies participate in collisions. I believe this meets all three of your conditions above.

**Working Example**

If you load up the Farseer "Samples XNA" solution and find SimpleDemo1.cs ("Samples XNA" project \> "Samples" folder), I rewrote it (code here) to test.

Hope this helps. Let me know if you have any questions.
> 6 votes

# Answer
Unfortunately I cannot check this answer since i'm on a phone right now, so apologies if it doesn't work as I expect.

I think you could use several existing joints to achieve what you want. Create a body with no collision geometry at the corner of your triangle, you can then use three distance joints to achieve the translation you want. Then if you connect the two collidable bodies together with a fixed angle joint they will rotate together.
> 0 votes

---
Tags: xna, farseer-physics-engine
---


title: Ball bouncing and throwing, how to?

text:
# Question
Title: Ball bouncing and throwing, how to?
I was given a task to make a 3D game for Android, but since I never programmed games and opengl until now I'm totally lost on how and where to start. Right now I'm using libgdx framework to ease my development or at least I thought it would. I looked into invaders libgdx demo, but everything is so confusing and not consistent with latest version of framework, and it also looks that it's not very clean and scalable approach.

I have two 3D models, ball and basket. Now I need to animate ball throwing with all the math for hitting the basket, bouncing from basket and floor etc. So my question is can somebody please help me out or direct me to some useful resources about those kind of games.

I somehow managed to get ball moving by rendering ball model and calling `glTranslatef` to move it, but that's it, all it do is just moves constantly in same direction. I would like to pick it and throw it in arc to hit the basket.

# Answer
You should probably look into using an existing 3D physics library. Implementing even basic rolling and bouncing is not an exercise for the faint of heart or those lacking in physics simulation experience. Bullet (bulletphysics.org) supports Android.

The basic concepts of physics simulation in games are pretty intricate, and I couldn't possibly do them justice here. If you're being required to do everything from scartch, you're going to have the following problems to solve (of which Bullet will help with immensely):

1. Collision detection with the floor and walls. This is relatively simple math for planes and spheres, but may require more complex work to collide a complex triangle mesh like a basket with a sphere.
2. Collision response with the walls, floor, and basket rim. This is going to at the minimum require calculating points of contact and normals, and then calculating friction and elasticity (bounciness) to alter the ball's trajectory.
3. Rotational forces for the ball to keep it animates nicely. Simply tracking the linear velocity of the ball is not enough. When the ball bounces, you need to know the center of mass of the ball (easy enough) as well as the point of contact and a few other bits of info to calculate the change in rotational velocity.
4. Collision detection with the inside of the basket to detect if the goal has been scored or not.

I'd recommend the books Real-Time Collision Detection to help with parts 1, 2, and 4. For parts 3 and 2, one of the best sources of learning I know of would be to read the manuals, GDC slides, and articles by Erin Catto, who is the primary author of Box2D. Jumping straight into 3D physics without any experience writing a 2D physics engine first, however, is likely a path to madness. Trust me on that one.

Actually rendering everything is a fair bit easier. You can draw static geometry likes the walls and floor easily enough. The ball is just a circular mesh that you need to translate to the proper position and rotate to the proper angles. The basket is likely a simple mesh of triangles to render.

Definitely look into Bullet for handling the physics parts of that if you can. Writing those on your own is non-trivial. Physics simulations are amongst the hardest parts of games to write (even in simple games). That's why physics middleware libraries like Havok or PhysX or Bullet are so widely used both in small indie games and in big commercial game engines that have large teams of badass developers.
> 5 votes

---
Tags: 3d, android, opengl-es, libgdx
---


# Question
Title: Securing a TCP connection on iOS for an MMO
I am currently building an iOS MMO and I'm leaning towards using TCP as my networking protocol over the higher level HTTP (for the speed difference and the fact that it does not require the client to poll constantly for updates.)

Now, through my research I know that with MMO and any client-server multiplayer games, you should never trust what the client sends to the server. As an extension of that, you wouldn't want anybody to read your packets to see the contents so it's harder for them to send correctly formatted data to the server. (Maybe I'm paranoid.)

The only problem is, where in HTTP there is great support for a secure channel in HTTPS through SSL where the setup occurs mainly server-side, I am not aware of a way to achieve the same thing on TCP. Is there any resource I could be referred that could help me achieving similar security, or at least good enough, on both the iOS side and server-side?

On a side note, if the answer involves doing the encryption and decryption on the client-side, would that severely impact the performance of my application?

Thanks!

# Answer
> 2 votes
If you are looking to prevent people from modifying the client, the short answer is, you can't. Seeing that you plan on making a turn based game it doesn't really matter, you just have to make sure that the client doesn't get any information that the user is not supposed to get, and that the server disregard any illegal action.

Still, you could use an encrypted channel to protect the user, but that is a feature you can always tag on, there should be some security libraries that make this pretty easy.

---
Tags: networking, mmo, ios, mobile, security
---


# Question
Title: How do you incorporate cocos2d with regular iPhone UI widgets?
I want to build a sprite based game using cocos2d. I will be mostly drawing everything in code. I also want to incorporate iPhone UI widgets such as buttons and such. Can these be created to appear on top of the cocos2d canvas? Will this affect the performance of what is drawn/animated?

# Answer
You can get the reference to opengl view with: `[[CCDirector sharedDirector] openGLView]`

With that any UIView's can be added as subview of that opengl view as follows:

```
UIButton *myButton;
//initialise myButton here

[[[CCDirector sharedDirector] openGLView] addSubView:myButton];

```
> 5 votes

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


# Question
Title: What is the logic behind the 'Loading' scenes in games?
I'm making my first game, it's a tower defense type of game, using Unity game engine and taking Fieldrunners as a reference. I would like to know more about the functionality behind 'Loading' scenes in games.

Until now I am instantiating/creating objects at run time and I'm not facing any delay or similar issues doing so. So what are 'Loading' scenes in other games used for? Is there some functionality or instantiation of specific objects for the next round or stage? If yes why do I need them if I'm not getting any delays?

# Answer
> 10 votes
Basically, I'd say that during the "Loading" process the game tries to load and precompute all operations that cannot be done in runtime. For example, retrieving images (to be used as textures) for the hard drive is usually a slow process. On the "Loading" step these images can be copied to RAM memory, which is muuuuch faster access storage, enabling real-time access to images on run time.

# Answer
> 1 votes
A loading screen can also be used as a "cut scene" (http://en.wikipedia.org/wiki/Cutscene) to give the user a chance to catch their breath, to learn more about your game story & features, or to try to sell them a paid version/in-app purchase

# Answer
> 1 votes
I think games modern should have been able to ditch loading screens.

I'm guessing the real reason that we still have loading screens is that most games are designed to run on Xbox 360 hardware. As such they will be limited in the amount of ram they can load stuff into and how much threading they can do. If you don't have enough ram then you will need to be dropping a lot of stuff out of memory and then reloading it from disk. Also it's just easier to load everything at once.

There are also times when things like the harddrive might stall. What happens if the user is running antivirus in the background. If your not preloading stuff then you might have to have the game pause while it waits for that mesh to load or having things spontaneously appear.

Games like Skyrim can provide you with a wide open world that you can run across as much as you want but as soon as you open a door to load a relatively small dungeon you get stuck with a loading screen.

About the only reason I could see the dungeon load screen being needed is if they use some extra heavy prebaked lighting used for indoor scenes which if fairly large to load (made from 1 giant mesh or has detailed lightmaps) or needs some calculations to be done at runtime. I believe the Skyrim dungeons are just built from modular meshes rather than one giant mesh (at least I think Oblivion's where).

There's no real reason to load more than the stuff you can actually see when entering the level. The same way games don't render stuff you can see, you can cull what you actually need to be loaded straight away. You can also stick in a lot of dummy place-holder objects. Then you can use threading to asynchronously load objects in surrounding areas, their meshes, the textures and so on as the player moves around the environment.

The way I would ditch loading screens is as follows:

1. Load the basic game world properties. Global scripts.
2. Load the player's position.
3. Load the gridcell/BSP node of that position.
4. Load just the bounding boxes of the objects in that cell.
5. Work out what would actually be rendered (tests on the bounding boxes, maybe occlusion rendering tests)
6. Load the meshes of the stuff that is rendered.
7. Load the materials the textures of the meshes.
8. Preform more tests to see if more regions are visible and need to be loaded (ie query a render a whole grid cell as a giant cube).
9. Once everything visible is loaded start rendering.
10. Load the rest of stuff in the cells and Load more stuff as required. Load nearby regions and do some basic prediction on the players movements to choose which regions need to be loaded first. Keep going until memory fills.

There are some other things that need to be taken into account. For example some stuff needs to be loaded even though it isn't visible. For example an enemy that is standing behind the player outside of the region would need to be active so they can run toward the player and attack them. Possibly the occlusion test stuff is unessential since you will immediately want to load anything near so its there when the player moves and it becomes visible but it could shave off a second to get straight to the render (but if time is that close then you are likely to get problems with stuff appearing).

If possible those steps should be started *before* they are required, threaded off in the background. For example if you are at the main menu of the game then it should start to preload the starting area the loads after you choose "New Game" (or as soon as the menu appears) and the last save for continue. Other saves can preload when you move the mouse over them. As you approach a dungeon door, it should start to load the next level (although if you can do that then you don't need a special dungeon door since they are really only to trigger a loading screen). Load in the background while the video plays. That way you wouldn't even need a short initial loading screen.

You can skip a lot of that if you don't mind stuff 'popping' into existence. Something like Second Life just leaves you with stuff appearing, since its being retrieved from the internet there's not much you can do about that. Assassin's creed has that effect where stuff whooshes into the scene so you might be able to get away with stuff for artistic reasons.

# Answer
> 0 votes
In Unity, scenes are a combination of multiple game objects. So if you don't want to specify all your gameobjects separately and load them one by one, you can simply load a complete scene.

When loading a scene in Unity, the already existing objects are trashed and therefore a whole new level is loaded. You can indicate which objects you want to keep with the DontDestroyOnLoad method.

In your build settings when publishing a game, you can also indicate which scenes are used in your game and include them in your current build. This makes it possible to make a distinction between multiple platforms that contain different levels, but the same code logic.

Unity specific questions can be asked on the unity answers forum as well. These users are more specified to Unity, instead of overall questions on game engines.

# Answer
> 0 votes
A 3D graphics scene takes time to set up, and maintaining it can push a computer beyond its limits. The contents require extensive memory. The visible contents require extensive time. And as the observer zooms out and looks at the horizon, an awful lot of the total contents can become visible. (Ever notice how some games work better if you don't zoom out too far? Ever notice how some games don't let you zoom out too far *or* look at the horizon?)

The solution is to set up individual scenes with limited contents. Now the game works fine until the observer leaves one scene for another. At that point, the old scene is discarded and a new scene is set up, which takes time (and a loading screen to try to keep the user from getting bored). 3D engines usually try to do as much work as possible during the set up to make the graphics as smooth as possible later.

I have seen games that seem to allow rapid, free movement and zooms over an entire world. There's probably a lot of genius and a lot of laborious programming and artistry there; they didn't just download some free graphics software.

---
Tags: unity, tower-defense, loading, preload
---


# Question
Title: For making an online multiplayer browser-based game, what tech would be more efficient to use?
I asked a partial question on stackoverflow, and then realized that this would be the place to get a better answer because this is the game dev website, and you all may know more than the programmers over at stackoverflow about this subject.

So my question is: for making an online multiplayer game that runs in the browser, what would be more **efficient** to use? flash, javascript, html5, or anything else? Also take into consideration that whatever language is used will be using PHP to access databases and such.

Edit

---

Efficient as in up to date: what is used today by most people, what should be used by a group of people who aren't that experienced in programming (AKA easy, well documented) this isn't really a yes or no question, more of an opinionated answer. Some people hate flash but others love it, I'm unsure of what I should use for a Browser MMO RTS and would like your opinions on it.

Just to clear this up to people who don't know: an MMO RTS usually means its a game with not too much movement, but nifty animations when you scroll over pictures. Also has pretty nice art (dealing with pixel art or whatever will be an issue...).

Also, should I use Javascript+Flash? Say most of the game was written in javascript, but certain fight animations or something were written in flash... is this plausible? Or should it be entirely done with a certain language (the visual aspect).

# Answer
> 8 votes
Ok, currently there's 4 major options for browser based games.

**Java** \- Revived mostly due to Minecraft and Android, Java requires a plugin with about 75% market penetration (source). It's also a fairly complicated language that really isn't suited for first time programmers. There's advantages to using it, but it's probably not the *best* option.

**Unity** \- Great browser plugin for developing 3d games, tons of tutorials, and support for C#, Javascript, and their own scripting language. However, the more advanced features require paying for the pro version (~$1,000), and it's not really suited to a team development environment (unless you pay for the pro version...). It also doesn't really handle 2d games very well, though it can do 2d if needed.

**Flash** \- Market Penetration is about 95%, and a large amount of people are using Flash for their games, it's great for 2d, has recently added support for 3d, and has toolsets and libraries out there to make development quick and easy (Flashpunk and Flixel). That said, networking could be a problem (I don't know how performance is on real time networking...), and it only really supports left click (right click is massively useful for an RTS) Flash is becoming more useful for games, but most of these games are single player with high score tables, or similar sorts of things. Some mobile devices (such as Apple's, or low-end Androids) doesn't support Flash, as well.

**Javascript/HTML5** \- The biggest issue here is that support for HTML5 is not yet 100%. You're cutting out anyone who uses older browsers (such as IE\<9). Performance is also a fairly major bottleneck, since Javascript is a bit slower than Flash or Unity plugins. Additionally, even though Javascript can be pretty easy to learn, there are a few minor/major problems with it that can cause new programmers confusion. The trick here is to find a tool or library that can help development. You can probably find some info here: http://html5games.com/

Side note: there's other options out there, but most of them have even less support or market penetration than anything listed here.

# Answer
> 1 votes
First of all, quit talking about HTML 5. Whether something is HTML 5 or 4.01 is in itself irrelevant, what matters is if browsers support the features you choose to use.

To get a broad browser support you will most notably have to not use Canvas, as that is not supported in IE8.

You can however get a lot of stuff done simply using document manipulation, for oldschool 2D it works pretty good.

JavaScript and HTML may not be the easiest platform to work with, but potentially you can have the game working on pretty much any platform, don't underestimate the power of reaching all the smartphones out there.

# Answer
> 0 votes
It really depends on the dynamics of the game you want to make. If you are building a turn based game, you can pretty much use whatever you like.

If you want more real time mechanics but light on reflexes, you may get away with flash remoting. You can handle the communication with flash and leave everyting else to the "native" browser facilities. Check out Red5 if you can put up with enterprisey java b.s. for a while.

Then there is always the java plugin. But we all know there can be only one plugin installed and flash has won already...

For javascript, XMPP with BOSH might be an option if you don't mind the heavy network utilization. I haven't used websockets professionally, but looks like it will be usable within a year or ten.

WebGL aces the rendering part with shader capable hardware. You can do it in java too. For netbooks, you can't do much about it. I don't know how good flash handles 3D, I don't even want to know...

You are gonna have a run off the mill web application backend, I see. There is no way you can build a playable FPS with it. Just stick with good ol' UDP for them.

Some suggestions about a game that is meant to be played inside a browser chrome:

* Make it light on assests. MB's of downloads is wrong on a limited data plan.
* Integrate it to the browser UI (i.e. links, history, selectable text, ctrl+f...). If it is just a desktop game confined to the browser chrome, make it a desktop game.
* Make it light on battery. I can hear my friend's laptop's fan whirling furiously while playing farmville from 25 meters.
* Obviously, make it fun. People forget this quite often.

**Edit for edit:**

Using javascript+flash is an entirely acceptable approach for a MMO RTS. Still, I would question the need for flash just for the bling where even a GIF would do just fine. Simplicity is worth more, I think.

---
Tags: flash, javascript, mmo, php, rts
---


# Question
Title: Designing the main classes in a solar system simulation game in C++
***If this is not the right place for this question, could you please direct me to a more suitable site/forum?***

I'm a beginner in game development (and in the use of this site). I've worked with C++ only for rather small scientific simulations, so I can "code" but I've never done a full-blown design of an OO program, much less of a game. You can tell from what I'll write next :P

I've decided to write an open source educational game that simulates accurately the motion of the Sun, the planets and of one or more spacecraft controlled by the player. By "simulates accurately" I mean that I want to use a scientifically valid and precise algorithm to obtain the forces and thus the motions of the bodies.

The game will be in 3D and will use the Ogre3D engine for the graphics. Graphically it will look similar to Celestia.

The first difficulty is that I've never designed the structure and the classes of any game. By reading a few references and guides I think I have a vague idea of how the dynamics could work, but it's *vague*: each entity (planet or spacecraft) could store its own state information and then have an "update" function that updates the state based on some input (like user commands). There are probably many other ways to do this, I guess.

The main problem, however, comes from the particular needs of this project:

1. my objects must not only respond to user input, but also obey accurate physical laws, and **the algorithm that computes them must be centralized**. This is because it needs to know the positions of all the bodies at the same time to perform its computations;
2. I plan to add different kinds of spacecraft with different types of propulsion, and some of them would **react to the other bodies in special ways** (think antigravity).

## The Question

*Is there a design pattern or architecture suitable for this problem?*

The best I can think of is to have a singleton Universe class containing the central algorithm for the dynamics. The various objects of the solar system then communicate with Universe. They would contain basic parameters like mass and size, and they would listen to Universe telling them where to stand.

However this doesn't sound right. Where do I put the ever-changing trajectory data of all the bodies, in Universe? What's the point of having all those objects then? Only for the graphical part of the game?

And what about the special dynamical properties of some spacecraft? I can't possibly include them all in the central algorithm from the beginning.

---

Ok, I think you can tell how confused I am about the matter much better than me. I would be grateful for any kind of input.

# Answer
> 7 votes
Don't conflate the physics modeling of the universe with the graphics, that way leads to madness =) For something like what you're talking about an MVC architecture might work well.

M = model. Your model is the physics simulation of the universe. While this may be a singleton you'll find many more arguments to making it a class that can stand alone but of which you could make many. Your model is responsible for number crunching the simulation, that's it. This is completely independent of Ogre and would exist as pure data.

V = view. Your view gets its parameters from the Model and decides how to render them. There can be many different views of a model; maybe you have one that shows a condensed overhead, a second view that follows a spaceship around, and a third that, well you get the idea. A view simply looks at the model and shows it to the end user, and each view is specialized so you don't have a mega-view with a million options. This is where you would extract the numbers from the model and set them into your Ogre objects to render.

C = controller. The controller is where you interact with the model, adding new physics objects or piloting spaceships. Note that there can be many different controllers, one for each spaceship that an AI or end user controls, you get the idea.

The rest of your program is now a framework to setup and run the MVC.

There are many other ways to design your idea, MVC is mainly suited towards information displays and games like Eve but it does let you neatly organize how your program works.

**You'll get many more ideas from other people** but no matter how you choose your final design please separate the simulation from the graphics.

# Answer
> 3 votes
You need to define "accurate". Even Newtonian Mechanics is not accurate enough to simulate Mercury properly. Newton is off by 43 arc seconds per tropical century. This was discovered with technics used in 1859, so its not a small deviance. In fact this was the first test case for Einstein's Relativity Theory, and he succeeded explaining mercuries perihelion precession using this theory. Most likely you don't want to use Relativity Theory for your simulation, so you probably need to relax a bit on "accurate".

# Answer
> 1 votes
In PseudoCode

```
   GBody {
       Velocity as (x,y,z)
       Name
       Mass
       Acceleration as (x,y,z)
       Position as (x,y,z)
       Diameter

       void update(){
       //do update math here
       }
   }

   GBody Mercury=new GBody( Mass=10,name=Mercury,...)

   do{
     //iterate through GBodies
      Mercury.update()
    }while (sim is running)

```
* gbody is gravitational body
* use a list to keep all the masses you are tracking in the n-body problem.
* the ship should probably be a camera with seperate physics. (wouldn't want to have the ship crash into the sun.
* use simple spheres with bitmaps for the planets/moons etc.
* to simplify the math sun is fixed at 0,0,0.

---
Tags: architecture, physics, design-patterns, objects
---


title: Disable V-sync in WebGL?

text:
# Question
Title: Disable V-sync in WebGL?
Normally my app runs at 60 fps, But when I add some simple models it decreases to 40fps.

I think v-sync on, which is might be causing it to run slower.

Is there any way to disable v-sync in WebGL?

Would glflush at the end of rendering work?

# Answer
In WebGL, Swap Interval is what they call v-sync.

To enable Swap Interval

```
wglSwapIntervalEXT(1)

```

To disable Swap Interval

```
glSwapIntervalEXT(0)

```
> 3 votes

# Answer
WebGL does not have control over v-sync or buffer swapping.

gl.flush is not going to either force or prevent a v-sync. gl.flush "force execution of GL commands in finite time" http://www.dei.isep.ipp.pt/~matos/cg/docs/manual/glFlush.3G.html

If you schedule your draw routine via setInterval or setTimeout it might be detrimential to rendering quality and v-sync artifacts might be more apparent (I have observed this in Chrome, but have not seen a difference in Firefox).

To avoid out of page-redraws you can call requestAnimationFrame to sync up your redraws with the page redraw. However this will not cause v-sync to be either on or off, it merely might reduce the impact of v-sync artifacts, and it makes your app behave more nicely performance wise (because you will not draw if your tab does not have focus).

A drop from 60fps to 40fps might indicate that you're making the GPU busy and you'll need to go over your code to make it faster.

Note that in order to measure accurate performance and exclude other effects, you should capture a start time before drawing, call gl.finish() after you're done, and then take an end time and log the difference into a collection from which you calculate an averaged result.

The gl.finish call ensures you are going to see a true performance measure and not just how fast your commands get commmited to the browsers backlog of WebGL calls (which is asynchronous).
> 3 votes

---
Tags: webgl, vsync
---


# Question
Title: Best next step for game AI implementation
I have recently finished a small framework that employs agents governed by a small hierarchical finite state machine, however I have quickly discovered the drawbacks of this approach. Namely the fact that increasing numbers of behaviours call for an exponentially complicated rule-base to govern the switches.

It occurs to me that there is probably a much better way of coding AI, where they have overall goals and can assess new information with regards to this.

I did some research but was a little overwhelmed by the amount of methodologies, and for that matter the lack of information about which techniques are more commonly used and which are best for certain situations.

what would be a good next implementation/methodology for a 3rd / 1st person shooter? such as a neural network or GOAP.

# Answer
> 8 votes
Obviously there is no "one size fits all" approach to game AI, at least not yet. There are a variety of different approaches and usually you choose one that is a good compromise between performance and control.

One increasingly popular approach, at least in shooter-style games is to use behaviour trees. These effectively give the same results as a hierarchical state machine except that instead of trying to control all the different transitions, you basically evaluate each behaviour node in turn until you find one that triggers, meaning that is the current state. The way you organise the tree lets you encode priorities, parallel behaviours, complex selection criteria, etc.

The downside is that they are basically a graphical language for AI rather than a single approach, and everybody codes them up slightly differently. On top of that, due to the naive approach requiring a lot of tree traversal, a lot of people try to optimise them by remembering where they were in the tree last time, adding external triggers to invalidate current states, etc. The majority of talks and papers on behaviour trees seem to be documenting the way that people twist them in unusual ways to get better results, so I'm not convinced that they're all that great.

But lots of people do manage ok with hierarchical state machines. As long as you have a clearly delineated hierarchy (eg. game objective/strategy/tactics/navigation/steering) it's not impractical. The hierarchical nature is meant to prevent the exponential growth, so you might want to reconsider your transitions.

In fact you can get a long way with a trivial set of conditions. eg. If healthy and no enemies nearby, explore. If healthy and enemies nearby, attack. If unhealthy and enemies nearby, flee. If unhealthy and enemies not nearby, apply health pack. 4 basic states, no explicit transitions, and easy to tweak or personalise by adjusting the definitions of healthy and nearby.

Nobody (or next to nobody) uses neural networks, by the way. They're not a very effective tool, except for learning basic AI concepts.

# Answer
> 1 votes
As you said, there are tons of approaches. However since you want a 3rd or 1st person shooter, I can give some specific pointers.
When doing my dipoloma thesis, I ran into a few projects:

* Jazzbot, for the Nexuiz game
* Pogamut, a similar project based on Unreal Tournament 2004 (I liked this one better).

These are frameworks for 1st person shooter bot programming. They come with academic publications and tools, so you can study the algorithms and principles used, or try out your own approaches.

# Answer
> 0 votes
A common step up from state machines is a utility framework. Have each state calculate a score that is its desire to run / applicability. Each time the entity thinks, he reevaluates if he is in the highest utility state, and if not, transitions to it. This way, all your transitions are implicitly defined in your utility functions.

A simple example would be a ShootEnemy state has high priority when in range and able to fire. A MoveTowardEnemy state has high priority when far away. Together, they can manage to get to the enemy and shoot him without having to know about each other.

---
Tags: ai
---


# Question
Title: How Plants vs Zombies animation is done?
I really like the plants vs zombies style of animation and it doesn't look complicated yet the result is really good. I doubt it's made of sprites seeing there's a large number of animations, combinations, distortions, outfits. So how that kind of animation is done?

# Answer
> 6 votes
**Concept**

To me it looks like a **2D Skeletal Animation** system. In other words, animations are constructed out of *smaller pieces*, which are *transformed* and put together to create each frame of the animation.

*Optionally*, there may even be a *bone hierarchy* (i.e. a skeleton) in place, so that for instance, arms will be attached to the torso and moved automatically whenever the torso moves, etc. That's not strictly necessary though, since it's possible to just place each of the pieces manually, at the root level. That's the equivalent of having only one bone in the system.

It's a bit outdated by now, but *James Silva* (who created *The Dishwasher: Dead Samurai* for XBox Live Arcade) wrote a XNA book where he goes into great detail on this topic, even providing a full implementation. And here's a few other links that might also be relevant: this and this.

***Very*** **Basic Implementation**

Here's an example (with C# syntax but a bit as pseudocode) of how to implement the *most basic* system of this type:

```
class AnimationPart
{
     Texture2D texture;
     Vector2 position;
     float rotation;
     float scale;
}

class AnimationFrame
{
    var parts = new List<AnimationPart>();
    void Draw(Vector2 position)
    {
        foreach(var p in parts)
            DrawTexture(p.texture, p.position + position, p.rotation, p.scale);
    }
}

class Animation
{
    var frames = new List<AnimationFrame>();
    int currentFrame = 0;
    void AdvanceFrame() { currentFrame = (currentFrame + 1) % frames.Count; }
    void Draw(Vector2 position) { frames[currentFrame].Draw(position); }
}

```

That's really as simple as it gets though. The sprites themselves can only be translated, not rotated or scaled, and the hierarchy is flat, meaning that there are no parts inside/attached of/to other parts.

Also this simple system only supports translation, rotation and uniform scaling of animation parts, but it's possible to support other types as well, such as mirroring, non-uniform scaling, or skewing.

---
Tags: 2d, animation
---


# Question
Title: Keeping user's attention with tycoon style games
I'm developing a tycoon game, and with most games in the "genre", some in game things just take time. Making money, waiting for things to happen, etc. For mobile gaming (ios, android), how do I keep this entertaining. Without talking specifically about my game, there are day cycles / things that happen at certain points (can I be more general?...)

There's different possibilites, and some I've seen have either a fast-forward button or something in order to not make it boring. (I'm talking about a tycoon game with a little bit of stuff to do; you can't constantly be busy like sim city or something). Do I just have notifications generated at certain times to tell the user a "day is over" or a "power up is attained"? Or would that get too annoying?

I'm open to any ideas on how to keep users interested, but it's really not a game that you can constantly play for hours. Not enough stuff to do, doesn't require that much micro-management.

# Answer
> 11 votes
Being able to speed up time is the easiest/quickest solution to this problem.

That said, most of the enjoyment of Tycoon games comes from the fun of seeing the world you've built up exist. Animations of objects in the world, people walking around, the "cha-ching" sound of money going into your virtual bank account, all these things add to the "fun" factor in a tycoon game. There's other elements that make certain tycoon games more fun than others, but without knowing more about your game, it's hard to give advise and know what would be applicable and what wouldn't.

So, some general thoughts: One aspect that people like with Tycoon games is solving a puzzle. Having to lay out paths or roads to maximize traffic patterns to be more efficient, having to figure out where to place a ride or police station to get the best results, having to make overly complex train networks to get 99% goods transported. Add to this that some people like having to deal with certain business aspects of Tycoon games, hiring and firing workers, training workers, setting up their paths, balancing a budget, making sure that popcorn prices are high enough to make the most profit but not too high that no one buys any, work with limited funds so that it's an accomplishment when they build a massive rollercoaster that cost $20,000 and has a perfect rating. Finally, unlocking content, seeing all the new, cool stuff that a game has to offer, and including it in their plan for their game.

# Answer
> 8 votes
I dont know about those time adjustments. The last tycoon game I played was GameDev Story, and it was basically something which gave you sequences of choices, reaction time was not a factor, nor would it be helpful to have speedforwarding since you have to make relevant choices often. So I think, that is the magic: giving relevant choices, with frequency, and allow the user to learn from the results. The assumption is that the user must learn to play and win the game. Once the user knows the system, he is assumed to win with \> 50% chance. How to keep interest after that point, there is the deepest question...

---
Tags: game-design, android, iphone
---


# Question
Title: Simple WP7 pong game with real time multiplayer using sockets
I'm making a pong clone for Windows Phone 7 and I'd love to add a multiplayer option. I've been trying to use this Ricky Tan's tutorial:

Link

The problem is it is designed around the platformer example which has several classes such as Player, Level and Game whereas my game takes place in a single Game class with much less logic for player movements.

I've tried putting my `handleInput()` inside the `Channel_PacketsReceived` method but there's still no connection between devices. I've been at this for days and I can't get it. Is there something I'm missing? I'd love some help with this or if anyone knows a more straight forward tutorial with things happening in the same class.

Also if it matters my game includes the gsm example.

```
 //Sockets
    private UdpAnySourceMulticastChannel Channel;
    private Vector2 oldPosition;
    int identifier;

 public void HandleInput(int id, Vector2 position)
    {
           TouchCollection touchCollection = TouchPanel.GetState();
           foreach (TouchLocation touchLocation in touchCollection)
           {

               // upper left corner touche detection
               if (touchLocation.Position.Y < 400)
               {

                   if (touchLocation.Position.X < blueBar.X && touchLocation.Position.Y < 400)
                   {
                       blueBar.X -= 30;
                   }

                   else if (touchLocation.Position.X > blueBar.X + 128 && touchLocation.Position.Y < 400)
                   {
                       blueBar.X += 30;
                   }
                   else if (touchLocation.Position.X > blueBar.X && touchLocation.Position.X < blueBar.X + 128 && touchLocation.Position.Y < 400)
                       blueBar.X = (int)touchLocation.Position.X - 64;

               }
               BlueSaber.X = blueBar.X;

               // upper right corner touche detection
               if (touchLocation.Position.Y > 400)
               {

                   if (touchLocation.Position.X < redBar.X && touchLocation.Position.Y > 400)
                   {
                       redBar.X -= 30;
                   }

                   else if (touchLocation.Position.X > redBar.X + 128 && touchLocation.Position.Y > 400)
                   {
                       redBar.X += 30;
                   }
                   else if (touchLocation.Position.X > redBar.X && touchLocation.Position.X < redBar.X + 128 && touchLocation.Position.Y > 400)
                       redBar.X = (int)touchLocation.Position.X - 64;
               }
               RedSaber.X = redBar.X;

               if (touchLocation.Position.X > start.X &&
                   touchLocation.Position.X < start.X + start.Width &&
                   touchLocation.Position.Y > start.Y &&
                   touchLocation.Position.Y < start.Y + start.Height)
               {

                   play = true;
                   touches++;
                   if (redServe)
                   {
                       // default velocity
                       Random rand = new Random();

                       // randomize the ball orientation
                       switch (rand.Next(2))
                       {

                           case 0: ballVelocity.Y = -speed1; ballVelocity.X = speed1; break;

                           case 1: ballVelocity.Y = -speed1; ballVelocity.X = -speed1; break;
                       }
                   }

                   else if (!redServe)
                   {
                       // default velocity
                       Random rand = new Random();

                       // randomize the ball orientation
                       switch (rand.Next(2))
                       {
                           case 0: ballVelocity.Y = speed1; ballVelocity.X = speed1; break;

                           case 1: ballVelocity.Y = speed1; ballVelocity.X = -speed1; break;

                       }
                   }

               }
           }
    }

```

// Outside of update method

```
private void InitializeSockets()
    {
        this.Channel = new UdpAnySourceMulticastChannel(IPAddress.Parse("224.109.108.107"), 3007);
        this.Channel.PacketReceived += new EventHandler<UdpPacketReceivedEventArgs>(Channel_PacketReceived);
        this.Channel.Open();
    }

    void Channel_PacketReceived(object sender, UdpPacketReceivedEventArgs e)
    {
        string data = e.Message;
        Console.WriteLine(data);
        string[] pos = data.Split(',');

        //Discard packets that do not match
        if (pos.Length != 5)
        {
            return;
        }

        try
        {
            if (pos[0] != identifier.ToString()) //if not originated from this phone
            {

                    Vector2 position = new Vector2(float.Parse(pos[1]), float.Parse(pos[2]));
                    Vector2 velocity = new Vector2(float.Parse(pos[3]), float.Parse(pos[4]));
                   // UpdateOtherPlayer(int.Parse(pos[0]), position);
                    HandleInput(int.Parse(pos[0]), position);
              }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Caught unexpected exception: " + ex.Message);
        }
    }

    private void SendPosition(string position)
    {
        if (redBar.X != oldPosition.X)
        {
            oldPosition.X = redBar.X;

            this.Channel.Send(position);
        }
    }

```

and i am calling the SendPosition method inside of update

# Answer
> 1 votes
handleInput() should be it's own function, and Channeletc should be it's own function. Try to clarify with sysouts what the program is doing: there is usually a draw area, and an update area. Handling input is done in update, drawing is done in draw, and if youre doing multiplayer then networking is done in its own area. Do not mix these up. Keep them clear and separate.

---
Tags: c#, xna-4.0, multiplayer, windows-phone-7, socket
---


title: Unity3D animation and world collisions?

text:
# Question
Title: Unity3D animation and world collisions?
I'm using death animation for my enemies but the problem is that when enemy dies he crosses the walls/world. I want enemy/animation to be pushed back into world when he dies (animation is playing). Currently all my enemies (contains skeleton, gun mesh & enemy mesh) are rigid-bodies (kinematic) with character controller and all walls have mesh collider attached to them. I have turned on animatePhysics for enemies but there is no effect. HELP? What am I doing wrong?

# Answer
Look at any triple A quality game, and most of them accept that it is impossible to keep all the bodies out of all the geometry. Why? It is expensive to calculate. If your game is looking ugly because of this, try to precache the space needed for the dying animation, and use the data to move the player away from geometry if needed. Be warned stuff like this will often cause new glitches in funny situations like corners, causing more pain than fun.
> 1 votes

---
Tags: c#, collision-detection, unity, animation, ios
---


title: Loading multi-texture 3ds c++

text:
# Question
Title: Loading multi-texture 3ds c++
I have a question about loading 3ds using this tutorial. I want to use more than one texture on the model (because here all the models have more than one) but it seems that this library can't do that. Do you know any other alternatives or a way to edit this existing library to reach my aim?

# Answer
> 3 votes
You can make use of AssImp.

It's a fairly comprehensive library with importing code already written for you and even provides a sample C++ OpenGL program here.

# Answer
> 0 votes
Well I don't know, but if you read a little the documentation of the file format, it should not be that hard, since the space simulator done the most part for you, you just need to tweak a little the code to add support for this.

You can find a lot about the 3DS File format googling it

Also, here's a search made for you: http://the-labs.com/Blender/3DS-details.html

I think the relevant part for you is at the chunks 4140H, 4170H, A200H(Maybe), F140H(For animations)

Good luck :D

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


# Question
Title: Android - Using opengles through java vs c++
Ive been reteaching myself opengl so I can make a game on android. However Ive been struggling with how to build objects and scenes in opengl using c/c++ and passing them through the jni to the virtual machine where android can use them. Can some one point me towards some tutorials that actually show the use of natively built objects being created and passed through to the jni. Im fine using c++ or java I just dont have much experience using the jni. Ive built some sample projects where I pass primitives like floats and perform operations on them on the native side and then passed them back but I cant figure out how to create a scene in opengl in c++ and then pass it to java. Ive been looking at writing everything using java but Im not sure if the java bindings make for some performance loss.

Any help would be much appreciated

# Answer
> 1 votes
Well it looks like for the time being I will go with Java to use the opengl. I have noticed a definite increase in performance so I cant say how much more I would see rewriting my code all in c++ although I just got a new book on the developing apps all in the ndk and I might take it up some time soon. If anyones interested the book is called Android NDK Beginner's Guide and so far its helped me quite a bit.

---
Tags: c++, android, java, opengl-es, jni
---


# Question
Title: How to make a world-to-player inventory system?
I am running into an issue of trying to implement an inventory system within XNA (doesn't really matter, could be any platform) but so far. Here is the issue I am trying to wrap my head around:

How can I get an item from the world (think when you kill a monster it drops armor) and get it into my player's inventory?

If an inventory is just a list of items, technically, how could I get Steel Sword from the world into my player's inventory without having a class do more than one thing?

I currently have an item struct, which contains a unique hex value, a count of how many items there are (for stackables, like arrows) and a Texture for rendering within the inventory, and some other unimportant properties (name, description, etc).

It would be bad design if I had to modify my existing item class to house a world position, along with collision detection (don't want the item falling through the earth).

Thanks for any considerations!

# Answer
> 16 votes
The approach I would go for is to have 2 different structs (or classes). `WorldItem` and `InventoryItem`.

You could then add an `InventoryItem` as a property/field of your `WorldItem` which is what gets placed in the player's inventory when the world item is picked up.

You'd want a method somewhere (on the player class, or either item class) that handles adding an inventory item to the player's inventory, to deal with stacking like items.

# Answer
> 0 votes
As mentioned before splitting up into multiple classes or arrays would be your best bet. I'd create 3 classes, World, Player and Item The world class would have a List WorldItems in it, so would the Player class, but named List Inventory When a player picks up an item, you move it from the list in the World class to the list in the Player class.

In the draw loop of your game you could make a loop which draws all the Items in the WorldItems list to the screen, but off course ignores the Inventory list on the player object.

---
Tags: xna, c#, 2d
---


# Question
Title: Is game software design the same as non-game software design?
Is the software design process for a game similar to a non-game? Do developers create UML diagrams? I ask because of the iterative nature of game development, I wonder if creating a UML diagram would just be a waste.

# Answer
> 10 votes
UML diagrams have 3 purposes:

1. Something that university professors can teach their students so that it seems like software development is a universally well defined structured process, and not some cowboy field where everyone does things their way.
2. Being a way of stalling when you want to look like you do some real work, or bureaucratize a process to slow everyone down. Not only does the creation itself take time, but the subsequent requirement that development follows the diagram can greatly slow down or even derail the work.
3. Helping people understand complicated data structures.

Point 1 and 2 are by far the most common.

This mocking is not to say that you shouldn't plan, but your initial plan probably doesn't need so much structured diagramming that a software framework is required.

The most important things for a game I'd say is:

* A list of desired features, and a note on what considerations should be taken when designing the core engine to make it possible to implement them all.
* A rough estimate of performance and possible issues, you don't want to have to deal with structural performance issues when the game is halfway done.
* A plan for the gameplay. Story, theme and artwork can all be tagged on later, they are not mandatory at this stage, but if you haven't got at least a sketch of what mechanically makes the game exciting to play you won't have any direction for the work.

If you do prototyping you'd probably want to first do a quick round of planning, then do the prototype, and then make a more thorough plan.

As the work progresses the plan should continuously be adapted as new knowledge about the game is gained.

@everyone Is there anything else the planning list should contain?

Flamebait disclaimer: UML is a tool, some people regard it as a solution, which is wrong and potentially dangerous. There is noting wrong about UML itself, only the way it is sometimes (mis)used.

# Answer
> 7 votes
Yes, software design for games is very similar to non-games -- which is not to say that game developers create UML diagrams (because not all software design involves UML diagrams).

Software design is a very varied process and the methodologies employed will differ widely between companies and individuals. But at the end of the day, games or non-games, it's all just software. The requirements may differ but the fundamentals are similar.

# Answer
> 2 votes
Most game development teams have been doing Agile since before Agile was a buzzword.

# Answer
> 2 votes
I think game development adds one step to traditional software developent, and that is creating some game art and sounds to demonstrate the look and feel. Since this is much more important then in regular software. In developing regular software you could work with mockups to show wich elements are positioned where and when on the screen, this would work for the gui part of the game, but the overall look and feel is best demonstrated using real art.

Most features in a game could be put in UML diagrams, entity diagrams and a database diagram (i think most games use some sort of internal database system for all the data)

# Answer
> -1 votes
I would say that game development is very different from software development. Mostly because game are artistics, while software aren't.

Actually I think it's closer to an animation movie than a software. Don't forget you're doing it for fun.

But I may be wrong, because I've never worked professionally in any domain.

---
Tags: software-engineering
---


# Question
Title: Is there a standard camera position / orientation?
I've come across a need to position a camera for an arbitrary (unknown) scene. The camera can be updated later, but I thought I'd give it a reasonable default, and the thought crossed my mind that there may be a decent "standard" for this.

At the very least, a given modeling program (Maya, 3dsMax, blender...) ships with a default position / orientation for a camera.

A default light would be useful too; is there a similar standard for this?

In the lack of any good suggestions here, I thought I'd try to orient the camera so that an object of approximate diameter of 2 (such as a unit circle) would fit well in the scene and provide a directional light in the direction of the camera.

**Edit:** while we're at it, what about:

* camera FOV / frustum
* light color / intensity / etc

# Answer
> 3 votes
Generally speaking, most people plug in a 45 degree angle in for the FOV. If you do this, a camera is then usually positioned just far enough away to include everything in the scene. No default on this distance because scale is so arbitrary in a 3d virtual world.

There is a concept of a default lighting rig where you have 3 directional lights. One lighting the front, a dimmer one lighting the back, and a side one to enhance the scene. This is basically borrowed from the movie industry. Here is a link: http://en.wikipedia.org/wiki/Three-point\_lighting In Xna, this lighting rig ships with the framework as a default in the BasicEffect: Link

---
Tags: camera, standards, lighting, scene
---


title: Bullet physics with OpenGL

text:
# Question
Title: Bullet physics with OpenGL
I have got some problem implementing bullet physics into my opengl game. The thing is that it doesn't want to update my translatef value continously but only at the end. The code for bullet looks like this:

```
void CGL::initPhysics( void ) {
broadphase = new btDbvtBroadphase();
collisionConfiguration = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfiguration);
solver = new btSequentialImpulseConstraintSolver;
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);

dynamicsWorld->setGravity(btVector3(0,-10,0));

ballShape = new btSphereShape(1);
pinShape = new btCylinderShape(btVector3(1,1,1));
pinShape->setMargin(0.04);

fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,10,0)));
btScalar mass = 1;
btVector3 fallInertia(0,0,0);
ballShape->calculateLocalInertia(mass,fallInertia);

btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),1);

btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,-1,0)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0));
btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
dynamicsWorld->addRigidBody(groundRigidBody);

btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,ballShape,fallInertia);
btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
dynamicsWorld->addRigidBody(fallRigidBody);

for (int i=0 ; i<300 ; i++) {
    dynamicsWorld->stepSimulation(1/60.f,10);

    btTransform trans;
    fallRigidBody->getMotionState()->getWorldTransform(trans);

    fallY = trans.getOrigin().getY();
}
state_list.remove( STATE_FALL_BALL );
printf("stoped\n");

```

}

And the drawing function which is called at the beginning looks like this:

```
void CGL::fallingBall( void ) {
glPushMatrix();

float colBall2[4] = { 0.0f, 0.0f, 1.0f, 1.0f };
glMaterialfv( GL_FRONT, GL_AMBIENT, colBall2);

glTranslatef(0.0f,fallY,0.0f);

printf("fallY: %f\n",fallY);

glutSolidSphere(1.0f,20,20);

glPopMatrix();

```

}

The thing is that it shows correct value in this function's printf but translation is called only at the beginning I mean I can only see the last state.

Can anyone help me, please?

# Answer
> 2 votes
Your code doesn't magically connect the values in the physics simulation to the graphics. You have to have a loop which both steps the simulation *and* redraws the scene with the updated positions.

I can't show you specific code to do this because you haven't shown where `CGL::fallingBall` is called, but if you're using an existing framework (are you?) then you're abusing it by running the simulation inside a function called “**init**Physics” — you should do only the setup there, and find the main loop/callback and put your stepSimulation *there*.

---
Tags: opengl, c++, bullet-physics
---


# Question
Title: Why are there fewer glitches in current day games?
I remember that almost every single game in the early 2000s had at least a few amusing glitches, mostly related to animations, that often produced funny situations. I also remember that game magazines used to dedicate a section with the funniest screenshots people sent in.

As an example, I was just playing Far Cry from 2004 and out of nowhere, whenever I killed some bad guy, instead of dropping to the ground they'd start playing the running animation. This was getting me confused since I was trying to shoot them down from a large distance and didn't understand why they weren't dying.

I've rarely seen stuff like this in current-day games. Was there some change in the technique used to develop games that would make these programmer mistakes less likely?

P.S. I'm not talking about RPGs and other inherently complex genres. I'm talking about games like Far Cry; shooters like Battlefield 3, Modern Warfare 3, even Mass Effect. I've seen plenty of glitches in games like The Witcher 2, Skyrim, etc.

# Answer
> 7 votes
I don't think there are fewer glitches in games today at all. If anything, I would put my money on there being *more* bugs and defects in shipping game software than in the past, simply because games are massively more complex than they were years ago -- many games these days ship with bugs, as evidenced by the number of day-one patches that exist for a lot of games.

There's no way to stop a programmer from making a mistake; the programmer (and most other game developers) operate in essentially a full-trust environment where they can do anything because they are creating the product. There are techniques that can help alleviate certain classifications of defects (unit testing, for example, smoke and regression tests, usability testing, et cetera), however.

Console games undergo fairly rigorous certification procedures that help catch some bugs -- but this was almost always the case, starting in some form or another with the NES. But as the plethora of tool-assisted speedrun videos for various NES games (which generally exploit bugs and glitches for fast completion), that didn't make those games bug free.

There's an argument that could be made that the increased complexity in art and visualization techniques for games tends to hide some bugs -- for example, as games approach a more realistic presentation, errant NPC behavior that is technically a bug might be perceived by a player as emergent. That doesn't mean that there isn't a software defect there, though.

It's very difficult to gather scientific evidence regarding bug count in shipping products, but I would say that if you were able you would either find that the numbers are relatively stable, or increasing. Decreasing seems quite unlikely.

One argument you could make for there being fewer bugs, however, is the fact that some games are built on existing engine technologies that have been iterating (and thus weeding bugs out) for years. However, this is not true of all games and any time an individual game adds a new feature to the engine or at the higher-level gameplay layer there's a risk of introducing a bug.

# Answer
> 3 votes
There are glitches in games all the time. You kind of have it in reverse.

Go back further. How many glitches do you remember seeing in Pong or Q-Bert or Tetris? The larger the codebase, the more room there is for bugs. If anything, there are more glitches in games today than there have ever been.

---
Tags: software-engineering
---


# Question
Title: How can I draw multiple vertexbuffers with indices?
I'm using to types of vertices.

For the triangles:

```
 0 Vector3 Position,
12 Color Color,
16 Vector3 Normal

```

For the lines:

```
 0 Vector3 Position,
 12 Color Color

```

I setup a vertex buffer for each type, and adding them to the GraphicsDevice using VertexBufferBindings. My problem is that I'm only able to draw vertices from the buffer at index 0 of VertexBufferBinding-Array.

```
//
// This is only a shortened part of the code, which draws the lines but NOT the triangles
//
//
   protected override void Initialize()
{
//Triangles
avl = new AllrounderVertexList(new VertexElementUsageDescriptor[]{
  new VertexElementUsageDescriptor(VertexElementUsage.Position,0),
  new VertexElementUsageDescriptor(VertexElementUsage.Color,0),
  new VertexElementUsageDescriptor(VertexElementUsage.Normal,0)
});
//Clock- and counterclockwise
avl.AddAllrounderVertexList(new Vector3(0, 0, 0), Color.Orange, new Vector3(0, -1, 0));
avl.AddAllrounderVertexList(new Vector3(0, 10, 0), Color.Yellow, new Vector3(0, -1, 0));
avl.AddAllrounderVertexList(new Vector3(0, 0, 10), Color.Navy, new Vector3(0, -1, 0));
avl.AddAllrounderVertexList(new Vector3(0, -10, 0), Color.Gray, new Vector3(0, -1, 0));

//Lines
lines = new AllrounderVertexList(new VertexElementUsageDescriptor[]{
  new VertexElementUsageDescriptor(VertexElementUsage.Position,0),
  new VertexElementUsageDescriptor(VertexElementUsage.Color,0)
});
Color xCol = Color.Red;
Color yCol = Color.Green;
Color zCol = Color.Blue;
for (int i = 0; i <= 50; i+=5)
{
    lines.AddAllrounderVertexList(new Vector3(-50, i, 0), yCol);
    lines.AddAllrounderVertexList(new Vector3(50, i, 0), yCol);
    lines.AddAllrounderVertexList(new Vector3(i, -50, 0), xCol);
    lines.AddAllrounderVertexList(new Vector3(i, 50, 0), xCol);
    lines.AddAllrounderVertexList(new Vector3(0, -50, i), zCol);
    lines.AddAllrounderVertexList(new Vector3(0, 50, i), zCol);

}
short[] lineIndices = new short[lines.Count];
for (int i = 0; i < lineIndices.Length; i++)
  lineIndices[i] = (short)i;
indices = new short[6];
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 0;
indices[4] = 3;
indices[5] = 2;

    //Adding indices for the 2 triangles at the end
short[] tmp = new short[indices.Length + lineIndices.Length];
Array.Copy(lineIndices, tmp, lineIndices.Length);
Array.Copy(indices, 0, tmp, lineIndices.Length, indices.Length);
avl.AvgNormalize(indices);
  indices = tmp;

triangleBuffer = new VertexBuffer(GraphicsDevice, avl.vertexDeclaration, avl.Count, BufferUsage.None);
triangleBuffer.SetData<byte>(avl.Data);
indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.None);
indexBuffer.SetData<short>(indices);
lineBuffer = new VertexBuffer(GraphicsDevice, lines.vertexDeclaration, lines.Count, BufferUsage.None);
lineBuffer.SetData<byte>(lines.Data);
bindings = new VertexBufferBinding[2];
bindings[0] = new VertexBufferBinding(lineBuffer, 0, 0);
bindings[1] = new VertexBufferBinding(triangleBuffer, 0, 0);
GraphicsDevice.SetVertexBuffers(bindings);
GraphicsDevice.Indices = indexBuffer;
}
VertexBuffer triangleBuffer;
VertexBuffer lineBuffer;
IndexBuffer indexBuffer;
protected override void Draw()
{foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
{
  pass.Apply();

  GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,lines.Count, 0, 6, lineBuffer.VertexCount, 2);
  GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.LineList, 0, 0, lineBuffer.VertexCount, 0, lineBuffer.VertexCount / 2);
}
}

```

Do I need to switch somehow between the vertex buffers? Or what am I doing wrong?

# Answer
> 1 votes
Before doing each draw call you need to bind the buffers appropriate to that draw. So you'd first set the vertex/index buffers for triangles to the `GraphicsDevice`, then do the `DrawIndexedPrimitives` call(s) for the triangles; then set the buffers for the lines and draw the lines. You'd only have one vertex buffer set at a time, so you'd only use a one-element `VertexBufferBinding` array.

Setting multiple vertex buffers at once is done when you want to use instancing, or when you want to have some vertex components in one array and others in a different array (this is done in some cases for performance reasons, or to allow some vertex components to be dynamic and others static, etc.) All the components from all of the currently-bound vertex buffers act as inputs to the vertex shader.

---
Tags: xna, xna-4.0, vertex, index-buffer
---


# Question
Title: What kind of hardware would be required to render an Earth sized minecraft like map?
I have been thinking about this problem. Is it possible with current technology to create a 1:1 replica of the earth in voxel based game? What's the best data structure to store this giant map? Which algorithm should be used to render this data structure in real-time?

These questions make these assumptions:

* Each voxel has a resolution of 1 cubic meter.
* For simplicity sake, each voxel requires only 1 byte of metadata information. This information will be used to store the identify the "type" of the voxel (earth, water, rock, etc).
* The earth volume is 1 * 10ˆ21 cubic meters.
* By "current technology" I include anything that is commercially available, but not super computers.
* Only the Earth topography and bathymetry will be used to generate the map. Human building, plants or caves are excluded. The underground blocks will be chosen based on geological studies e.g.: if depth is greater than 3000km render a 'magma' voxel.
* Just like in Minecraft, the map is not static, it can be modified in-game.
* A 'infinite' draw distance is a big plus, what's the point of having the whole earth in a map if you can't fly up and watch the whole planet?

The first conclusion that I came when I thought about this problem is that storing the Earth data in a linear way is infeasible, assuming that each voxel occupies only 1 byte of memory this would still require 1 zettabyte to store the map. So some kind of compression is required.

I think that a voxel octree could compress the map, but I am not sure by how much. The entropy of this voxel map is probably very low, so I guess that a very high level of compression can be achieved.

## Disclaimer

This is a theoretical question, I have no intentions of writing a voxel earth

## EDIT

The ESA GOCE has already mapped the Earth geoid with a 1cm-2cm precision. I believe that this information could be used to generate a very precise heightmap of the Earth. This would exclude the need to use an algorithm to fill gaps in the Earth topography.

# Answer
> 6 votes
That depends on the spatial subdivision method you use, although all subdivision methods (like any compression method) eventually pan out where no further compression can take place, due to data structure overheads and other logical/mathematical factors. An example can be found in octrees. For each node in the octree, a pointer must be kept to it's parent and/or children (depending on how you go about your data sructure architecture), to enable meaningful traversal. Any tree structure may contain n children. The lower the ratio 1:n, the more efficient use of space you gain, and consequently the larger the overheads in tree-traversal since you must have more ancestor nodes to contain the same number of leaf voxels (in your case, roughly 510 trillion of these representing the surface area).

Considering that in your instance the primary issues are storage cost and rendering the whole planet (or parts thereof) from a fair distance, there is no data structure I would recommend over an octree. Mipmapping is a necessity: 12.8 million meters diameter at the nearest higher power of 2 is 2^24=16.8 million. 24 octree levels to traverse would amount to a gargantuan amount of branching -- very costly for GPUs and CPUs alike. But provided you do things right, you will only ever need to traverse a few levels at a time. Given the amount of space required, though, alternatives are few and far between (see below).

The mipmapping capabilities of octrees are what make it such an incredibly powerful tool for large volumes such as that you describe. Unlike all other known subdivision methods (with the exception of KD-trees), the octree keeps subdivision per level minimal, meaning that the visual and physical differences between mipmap levels are also kept minimal, meaning much finer deltas in granularity as you walk up and down the tree.

If, on the other hand, you want to generate a world where hierarchical grid traversal is kept to a minimum, then you will need to trade off space for increase speed.

Speaking of the ideal 1:n ratio, there is no finer structure than the kd-tree in this respect. Where the octree divides in 2 for each axis, resulting in 2^3=8 individual child cells, the kd tree splits exactly once per subdivision level. The problem with this is that you must choose a hyperplane to split by, and this hyperplane could be chosen around any of the 3 axes. While it is optimal in terms of space, it makes 3D traversals (such as during raymarches, a fundamental op when using octrees for physics or rendering) much more difficult than in an octree, since a dynamic portal-type structure must be kept to record *interfaces* between individual kd-tree nodes.

RLE is another approach to compression, but is in many ways harder to apply to a problem like this (where the base of operations is spherical), since RLE compression is one dimensional, and you must pick the axis that it operates in. For a planet, one might choose the polar axis, but any single-axis choice would introduce certain issues with traversals for rendering and physics when acting from certain non-optimal angles. Of course, you could also run RLE in 3 axes simultaneously, tripling the storage cost, or in 6 axes (-x, +x, -y, +y, -z, +z) as a further optimisation.

**So to answer your question (or not!)**

I'm not going to go directly into answering what kind of hardware, but I think looking at it from an octree perspective *begins* to give you an idea of what is in fact possible on what kind of hardware. I would encourage you to go down this route, if you really want to know, it might be easiest to actually implement a simple sparse octree (see Laine's paper in the refs) and place a spherical shell of surface voxels into it, and see what the resultant space usage is like. Step up from there. See just how far you can get before your system memory starts to give out. This doesn't require you to write a renderer unless you want visualisation. Also bear in mind this is best done on the CPU -- GPUs by and large do not have the memory capacity to deal with problems of this scale. This is one of the reasons Intel is looking at moving towards massively parallel processors: the benefits of GPGPU, which is better at this sort of thing, can be applied to a far vaster memory space without system bus bottlenecks to contend with. There are probably others here, or on mathematics.stackexchange.com, who could answer this space-requirement question directly using mathematical means given just the size of the shell and depth of the octree.

In terms of your infinite view distance requirement, sure, but the question always comes down to, "how much detail at what distance". Rendering infinite detail would require infinite resources. That's where variable-per-scene mipmapping comes into play. Also bear in mind that all data structures embody some tradeoff of speed for space or vice versa. That means less/slower rendering, if you want a larger world for the same amount of engineering effort.

# Answer
> 4 votes
> The first conclusion that I came when I thought about this problem is that storing the Earth data in a linear way is infeasible, assuming that each voxel occupies only 1 byte of memory this would still require 1 zettabyte to store the map. So some kind of compression is required.

Since you're most likely never going to find out the properties of each cubic-meter of the real world, you'll need some way to generate that data that is uncertain based on assumptions. So if you have that figured out, there's no need to calculate and store all that data, but you can rather generate it on the fly.

First and foremost you can discard all the voxels within the earth, because these will only have to be calculated if somebody actually digs a hole, eg. the voxels become visible.

For the surface of the earth, I'd probably take an image as starting-point for my calculations. Maybe some sort of temperature- and humidity-map will allow you to calculate the type of blocks to apply. Eg. Water, sand (desert), grass, snow etc. Since the image probably won't have one pixel of information for every square-meter of the earths surface, you would have to mix this with some noise to generate a bit of variation on the surface. If you always use the same random-seeds, your result should be deterministic nevertheless.

In addition, an elevation-map would be useful, so that you can determine the height of the surface features. That way you can add mountains etc.

So this boils down to a data-volume of some 2D images that contain information about the earth surface. For everything on the inside, you would revert to a pure procedural approach, where you render different types of blocks, depending on the distance from the earth-center. But as said above, these have to be calculated only, when somebody digs a hole.

To make changes persistent, I would only save *modifications* to the world. So if somebody digs a hole, I would store information about which voxels have been removed, as I should be able to render the surrounding voxels procedurally.

As for the rendering: You will need some sophisticated level-of-detail and culling algorithms to make this work. It's silly to render all the surface voxels, when the camera is at a zoom level that shows the whole world. At this level, the voxels should be much bigger, maybe even a simple textured sphere would be enough.

I guess the most tricky thing would be to have a solid generator that allows you to calculate voxel properties, even for different "resolutions", so that you can use it to generate different levels of detail.

# Answer
> 0 votes
You can basically do the same thing that Minecraft does. Rather than making such an amount of data you can define a world as a mathematical formula, whenever a piece of data is required for display you generate it using the formula.

Such a formula is usually constructed using the concept of Perlin noise, this allows for details at all levels, you can have mountain ranges as big as those in the real world, yet choose to only generate a small part of them. You can generate the amount of detail you like, so it's possible to make very fine details for close stuff, yet also generate far off scenery in the required level of detail.

Minecraft saves all those blocks you have visited, complete with whatever changes has been made, one could simply save only the difference between the generated world and the updated world, but I guess saving big blocks was easier, and they do compress relatively well.

I don't think there is any game that really takes this to the limit, but it is very common to use formulaic generation of all the "unimportant" details of large game worlds. I'm not sure how common the generate when needed approach is though, as opposed to simply generating the lot and putting it on the disc.

# Answer
> 0 votes
You could look for vector data of the landmasses of Earth, as vector data has the advantage of scaling to any scale you want. Combine it with a height map of Earth to generate the height of the terrain. Last step is some detailed satellite imagery, from where you can pick the type of the top block based on the image, so you get rock where there's rock, sand where there is sand, etc. The actual insides of the planet should probably be generated like Minecraft does it, unless you can find detailed geographic data to work from. Basically, what you want to do is find geographic data, and extrapolate from it, given only the XYZ coordinate input. This means you have limited data, and you extrapolate the rest as precise as you can.

---
Tags: algorithm, minecraft-modding, voxels
---


title: Rotating a planet around a ships axis

text:
# Question
Title: Rotating a planet around a ships axis
I have a planet rotating around its own axis (like regular planets, and Pluto) and a spaceship that can fly around in space. The idea is to lock the player (ship) in a deadzone "above" the planet and when he moves to an edge, the planet begin to rotate in the direction that the ship is traveling. I.E. not rotate the player or camera, but instead rotate the planet.

The problem is I need to rotate the planet (in THOSE cases) around the ship's axis and not its own. So I need some way to create the rotation matrix for the planet using the ship's right and Up vector.

I don't want to use the CreateAxisFromAngle method because I don't want to automate the rotation (assuming that is how the function works, correct me if I'm wrong). I want to rotate the planet while the player is moving in a direction and stop rotating when they stop moving.

I also am not very comfortable with Quaternions. So if that is the solution (which I fear it is), please lay it out to me like you would a child, cause I am quaternions retarded. General math is fine though.

# Answer
> 3 votes
Only rotating the planet is probably going to look strange, since any background objects (moons, other ships) and star field are not going to move as they should.

Attempting to only rotate the planet will make things very complicated. For example, say the player approaches a planet, orbits half way around then flies off directly away from the planet. If you only rotated the planet in that situation (instead of player and camera) the player would fly away to the same place they flew in. Or they go to a planet at the south pole, fly to the equator and leave. Now the planet is sideways relative to the rest of the solar system.

What about some kind of orbit function. Where the player flies into this "dead zone" you mentioned, then their controls change into "orbit mode". When in orbit mode, the player is at a locked altitude from the planet and their controls act as if they were stuck to a invisible sphere surrounding the planet.

# Answer
> 0 votes
Please just simplify everything. Player is moving on angle, radius of planet. If angle is \<\> value, start rotating both planet and player. Since you are rotating around a fixed point, you can make it a looping xy space ( rotation, height ) problem instead of complicated 3d problem.

---
Tags: c#, 3d, xna-4.0
---


# Question
Title: What sort of GDC pass (if any) is best for a cash-strapped indie?
I'm doing a web game startup with one other person. We support ourselves with contract programming. I'm considering attending GDC for the first time, but we're really tight on cash. Money spent on passes and plane tickets slows our startup's growth.

Some say GDC is a good way to meet clients, but fortunately we have plenty of client interest, so I don't consider that a major concern. Still, it's generally good to network, and it's healthy for us as designers and developers to learn from the rest of the community.

Which type of pass should we invest in?

# Answer
> 4 votes
Likely the cheapest pass you can find that gets you in. Also, purchase early (before Feb 2). Looks like the Expo pass would suit you since you're not sure what to expect: **$195**.

> **Expo Pass**
>
> This pass is good for people interested in an introductory look at all the GDC has to offer.

Or if you're more interested in the Independent games summit: **$325**

> **Independent Games Summit Pass**
>
> This pass is good for people interested in attending the Independent Games Summit. The Independent Games Summit Pass is available on a limited basis.

Break down of all the passes offered: http://www.gdconf.com/attend/passes.html

---
Tags: business
---


title: Tools for 2D skeletal animation

text:
# Question
Title: Tools for 2D skeletal animation
What good free and widely used tools are there for editing 2D skeletal animations? Preferably, one that allows me to write custom animation exporters.

One pretty good indie tool that I know of Demina, but it's not ideal. It doesn't allow you to export the data as you want (although, it is open source, so you can change that) and I find it clunky in how you edit individual joints.

What other tools would you recommend?

# Answer
Personally I would just use a 3D tool and ignore one of the dimensions. Something like Maya is likely going to be a lot more robust than some custom tool just to do 2D animations.

There are a handful of games that I've worked on and that I know about that have used this approach. As an example, here's an article that talks about Zombieville USA (iOS game) and how they do it. http://www.thecareergamer.com/braaaains-zombieville-usa-tech-review/ Scroll down to the first picture to see what they're doing.
> 7 votes

---
Tags: 2d, animation, tools, editors
---