title: Java rendering performance bottlenecks

text:
# Question
Title: Java rendering performance bottlenecks
I've read a lot of forums about making 3D games in Java but I was unable to build a full picture of how it performs in video games.

I know that it works smoothly for small and average size games, but what would happen if one tried to write Crysis 3 scale game on Java? What would become the bottleneck of rendering performance? Would there be any difference at all compared with the same game written in C++? How much performance trouble would additional JNI layer give?

I would be glad to receive a detailed answer (or at least a link to some article) describing parts that JVM would never be able to optimize enough to give performance comparable with C++.

Thanks in advance.

# Answer
Large games commonly make liberal use of 3rd party technologies and APIs, generally these are C or C++ libraries. Many of these libraries do not exist for Java, so a developer will have to spend more time(money) on developing a Java equivalent.

Code in Java will at best run about the same as C++, but generally in the real world, **it runs much slower than C++.**

Also Java is not compatible with any consoles, so that is going to limit you to Desktop systems, and possibly android. (I am ignoring low end java capable phone as they cannot run anything of visual interest)

Use java if you are going to be building most of your systems for scratch, or you know of some java libraries that you will use, and are targeting Desktop systems.

Do not use java if you are going to want to use C++ only Apis, want bleeding edge performance, or want to create console games.
> 1 votes

---
Tags: java, rendering, performance
---


# Question
Title: Getting Started With Web-based Games....Can I Reasonably Target Flash And Silverlight And HTML5?
I come from a .NET background and I've done a few simple things in Silverlight. I'd love to adopt that and make my site and games Silverlight only; but I hear it has a fairly low install base.

I know Flash has a much higher install base.

I also know that everyone seems to say that HTML5 is the way things should be heading; but there is still a bit of a bumpy road ahead.

Short of maintaining three code-bases; are there any cool tools that would allow me to write once and end up with three versions of the same game? I'm guessing the answer is 'No' but from a theoretical standpoint, I can't think of any reason why it wouldn't be possible.

# Answer
> 2 votes
Check out Forplay which is built on top of Google Web Toolkit.
It is created by a couple of guys at Google.

**It can currently export to:**

* Desktop
* Java
* HTML5 Browsers
* Android
* Flash

There are working plans to allow exporting to iOS as well. Your code is written on a single codebase using Java and you can use existing Java libraries such as JBox2D.

Here is a video of their presentation at GoogleIO
http://www.youtube.com/watch?v=F\_sbusEUz5w

# Answer
> 4 votes
Doesn't matter what userbase Flash has if you can't develop for it. Stick with what you know, go for .NET. After all- if your game sucks, nobody will play it, whatever technology you use.

# Answer
> 1 votes
I don't know if this hits Silverlight, but you can develop games that work on a ton of platforms using monkey

# Answer
> 0 votes
> but I hear it has a fairly low install base.

Did you get any numbers to support that opinion? Here is a quickly found source: statowl plugin, there should be more.

From my own knowledge (articles read, etc...), Silverlight has a fairly good install ratio on Windows machines. It runs on MacOS too, but might not be installed as much, I haven't seen statistics for that.

If you don't want to target smartphones (other than WP7) and tablets running mobile OSes, it can be a good choice, especially if you already know it, or at least know .NET and some XAML.

# Answer
> 0 votes
At the moment, there is no 'single development tool' that exports to Flash, Silverlight, and HTML5 (and Unity, and iOS, and Android, and whatever else you might want to export to). For the most part, this is due to Silverlight not being supported by various gamedev tools. (Unity, for instance, exports to Flash 11, and iOS, along with being a plugin of it's own) *This* is mostly due to Silverlight not really being viewed as a "game development" tool. It's not worth going into the reasons here, though. It *is* a good choice if you want to do Windows Phone 7 development, though.

At the moment, Unity seems to be the platform to develop in for 3d web games, since it'll export to the new Flash 11 and iOS. It also supports C#, so it's somewhat .net developer friendly. Flash has become the main tool for 2d web games, and there's a few things like Flex and Flixel that let you develop in Flash without having to use the "normal" Flash software.

HTML5 has it's own set of problems, mostly due to it being too slow or not supported enough. There's also the issue of monetizing an HTML5 game. The route most people take with Flash doesn't seem as feasible for HTML5, though we'll see what the future holds as technology changes.

---
Tags: c#, flash, html5, cross-platform, silverlight
---


# Question
Title: What other online descriptions exist for specific game engines 8-bit and 16-bit game engines?
I found a good description of the engine in the Sonic games. It describes roughly how the engine works for people writing their own clones. In my case, I am simply interested in getting a general view of how the many 8-bit and 16-bit game engines worked on their respective consoles.

What other online descriptions exist for specific game engines 8-bit and 16-bit game engines?

# Answer
Most games of that era functioned very uniquely; there was very little engine-like code reuse.

That said, you're fairly likely to find the kind of detailed descriptions of gameplay mechanics you want from games that are very big/popular like Metroid, Final Fantasy 6 or Final Fantasy Tactics -- people have been researching the mechanics of those games extensively and you can find a fair bit of information about them scattered arond. Also games that are popular among tool-assist speed run fans as they tend to have know (and thus, hopefully document) a lot of the interesting quirks of the game code used in the games they run.

(Note that the TASVideos link was being really flaky at the time I wrote this and may not connect reliably.)
> 10 votes

# Answer
There is commented data formats with little code of several 8-bit games, these games are:

* Lords of Midnight
* Doomdark's Revenge
* The Hobbit
* Manic Miner
* Jet Set Willy
* Jet Set Willy 2
* Atic Atac
* Knight Lore
* Alien 8
* Sabre Wulf
* Wanted: Monty Mole
* Nodes of Yesod
* Dynamite Dan
* Starquake
* Ant Attack
* PAW
* Driller

I found it interesting that some of them use compression (RLE, dictionary), some of them don't, some use name generators; they had to save space because 8-bit computers had little memory. I believe that by examining these data formats You can derive algorithms yourself. :)

There is more 1 hour long video of making of Google's Pacman clone on Youtube and they used this detailed study of Pacman (Gamasutra link). In video they talk how they used some "good old" techniques like packing multiple textures into one ...
> 6 votes

---
Tags: game-design
---


# Question
Title: Any fixed-point portable open-source 3D physics engines?
I'm looking for a fixed-point 3D physics engine (basic kynematics and collision detection-resolution... nothing too fancy.)

I need fixed-point math because I'd like to have deterministic results, for reproducibility purposes, and high portability, because I expect my game to be highly portable for devices such as mobile phones or portable gaming consoles without floating point units.

# Answer
You can try asking guy who made tutorials on Flipcode on 3d fixed point math on mobile devices, he made games and they included physics.

(Some old games used fixed point (guessing Carmageddon, Destruction Derby ...). Fixed point is used on some mobile devices and they have games, and some of them are 3D.)

I hope it helps. :)
> 3 votes

---
Tags: physics, physics-engine
---


# Question
Title: Software Design/Modelling method and tool for games?
I've heard that UML is a great modelling language for software design. However, for software, such as game, that will certainly encounter major changes during the development, I doubt that UML will work effectively.

What are the common ways or models that the game programmers used? and is there any recommended tools for game designing process?

# Answer
My most recommended tools are **Trial and Error** (Iterative Development) and **Communication/Documantation**, and the experience coming out of it.

Whether you accomplish that by using good old pen and paper or sophisticated collaborative software tools doesn't matter much.
> 2 votes

# Answer
Real software (inc. games) changes a lot during development. UML is a very practical way to visualize and think of your design. Just use a tool that saves your UML in a textual format and save your UML, all your documentation, and your game code in a version control system. That way you can see the changes that happened to your design.

I would also like to mention rapid prototyping, as a development method to test if your design works.
> 2 votes

# Answer
As long as you are not afraid to modify your UML diagrams and make new ones, UML will be a very powerful tool for designing and engineering any piece of software regardless of the frequency at which it changes.

Iterative Development was mentionned in another answer and makes heavy use of UML diagrams to express the software small parts at a time. You basically give your team an objective for a small (2-3 weeks) iteration, make a bunch of UML to conceptualize the goals and model of your iteration then code after that. Iterative Development strongly encourages you to modify existing artifacts such as UML diagrams.

The thing to keep in mind here is that UML is not limiting because your software changes a lot during development, but it might become limiting if you make one batch of diagrams and never change them or make new ones to better reflect your ever-changing piece of software.
> 1 votes

# Answer
Rapid Prototyping is a great way to develop new ideas and test which ones are actually fun. It's often used in the early stages of design and is relatively inexpensive compared to implementing a large part of a game and realizing it's no good.

Many smaller teams also use Agile Development Methods such as SCRUM
> 0 votes

---
Tags: architecture, tools
---


title: How to make a fun slot machine?

text:
# Question
Title: How to make a fun slot machine?
We currently have a simple slot machine in our online virtual world game.

You set the amount you want to bet (in virtual money) and pull the lever, and depending on the 3 figures (there's only one line) you get a reward, a free round, lose some more money, or most of the time, get nothing at all. You can instantly pull the lever again. The previous bet will be maintained.

At the moment this slot machine isn't really fun to play. The chances of winning something are pretty low (though when you win, you can win a lot). When you pull the lever, the result is determined (though not shown) immediately, so there's also no way influence the outcome of the wheels.

How can it be made more fun?

# Answer
I think it's important to draw a distinction between "fun" and "addiction". Slot machines are not fun, and never have been; they are skinner boxes which apply feedback according to a simple reward schedule when the user pulls a lever, in an attempt to condition the user into repeated behaviour. As such, they can be fabulously addictive. Adjusting prizes and reward schedules will never make a slot machine fun; they will only make it more (or less) addictive.

If your goal is really to make the game fun (and not just make it more addictive), then you're going to need to add some play dynamics, so that the player can make meaningful choices which affect the outcome (as happened with video poker), or can affect the outcome via application of physical skill (as happened with pinball).

Or in other words, in order to make a slot machine actually be fun, you need to make it no longer be just a slot machine; it needs to be something that will stimulate the mind.

On the other hand, if addiction is actually what you were aiming for, then the answers from AttackingHobo and Tetrad are pretty much spot on.
> 5 votes

# Answer
There are a lot of articles out there that a simple search will yield answers to, but here are some highlights from what I've found:

1) You absolutely want to give out small rewards. Most slot machines actually have a pretty high payout ratio (on the order of 70-95%) of what's put in. A good percentage of the time you'll make your money back. Of course, over time slot machines are guaranteed money makers for the house, but you want to string people along.

2) The idea of risk vs. reward is important. Almost all slot machines let you place higher than the advertised minimum, and scale up the rewards accordingly. So a $1 slot machine is really a $3-5 slot machine since players will naturally want to put more money in after they see that their winnings could've been higher.

3) The "almost" win is an important psychological factor. Consider showing the images above and below the one you are scored on so you get the occasional "so close" thought.

4) It needs to be flashy. Spins need to be quick so that they can play again quickly. Sounds are important.
> 7 votes

# Answer
First off, do some research on the psychology of gambling.

You can't expect something that most of the time constantly eats your money without any reward to become addictive.

Don't give out free rounds, give out money equivalent to free rounds. Have a constant streams of wins and losses

Adjust the payout so that after 1000 spins, the bank is ahead, but not by much.

Also it seems you have a enter bet, and then press to spin. You should have a few quick bet buttons, with a preset amount, that pays and instantly bets and spins. As well as a way to enter a custom amount, if you really need to have one.

When the player wins, make sure to have flashing lights and bells going off sounds of coins falling, etc. If can set up an area in the world with lots of slot machines with different prices and rules, it will make it more likely that a user will move around to try change his luck or to have some variation. If you can sync these areas up to allow other users to see/hear winners it will also increase everyone's excitement.
> 1 votes

# Answer
It's probably worth adding some elements of skill to the gameplay. Even something as simple as nudge and hold buttons would add some depth.
> 1 votes

# Answer
My own ideas:

* Instead of a few big rewards, give more smaller rewards, so the player wins more often.
* Instead of just handing out more money, also reward the play with special items he can't get anywhere else in the game.
> 1 votes

---
Tags: game-design
---


title: Direction vector in raycasting

text:
# Question
Title: Direction vector in raycasting
When I read about how to get the direction vector in raycasting, for example on this site: http://www.daimi.au.dk/~trier/?page\_id=98

They first render the mesh with front face culling and then with back face culling. And then subtract the backface from the front to get at a direction vector for each pixel.

But is this not to much work to get the direction vector, is it not more simpler and faster to just take the vertex position(in world coordinates) and subtract the camera position in the fragment shader to get the direction vector? This should give the exact same answer but we skip the backface and frontface rendering.

# Answer
> 4 votes
The issue here is that there is no "vertex position" to compare against the camera position; the article you mention is talking about a raytracing implementation which doesn't feed model vertices and triangles to a shader in the usual way; instead, it would feed the GPU just one big 2D quad to cover the whole screen, and the rendering of model data would then be performed within the pixel shader applied to that single quad. (In this case, the model data is being provided as a large translucent 3D texture for the ray-tracing to sample through)

The approach described basically seems to be a clever method of generating the direction for a ray through every pixel of the screen, which ordinarily requires some trigonometry per pixel to generate. By using this approach, it seems to be possible to get those same rays using some pre-calculated renders and a simple vector subtraction per pixel. Of course, I haven't actually tried this approach to verify that it works, but the approach seems plausible to me.

---
Tags: shaders, raycasting
---


# Question
Title: Why hasn't OBJ been extended to support skinning?
Out of every format I know, the only one that works accross all applications perfectly is OBJ. I think it is an excellent format and I would use it for everything - except it does not support skinning.

I am wondering, why the spec has never been extended to include support for skinning. It wouldn't require overhauling the format - just add a 'vertex weight' and 'vertex bone id' parameter, and a list of bones and transforms at the end (or perhaps store all skinning data in a seperate file in the same way as material parameters are)

Its frustrating battling with all the other formats, while OBJ is just sitting there lacking this one thing.

Could someone with more industry experience theorise as to why this extension has never been added?

# Answer
Lack of time and expected reward.

There's a lot more to skinning than just adding vertex / bone weights to a geometry format, there's not much point in having that unless you also have the skeleton definition. And that's a lot more work, even for a basic implementation. Not to mention, none of the tools which export to OBJ format will support it. Why bother, when you already have other animation formats already defined, formats which are much better suited to storing animation data?

There's nothing stopping you or anyone else from extending the format yourself, both on the export and import sides. But an organised extension to the spec would be work for whomever took it on. Better to treat OBJ as what it is: a static geometry format.
> 4 votes

---
Tags: file-format, extension, skinning
---


title: Alternatives to distance fog

text:
# Question
Title: Alternatives to distance fog
I'm looking for some ideas/algorithm name for alternative to distance fog.

I'm playing around an "infinite" terrain engine. I can't draw the whole map because there are no borders and I don't like the idea of hiding the terrain at a distance with fog.

# Answer
A standard approach to this is to use Level of Detail algorithms to draw less-detailed versions of far-off terrain. These lower-detail versions can either be pre-generated, or may be generated on the fly, if you have dynamically changing terrain. (But in almost all cases, you want to pre-generate these terrain LODs, as that's dramatically simpler)

A good starting point for researching different methods of implementing terrain level of detail can be found at http://www.vterrain.org/LOD/
> 10 votes

# Answer
As jhocking said in the comment, FOW is unknown areas.

Computers can't draw infinite terrain. The lag would be incredible. Fog is used to blend in the edge of the render distance, which doesn't need to be close to the camera, nor does there need to be a large blend range.

You sound like you are thinking of a very short view range. Increasing your view range to a large number (this is set in your projection matrix), and sticking fog at the end, makes it seem like an endlessly shown terrain. And the fog isn't really that noticable.

However if you still want a precise answer to your question,

Weather, such as rain, snow, wind, etc. can help obscure the out of range area.

Terrain which reaches the clouds... Having mountains in your terrain, then having clouds at the top of the world, means that in the distance, you will find the edge of the world hidden by mountains, (or if your high up, clouds).

Finally, if your really desperate you could stick a curve onto your world, so that it appears that things in the difference are disappearing over the horizon.

However i still suggest you use fog, as it is simply a blending for the out of range area.
> 2 votes

# Answer
In addition to terrain LOD, you can render distant game objects and other things like buildings and vehicles using impostors. A good example/visualization of this technique can be seen here: http://www.markmark.net/clouds/

The idea being that you render distant objects once into a texture, then, as long as your viewpoint doesn't change dramatically, or the object itself doesn't change you can continue to render the texture for very little cost.
> 2 votes

# Answer
Maybe you could draw your terrain with a spherical bend to it like on real planets :) The clipping would be hidden naturally as you wouldn't have to draw anything that is hidden by the terrain you're on.

Of course, you wouldn't want (or be able) to infinately draw terrain anyway, as your objects will be too small to be correctly drawn on screen (less than 1 pixel) and it will aliaze like mad.

Your terrain will also never be infinate as you have finite resources (VRAM, RAM, HDD) on your computer. I am therefore guessing it is a terrain generator, that generated terrain randomly in front of you.

In this case you get nasty artefacts when geomety starts 'popping-up' out of your far plane. If your far plane is 'far' enough, only objects of certain height will noticabely 'pop' out of the plane. In this case you could maybe pre-calculate the large objects and always draw them, sclaed dependant on the distance from the far plane.

**Or** you could just use fog.
> 1 votes

---
Tags: xna, 3d, terrain
---


# Question
Title: iPhone, iPad Rendering Ahead of Input (4-5 seconds)
**UPDATE** *I think I solved this one, though any thoughts or suggestions are always welcome!*

This one is truly bizarre... I'm developing using both an iPhone 3GS and an iPad 2. This symptom is repeatable on the older iPhone hardware much more readily than on the iPad 2. Here's what happens:

I start the game and the FPS is ticking at about 47 on the 3GS in OpenGLES2.0. I have quite a lot on screen right now, so that is reasonable at this stage (I still have a few optimizations I can make too).

If you put a break in touchesBegan, it takes roughly 4-5 seconds before the break occurs and the game halts. This doesn't happen all of the time, and in fact, if you restart the app several times, it usually goes away. Moreover, if I let the game sit for a bit, it will eventually "sync." Like I said, the iPad 2 rarely exhibits the problem (one out of every 15-20 test runs), but it is definitely still present. If you perform a series of touches and accelerometer events in sequence, they are queued up and rendered just like you did them 4-5 seconds later. Very reminiscent of 4-5s lag delays back in the day online :)

I've tried a couple things like glFlush, or glFinish at the end of each render loop (doesn't seem to have any effect). Here's the top game loop:

```
- (void) drawView: (CADisplayLink*) displayLink
{
double dt = 0.0f; // Time in seconds since last loop
if (displayLink != nil) {
    dt = displayLink.timestamp - m_timestamp;
    m_timestamp = displayLink.timestamp;
}

// Update the game
m_gameEngine->Update(dt);

// Render the game
m_gameEngine->Render();
[m_context presentRenderbuffer:GL_RENDERBUFFER];
}

```

**UPDATE:**

The more I think about it... this could be a loading issue. Right now, I instantiate my main controller class for the game loop in the `- (id) initWithFrame: (CGRect) frame` call, which is also where I initialize OpenGL and (finally) call `[displayLink addToRunLoop:[NSRunLoop currentRunLoop]
 forMode:NSDefaultRunLoopMode]`. It's almost as if the renderer gets behind or ahead of the game logic and it takes it awhile to get caught back up.

From research, I could also just be throttling the CPU too hard. But if that were the case, I would imagine it wouldn't catch up... the FPS stays at a solid 44-46, and the input lag does go away if you let it sit for 10-15 seconds (with or without doing anything, it eventually catches up). I'm stumped, but I'll keep digging...

**UPDATE 2:**

Doing some profiling... figured out that the accelerometer being polled 1/60 was a bit taxing. If I moved it to 1/30, this problem went away. This is concerning to me, as it likely suggests I do have a CPU overloading issue that will only be solved through some serious optimizations across the board (which is okay, I knew I had to do it anyway).

For anyone with a similar issue, especially if you are using the accelerometer, make sure you disable it if/when you aren't using it. I only use the accelerometer to allow the player to rotate/move the camera - so when the player has the camera locked, I am now toggling it off. This has solved my problem for now, but like I said, I probably only solved it temporarily. A real solution is going to take more work!

Hope this helps.

# Answer
> 0 votes
After more experimenting, I do believe this has to do with the accelerometer. Regardless of the in-game frame rate, I hit this input lag delay (touch and acceleration), but only when constantly polling the accelerometer. I'm using a lowpass filter on the info, but that should be unrelated. If you have a similar issue, try talking with the accelerometer at a reduced rate.

---
Tags: iphone, input, ipad, cadisplaylink
---


# Question
Title: how can i make GUI that used to be in the old dos games but without the old look in openGL
I want to build simple OpenGL application that mustily are GUI based to collect from user input and to the user can push buttons . now i saw allot of GUI frameworks that offer GUI to openGL . but none of then offer GUI that is seams to be part of the 3d/2d game the closed example i can think of is the old dos games GUI .

# Answer
> 2 votes
Just about any existing UI framework that allows you to control the textures used in the GUI widgets should work -- just because none of them *ship* with an out-of-the-box "DOS" look doesn't mean they can't support one.

After all, what you are talking about is mostly just appearance. You just need to use highly pixelated (or "lo fi") textures for your UI artwork. Kind of like this sprite set, which has some bitmap letters that might be a good start for you, at least.

---
Tags: opengl, gui
---


# Question
Title: creating random monster encounters for 2d rpg. im using visual basics 2010
i just started programming a couple days ago. ive picked up on it pretty easy enough, but i still have a lot to learn. i was wondering if someone could help me out with making a system for random enemy encounters. with how many monsters appear and their stats.drop rates,enemy commands, etc. i have a program with a char on a bitmap to test things on, so if anyone could help me, it would be greatly appreciated. thanks!

# Answer
That is the art of programming, figure what you want and make a program that does it. You haven't yet figured what you want. You have an idea on the level of: "Sorta like Diablo", but you are not able to describe in sufficient detail what that actually means, and thus you can't convert it to code.

I think you should skip the random part for now, it's a whole host of problems and tricky decisions that you shouldn't worry about now. For someone a few days green an RPG is plenty overambitious on it's own.

What projects have you by the way done so far?
> 2 votes

# Answer
If you're thinking of developing something along the lines of a Roguelike, try this FAQ. While that wiki doesn't generally tell you how to program any of the things it describes it does give you a good look at what you need to consider while designing an rpg.
> 1 votes

---
Tags: software-engineering
---


# Question
Title: How standardized are joystick / gamepad configurations?
Right now I'm working on input for my game.

The only controller I own is an XBOX 360 one.

From what I can see, if a controller's stick has a Z axis, these are actually triggers.

Essentially I'm wondering if from one controller to the next, will this be consistent?

# Answer
> 3 votes
Joysticks and alternative input devices tend to vary wildly in how they expose their inputs through to the drivers, so it isn't always the case that an analog Z axis will correspond to triggers (for example, if the controller's triggers don't have analog input values, they may just be additional buttons).

The API you use to access the joysticks may do some of the work for you and attempt to homogenize the data from the controller, but this depends heavily on the API and isn't always done properly, unfortunately.

It sounds like you're on a Windows platform. XInput only supports Xbox-like controllers, the "next best thing" is probably DirectInput, even though it's a bit long in the tooth and COM-like.

# Answer
> 1 votes
As a practical matter, under Windows and Mac operating systems, different gamepads expose their controls via vastly different mechanisms.

About the only thing you can count on is that if there are multiple analog sticks, the left one will be number zero, and that digital buttons 0 and 1 will be face buttons accessed by the right thumb.

Everything else seems to vary from manufacturer to manufacturer, and even device to device. This is one major reason why computer games absolutely must have a "controller configuration" feature, which allows users to map their gamepad's buttons and analog stick axes to in-game functionality. There's currently no other way to make games work properly for all players with all gamepads.

# Answer
> 1 votes
There's virtually no standardisation at all. Even if you just take the default controller for each platform they all map controls differently and the expected behaviour differs (eg. which of the buttons is meant to go back, which is to confirm, etc). And even if there was something common across all the controllers, what about the other controls - users may wish to use them, especially if they chose that controller especially for the extras.

At a minimum you need to test with the main individual controllers you wish to support. Ideally you need to be able to remap any button, trigger, or axis to any appropriate in-game action, then ship with defaults for common controllers and let players configure controllers to their satisfaction.

---
Tags: c++, input, joystick, controllers
---


title: shake / Vibrate a body in box2d?

text:
# Question
Title: shake / Vibrate a body in box2d?
How do you vibrate or cause a shake effect to a body of type static or dynamic or kinematic. I tried applying forces to a dynamic body in the timeStep, which did not work, as well I tried ApplyLinearImpulse many times a sec within the timeStep, which again did not give me the result. So right now Iam experimenting with adding a static circle body as a hinge point to my rectangular body and create a revolute joint between them. May be then applying a force could result in Tension between the 2 bodies? Does anybody know about this? have any ideas please let me know?

# Answer
> 3 votes
okay I just figured everything out...all I had to do was to set the linearVeolcity using boolean logic. i.e

```
if(counter <50)
{
 if(toggle)
  {
    body->setLinearVelocity(5.0,0.0)
  }
 else
  {
    body->SetLinearVelocity(-5.0,0.0)
  }
  toggle = !toggle
}

counter++;

if(counter>50)
{
 break away from being static body
}

```

all of the above code has to go in to the timeStep under the loop in which you iterate the b2Bodies of the world.....the logic is simple.

---
Tags: iphone, box2d
---


# Question
Title: Controlling the draw order (z-index) through instancing?
Is there any way that I can control in which order elements are drawn with instancing?

Do all elements get drawn in the same order they are added to the instance buffer?

Edit: What about the Z coordinate! Since I am drawing my GUI through this, I should be able to just put elements in front of others, right? I am not at home to try this out yet. I will keep the thread updated.

# Answer
> 2 votes
If you are doing 3D, depth should be drawn according the the z-buffer.

# Answer
> 2 votes
Object are drawn in the order they are sent to the graphics hardware (generally, I don't want to get into nit picky here :)). So to your original question, if those are the instances you are talking about, then yes, the order is obeyed (and becomes very important when dealing with alpha blending for example).

In the realm of 2D GUI/HUDs, I will generally Render the scene, then disable zBuffering and render the HUD using its by-design root to leaf nature to get the proper layering.

Can you use the z value? Yes.. I am just not sure if there are enough polys to really make this a huge concern however. (I have worked in a system that did this, but that was because the GUI was the same system as the Particle System.)

Hope this helps

---
Tags: xna
---


# Question
Title: Scale my pixel art files when designing them or when rendering?
If I create pixel art files that need to be scaled up on the screen later, so that a single pixel becomes a box of 4 pixels. Should I create my pixel art with 2x2 pixels or should I create it with 1x1 pixels so that I can I 1:2 scale it later in XNA to 2x2 pixels?

I tend to believe that 1:1 would result in too much detail rather than the pixel art effect, thus I want the end result in 2:1 style where a 1x1 pixel of my intended sprite will take 2x2 pixels on the screen.

# Answer
> 8 votes
Bad idea to scale it up beforehand like that.

Doubling the size of a texture quadruples the storage, and the memory it uses. It will also slow down spritebatches, and generally take more time for rendering.

What you want to do is scale the textures up by 2 when drawing them in XNA, while making sure to scale with a PointClamp image sampler.

How do I disable texture filtering for sprite scaling in XNA 4.0?

# Answer
> 1 votes
You're really looking at a 6 one way, half a dozen the other situation here.

The main advantage of doing it on a 1 to 1 scale before hand is file size. On top of that, you don't have to manually make sure all your "pixels" are in the right 2x2 setup, and so long as scale up by whole numbers it will work clean (rotation's still a mess but you probably know that already)

If you do all the pixels as 2x2 beforehand you're in the same situation as before, except now you have to go up by .5's in order to keep a steady ratio. You do gain the ability to go half size, but really the half size from this is exactly equal to the size of the full size on the 1x1.

I personally would go with just having one pixel be one pixel as far as your assets go, and then scale them to the proper size. It will make your image creation easier and it will make your assets ~1/4 the size for faster loading.

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


title: Draw real time fog of war in 2d game

text:
# Question
Title: Draw real time fog of war in 2d game
I have game situation as shown in picture:

* Red dot: player
* Brown dot: obstacle ( rock, tree, etc)
* Grey: non visible area ( under fog of war)

My question is: how can I draw that kind of shape, changed dynamically, with XNA 4.0. I can calculate each point of this shadow polygon. I would avoid drawing it pixel by pixel due to performance reasons, maybe particles? But i won't have sharp edges with this technique. Any tips?

# Answer
See here for an in-depth tutorial/example of doing it in HLSL (shader) code.:

http://www.catalinzima.com/2010/07/my-technique-for-the-shader-based-dynamic-2d-shadows/

If you want sharp edges remove the final blur step.
> 9 votes

---
Tags: xna, 2d, line-of-sight
---


# Question
Title: What kind of culling does XNA do for me?
Which kinds of culling and clipping does XNA do for me as default, and which kinds does it not?

Z-culling? Backface culling? etc.

# Answer
Z-culling (culls *pixels* that are behind already-drawn pixels in the Z-buffer) and back-face culling (culls *triangles* that are facing away from the camera) are handled by the `DepthStencilState` and `RasterizerState` respectively. These are state objects.

They are also the names of properties where you can set those state objects on the `GraphicsDevice` (MSDN).

The default values are:

`DepthStencilState.Default` (MSDN) which is set up to both read and write from the depth buffer.

`RasterizerState.CullCounterClockwise` (MSDN) which is set up to cull triangles where the vertices are counter-clockwise.

There are other built-in states available on the state objects, see the static members for each state object (MSDN: `DepthStencilState`, `RasterizerState`). Additionally you can create your own state objects that further customise the behaviour.

---

XNA itself does not provide any built-in culling mechanisms, *except* exposing those provided by the graphics device. These include Z-culling and backface-culling. You could also argue that the stencil buffer, scissor tests, and the viewport are also kinds of culling.

XNA does, however, provide some useful classes for adding your own, more advanced, object-level culling mechanisms. For example `BoundingFrustum` provides intersection tests to allow you to determine what objects (usually represented by a `BoundingBox` or `BoundingSphere`) are visible in your 3D camera.

This question and answer provide some useful information about how to decide where culling is appropriate.
> 9 votes

# Answer
The default value is `CullMode.CounterClockwise`. Options are:

* `CullClockwiseFace` \- Cull back faces with clockwise vertices.
* `CullCounterClockwiseFace` \- Cull back faces with counterclockwise vertices.
* `None` \- Do not cull back faces.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.cullmode.aspx
> 8 votes

---
Tags: xna
---


# Question
Title: Does SoundEffect.CreateInstance load from file everytime?
This is something which has been bugging me. If I create a SoundEffectInstance via SoundEffect.CreateInstance() I'm meant to dispose of it when I'm finished with it. SoundEffect.CreateInstance() does not use ContentManager as far as i can tell.

So does it load from file or does it keep a copy in memory? Loading from file would obviously be very slow :-/

# Answer
It's an **implementation detail**. You don't know for sure, it doesn't matter, it might differ between platforms, and it might change in the future.

However you can make an educated guess: First of all the fact that `SoundEffectInstance` exists, and that you load sound files into `SoundEffect` indicates that `SoundEffect` is probably responsible for holding the sound effect in memory. And the existence of `SoundEffect.FromStream` and the buffer-based `SoundEffect` constructors are strong indications that `SoundEffect` *must* have a mechanism for keeping a sound buffer in memory. Therefore it is fairly safe to assume that when you load a `SoundEffect` from a file, it uses the same mechanism.

If it's really important, you could test it by deleting or modifying the sound file, after loading the `SoundEffect`, and then creating an instance.

As always, if performance is really important, you should *measure it*.

Of course, creating a `SoundEffectInstance` does allocate resources (audio voices, managed and probably unmanaged memory). So it's not something that you should be creating regularly if you can avoid it - such as by pooling and reusing instances. When you're using `SoundEffect.Play`, then `SoundEffect` is internally managing a pool of `SoundEffectInstance` objects for you.
> 5 votes

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


# Question
Title: How are trajectories calculated and transmitted to other players, in multiplayer?
I play a lot of *"Call of Duty"*, and can see tracers for gunfire, missiles, care packages falling from helicopters etc. There is a lot of activity. I am curious to know the algorithm one would use, at a high level, to manage all this action when you have 20 people on a map shooting each other to death.

This question touches on the subject, but doesn't ask for a more in-depth answer as to how you the developers go about calculating and transmitting movement and collision detection for projectiles, be it missles, bullets, or any other object that is flying through the air in real-time.

How are trajectories calculated and transmitted to other players, in multiplayer?

# Answer
> 7 votes
It depends on how important object for gameplay and how it working.

Generally projectiles like missles move along a predictible trajectory so server can spawn a new object, set its position, direction, speed and transmit data about new projectile to clients. Client-side code will simulate movements of a projectile using this data. If projectile hit something important (world geometry, other player or something else) server process this and inform clients about this.

Human controlled objects require different approach. Since it cannot be fully predicted on client-side, server frequently send updates about position and direction to clients. Often this data include speed of object to allow client to interpolate and/or extrapolate movements of object between updates from server.

---
Tags: collision-detection, multiplayer, projectile-physics
---


title: How to make game appear to run faster?

text:
# Question
Title: How to make game appear to run faster?
I believe I read somewhere that there is a technique which will make games appear more smooth than they are. I believe it is some visual trick, but I don't remember which one. (It is be something like "You percieve game to be more fluid if there is good shadows").

I may be wrong and there is no such thing.

# Answer
You're probably thinking of motion blur.

Edit for more content: Here's a bit from GPU Gems 3 on motion blur:

Motion Blur as a Post-Processing Effect

> One of the best ways to simulate speed in a video game is to use motion blur. Motion blur can be one of the most important effects to add to games, especially racing games, because it increases realism and a sense of speed. Motion blur also helps smooth out a game's appearance, especially for games that render at 30 frames per second or less.
> 9 votes

# Answer
There is a way to allow updating at fixed rate, and rendering at whatever rate the users system can handle.

You need to implement a fixed time-step, which has the upside of making your game simulation determistic. And you need to implement interpolation in the drawing method, which will allow the drawing rate to be much higher than the updating rate, while looking really smooth.

**Fixed time-step**

Semi-fixed or Fully-fixed timestep?

**Interpolation**

How to Interpolate between two game states?
> 5 votes

# Answer
Check out Real-time Frame Rate Up-conversion for Video Games, which was presented at Siggraph 2010.
> 3 votes

# Answer
You can't really make the game overall appear faster than it is, but you can make slow parts look faster (or at any rate less noticeable) by de-coupling them from everything else so that everything else can run faster. Indeed, this is precisely why network commands are done asynchronously.

Similar things can be done locally, whenever one part of the game is slower than other parts. For example, physics updates are often run asynchronously from the rendering loop. Perhaps character animations are updated on a separate thread from background graphics, etc.
> 2 votes

---
Tags: graphics, graphics-programming, frame-rate
---


title: Populating NPC's Outside Of Loop

text:
# Question
Title: Populating NPC's Outside Of Loop
This was my original question: Populating Sprites I used the following code to spawn Enemy Sprites in my game. I have 2 types that I was using and it would display one then remove it and display the other. It did this repeatedly(Imagine someone playing with a light switch and you have what is happening with the NPCs. EnemyType1 is Off and EnemyType2 is On.).Also It does not apply the current level number meaning, it does not spawn the number of enemies for the level. The number of enemies I want to spawn is the exact number of the level. I used other types of random methods( nextBoolean(), nextInt(), nextFloat() ). I showed the code to my friend and he told me that I would need to spawn them outside of my loop, but he did not know how to. So now I am trying to see if anyone on stack could help me. What I am trying to do is this:

NPC's = Enemies

I have 2 types of NPC's that I want to use. The number of Enemies that are spawned are equal to the the current level number. I want to be able to spawn how ever many is needed for that level and have it to where which Enemy that will spawn is random, so you don't know if you will get EnemyType1 or EnemyType2 or a Mix. Ex: Level 1, only 1 Enemy spawns, the type is random. Level 2, only 2 Enemies spawn, the type is random. Level 3, only 3 enemies spawn, the type is random. etc.

Thanks In Advance.

# Answer
Basically at the start of the level you need to call a function that creates the enemies for the current level, for example you could do :

```
for(int i=0; i < currentLevel; i++)
    enemyList.Add(new Enemy(nextInt() % 2));

```

This would populate the list with a number of enemies equal to the current level. This should only be done when you change level, for example :

```
if(enemyList.Count == 0) {
    currentLevel++;
    CreateNewEnemies();
}

```

This means you have to unpopulate your list when the enemies die, this will be done in your Update loop.

```
foreach(Enemy e in enemyList) {
    if(e.IsDead)
        deadEnemies.Add(e);
}

foreach(Enemy e in deadEnemies) {
    enemyList.Remove(e);
}
deadEnemies.Clear();

```

This is not optimal, but should work.
> 1 votes

# Answer
I am not 100% sure what you are asking, but from this post and the other one here is my guess:

It sounds like you were selecting which type of NPC the NPC should be during the update for the object. This would be why it constantly changes every frame.

What you need to do is find a place where you can set that value where it will only be set one time. This is probably what your friend meant by 'outside of the loop'.

If you can more clearly describe what you are seeing as opposed to trying to explain what you are doing, it might help be able to refine this answer more.
> 1 votes

# Answer
It sounds like you need to learn more about how Object Oriented Programming works.

I think that you are creating an instance of an enemy, and then without storing that instance in an array, just creating a new instance with the same name, effectively destroying the original instance and creating a new instance.

Create an array that will hold all the enemies. When you spawn an enemy add it to next position in the array.

In your update method loop through all the enemies and update 1 per loop.
> 0 votes

---
Tags: android
---


title: 2D game physics, doing it right

text:
# Question
Title: 2D game physics, doing it right
I have a ball that you can make jump,

I have a sneaking suspicion I'm doing this wrong. It works now, to the extend that gravity pulls the object down toward the ground, but I'm having trouble manipulating the speed of the object.

What this is, is a ball jumping and falling towards the ground.

I have another function called "jump" that just adds a value to it's yVel

I can increase gravity, and it falls faster.

I can increase the jSpeed speed, and it'll rise up longer, but not faster

But I can't get it to do everything faster. It just looks painfully slow, which may or may not be because of my emulator running at 11 fps, on average.

Is it just my emulator, or is it something on my end?

```
float time = elapsedTime/1000F;
 if (speed < maxSpeed){
            speed = speed + accel;
            }
            if(mY + mVelY < Panel.mHeight){ //0,0 is top-left
            mVelY += (speed);
            }

            if (!(mY + height >= Panel.mHeight)){
            mVelY = mVelY  + gravity ;}

            mX  =  (float) (mX +(mVelX * time));
            mY =  (float) (mY + (mVelY * time));

```

# Answer
There are some errors:

```
speed = speed + accel;

```

acceleration must be multiplied by time to get the change of velocity/speed during this frame:

```
speed = speed + accel * time;

```

The same problem is how you handle gravity, you cant simply add it to velocity.

Then you add speed to velocity each frame. Speed is actually the length of the velocity vector. Adding speed to velocity doesn't make sense physically.

You can find a proper implementation of Euler Integration in my answer here, there is a simple example showing how to deal with Acceleration, Velocity and Position.
> 1 votes

---
Tags: android, physics, frame-rate
---


# Question
Title: Calculate winner of battle when auto is chosen
There are two slightly different scenarios I am interested in and I'l give you examples of each.

The first is like the tournament system in *Super Smash Brothers Melee*, when there can be dozens of cpu vs cpu battles and it has to choose a winner. This could be done with a random number generator but I feel there is something more there.

The second is in some games, mostly strategy games, you can choose to play a battle or have the computer calculate the battle for you. The game *Medieval: Total War* comes to mind, where it calculates how many troops you and the computer lose. In these scenarios, it never goes as well as if I had done it myself but I usually win if it is plausible.

What I want to know is, how are these battles are calculated? Does anyone know how it is done, or have an idea of how to implement it?

I had an idea of just doing the battle normally but disabling all graphic display so it would conclude very fast, but I'm not sure this would work too well.

# Answer
> 0 votes
Probably there is not a single answer for this. To be generic, you should use a model for the battle and put some order of randomness on it.

The random may be the weighted dice trown to se who wins a direct fight (as in Risk or D&D) where your model computes the direct fights.

Another aproach may be that both the contenders choose a random strategy and the match of this couple generates the direct fights to compute through another random number.

The strategy can be choosed by each army unit accounting the unit's nature or personality, a Markov chain can be used to move the army or each army unit from a strategy to the next taking into account the current overall result.

In any case what you do is to choose a granularity between a model for the battle and the success of a dice trown and keep it secret. Notthing is more boring that know how the battle will finish because you know the dynamics.

corollary: who designs a game hardly finds it enjoyable as is for the rest of the world.

# Answer
> 3 votes
The idea of doing the battle "normally" (usually multiplying any time deltas to make it go faster) is a simulation approach, like used in Football Managers, etc.

This approach has the benefit of being **precise** and if it is an option to 'skip' the battle, it is also reusing game code with an AI replacing the player.

A random number generator can work, it all depends on your needs. You could couple this generator with simple calculations dependant on player stats (wins/losses, strength, etc.) and use these to determine the outcome.

It is a fine balance between simulation and randomness when the only data the player has is the starting state and the end state. You need to balance it so that the player doesn't have an advantage in skipping battles if it is optional because he will prefer not to play. He also needs to feel that he is not cheated out of an easy win.

---
Tags: c++, automation
---


# Question
Title: Simple physics for modelling ship/submarine movement
for a first iteration of my sim, I need a very basic physics model for ship/submarine movement. I'd guess it might be a good approach to use vectors here (ship heading but also considering sea states etc.). Basic acceleration and that stuff should be taken into account

I do not need any 3D stuff...the 'client' for that 'ship movement' physics is only the 2D rendering of a navigation map.

I've found some papers on the net but they are far too complex for my needs.

Anybody does know some 'simplified' vector algorithms etc. for that?

Thanks a lot.

EDIT: To be clear: I do **not** want to simulate ship movement/ocean physics in detail, because this is not the focus of my (naval) simulation. It 'just' must be somewhat believable in that sense that if you have different sea states(wind/waves/currents) that the vessel is somewhat believable influenced (on the navigation map) by those forces.

The main issue for me is how I model/calculate those forces (wind etc.) by simple vectors and (eg. for a given wind velocity like 50kn) in an easy way withouth studying physics ;).

# Answer
Simple Euler Integration will fit your needs, see my answer here

**Edit:** However, for the feature list that you appear to have (which is not that simple btw) the easiest solution is using Box2D
> 1 votes

# Answer
You should consider friction specially in submarines, this ships can travel both under and on whater surface so the speed they can reach may vary according - this to account basic fluid dynamics.

The whole dynamics should be that the ship has an orientation and a propulsion force (both positive or negative), this means an acceleration toward the ship direction. Another acceleration is due the friction, it should be propotional to the speed and backward oriented. The propotional factor may depend upon the ship's shape (repeat it 10 time as fast as you can) and if is in submarine or normal mode.

Then you need to integrate the acceleration to the speed and the speed to the position. Euler integration is not THE integration (what about runge-kutta?) anyway you have to integrate and have to choose between speed (of integration calculus) and accuracy (your ship should not explode or travel backward faster than light).

Summarizing, a ship can be represented by:

* friction states
* max propultion acceleration
* the friction status
* current position
* velocity vector
* current acceleration factor
* heading

The first two depends upon each ship type, the others defines the complete status of each ship in the game and the last two of this are the ones you can directly control (you should consider the rudder so the heading become an indirect parameter controlled by the rudder position, the choose is yours)

**EDIT:**

The friction model for wind is the same:

The wind hits the ship in a direction, the shape (CX) for that direction is connected to the (air)friction experienced by the ship: the acceleration is propotional to that friction and has the same direction of the wind (as if the ships goes where the wind comes at the wind speed and the air is still). Assuming that your ship is simmetric over the heading axe, you can compute the angle of wind incidence throught the scalar product of the normalized heading and wind vectors, then use a function that compute the friction ( max friction for 90° degrading to min friction when going to 0° or 180°).

If you are lazy you can consider the ship spherical (I whould like to see one in my life) and completely ignore the wind angle measurement simply applying the constant friction multiplier to your wind vector.

The same for the currents of course.

Obviously the final acceleration you have to integrate is the vectorial sum of all the trust and friction based accelerations you compute.
> 2 votes

# Answer
It's not couched in terms of vector math, but you might find this answer from a previous question about ocean simulation and physics useful. Make sure you understand what it is you're simulating before you get into how you simulate it.
> 0 votes

# Answer
The only thing different about a ship as compared to a standard rigid body is that it has a keel that moderates forces coming from tide and current; a ship making 0 knots simply has its propulsion force 0 in the equation, it's not a special state you have to go into.

And the only thing different about a simulation environment for a ship versus a rigid body is that surface friction is basically nonexistent. Go down to the harbor and find a huge 40 foot yacht that weights tons, push a finger against it and slowly just that little force will accelerate it until the guy lines stop it.

Unfortunately what you are trying to do is exactly studying physics, no way around that. The good news is that all you really need to know is some basic vector math and integration to get the numbers back out.

I'd suggest looking at something like Box2D (http://www.box2d.org/) as a physics harness, you won't need most of the features.
> 0 votes

---
Tags: physics
---


# Question
Title: Count number of Vertices in VertexBuffer in XNA 3.1
Where in XNA 4.0 one can go:

```
 myVertexBuffer.VertexCount;

```

What is the best way to count the number of vertices in 3.1 for a dynamic buffer (i.e. where I do not know the number of elements that could be therein). I have come up with:

```
myVertexBuffer.SizeInBytes / VertexPositionNormalTexture.SizeInBytes

```

Where my vertices are VertexPositionNormalTexture's, but is this the best way? (it will be called often in Draw()).

# Answer
@Blecki's answer is correct, I also don't have 3.1 installed, but some quick googling with bing shows a few examples.

```
foreach (ModelMesh mesh in model.Meshes)
        {
            int numberVertices, numberIndices;
            numberVertices =
                mesh.VertexBuffer.SizeInBytes / mesh.MeshParts[0].VertexStride;
            if (mesh.IndexBuffer.IndexElementSize == IndexElementSize.SixteenBits)
                numberIndices = mesh.IndexBuffer.SizeInBytes / sizeof(short);
            else
                numberIndices = mesh.IndexBuffer.SizeInBytes / sizeof(int);

            totalNumVertices += numberVertices;
            totalNumFaces += numberIndices / 3;
        }

```
> 2 votes

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


title: Moving object through nodes in Quadtree

text:
# Question
Title: Moving object through nodes in Quadtree
I'm working on my own quadtree for use in games for physics (collision detection to be exact) but am unable to move an object from one node to another node.

What I'm doing is if some object is to be moved, I'm deleting it from its old position and adding a new object (with same property, such as width and height) to the new position. Is my approach correct or is there any other optimized process to do same?

The problem I'm facing is that if I move an object from node 0 to node 3 (both node being children of, for ex., root node) the root node container(I'm using std::vector) gets the object but it is not updated in the node 3's container.

Any solution to my problem? Though would be happy to try some other method too.

Thanks.

# Answer
You should be working with references (or pointers depending on your language) ... moving something should almost never require one object to be destroyed and another created.
> 2 votes

---
Tags: physics
---


title: Does openGL fit my needs?

text:
# Question
Title: Does openGL fit my needs?
I am looking to create a game. Starting with something simple, the "hello world" of gaming if you will. I think OpenGL will fit my goals. I want to start on a PC because its readily available to me. Eventually I would like to develop on the iPhone and since it uses openGL I feel this is a good translatable skillset.

I would really like to keep things simple. Maybe start with PONG then a 2D scrolling Mario-ish game. Ultimately I want to create a game similar to Farmville.

To the experienced game devs out there, do you agree? Does OpenGL offer a free/low cost to entry as I think it does? How well does the skillset Xfer to the iPhone (I believe I'll need to use C on the PC and Obj-C on iPhone)? Finally, what are the "big-3" using for development (PS3, Nintendo, Xbox)?

# Answer
> 7 votes
**On OpenGL:**

OpenGL is a suitable choice for a graphics API. There's a fair bit of legacy cruft floating around in the API, especially if you are not using the latest version, which can be distracting and confusing for a newbie. It's also a fairly low-level system and it's possible you may want to investigate other potential 2D engines that provide a higher-level API. This is especially true if you only want to focus on 2D graphics initially, because OpenGL is a 3D API -- it has no "2D mode," and if you don't understand the fundamentals of the 3D graphics pipeline that you're using, even when faking 2D with it, you can get yourself into some uncomfortable spots with weird, difficult-to-diagnose (for you) bugs.

There's a lot of questions on the subject of 2D engines here.

OpenGL, Direct3D, whatever -- it's more important that you learn the fundamentals of graphics programming. *That* skillset will transfer to any API or any engine, which means when changing platforms you simply need to learn another API and how that API exposes those fundamental, shared concepts, which is trivial. Or at least should be, for a good programmer -- if it is difficult for you, you just need to practice it more.

> Does OpenGL offer a free/low cost to entry as I think it does?

Yes, it costs nothing to use OpenGL itself.

> How well does the skillset Xfer to the iPhone (I believe I'll need to use C on the PC and Obj-C on iPhone)?

You can use C and C++ on iOS as well -- you'll require a minimum amount of Objective-C bootstrap, but the bulk of your program can easily be written in other languages. The iPhone provides you the OpenGL ES API, which is essentially a subset of the full OpenGL API. It should be relatively easy for you to adapt your code to run on an iOS device.

> Finally, what are the "big-3" using for development (PS3, Nintendo, Xbox)?

It doesn't matter. This kind of question is indicative, usually, of a concern that you should pick the one "right thing" to learn and focus on that. But there isn't a right thing and if you know the basics, as I noted in the initial part of this answer, you can learn any API presenting those basics with relative ease.

That said, the PS3 has an OpenGL implementation that nobody takes seriously and a proprietary API for anything real. The 360 uses an API that is quite similar to Direct3D. The Wii probably uses something OpenGL-like as well, although I couldn't say for sure.

**On "Your Needs:"**

We can't really answer that for you, since we only have the most cursory understanding of your needs and your ability. Just like learning APIs, evaluating requirements and potential solutions for those requirements is an important part of a developer's training.

The best way to do this is to try it -- set up a project and try to build a quick tech demo with OpenGL. You'll get a feel for how the API works, where you can find good reference material (because you will invariably get stuck somewhere and have to hit up Google to find out, for example, "how to create a shader in OpenGL."

You can then grab some higher-level 2D engine and try to recreate the same tech demo and see how you feel about the relative experience. You can try to demonstrate features you know you'll want in your game -- if you want fancy alpha-blended explosions, try building demos that render a bunch of transparent sprites (or even just blank, colored quads) intermixed with some opaque ones. You'll discover the problems inherent in rendering transparent graphics and you'll have to solve them with both pieces of technology you're evaluating. One will, perforce, work out better/easier for you. That may be the API you want to actually stick with.

# Answer
> 0 votes
Yes you can use OpenGL freely. Its a good place to start since its a well-known api with a lot of resources already out there. Since OpenGL is available on a lot of platforms, your skills once you learn it will probably transfer nicely.

However, if this is your first time diving into unmanaged code, you could lessen the learning curve my using a managed graphics api and then jump to OpenGL. But that depends on where you stand now.

Also, you can use c++ with OpenGL on the pc. Hope this helped :)

# Answer
> 0 votes
Yes, you can use OpenGL to render 2D stuff and it gives you some flexibility. I regularly does this, but it is a bit trickier than using a simpler 2D only API. What you gain is accelerated scaling and rotating, and the step to 3D is not that big if you want to take that later on.

The API itself is C, and so is the GL ES API (for iPhone), but you can use it from Objective C and C++ (and most other languages).

The consoles usually use custom low level API:s, but the Xbox360 one looks a lot like DX9.

# Answer
> 0 votes
Listen to this sentence and repeat it a couple of times, because it's very important if you want to program games: Develop games, not engines.

If you want to develop games, you shouldn't use low level things like DirectX or OpenGL at all, because 99% of your learning time will be spent dealing with the graphics API instead of actually programming your game.

There are tons of free good engines for 2D and 3D out there, and even if you don't want to take a finished engine and work with it, you should at least consider using an abstraction layer library like SFML, which builds upon OpenGL, but also provides most other stuff that you need for game programming, like support for audio, window and input handling, networking, etc. ( http://www.sfml-dev.org/ ).

So my advice: Forget about OpenGL for now, search for engines or high level APIs out there which let you achieve your first Pong game more quickly, and go with it.

---
Tags: opengl
---


title: One- to Two-Week Game Competition

text:
# Question
Title: One- to Two-Week Game Competition
Ludum Dare is great, except it's only 48-72 hours (depending on your flavour). Is there any particular (good) competition that gives you 1-2 weeks to develop? I don't usually get enough time to put significant effort in 2-3 days.

**Edit:** I'm using .NET. It must be open to .NET (Silverlight, preferably) games.

# Answer
> 12 votes
Two major ones I know of are the Seven Day Roguelike Competition and Pyweek.

The Something Awful Forums also has a month long gamedev competition, starting in July. You can form teams, but you or someone on your team has to have an account there.

The Experimental Gameplay Project also has month long competitions where you're only allowed to spend a week on development. Each month there's a different theme.

TIGSource forums also occasionally do month long competitions, though they seem to happen somewhat rarely.

---
Tags: competition
---


# Question
Title: Should frame rate affect the speed in a game engine?
I am writing a 2D game engine for fun. I am able to perform animation using the engine. However, if I change the frame rate (frames per second) the speed of the animation changes.

I have never used any game engine. I want to know whether other game engines handle this issue or not. If not, what is the ideal frame rate for a 2D game?

# Answer
> 13 votes
No, frame rate should not affect the speed - the gameplay will hinge entirely on their video performance, which is disastrous (even if you limit the speed, you can't control people whose systems will run the game at half speed).

You're experiencing this problem because you did something wrong: Your update/render routines run one after the other as fast as possible, with objects updating on a per-call basis (thus when the call speed deviates, so does theirs).

### A time-based approach

The correct way to do this is to update objects on a *per-second* basis.

Consider a bullet for instance: Right now it probably knows how much it needs to move per frame. You need to turn this into how much it moves *per second*. How you do that is actually not too complicated.

First, your bullet's going to be updated more than once per second, so we need to actually update it every few milliseconds. Each time you update your physics engine, a certain number of milliseconds have passed since the last update: this is called the *delta time*, normally *dt* for short. The dt is determined *before* updating all objects, then all objects update using the same dt in order to keep in synch. The dt is generally passed as an argument to each object in its update call.

In fixed-step physics, the dt is a fixed number, whereas in variable-step physics, the dt varies depending on the actual amount of time since the last update (hence their names).

That brings us back to your bullet. It's been told to update with a dt of 16 milliseconds, for a physics engine updated 60 times per second: if the bullet moves 12 metres per second, you move it `(16.0/1000.0) * 12.0` metres in this update.

# Answer
> 10 votes
The best way to make your game run the same speed on all systems is to use a Fixed Timestep.

With a fixed timestep, the game will always update at the same rate, no matter what the render rate is, and when using interpolation, it will look smooth even when the render rate is much higher than the update rate.

Here is an answer with resources on how to implement a fixed timestep.
Semi-fixed or Fully-fixed timestep?

Here is an answer that explains how to implement interpolation for movement and transformations.
How to Interpolate between two game states?

# Answer
> -2 votes
No it should not. One type of timing you can do in your game is frame-based timing. The idea is to let the game loop run as fast as your computer can run it thereby having the bast overall experience and you control the rate at which your simulation runs. Now you've decoupled your updating from rendering and have precise control over it.

In this scenario, your game loop can be running at say 60 fps on one machine and maybe 45 or something different on another, but your simulation will always run at the precise specified rate between them.

You game now is divided into two section, one to render your graphics and the other to updating your simulation. You set your desired simulation rate at game start and at the top of your game loop, you get the elapsed time. Note, this elapsed time is a time quantity based on your desired simulation rate. This value is then used as a multiplier against your game objects to keep them moving at/or very close to your desired simulation rate. For example, if you want your simulation to update at 30 fps and your game loop is currently running at 60 fps, the elapsed time value for this frame will be 0.5. When you multiply this by the speed of your moving objects it will cause them to move at 30 fps. Know that from frame to frame your game loop speed will vary greatly and frame base timing can keep your simulation running at a known and predictable rate.

The result is silky smooth animation.

---
Tags: frame-rate
---


# Question
Title: Combination of DLL/Plugins with Object/Components
I worked on a personal game project (learning) for about the last year or so off and on in Ogre3D. Now that I am starting a new project, I want to avoid the Class Heirarchy for objects and having all of my libraries stuffed into one project file.

After a massive amount of reading, I am going to start implementing a Object/Components system tomorrow, mostly based off of what I have read on http://gameprogrammingpatterns.com/component.html but I want to have a better understanding before I proceed.

Ogre3D offers a Plugin system, which I understand to basically be the equivalent of a normal .dll library except it has install()/initialise()/uninstall()/etc methods, intended for registering factories.

So my confusion comes down to what would be best kept in a Plugin or DLL?

Most of what I read, people recommend putting wrappers for third party libraries into Plugins/DLLs so I am assuming I would want to have one for my Physics (Bullet) System, Audio (OpenAL) System, Input (OIS) System, and so on.

In that case, should I basically just strip the Managers out of my project, and move them to a Plugin/DLL? I am still quite confused on how I will actually go about implementing them into Components once they are moved, but I guess that will come with time.

# Answer
> Ogre3D offers a Plugin system, which I understand to basically be the equivalent of a normal .dll library except it has install()/initialise()/uninstall()/etc methods, intended for registering factories.
>
> So my confusion comes down to what would be best kept in a Plugin or DLL?

Plugins are generally used to extend or build upon the behavior of some existing service or library -- in this case, Ogre. If you aren't intending to directly extend or modify the behavior of Ogre, you don't need to be writing Ogre plugins.

Plugins (and DLLs) are an entirely orthogonal concept to that of component-based game object systems. Generally if you don't know what parts of your game should be in a plugin or DLL, you don't need to put anything in a plugin or DLL -- you'll just create extra work for yourself, to no real advantage.

> Most of what I read, people recommend putting wrappers for third party libraries into Plugins/DLLs so I am assuming I would want to have one for my Physics (Bullet) System, Audio (OpenAL) System, Input (OIS) System, and so on.

Some people certainly do organize different subsytems, such as physics and rendering, into distinct DLLs. There's no reason you have to do this, though, and as above it just creates extra complexity. You don't have a reason to be doing so at this point in your project, it sounds like, so I wouldn't worry about it. Generally you want to factor subsystems out into DLLs when you expect them to be versioned independant, shared by multiple projects, or swapped out for alternative implementations. All of those are the domain of very moderately complex projects.

> In that case, should I basically just strip the Managers out of my project, and move them to a Plugin/DLL? I am still quite confused on how I will actually go about implementing them into Components once they are moved, but I guess that will come with time.

Just because "other people" do it doesn't mean it's a good idea. If you don't have a reason to factor things out into DLLs, don't.

As for components, I don't think you've fully understand the concept if you are thinking your are going to turn your "manager" objects into "component" objects. Components -- in this context -- are generally very small, reusable packages of data and/or functionality that can be aggregated together (implicitly or explicitly) to form a logical "game object." A component may serve as a connection point between a game object and an unrelated subsystem, such as the renderer, but the renderer itself is not a component and doesn't usually know about components.

Be wary of falling into the trap of assuming that *everything* is a component or in some way is a direct participant in the component object system in such an approach -- that's not a good way to do it.
> 4 votes

---
Tags: architecture, component-based, ogre
---


# Question
Title: Power, achievement and affiliation games for psychology research project
For a psychology research project we're looking for **short** (ca. 5 minute) **single-player games** to observe people's basic motivation. We would like to ask people to list games that provide the closest possible (even if not perfect) fit to each description. We need 2-3 promising candidates for each of the following 3 categories.

We would be happy with anything we can use, build on, mod, change slightly etc. to fit our purposes.

### A) Game that taps into affiliation

Affiliation involves being emotionally close to others and establishing new relationships. The game should revolve around meeting other characters. I.e. through simple means (clicking certain actions) one can explore possibilities to meet friends. Requests to establish relationships should be accepted in most cases, because the player is well-liked. This liking not related to status or performance, but to the warm fuzzy feeling of friendliness. When getting to know each other, many commonalities between player and character emerge and are happily acknowledged.

### B) Game that taps into achievement

Achievement involves mastering difficult goals. In achievement games you would solve several quests by using some ability (speed, spatial thinking, strategy use). It should adapt to the player's ability, so that it is always possible to solve 60-70% of the quests. Player's should be able to improve their abilities and results with some training. Results should always be related to the individual performance, so there is no high score ranking with others or some such.The goal of this game should simply be to remain focused on a task of moderate difficulty, trying to become better at it.

### C) Game that taps into power

Power involves obtaining social status and influencing other people. A power game would involve influencing characters and yielding reactions. It should have a low difficulty and work without points (kind of like a cheat mode maybe). In other words: Influencing other people should be easy, not dependent on achievement or liking. For example, the ability to change the lives of others could be due to insurmountable and unquestionable status differences between the person playing (e.g., a deity, a biologist) and the characters of the game (sticking to the example: mortals, ants).

Now, we hope to find resources we can re-use for our games. We don't have the ambition to create new games and many games already suit our needs. We only need the game to have at least 10 events relevant to the motive and to log these events (so we can align it with the reactions of our participants). If we can change it to do that, that'd be cool too.

Probably many quite simple games have been lost in the drawers of computer science students who made them as finger exercises and homework. We would only use these games in our research setting, so there is no commercial interest involved.

Many thanks in advance and best wishes from the whole lab!

---

we edited this in response to some comments

# Answer
a) The Sims, FaceBook? (I know it's silly, but based on the stated requirements, I think facebook fits the bill :-P )
b) EA Skate (again, based on stated requirements, I think this fits. The game is very focused on the individual skills of the player)
c) Black & White, SimAnt
> 3 votes

# Answer
For point (B) you can give a try with the game called "achievement unlocked"
http://www.freewebarcade.com/game/achievement-unlocked/
This game was supposed to be a joke about people just chasing achievements in games
it rewards you about quite everything (like just starting the game ^^)
But in fact it appears to be an addictive and rewarding memory and skill game
the achievement concept can't be more isolated than in this game !

Let me think about other points ...

Point (A) maybe you should try to steal the core mechanic of Pikmin series
http://en.wikipedia.org/wiki/Pikmin
"meeting other characters through simple means" and do things you should'nt be able to do alone.. this is all the game is about

Point (C)
I guess pikmin could also work here
i'm also thinking about
> 1 votes

# Answer
There are lots of choices to be made in the Mass Effect series, in fact every time there is a choice to be made there are options for doing the nice thing or the mean thing (and several more)... To lie or not to lie ect... The whole game is setup for kinda what you want really. Though the games are hours long every few mins there is another choice to be made and you have to decide what kind of person you want to be.

Its an RPG so theres plenty of achievement. And lots of power issues going into the story as well.
> 0 votes

---
Tags: game-design, open-source
---


title: Understanding .obj file

text:
# Question
Title: Understanding .obj file
I downloaded a 3d model of a car. By judging by the skins and images available model treats wheels and car body as separate nodes. I want to access its child nodes (wheels) to specify animation.

But I don't know the names of its child nodes. Is it possible to figure out names of its child nodes by looking at the file content. I have a obj file of the 3D model. I am using JMonkey 2.

**EDIT**
here is the link thefree3dmodels.

Thank you in advance

# Answer
According to the obj file specification it should be a string after the 'g' command, but from my experiences each obj exporter handles those things specifically.

It might help to add link to obj file in your first post.

**EDIT**

According to the model file, those wheels are groups with numbers 13, 14, 24, 25 Proof:

So those faces (and according vertexes, normals and textures) after line `g part 013` to the next line with `g` command is the mesh of the wheel and so on..

I'm not using JMonkey so I don't precisely know how to rotate those parts, but you could cut the car mesh into two files (wheels and rest) and then it should be easy to animate..
> 2 votes

---
Tags: 3d-meshes, file-format, file, jmonkeyengine, obj
---


# Question
Title: What maths should I learn for game programming, and what aspect of programming does it relate to?
> **Possible Duplicate:**
> What math should all game programmers know?

Obviously a good knowledge of maths is essential for good programming, my maths isn’t the best ( I didn’t pay attention in school all those years ago) so, in order to get one step closer to being the best I need some advice. What maths should I learn for specific areas of game programming? If someone could outline some subjects and say one or two words about what areas of game programming they would be used in I’d greatly appreciate it. I’m working through the Khan academy programme at the moment, and I’m just getting into algebra now.

# Answer
Learn the math as you need it. That's how I did, and it will "save you time". The math needed depends a lot on the game you are making (whether or not it's 2D or 3D, whether or not it has advanced physics, etc etc).
> 1 votes

---
Tags: collision-detection, mathematics, physics, graphics-programming
---


title: XNA ignoring the Z-coordinate?

text:
# Question
Title: XNA ignoring the Z-coordinate?
XNA seems to be ignoring my Z coordinate. There is no form of Z-culling at all it seems. How come? I am doing an orthographic projection, and clearing the depth stencil buffer for every draw-call.

My elements rendered are quads with textures, through instancing. These elements have 1 difference in the Z-coordinate in order to eachother, based on theri Z-index.

# Answer
> 4 votes
What have you set `GraphicsDevice.DepthStencilState` to? It should be `DepthStencilState.Default` to both read and write the depth buffer.

Are the differences in the Z-coordinate within the available precision of the Z-buffer? Are you getting Z-fighting? Are your near and far planes too far apart? (The further apart they are, the less precision you have.)

Do your textures make use of transparency? In that case you must either use alpha-testing (to skip transparent pixels) or you must Z-sort your objects and not use the Z-buffer. You can't use the Z-buffer for transparent objects.

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


# Question
Title: Tips for writing 3D Collision detection with opengl
I would like to any tips/articles/tutorials on how to write collision detection using OpenGL and C++ in 3D mainly just simple box collisions etc but also if there are any advanced resources that would be great to. i also don't wont to use any external library\`s if possible.

thanks

# Answer
> 3 votes
There will be huge amounts of resources out there, I dont know how much you know about current collision techniques, but a good idea if you're not familar with them could be to download Unity3D and play around with the buit-in physics engine (PhysX).

Box collisions are generally done using AABB's (Axis-Aligned Bounding Boxes), Sphere collisions are faster but obviously can't give you as good a representation for a box for example. Capsule colliders are elongated spheres and are very useful for characters and such.

You should also look for details on Terrain/BSP collision detection depending on what your needs are.

Good simple tutorial for AABB's

Here are a few things I googled (but may not be pertinent)...

http://www.gamasutra.com/view/feature/3383/simple\_intersection\_tests\_for\_games.php

Bounding Sphere Collision

http://www.essentialmath.com/CollisionDetection.pps

# Answer
> 1 votes
You could also look into various Open Source Game engines, and see how they handle collision, like for example panda3d.
You might also take a peek into sources of physics engines like ODE or Bullet

---
Tags: opengl, c++, collision-detection
---


# Question
Title: Success checks for client-side javascript mini-game embedded within a server-side browser game
**Disclaimer:** I know that client-side is always to be held with suspicion, but I'm trying to conceive of a way to verify the success or failure of javascript-based mini-games.

## Mini-games to add fun to client-side game

Here is an example scenario:

I implement a javascript-dependent picture-sliding game for various pictures.
You know the type:

So that would be a javascript game that would be served from my website.

## How to check success

I then want to set up a verification scheme to verify that the game has been completed, the browser would ping the website with a verification code or scheme to say "hey, I'm done, and the javascript mini-game is complete".

There are two ways that I can think of to make the verification work.

1. One is a "replay" scheme, e.g. each of the moves that the user does would be concatenated and sent to the server, which would have a system for verifying that the end result was indeed a valid solved state.
2. The other is a "summary" verification code, for example if each of the numbers is assigned a random letter client-side, the final sliding puzzle state would result in a word-code like asdfaseasewadsfwef when read from left to right, top to bottom, which can be sent to the server upon completion to receive a pass/fail grade of success. Obviously that isn't checking the intermediary steps, just the final result, but it'd probably be a lot faster and less resource-intensive, and would probably prevent a bit more abuse than just a GET request with a "go" parameter.

I don't have a huge, high bar for 100% secure communication in this case because I just want to add fun, and give some minor/non-overwhelming benefits from the mini-games, not build a fort-knox system. And if someone is smart enough to hack up a solution to the mini-games to automate them, I won't be excessively broken up about it.

## Techniques?

So with that in mind, are these two approaches valid? Are there other approaches to try with this? Any examples in the wild that I could learn from?

# Answer
**new answer**

(I thought of a better approach than what I wrote in the first place, but I'm leaving the original answer for reference)

Instead of having the client tell the server when the puzzle is completed, do it the other way around (ie. the server tells the client when the puzzle is completed). That way the client simply tells the server what move was made every time the player makes a move, and then the server can tell the client when the puzzle is complete in the response to the request from the client.

This way you get the security of option 1 without the bother of writing code to playback a series of moves.

---

**old answer**

Personally I would go with option 2 because you don't need this to be 100% secure. That is definitely a lot easier.

However, are you sure you don't care about cheating? Whether or not cheating on the mini-game matters depends on the reward for successfully completing the mini-game. If successfully completing the mini-game has any affect at all on other players, then I would consider cheating pretty important and go with option 1.

And note that "any affect" can be very subtle. Let's say that completing the mini-game just earns access to a new level for that one player. In that case, I wouldn't really care if they passed the mini-game by cheating. If however the mini-game earned them some visible trophy (eg. a badge on their profile) that other players can see then I would want to protect against cheating. And if the mini-game earned them a special weapon then I would *definitely* want to protect against cheating.
> 3 votes

# Answer
Recording all the player moves and sending them to the server, is a good choice.

If you wanted more cheat protection, you could even have a key that is generated each move, using a seeded random number generator, using the the time in milliseconds for each key. Verify the moves and verify that the moves were created validly.

This will prevent people from packet sniffing and trying to spoof the moves with a solver program.
> 2 votes

---
Tags: browser-based-games, security
---


title: Angle of Reflection

text:
# Question
Title: Angle of Reflection
I have this "Breakeout style" game.

I have a cannon at the center, blocks around the cannon and pads around the blocks. This is how the game looks like:

I've managed to get the collision per pixel and my ball "*reflects*" on contact with the blocks with the following math:

```
Ball.Direction = 2 * (Block.Direction - Ball.Direction) + 180;

```

Where the blue line is the ball direction, and the black line (base line) is the block surface.

**Direction** is a angle expressed in radian (that can be convert to degrees, of course).
The ball is moved by:

```
// Event.ENTER_FRAME
x += Math.sin(Direction) * Velocity;
y -= Math.cos(Direction) * Velocity;

```

So far, so good.

My problem comes now, with the pads (the 3 dark and large blocks around the small colored blocks).

As they turn around, the surface angle changes.
More than that, the ball should hit the sides too, so, how can I measure the direction of the hit and the new direction of movement of the ball?

*ps*: If needed, I can supply code and a playable swf.

---

# Edit

Ok, the problem with angles was solved with **Vectors**, but I still have the problem with sides and back collision.

I'll open another question for that and link it here.

# Answer
I'm not sure if I understood your problem correctly, but I assumed that what you want to do is find the resultant direction of you ball after a collision.

Here's a quick drawing on my white board that shows a possible solution for that:

The green arrows represent the ball's velocity (as a vector), the blue blocks represent your large black blocks and the red arrow is the resultant vector.

On the first case, the blue block has an inclination of 30 degrees. One of the way to fix the collision problem is to bring everything back on the horizontal axis. What you need to do is **rotate everything** by 30 degrees (the inclination of the block) (you can use matrices for that).

Then, you **check where the collision was from**. If the collision was horizontal, **reverse** the x component of the velocity. If it was vertical (like in this case), the y component (`ball.Velocity.Y = -ball.Velocity.Y`). This will also make the ball act correctly when it hits corners (it will reverse both components). After that, you just have to **rotate back** to the real situation (which is not on the drawing).

On the second case, it's the same thing, except that the ball's velocity is not perpendicular to the block. You rotate by 70 degrees, check where the collision was from, and reverse the appropriate components. After, you rotate back to your real situation.

Note: I noticed that you're using an angle to represent the direction instead of a vector. You could just create a vector for these calculations or keep the same general idea but working with angles.

This is certainly not the best way to go and I'm sure you can just calculate it in some way but I think it's a possible solution to your problem.
> 8 votes

---
Tags: 2d, mathematics, physics, actionscript-3
---