title: Data-driven animations

text:
# Question
Title: Data-driven animations
Say you are using C/SDL for a 2D game project. It's often the case that people use a structure to represent a frame in an animation. The struct consists of an image and how much time the frame is supposed to be visible. Is this data sufficient to represent somewhat complex animation? Is it a good idea to separate animation management code and animation data? Can somebody provide a link to animations tutorials that store animations in a file and retrieve them when needed. I read this in a book (AI game programming wisdom) but would like to see a real implementation.

# Answer
> 4 votes
> Is this data sufficient to represent somewhat complex animation?

Yes. When you get down to it, everything on your computer is just data.

> Is it a good idea to separate animation management code and animation data?

Absolutely.

> Can somebody provide a link to animations tutorials that store animations in a file and retrieve them when needed.

I develop a pair of projects for animating sprites in a data-driven way. There's a sprite maker (not recommended), and a sprite library for XNA that I think works quite well. Here's a copy of some of the documentation. The high-level concept is quite portable:

* A `Sprite` is the collection of Sequences that represent a `Game Element`
* A `Game Element` is a visual element in the game-world
* A `Sequence` is a collection of ordered `Frames`
* A `Frame` is a rectangular section of an image

That is to say that menu items, HUDs, buttons, text, loading screens, all of that is not a `Sprite` because they do not exist in the game-world.

Also, each `Sequence` has a unique combination of `Set`, `Animation`, and `Rotation` where:

* A `Set` indicates the set of the sprite to use. This can be used for a second, complete set of Sequences for the sprite. Examples are: (full health, half health, and almost dead) or (sword, vs spear).
* An `Animation` represents an action that the sprite is doing. Examples are: Idle, Walking, and Jumping
* An `Orientation` represents the direction the sprite is facing. Examples are: (left and right) or (0, 45, 90, 135, 180, 225, 270, and 315 degrees)

Any of the above can be left as "Default" if they aren't useful for your application. Every frame can be accessed by using a 4-dimensional array like so:

```
frame[set][animation][orientation][frame#]

```

Where the `frame#` indicates the progress through the sequence. When the Animation changes, the Frame counter restarts at 0. When the Set or Orientation changes, the Animation and Frame counters do not change, the current animation just continues in the new set or orientation. Each Animation indicates which Animation should follow, once completed. For a looping animation, the animation will refer to itself. For a ping-pong animation, there will be a second animation that uses the same set of frames, only in reverse. And for animations continuing on to greater things, they point elsewhere. Whenever an animation completes, either a flag will be set to indicate this, or an event will get fired to allow the game to take any required actions (like start moving after standing up).

This concept can work well for frame-based animations, but will require some more thought to be functional for skeleton animations.

My SpriteLib project consumes XML that looks something like this:

```
<sequence set="Axe" animation="been hit" orientation="N">
    <frame image="Vlad.png">
        <anchor x="0" y="0" />
        <rectangle x="0" y="0" w="96" h="96" />
    </frame>
    <frame image="Vlad.png">
        <anchor x="0" y="0" />
        <rectangle x="0" y="128" w="96" h="96" />
    </frame>
</sequence>

```

And splits the SpriteDefinition from the SpriteAnimator because you can have multiple sprite animators working off the same sprite definition.

This is just one way to think about 2D animations, but hopefully it will give you a place to start.

---
Tags: animation, sdl, c
---


title: Do 3d assets cost a lot more than 2d?

text:
# Question
Title: Do 3d assets cost a lot more than 2d?
I'm planning to create a game on my own and will most likely hire an artist in the future. I just want to know if making a game in 2d will a lot cheaper than making it on 3d?

Here's my plan:

If it will be a 2d game.. I'll probably make a platform game. More like a Braid level of graphics.

If it will be a 3d game.. Closest of graphics I'll ask for will be far cry 1 or if possible oblivion.

So any thoughts? I'm funding all of it on my own. It will be my first game but will use maybe an engine around if it will be a 3d game. If 2d, I have my own engine lying around here.

Thank you, Balls

# Answer
To answer your question, here are some factor of assets cost, as a factor of time, skill and quality of the resulting art.

To make sense, shall we quantify that we are talking about a single asset. A game character.

The pricing will differ greatly, not between 3d & 2d, it will differ between professional experienced artists and skilful amateurs. It will also differ if you decide to use outsourcing.

Now, lets look at 2D vs. 3D, again, the cost will differ a lot based on the amount of animation the character requires, more animation = more work. That being said, it is generally less time consuming to animate in 3d because of advanced software that offers tools like bones. When animating a 2d character, the artist has to in most cases(unless using cut-out style rotating limbs) render each frame of animation by hand, that is a very time consuming process. Generally per character, it is nearly completely obvious from a technical perspective that building one 3d character with basic animations, is more expansive than one 2d character in the same 'league' of quality. Why is that?

Well, when building a 3d character, you need to construct a model, create a uv-map, paint a texture, rig the bones and then animate it. Since it is 3d, it has to look good from every angle, so a lot more thought and work has to be put into examining the model from various angles while animating and constructing it. Also, because of the technical aspects of UV-mapping and rigging - bones, certain software related issues could rear their ugly head and the artist will have to face these technical issues.

You can normally only see 2d characters from one angle, so that is worked out, there is no use of advance software need to create classic animation. That said, animating something like King Of Fighters takes great mastery, knowledge and dedication.

So the short answer is yes, 3d is more pricey in terms of work hours. high level 2d animation is also very pricy. The previous two comments are less prevalent than the choice between outsourcing vs. working with someone in the same office and the choice between taking on someone who has proven experience vs. a skilled amateur. The most important variable is the scale of the project. Also, remember that if you take a 3d-modeler you would probably have to hire a level designer as well, cause a professional character modeler might is not very likely interested to be involved at all in level design. A 2d artist that can design characters well is likely a reliable source for background art too.

I suggest you ask several artists and compare their proposals.

Good luck.
> 8 votes

# Answer
**In context you described, 3D assets do cost a lot more then 2D assets**, because you need more assets for a 3D RPG game then you need for a 2D platform game.

I'm a big fan of 2D graphics, as what artist creates is what a player sees. It's much harder to create a 3D game with contrast and beauty on similar level to 2D games. That's why creating a 2D-like game in 3D technology is more expensive, but not always.

I'm creating a 2,5 D game, where camera is in fixed position above action (satellite-like view, same as in GTA 1 & 2). I found an artist that made character vector animations for a flash strategy game in a similar view setup. The price per sprite-sheet was very high. Later, when I decided that I need a different feel (not pixelart, not vector, but 3D with lights and shadows) I managed to find a talented 3D artist, and his animations were of better quality, and much cheaper! The reason is number of animations I requested.

**When buying 2D assets, you pay for:**

* design
* every frame of animation drawn

**When buying 3D assets, you pay for:**

* design
* model (mesh, or however 3D professionals call it)
* rig (skeleton, or again, however pr0s name it)
* animations

The thing is, that price of an animation isn't high; if you have a lot of them, cost of everything else becomes less significant, and you can even afford motion capture for similar price as 2D graphics of worse quality. True story.
> 5 votes

# Answer
There is no connection between the amount of money required to develop something and the "number of dimensions used", so your question can't be answered and it's only misleading because you are not even focusing on the assets themselves but only on the money.

There is also no connection between how much you will invest and how much you can make, there are games that are reasonably cheap but very successful and viceversa.
> 2 votes

# Answer
3D assets rely on 2D assets. You texture 3D models with 2D textures. 3D mesh is what defines the shape in 3D, 2D textures are what define the color of the 3d objects faces.

3D will usually cost more than 2D, but it depends on the quality of the 3D asset. You can color 3D faces without referencing a 2D texture from an image, but this doesn't really look good. 3D also adds another dimension to your game/application logic, so if you need to to vector math you're now not only calculating X and Y, but also Z.

I feel like in order to have successful 3D assets you need quality 2D assets as well. A UV-map is just an image that is mapped to the 3D model.

You should also consider, 2D can be processed to appear 3D. You can use normal or bump mapping to accomplish this. Example, this is done using 2D assets assisted by a normal map which depicts how the light should behave over a texture.
> 0 votes

---
Tags: 2d, 3d
---


# Question
Title: Is it worth planning before jumping into the code?
I always thought that planning is important for a game, but I don't know at which point. Some are telling me to code instead of planning, but I feel like it's still important because when you will be in the code, you will know what to do next more easily. I am currently working on a game that will have lots of content, so I decided to start a design document, introducing those contents, it and at a side-level, I am doing proofs of concept to check if it can be done. Parts of each proof of concept then could be used later in the real game.

I am working alone on this project. Is it worth planning before jumping into the code? I'm still interested to know what others have to say about this because I still get some poeple saying I should code instead of thinking. What's your opinion on this?

# Answer
> 36 votes
You said two smart things in your question:

1. "code instead of thinking" - there's a whole philosophy describing this: http://gettingreal.37signals.com/toc.php
2. "proofs of concept to check if it can be done" - I've seen and had many ideas that turned to be impossible or extremely hard to make when they were almost finished. Sometimes you just can't predict it, because it's your programming environment (language, libraries, hardware performance) limiting you.

That's why I say:

* design, but don't make a huge design-doc if you're not looking for collaborators or investors, unless it's fun to you and you take it as a break from programming;
* always have in mind what you want to achieve; every module should have a designed input and output; that way you can easily test the module, and have no feeling of wandering in the fog;
* remember that you design most of the time anyway, as typing code takes only about 5% of your time (at least typing the final code);
* programming is not a theoretical science, instead of checking if something will work on a piece of paper, you can just code it and try; final product is mostly about making user input foolproof, GUI looking nice and dealing with special cases - a dirty test of an idea can be made straightaway;
* create a todo list if you're afraid of forgetting your ideas
* talk with your friends about your ideas, as they will be less enthusiastic and may have more experience in a field; once I had an idea of keeping unit parameters (in a strategical game) secret, but my friend told me it's a bad idea, as he played a game like this and it was a terrible user experience.

# Answer
> 5 votes
Yes, but **only a bit**.

For game programming, especially gameplay programming, it's essential to have a good **use case** before writing any code. E.g. what is the player supposed to do, where is he supposed to go and how, how does he interacts with the world, etc. This can be a storyboard sketched on paper, or come out from a discussion with a peer... This is part of **game design**, and it'll be foolish to start coding without even a rough idea of how the game is supposed to be played.

But games have to be created **iteratively**. You can't create a huge spec for your game and hope it's going to be fun to play. You need regular playtesting to find out what works, and what doesn't, and keep iterating. The quickest the executable runs, the quickest the game design can be tested, the best the game gets at the end. So it's always better to start coding ASAP, from a very non-formal game design, see what gets out, and keep going.

One thing for sure, as you're coding alone, you don't need any fancy software design document or methodology, the source code is the design.

# Answer
> 3 votes
Some say you should code instead of thinking? Well to code you need to know what you want to create, to know what you want to create you first need to think what you want to have, ergo you need to think before you code ;).

And seriously, you probably don't need a detailed plan right at the beginning, but having an outline and/or milestones is always benefical - also for your atitude, when you cross out things as done, you will be more encouraged to do more work.

# Answer
> 3 votes
Both coding and planning is needed. First plan, then code, but don't plan everything at once. Plan a core, code it, updating your plan as needed, then plan features that add up to playability, graphics, sounds, sprites etc etc, this will make the game you are creating look better and overall feel better. You can run such a cycle more than once, obviously, and I advise you making decisions that will support upscaling should the need arise.

# Answer
> 2 votes
You have to know where you are going before writing code and writing/drawing can be a good way to materialize what you want to achieve. I say *drawing* because drawing diagrams, sketches etc. may also help you a lot. You don't need to make a wonderful document made with Word or anything, just take a pencil and a piece of paper (lot of pieces of paper?) and draw, write everything you may think about.

To me, it's a good practice to use pencil and papers, it helps materializing your ideas and also set where you want to go to prevent going anywhere, fix your goal. It works for everything that needs reflexion. And it's obvious in a lot of domains to write things down before doing the actual work.

# Answer
> 1 votes
Do whatever works for you. Personally, I plan out things to a small extent, but don't have design documents are extremely detailed plans before I start coding anything. Do whatever is the most productive for you, especially since you're working alone.

# Answer
> 1 votes
(I assume the question is made from the code-design/architecture point of view, not game-design one, though the answer at least to some degree applies to both.)

As already said, you need both, and you need to balance it. Both overdesigning and underdesigning your code flow/structure can cause problems. It is hard to say what the right balance is, but generally I find that I need to have at least a vague idea how the rest of the code will join up with what I'm programming at the moment, and think about possible issues, otherwise I tend to "code myself into dead end" - get into a situation where I realize "okay, now thanks to how I solved this problem, I created a new problem which rendered my whole previous solution (or even more, in worst cases) futile".

Generally, in my opinion, you can roughly judge whether you have the right balance by thinking about "what if" scenarios as in "what if I later (when everything is fully implemented in the similar paradigm as I'm using now) find out that part A needs to work slightly differently which will mean I have to completely rework part B that connects to it accomodate the changes?". If architectural change in one part doesn't require you to change more than one or two other parts, and the changes do not cascade (meaning that in turn you have to change also next parts connecting to the part B, and then parts connecting to them, etc.), the code is compartmentalized in a relatively good way.

But really, this is something you'll get a feel for after gaining some experience. This is partially why everyone gives the beginning gamedevs advice to first code something known and easy (Breakout/Tetris/Snake) and to do it completely, with all the menus, sounds, effects, everything to make it fully finished game - it is better to screw up smaller project, and doing it (whether in a good or bad way) will exactly help you to get a feel how far effects of various architectural decisions span.

---
Tags: game-design
---


# Question
Title: When dealing with a static game board, what are some methods to make it more interesting?
Let's say you have a game board that you look at. It does not move but there is some action going on. For example Chess, Checkers, Solitaire. The game I'm working on is not one of these but it's a good reference.

What are some methods you can apply to the game or the design that increases the appeal of the game to the user?

Of course you can make it prettier but what are some other methods you can use?

For example: Visual cues, game design changes, user interface arrangement, etc.

# Answer
As a player, one thing that makes some games stand apart from others is getting the movement animations right. They must feel natural and not forced or be distracting. A few examples:

* In checkers, the piece should not move in a direct line from square to square. Instead, make it move as if the player would move it, in an arc. But too big an arc becomes distracting.
* The way gems fall in Bejeweled sets it apart from many of its clones.

I don't really have any tips on exactly how to achieve this, though. A lot of it must be attention to detail combined with trial and error.
> 11 votes

# Answer
Don't underestimate the power of having good sound effects. Combined with good animations, the sound effects can provide a bit of realism to your game. And don't simply use the same ones over and over -- for each sound that you have in the game, you should have a few different versions that you randomly pick for each one. If you can adjust the volume and panning based on where the sound is coming from, even better.
> 10 votes

# Answer
One extra thing to bear in mind:

Please give the poor player the choice about what level of "interesting" they want. I can't count the number of these sort of games I've given up on because they made (to me) annoying noises and wasted time with unnecessary (again to me) animations. The visuals did attract me to the game in the first place, but they can become tiresome. How many people turn off the Windows sounds as soon as they get a new PC?

Part of the appeal of this sort of game on the computer is that they are (or should be) quick and easy to play. You might only have 5 minutes to spare and need a distraction, you don't want to be waiting for half that time for the game to load or animate the setting up of the board.
> 7 votes

# Answer
There are tons of interesting mechanics you can integrate into a static board.

For a positional-based game like Chess or Checkers, you could add terrain or interesting shapes. Note for example how much more interesting the Stratego board is because it has those two lakes in the middle, creating three major choke points.

For a territory-control game like Risk, structuring the territories to form interesting shapes or clusters and unique landmarks on the board is more interesting than something purely symmetric. In Risk, both South America and Australia are easy to defend but give only a minor bonus, making them natural areas of early-game contention. In Pandemic, South America is an interesting region because it has the only dead-end location that's hard to get to, while Eurasia is also interesting because it has a lot of interconnected cities that lend themselves to major outbreak problems.

For a roll-and-move game like Monopoly or Life, make the spaces you land on interesting by having them give the players meaningful choices. This is one of the major reasons why the board game Talisman is marginally more palatable than Chutes & Ladders.

You can also, of course, include mechanics that change the nature of the board over time. Maybe you have some tokens that get placed on the board that make certain spaces temporarily (or permanently) impassable, or adding some additional effect to visiting those spaces. That keeps the board dynamic, even if the original starting game state is always the same.
> 4 votes

# Answer
The strength of Chess is it's simplicity. Sometimes a game is better when you keep it simple. Recently I played Neptune's Pride - I love how simple it is and yet how much you need to think about it sometimes (a fleet of 12 ships will approach your star with currently 3 ships in 10 hours. You can't reach the star sooner with your reinforcements, however you can buy enough industry structures to produce enough ships - but how many and isn't it more affordable to leave the star and buy industry on cheaper stars? I actually was analyzing the scenario for 30 minutes!). That said, if you're making a clone of some already existing board game, it is understandable you want to add something new to it.

* In Chess it could be various variants, like my favorite, Baroque Chess.
* A modding possibility is always nice. You may avoid losing players by only letting them turn some "feature" or mechanic off. I don't like going back to start in Mensch ärgere dich nicht, I want to turn it off!
* Humor! It's easy to come up with an idea of animated chess pieces, but what about speech bubbles with some situational jokes?
* Social features: a chat, posting results (achievements) on Facebook, getting automatic recommendations from your friends (after enemy pawn moving on e5, your friend Markus moved his pawn on e4, and Ioanna moved a knight on f3) etc.
> 3 votes

# Answer
One thing that many strategy games do is to provide a series of informational overlays that you can filter on top of a static board. Playing a game like Europa Universalis 3, it has a wide variety of filters that really let you delve into the deeper structure of the game. You have your simple "what country owns this province" layer, but you can also have it colored according to economic strength or etc. For a game like chess, you could add an overlay that indicates relative strength of positioning, which could help players learn about setting up mutually reinforcing positions. Since we're talking a video game here you could make some really interesting, user tweakable overlays if you devoted development time to it.

Another interesting idea I saw recently was in a XBLA strategy game called Greed Corp. If you watch a video of it being played, you can see that it takes place on a turn based hex grid similar to any number of board games. But, there's an interesting game design choice that makes it work significantly better in video game form: the board changes as you perform actions. "mining" a square lowers the height of adjacent tiles and by the end of the game the terrain is drastically different from when it started. This isn't really a "static" board, but you can apply a similar concept (such as outlawing certain squares temporarily) to any board game design to make it more dynamic and suited to video game form.
> 2 votes

# Answer
You might try use made skins and create a community for that.

A lot of people like designing stuff for their games. Such as the example of chess or checkers they should be able to draw their own custom board tiles or make their own custom pieces (with that though, if you let the make their own custom pieces be sure to be careful on what your animations are like as they can be easily made to look awkward). (A very good example of this is Spore).

Also, you should really add a community for showing of their custom skins. Their was a racing game (called Forza or something like that) that gave players the ability to paint cars and show them off or sell them on the community market. Even though this isn't a racing community your targeting, almost all communities like to this kind of interaction.

In addition communities can help with multiplayer challenges, leader boards etc. Computers just are not the same as human players. Look at Call of Duty as a good success of multiplayer. I mostly play that game for the multiplayer as well as others too.
> 2 votes

# Answer
Battle chess has always been interesting even if it was played in a static game board.
> 2 votes

# Answer
Aside from fluff. Varying degree of adaptive AI might also make it interesting. Achievements and rewards may also add some perceived value.

Skills like how they are implemented in some mahjong doujin game and puzzle quest might also add some dimension to classic gameplay (just be sure to add the option to turn it off).

Modes of play can also makes thing interesting. I.e. Scenario modes like play with no queen or knight cause the enemy has captured these pieces in chess.
> 2 votes

# Answer
I'm working on a hex-based boardgame-style game and have some things I'd like to incorporate to keep things engaging:

-Dynamic camera. As characters move and interact with each other the displayed view will pan and zoom to frame the action.

-Layered diegetic and non-diegetic audio. -Diegetic (heard by the game characters as well as the players): The electronic/mechanical sounds of the combat simulator the characters are in, the sounds made by the characters as they move and use their powers, anything the characters say to each other as the game proceeds and any calls made by the scorekeeper/referee. -Non-Diegetic (heard only by the players): Audio for unlocked achievements, menu navigation sounds, possibly a subtle sound made by the mouse cursor as it moves around. Announcements and color commentary made by the game announcers, and all the gamey sounds when people are killed, stunned, drop their tokens, score points, etc.

-Things for players to do when it's not their turn. I have actions characters can take in response to the actions of the current player's characters.

All of these things will hopefully contribute to the mood and tone of the game and keep players' attention. Although the game is turn-based, I'm hopeful that the players will remain engaged even in situations where they aren't personally involved in the action.
> 2 votes

# Answer
One example of a game that does this, that it worth looking at, is the card game "Magic: The Gathering – Duels of the Planeswalkers". Particle effects, sound effects, and lots and lots of animation paths for the cards.
> 1 votes

---
Tags: game-design
---


title: Does anyone write games in Delphi?

text:
# Question
Title: Does anyone write games in Delphi?
I am a very seasoned Delphi developer (over 12 years of experience not counting my Turbo Pascal experience) and was wondering does anyone write games in Delphi? I have seen DirectX API wrappers in Delphi that allow you to program against DirectX (even wrote a simple solitaire game with a friend), but haven't seen anything out there that shows me that I should keep up with Delphi. I just hate to walk away from so much knowledge and Object Pascal language, but I am not seeing much as to a reason to keep going with Delphi.

I currently program in C# and thinking about XNA, but it seems to me that the dominating opinion is go C/C++ route with DirectX.

Any other Delphi developers out there struggle with this too?

Thanks, MDV

# Answer
Okay, I hate to say it, but Delphi is effectively dead. I know, I know - it's depressing. Fear not, however: even better languages have evolved that have 99% of the advantages of Delphi, but are *gasp* still (REALLY) supported and enjoying widespread industry adoption. You're not doing your career any favors by sticking with Delphi. I worked with Delphi for about six wonderful years before following Anders over to the dark side.

If you're already playing with C#, you've no doubt noticed the incredible similarities between it and Delphi. Your Delphi experience will help a great deal given the similar object models, exception handling, etc.

The only advantage that Delphi has over C# is that it is compiled to native code. The only other game in town for that these days seems to be C and C++.

I'm having fantastic success with C# and XNA. The performance of managed code these days is very near that of native code. If you want to code for multiple platforms (windows, xbox, ps3, etc), you'll need to stick with c++ because it's the only thing that will build for everything.

If you're sticking with Windows and the Xbox, XNA is a great tool.
> 12 votes

# Answer
Soldat is written entirely in Delphi I think.
> 4 votes

# Answer
The team I worked in developed quite a few games in the past using Delphi and DirectX wrapper called Asphyre. They were all 2D games developed for payslot machines. We even combined Delphi and Flash through ActiveX, which turned up very satisfying.

Asphyre is one of the best (if not the only) DirectX wrapper for Delphi. We used a lot of particles and stuff there, so those were rather eye-pleasing games. Asphyre features 3D technologies too, but we never went beyond 2D cause we didn't need to.

In my opinion, however, Delphi is just way too old and it appears that C# provides the best alternative for it.
> 4 votes

# Answer
Not to dodge the main title of your question, but I can offer some advice in respect to the other aspect (where should you go next, since it seems you've already decided.) C# and XNA are simply an abstraction layer above DirectX. Using C# and XNA will help you decrease time to market, and can reduce some development costs; however, that is at the expence of some performance and control.

C/C++ and raw Direct X is popular because you get maximum performance and control. It really depends on your goals. Personally, I use C# and XNA because its entry level costs are basically zero (especially if you already know C#) and it only costs $99/year to be part of the Creators Club, which is only a requirement if you want to deploy your game to Xbox and or Windows Phone 7. Doing C# and XNA for Windows only is absolutly free, and can produce amazing results. At a minimum, I recommend you check it out before jumping headlong into C++ and raw Direct X.
> 3 votes

# Answer
It's a wonder, but there is a little game in Hungary, with lots of fans, written in delphi, and still new updates are coming out. It's called Stickman Warfare and it's a 3D MMOFPS.
> 2 votes

# Answer
SvEngine. It's an advanced 2D game engine for Windows® PC and use Direct3D® for hardware accelerated rendering. It's robust, fully object oriented, designed for easy use and suitable for making all types of 2D games and other graphic simulations. There is support for surfaces, textures, sprites, audio, streams, archives, configuration files, render targets, swap chains, databases and much more.

**NOTE: It's our own 2D game engine middleware that we develop and support. We will be using it to make all our upcoming projects.**
> 0 votes

---
Tags: directx, platform
---


title: Friction in 2D game

text:
# Question
Title: Friction in 2D game
I'm developing a 2D platformer, although this question could probably apply to just about any 2D type physics; What is the equation for friction? I have sort of a hacky type of friction set up in my game currently, but I'm not satisfied with it because it doesn't account for all forces being applied to my character outside of whatever forces he's generating himself.

# Answer
There's two types of friction, static friction and kinetic friction. Static friction is the friction that needs to be overcome to get something moving from rest. You'll notice when pushing a box across the floor, it can often take more force to get it moving than to keep it moving. Or you'll be applying force and it will jolt forward and you'll have to not push as hard. That jolt forward is the point when static friction is overcome and you're dealing with kinetic friction. Kinetic friction is almost always (always?) less then static friction.

Either way, friction is a force just like acceleration. It's calculated based on the normal force of the objects and coefficent of friction (µ).

This free body diagram shows a few forces.

* Green: The force of friction.
* Purple: The force being applied to move the object
* Blue: Gravity
* Red: The normal force, will equal gravity if the object is not sinking into the surface below.

So when the force of friction and the force being applied are equal, the object will not accelerate. So if it's stopped, it's not going anywhere and if it's moving it'll continue to move at that speed.

So you're going to want to collect some information to simulate friction.

* The types of materials, this is needed to get the coefficent of friction (µ).
* The normal force

Then you can simply calculate the force of friction with the following:

friction = µ • normalForce

When you're summing up your forces you include this force. If you have no other accelerations, then your friction is going to be the only force, and will slow your object down.
> 12 votes

---
Tags: xna, 2d, xna-4.0, physics
---


# Question
Title: How do I generate a smooth random horizontal 2D tunnel?
I'd like to create a *smoother version* of the navigable and quite natural-looking random tunnel found in this classic helicopter game.

It should ideally be...

* **infinite**, so more can be generated as the player progresses;
* **parametrised**, allowing control of its thickness over time;
* **made of smooth curves**, not rectangles as in the above game;
* **precomputable**, as knowing its bounds in advance allows collision detection for e.g. positioning powerups inside the tunnel.

I'm looking for a generic method I could implement myself. Further parameters and optimizations are welcome.

Asking here was suggested on StackOverflow. I think this fits in both places, as it's as much about the algorithm as about gamedev.

# Answer
Some intuition:

Step1: Randomize points-each time taking a step forward on the x-axis

Step2: Imagine segments(lines) between these points, add new points in the middle of each one

This is how it looks now without the segments:

Step3: Draw bezier from red point to red point, using the original point as control.

Step 4:

1. Randomize new control point
2. Imaging new segment
3. calculate new red point
4. Draw Bezier from previously last red point to the new one
5. Repeat

Answer:

You can use Beziers here to create a smooth continuous curve ... first randomize a continuous list of points:

```
//screen size 640 x 480
safeViewDistance = 700; //How far can the player see
playerX;
averageDist = 100 // averageDistanceBet
lastX = - 2.5 * averageDist //the further point in the tunnel
tunnelHeight = 300 // space between ceiling to floor

while(lastX < playerX + safeViewDistance)
{
    lastX += (0.5 + Math.random()) * averageDist;
    points.push(new Point(lastX, Math.random());
}

//to draw the ceiling and floor use bezier:
lastDrawnPoint = 1;
function drawPoints(yOffset, yCoeff)
{
    while(lastDrawnPoint < points.length)
    {
        i = lastDrawnPoint;
        startPoint = average(points[i-1], points[i]);
        controlPoint = points[i];
        endPoint = average(points[i],points[i+1]);

        startPoint.y *= yCoeff;
        startPoint.y += yOffset;
        /repeat for control and end

        drawBezier(startPoint, controlPoint, endPoint);
    }
}

```

Drawing a Bezier approximation can be handled by iterating with n = 100 on the function and drawing lines:

```
q(t) = (1-t)*((1-t)*start + t*control) + t*((1-t)*control + t*end)

```

By iterating I mean running on 0 \<= k \<= n like this:

```
q(k/n)

```

Here is a sample code for Bezier in AS3 copyrights

```
Raster class
*
*   @author     Didier Brun aka Foxy - www.foxaweb.com
*   @version        1.4
*   @date       2006-01-06
*   @link       http://www.foxaweb.com
*
*   AUTHORS ******************************************************************************
*
*   authorName :    Didier Brun - www.foxaweb.com
*   contribution :  the original class
*   date :          2007-01-07
*
*   authorName :    Drew Cummins - http://blog.generalrelativity.org
*   contribution :  added bezier curves
*   date :          2007-02-13
*
*   authorName :    Thibault Imbert - http://www.bytearray.org
*   contribution :  Raster now extends BitmapData, performance optimizations
*   date :          2009-10-16
*
*   PLEASE CONTRIBUTE ? http://www.bytearray.org/?p=67
*
*   DESCRIPTION **************************************************************************
*
*   Raster is an AS3 Bitmap drawing library. It provide some functions to draw directly
*   into BitmapData instance.
*
*   LICENSE ******************************************************************************
*
*   This class is under RECIPROCAL PUBLIC LICENSE.
*   http://www.opensource.org/licenses/rpl.php
*
*   Please, keep this header and the list of all authors

```

Actual code

```
/**

 * Draws a Quadratic Bezier Curve (equivalent to a DisplayObject's graphics#curveTo)
 *
 * @param x0            x position of first anchor
 * @param y0            y position of first anchor
 * @param x1            x position of control point
 * @param y1            y position of control point
 * @param x2            x position of second anchor
 * @param y2            y position of second anchor
 * @param c             color
     * @param resolution    [optional] determines the accuracy of the curve's length (higher number = greater accuracy = longer process)
     * */
public function quadBezier ( anchorX0:int, anchorY0:int, controlX:int, controlY:int, anchorX1:int, anchorY1:int, c:Number, resolution:int = 3):void
{
    var ox:Number = anchorX0;
        var oy:Number = anchorY0;
        var px:int;
    var py:int;
        var dist:Number = 0;

        var inverse:Number = 1 / resolution;
        var interval:Number;
    var intervalSq:Number;
    var diff:Number;
    var diffSq:Number;

        var i:int = 0;

        while( ++i <= resolution )
        {
            interval = inverse * i;
        intervalSq = interval * interval;
        diff = 1 - interval;
        diffSq = diff * diff;

            px = diffSq * anchorX0 + 2 * interval * diff * controlX + intervalSq * anchorX1;
            py = diffSq * anchorY0 + 2 * interval * diff * controlY + intervalSq * anchorY1;

            dist += Math.sqrt( ( px - ox ) * ( px - ox ) + ( py - oy ) * ( py - oy ) );

            ox = px;
            oy = py;
        }

    //approximates the length of the curve
    var curveLength:int = dist;
    inverse = 1 / curveLength;

        var lastx:int=anchorX0;
        var lasty:int=anchorY0;

    i = -1;
    while( ++i <= curveLength )
    {
        interval = inverse * i;
        intervalSq = interval * interval;
        diff = 1 - interval;
        diffSq = diff * diff;

        px = diffSq * anchorX0 + 2 * interval * diff * controlX + intervalSq * anchorX1;
        py = diffSq * anchorY0 + 2 * interval * diff * controlY + intervalSq * anchorY1;

            line(lastx,lasty,px,py,c);
            //aaLine(lastx, lasty, px, py, c);
            lastx = px;
            lasty = py;
    }
}

```

Once you clean up the code, the result will look like this:
> 13 votes

---
Tags: algorithm, procedural-generation, maps, random
---


title: How long to display each sentence?

text:
# Question
Title: How long to display each sentence?
When creating a sequence where text advances automatically, is there a metric which will allow me to calculate a reasonable duration to display each "sentence"?

My intuition tells me that because of the way we read, the number of words is probably more relevant than the number of characters, but I'm curious what people may have already figured out about this problem.

# Answer
> 8 votes
This sounds like we need a research paper. I believe Dynamic Text beginning on page page 344 should give you solid averages to work off of for however your planning to display your text. Of course you have the issue of wanting to be slower than the average for users who have a below average reading speed.

Personally I believe it would be ideal to start out displaying the text as long as the average person reads and and then have as an option for the user to change the speed. Some thing as simple as "B" to slow it down and "A" to speed it up as some of the older console games had would work.

Unfortunately this is all assuming that the reader is expecting it. I would add the high end of the curve of the average human reaction time 300 milliseconds or so to the display time if its a prompt.

---
Tags: game-design
---


# Question
Title: Problem creating levels using inherited classes/polymorphism
I'm trying to write my level classes by having a base class that each level class inherits from...The base class uses pure virtual functions.

My base class is only going to be used as a vector that'll have the inherited level classes pushed onto it...This is what my code looks like at the moment, I've tried various things and get the same result (segmentation fault).

```
//level.h
class Level
{
  protected:
    Mix_Music *music;
    SDL_Surface *background;
    SDL_Surface *background2;

    vector<Enemy> enemy;

    bool loaded;
    int time;
  public:
    Level();
    virtual ~Level();

    int bgX, bgY;
    int bg2X, bg2Y;
    int width, height;

    virtual void load();
    virtual void unload();

    virtual void update();
    virtual void draw();
};
//level.cpp
Level::Level()
{
  bgX = 0;
  bgY = 0;
  bg2X = 0;
  bg2Y = 0;
  width = 2048;
  height = 480;

  loaded = false;
  time = 0;
}
Level::~Level()
{
}
//virtual functions are empty...

```

I'm not sure exactly what I'm supposed to include in the inherited class structure, but this is what I have at the moment...

```
//level1.h
class Level1: public Level
{
  public:
    Level1();
   ~Level1();

    void load();
    void unload();

    void update();
    void draw();
};
//level1.cpp
Level1::Level1()
{
}
Level1::~Level1()
{
  enemy.clear();

  Mix_FreeMusic(music);
  SDL_FreeSurface(background);
  SDL_FreeSurface(background2);

  music = NULL;
  background = NULL;
  background2 = NULL;

  Mix_CloseAudio();
}

void Level1::load()
{
  music = Mix_LoadMUS("music/song1.xm");
  background = loadImage("image/background.png");
  background2 = loadImage("image/background2.png");

  Mix_OpenAudio(48000, MIX_DEFAULT_FORMAT, 2, 4096);
  Mix_PlayMusic(music, -1);
}
void Level1::unload()
{
}
//functions have level-specific code in them...

```

Right now for testing purposes, I just have the main loop call Level1 level1; and use the functions, but when I run the game I get a segmentation fault. This is the first time I've tried writing inherited classes, so I know I'm doing something wrong, but I can't seem to figure out what exactly.

# Answer
> 3 votes
You're doing it wrong. Making a class for each level? No, levels are **data**, not code. Make a generic `Level` class, and then load `.level` (or whatever) files into it. The files then should just have a list of all the resources that need to be loaded, a list of events/scripts, and so on.

Why? Because then you can make a separate level editor, that creates the `.level` files for you, and you don't even have to touch your game's code (which generates bugs and so on).

Classes are here to group similar behaviors and data (objects) together, creating a new class for each instance of an object is illogical and defies the very purpose of classes.

---
Tags: c++, levels, objects, polymorphism
---


title: How to deal with large open worlds?

text:
# Question
Title: How to deal with large open worlds?
In most games the whole world is small enough to fit into memory, however there are games where this is not the case, how is this archived, how can the game still run fluid even though the world is so big and maybe even dynamic? How does the world change in memory while the player moves?

Examples for this include the TES games (Skyrim, Oblivion, Morrowind), MMORPGs (World of Warcraft), Diablo, Titan Quest, Dwarf Fortress, Far Cry.

# Answer
The way to achieve a seamless world as big as you could fit on the hard drive, or server's hard drive for that matter is more complex.

1.Yes, first you divide the world into tiny pieces you can load quickly.

2.Then, in run-time you divide the loading process into tiny parts that fit in a frame, so that each frame you only spend the limited x% resources you can afford on loading nearby areas while still rendering the world and perfoming the game logic.

2\*. You can also use threads instead of dividing the loading process into chunks, however I found that they could be hard to control and dividing it into chunks offers more optimization.

3.Sometimes the world is randomized, in these cases you may want to save the world slowly back into the hard drive as it is being generated.

\*Having the world load from the server hard drive may be unreasonable considering the world complexity and the bandwidth allotment and costs.
> 2 votes

# Answer
Basically the world gets devided into chunks, and get loaded and unloaded depending on the distance to the player (in the background). When the player enters a area that isn't loaded completly yet a loading screen is displayed.

*In the case of single player games*, such as the "The Elder Scrolls"-Series, the chunks are divided after distance from the player, things in near chunks are calculated in-detail, frequently, the more far away the chunks are the less frequent and the less detailed the calculations become to save processing power. The things in far away land might even only ever updated when the player approaches them, the player won't notice anyway.
Another thing is LOD (Level of Detail), each chunk of the landscape mesh is saved multiple times in different detail levels, for chunks far away only the lowest detail level is kept in memory, for chunks near the highest detail level is used.
For procedurally generated landscapes, like those found in the Diablo games, when loading a chunk it is checked if this chunk was already generated, if yes it is just loaded from the hard disk, if not a new chunk is generated which is then saved on disk.

*In the case of MMORPGs*, such as World of Warcraft, the whole world is calculated and saved on the servers... the invidual clients wouldn't be able to do so. If the server isn't powerful enough alone then the chunks are distributed between multiple servers. The distance can't be used here because the players are everywhere, all chunks need the complete power.
> 1 votes

---
Tags: performance, memory-efficiency
---


# Question
Title: Unreal Engine - Scaleform - How do I capture a button click event?
I'm new to Unreal Development.

In a nutshell, how do I create a button, install it in a basic game, and capture the button click event?

# Answer
> 5 votes
* Send of signals:

We can send messages from flash to UDK with the ActionScript command fscommand( "mycommand" )

For example, we want a button that permit us exit from the game

With ActionScript, we asign the function fscommand("exit") to the click button event

```
btn_exit.addEventListener( "click", this, "btn_exit_click" );

function btn_exit_click():Void
{
    fscommand("exit");
}

```
* Receiving message:

From kismet we can receive the pulsation of the button, for this:

New event -\> GFx Ui -\> fscommand

Inside the properties, we have two that are necessary, Movie and FSCommand

On Movie we'll put the flash movie that we are using ( button with green arrow ) and in FSCommand we write the command that we are waiting for, in that case Exit

* Send of signals:

We can connect the exit to that we want to happen when the signal was sended from Flash.

With this example, we are created a "Console Command"

New Action -\> Misc -\> Console Command

# Answer
> 4 votes
The accepted answer is outdated. FScommands are deprecated and slow.

Try using scaleform CLIK and:

```
event bool WidgetInitialized(name WidgetName, name WidgetPath, GFxObject Widget)
{

    // Determine which widget is being initialized and handle it accordingly
    switch(Widgetname)
    {
        case 'btnStart':
            // Save reference to the label that displays the message to the player
            btnStart = GFxCLIKWidget(Widget);
            btnStart.AddEventListener('CLIK_click', startGame);
            break;

        default:
            // Pass on if not a widget we are looking for
            return Super.WidgetInitialized(Widgetname, WidgetPath, Widget);
    }

    return false;
}

function startGame(EventData data)
{
    // Only on left mouse button
    if(data.mouseIndex == 0)
    {
        ConsoleCommand("open DM-DECK");
    }
}

```

---
Tags: udk, unreal
---


# Question
Title: Polygon count target range for MMO being released in 2 years
What would a realistic poly count target range be for NPC and player models in a 3D MMO that will be released in 2 years? What about poly count target range for the entire camera view (environment, NPC and player meshes)?

I read in some places that one should not aim too low if the game will come out in a couple years because technology is always advancing. If you can give some mesh poly stats on what other current MMOs / MMORPGs are running and future projections, that would be great.

Thank you.

# Answer
> 7 votes
For MMO due to their nature, wide adoption is a must to survive. They need to have a window which enables them to run on mediocre pc. So, no matter how tech progresses forward, MMO should be always the least to take full advantage of it. And poly count doesn't matter too much, if you can cover this up with your art style and/or other visual stuff. For example, the average poly count of WOW characters are 500.

# Answer
> 6 votes
A good reference for a wide public is to check the average computer specs around christmas discounts. Also a good option is to have severall levels of details for your game so that you can adapt your graphic performances according to the computer specs.

# Answer
> 4 votes
Focusing on poly count and other rendering minutae is really putting the cart before the horse. Your question depends entirely on what client engine you're going to use, and so can't be answered.

Onwards to predicting future hardware platforms.

Many projects have been sunk by assuming that hardware speeds will always advance. Look at what happened during the switch we are just now completing from single-core processors to multi-core, raw speed didn't go UP at all and mostly went DOWN on each core...

You must define your target audience, do you want enthusiast gamers only or a broad population? There's a great resource here for platform dominance: the Steam store

My personal best guess is that if you take a 50% mark from Steam and call that your baseline platform then in two years you'll have a very nice customer base that won't alienate too many on the low end.

# Answer
> 2 votes
The performance of a game does not usually get bottlenecked by poly count first. This is one of the reasons that pixel shaders have been gaining speed faster than vertex shaders over the past several years.

To put it somewhat bluntly: If you are asking about how many polygons your models should have, then you should not be working on an MMO.

MMO production has bankrupted large corporations, yet in every game development community (XNA forums, gamedev.net, gamedev.SE,...) there seems to be a weekly newcomer asking about how to fix some widget in the MMO he's making as a one man show.

There actually have been a few successful MMOs that started as one man projects, however they were all created by game developers with a lot of experience.

Studies have shown that players notice and care more about shadows, lighting, and aliasing before they care about poly count. Look at minecraft.

You can get away with very low polygon counts if your lighting effects are excellent. Global illumination approximations, shadow quality, antialiasing post processes, deferred lighting pipelines, should all be a much greater concern than polygon count.

Since your question is about polycount, I'll point out that (new) critters in wow are typically in the range of 50-100 polygons.

Mobs are in the 300-500 polygon range.

CPU speed is typically a bottleneck for most wow players in my experience though, especially in cities where the number individual objects (and therefore the number of draw calls gets large).

# Answer
> 0 votes
I remember reading somewhere that a company (Blizzard?) puts its employees on bleeding edge workstations, with the assumption that by the time the game is released, that level of compute power will have become mainstream.

---
Tags: 3d-meshes, mmo, low-poly
---


title: Vertex fog producing black artifacts

text:
# Question
Title: Vertex fog producing black artifacts
I am rendering a textured model using the XNA BasicEffect. When I enable fog, the model outline is still visible as many small black dots when it should be "in the fog". Why is this happening?

Here is a minimal example showing my problem: (the ship model that this example uses is from the chase camera sample on this site — in case anyone wants to try it out ;))

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Model model;

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

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // TODO: use this.Content to load your game content here
        model = Content.Load<Model>("ship");
        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect be in mesh.Effects)
            {
                be.EnableDefaultLighting();
                be.FogEnabled = true;
                be.FogColor = Color.CornflowerBlue.ToVector3();
                be.FogStart = 10;
                be.FogEnd = 30;
            }
        }
    }

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

        // TODO: Add your drawing code here
        model.Draw(Matrix.Identity * Matrix.CreateScale(0.01f) * Matrix.CreateRotationY(3 * MathHelper.PiOver4),
            Matrix.CreateLookAt(new Vector3(0, 0, 30), Vector3.Zero, Vector3.Up),
            Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 16f/9f, 1, 100));

        base.Draw(gameTime);
    }
}

```

# Answer
Texture contains dark & almost transparent pixels. Fog is internally controlled by alpha to support alpha blending with fog enabled.

You should remove alpha from the texture (or set it to 100% everywhere) if you intend to use the fixed function pipeline. If you have shaders in mesh effects, you can alternatively implement fog differently in those.
> 1 votes

---
Tags: xna, rendering
---


# Question
Title: Need some advice regarding collision detection with the sprite changing its width and height
So I'm messing around with collision detection in my tile-based game and everything works fine and dandy using this method. However, now I am trying to implement sprite sheets so my character can have a walking and jumping animation.

For one, I'd like to to be able to have each frame of variable size, I think. I want collision detection to be accurate and during a jumping animation the sprite's height will be shorter (because of the calves meeting the hamstrings). Again, this also works fine at the moment. I can get the character to animate properly each frame and cycle through animations.

The problems arise when the width and height of the character change. Often times its position will be corrected by the collision detection system and the character will be rubber-banded to random parts of the map or even go outside the map bounds. For some reason with the linked collision detection algorithm, when the width or height of the sprite is changed on the fly, the entire algorithm breaks down.

The solution I found so far is to have a single width and height of the sprite that remains constant, and only adjust the source rectangle for drawing. However, I'm not sure exactly what to set as the sprite's constant bounding box because it varies so much with the different animations.

So now I'm not sure what to do. I'm toying with the idea of pixel-perfect collision detection but I'm not sure if it would really be worth it. Does anyone know how Braid does their collision detection? My game is also a 2D sidescroller and I was quite impressed with how it was handled in that game.

Thanks for reading.

# Answer
> 2 votes
I think you need to approach this issue on a slightly larger scale. As others have pointed out, changing the bounding box in-game at runtime might be quite tricky from the gameplay perspective. What do you want to happen for example when a player jumps, fits into some small place (where his bounding box wouldn't fit if he wasn't jumping) and then finishes jumping? You probably need some sort of "crouch" mode. And if you have that, you can easily apply it to jumping.

In the collision detection method itself, I guess the solution will depend on whether you want a discrete change or a progressive increase/decrease in size that lasts multiple frames.

# Answer
> 0 votes
Your objects will be thrown all over the place during collision resolution when their shape/size increases.

This is normal. If your object ends up inside another one it will "bounce". Your problem can be solved by:

* making sure that when you change the shape your character's feet don't enter into the ground. To do so if you collide with the ground while the shape size increase move the shape's position so your character stands up on the ground instead of ending up with his feet in the ground.
* Make sure there is room for your character to "stand-up". If your character ends-up in a place where there is no room to standup you have to make sure that the character doesn't end-up with his head inside the ceiling. It that was to happen add a crouching animation to fallback to in that case.

# Answer
> 0 votes
A possible approach is to define if the growing/shrinking is a force, and so it should be reflected during a collision or if it should be a particular case that the engine should handle separately.

In your case, increasing the size of a sprite is seen as a sudden increase in its speed in every direction pointing away from its center.

If you want it to grow in any case, you can't let it sink into some other sprite so you could handle it by calculating the grow, checking where collisions would occur and applying an increase in speed (using an arbitrary value representing how fast it is growing) in every direction point away from a collision surface.

Those vectors will combine to form the fake -controlled- collision result.

That way, before the collision detection system could react automatically, you have the special case wrapped up and fixed. You could also just move away the sprite of the amount of space it needs to grow, without letting it register as speed and avoiding potentially dangerous collisions.

# Answer
> 0 votes
Have to different lods for collision detection. One that is simply a bounding box for terrain collision and another that morphs to best fit your player that is used for damage calculations.

You dont want to change the size of the player in regards to terrain collision. First its technically very difficult. Second because if I fall off the map because I stop walking and my arms stopping swinging causes me to fall to my death while trying to line up jumps I'm going to dislike you strongly.

This is also most forgiving and fair to the player. No BS death because a projectile hit the larger terrain BB. And no BS death because your BB changes while platforming. I really would not change the BB used for terrain collisions at all for a platformer.

# Answer
> 0 votes
I'm assuming you push the player back when they collide with an object so they aren't inside the object thus making them no longer colliding.

The problem is probably occurring when your player starts to return to original size, the player was pushed out of collision with the object, then the player grew, colliding once again, or perhaps kept growing and you kept pushing the player back causing them to move back drastically, possibly inside of an object which then tried to push the player out, etc. Basically it creates a mess.

Assuming this there are 2 fixes I see:

1. You find the overlap of the player and push them back by the difference of the overlap. This is a technique I use for platformers, but can also be used in top-down tile based games. You can also push them back by the overlap of the original sprite size, this might work better.
2. An easier solution, and you can also use this with the solution I mentioned above. When calculating the bounding box collision use the original width and height rather than the scaled width and height.

Bounding box is pretty simple to implement. Here's a simple example in lua: https://love2d.org/wiki/BoundingBox.lua All bounding box does is check if given dimensions overlap based on there position, you don't need to create rectangles to check for bounding box. All you need is the width, height and x, y of 2 objects. I'm not sure if the implementation you're using allows that or if you give it a rectangle object to perform the check.

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


# Question
Title: openGL ES - change the render mode from RENDERMODE_WHEN_DIRTY to RENDERMODE_CONTINUOUSLY on touch
i want to change the rendermode from RENDERMODE\_WHEN\_DIRTY to RENDERMODE\_CONTINUOUSLY when i touch the screen.

WHAT i Need : Initially the object should be stationary. after touching the screen, it should move automatically. The motion of my object is a projectile motion ans it is working fine.

what i get : Force close and a NULL pointer exception.

My code :

public class BallThrowGLSurfaceView extends GLSurfaceView{

```
MyRender _renderObj;
Context context;
GLSurfaceView glView;

public BallThrowGLSurfaceView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    _renderObj = new MyRender(context);
    this.setRenderer(_renderObj);
    this.setRenderMode(RENDERMODE_WHEN_DIRTY);
    this.requestFocus();
    this.setFocusableInTouchMode(true);
    glView = new GLSurfaceView(context.getApplicationContext());
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub
    if (event != null)
    {
        if (event.getAction() == MotionEvent.ACTION_DOWN)
        {
            if (_renderObj != null)
            {   Log.i("renderObj", _renderObj + "lll");
                // Ensure we call switchMode() on the OpenGL thread.
                // queueEvent() is a method of GLSurfaceView that will do this for us.
                queueEvent(new Runnable()
                {
                    public void run()
                    {
                        glView.setRenderMode(RENDERMODE_CONTINUOUSLY);
                    }
                });
                return true;
            }
        }
    }
    return super.onTouchEvent(event);
}

```

}

PS : i know that i am making some silly mistakes in this, but cannot figure out what it really is.

# Answer
Override a method, setRendermode in ballThrowSurfaceview class and call that overridden method in your touchevent class.
> 2 votes

---
Tags: android, opengl-es, game-mechanics, movement, touch
---


# Question
Title: What's the standard location of a 3D clipping box?
The way I understand 3D rendering, polygons are transformed using several matrices, and they are then clipped if they are not inside a certain box, before projecting the box onto the screen. Before transformation, the visible area is typically a frustum, and after transformation, I am guessing it's a cube. This cube makes the clipping math easier than a frustum would.

My question is, what's the 'standard' location/size for this clipping box? I can think of 3 possibilities: (0,0,0)-(1,1,1), (-0.5,-0.5,-0.5)-(0.5,0.5,0.5), (-1,-1,-1)-(1,1,1)

Or is there no standard?

# Answer
> Or is there no standard?

There isn't. OpenGL and D3D define clipping to happen in post-projective space, which is a 4D homogeneous coordinate system. So not a cube. But they use *different* post-projective spaces; the difference being the direction and range of the Z coordinate.

After the perspective divide (when you turn the 4D homogeneous space into a 3D space again), what you have in OpenGL is called normalized-device coordinates. This ranges from \[-1, 1\] in X, Y, and Z. In D3D, the equivalent space ranges from \[-1, 1\] in X and Y, but goes from \[0, 1\] in Z. Note that in both cases, clipping happened before then.

You can write a renderer that does clipping in whatever space you want. It's all just math in the end.
> 4 votes

---
Tags: 3d, rendering, matrix, clipping
---


# Question
Title: Python library for scripting (C++ integration)
Please advise me good wrapper/library for python. I need to implement simple scripting in c++ app; Under "good" I mean pretty understandable, well documented, no memory leaking, fast. For creating base interface of GameObject on Python and C++; Your own experience and useful links will be nice!!! I found link about it, but I need more specific within gamedev context. What combinations of libraries you used for python integration into c++? For example about ogre-python it said

> built using Py++ and Boost.Python library

And one more question, maybe someone of you know how Python was integrated into BigWorld engine (it's own port or some library)?

Thank you!!!

# Answer
> 1 votes
I see no reason to avoid boost.python in game development. When you create a game, you don't just instantiate some template. You are designing it by yourself so it's of no generic design that some python library could adhere to.

Civilization IV uses boost.python, for example.

---
Tags: c++, python, scripting
---


# Question
Title: Client/Server game even in solo: any big problem?
I'm making a game which have strong basic design based on multiplayer but also should provide a really interesting and self-sufficient solo game. A bit like a real-time strategy game. The events and actions taken shouldn't be as massive and immediate as in a FPS, so you can also think the networking like for an RTS. It's a PC game, targetting Windows, MacOSX and Linux (Ubuntu & Fedora). It's programmed in C++, using a variety of open source libraries, so I have great (potential) control over the performances.

So far I always considered that just making the game work with two applications, client & server, even in solo mode was ok.

However, as I'm in the process of starting the network code I'm having doubts about if it's a good idea. I'm not a specialist so I might be missing something in my analysis.

I see these pros and cons:

Pros:

* The game works only one way so if I fix a bug it should apply on all game modes, whatever the distance with the server is;
* Basic networking issues would be detected early, including behaviour with the protection softwares (firewall) installed (i am not specialist so this might be wrong);

Cons:

* I suppose that even if it should be really fast enough, networking client and server on the same computer would still be slower than no networking and message passing in (one) process memory.
* Maybe debugging would be more difficult? I don't have experience in this case but so far I assume that debugging with Visual Studio allows me to debug multiple process so it shouldn't be really different. Also, remote debugging.

My question is: **is there a big disadvantage that I missed? Or maybe there are advantages that I missed and that should encourage me to just continue with only client-server game sessions?**

# Answer
There are two ways to look at this:

1. If you are *decided* as to the fact that you're going to be devoting a lot of time to this project, it would seem a good idea to build it multiplayer, client-server from the start. Changing a game design much later on to be multiplayer is a really bad idea, because it affects the entire dynamic, from the little things like latency right up to the high level design choices. The differences *will* lead to a completely different game, no doubt about that.
2. If you're *not yet 100% sure* that this is something you want to turn into the full-blown game that you envision, then be careful going down this route that (as it is not your specialty) is probably going to take up a whole lot of time that might be better spent hashing out the basic game dynamic to see if it's a viable project -- and then adding multiplayer. Also note that although you have the joys of BSD sockets under all your supported platforms (if you are using those directly), while that's *meant* to be largely identical from platform to platform, I would think that porting and bugfixing that code across all of those will probably be quite "fun".

Having said the above about porting, I sincerely hope you intend to write for one platform first, unless you write very portable code indeed. Getting a running game on one platform should be your first goal.

Re message passing: A socket is a socket. I've played a number of games in the last 15 years that ran TCP client and server processes on the same machine. Performance was, if anything, better because latency was reduced.

Re debugging: distributed debugging is ALWAYS harder -- no doubt about it. The best you can do in that regard is to inform yourself as to the best network debugging tools available that are within your price range. Also, I think you have already answered your own question about VS and process-specific debugging on your dev machine.

The main advantage in going client-server now is that you will be able to effectively account for latency as part of your game dynamic -- nothing to sniff at. Another is that you will be able to get feedback from others, affording a more objective view of the game as it develops.
> 1 votes

---
Tags: c++, networking, multiplayer, single-player
---


# Question
Title: OpenGL sprites and point size limitation
I'm developing a simple particle system that should be able to perform on mobile devices (iOS, Andorid). My plan was to use GL\_POINT\_SPRITE/GL\_PROGRAM\_POINT\_SIZE method because of it's efficiency (GL\_POINTS are enough), but after some experimenting, I found myself in a trouble. Sprite size is limited (to usually 64 pixels). I'm calculating size using this formula

```
gl_PointSize = in_point_size * some_factor / distance_to_camera

```

to make particle sizes proportional to distance to camera. But at some point, when camera is close enough, problem with size limitation emerges and whole system starts looking unrealistic. Is there a way to avoid this problem?

If no, what's alternative? I was thinking of manually generating billboard quad for each particle. Now, I have some questions about that approach.

I guess minimum geometry data would be four vertices per particle and index array to make quads from these vertices (with GL\_TRIANGLE\_STRIP). Additionally, for each vertex I need a color and texture coordinate. I would put all that in an interleaved vertex array. But as you can see, there is much redundancy. All vertices of same particle share same color value, and four texture coordinates are same for all particles. Because of how glDrawArrays/Elements works, I see no way to optimise this. Do you know of a better approach on how to organise per-particle data?

Should I use buffers or vertex arrays, or there is no difference because each time I have to update all particles' data.

About particles simulation... Where to do it? On CPU or on a vertex processors? Something tells me that mobile's CPU would do it faster than it's vertex unit (at least today in 2012 :).

So, any advice on how to make a simple and efficient particle system without particle size limitation, for mobile device, would be appreciated.

(animation of camera passing through particles should be realistic)

# Answer
Instancing isn't available in ES2 but ultimately it would provide the best approach.

In the absence of instancing there are a few other ways you can optimize the data. You know that the index array data is not going to change even if the vertex array data does, so the index array can become a static array. The same can apply to texture coords (assuming that you don't have an atlas of particle textures) so they can be also shifted into a static VBO, which would - of course - need to be non-interleaved. That effectively leaves position and colour as being the only dynamic per-vertex data that needs updating, with colour being the only attribute that is duplicated (and if you're using 4 unsigned bytes for colour then the duplication isn't so onerous).

None of this is perfect and you've correctly identified reasons to be unsure of it. However, before you go ripping things apart it would pay to benchmark and see if using duplicate data actually is a problem. This can fly in the face of instinct, but it's often the case that pulling tricks to reduce memory usage ends up having overall negative consequences for performance. Accepting extra memory usage and accepting some duplication of data - even if it does seem instinctively "wrong" - can frequently turn out to be the most optimal approach.
> 1 votes

# Answer
Yeah, I would say go with a 4-vertex triangle stripped quad.

If you are drawing large numbers of these triangle strips *using the same color*, and *the same set of texture coordinates*, you could do 1 of 2 things:

1) Send the 4 vertices for each object and store the color and texcoords in uniforms

2) "Hardware instancing"
> 5 votes

---
Tags: opengl-es, glsl, opengl-es2, particles
---


# Question
Title: Why does my game loop speed vary on different platforms with the same hardware?
I've got a serious issue with my game loop. This loop varies in time with the platform and with the same hardware. This is a list of `FPS` achieved:

```
  -  Windows       ======= 140 to 150
  -  Linux         ======= 120 to 125
  -  Windows(WINE) ======= 125 to 135

```

And since my game loop is fixed timestep, the speed of the game is not stable. Here's my game loop.

```
public final void run() {
    // Initialize the resources
    Map.initMap();
    initResources();
    // Start the timer
    GTimer.startTimer();
    GTimer.refresh();
    long elapsedTime = 0;
    // The game loop
    while (running) {
        // Update the game
        update(elapsedTime);
        if (state == GameState.GAME_PLAYING) {
            Map.updateObjects(elapsedTime);
        }
        // Show or hide the cursor
        if (Global.HIDE_CURSOR) {
            setCursor(GInput.INVISIBLE_CURSOR);
        } else {
            setCursor(Cursor.getDefaultCursor());
        }
        // Repaint the game and sync
        repaint();
        elapsedTime = GTimer.sync();
        Toolkit.getDefaultToolkit().sync();
    }
}

```

The timer package

How could I improve it?

# Answer
There is an excellent article here about this subject: http://www.koonsolo.com/news/dewitters-gameloop/

Normally I update my game in the same way for every update call. I have the speed at which things happen measured in terms of game loops elapsed (if you choose to update your game the same number of times per second you can still measure speed of things in time with some basic math)

The best of the simple ways (i.e without interpolation parameters for the display method) to do the game loop is this (I added comments on this code which is from the article):

```
const int TICKS_PER_SECOND = 50;
const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
const int MAX_FRAMESKIP = 10;

DWORD next_game_tick = GetTickCount();
int loops;

bool game_is_running = true;
while( game_is_running ) {

    loops = 0;
    //Let's update the game... And take note of when we need to update again
    //If there is time left (GetTickCount() < next_game_tick), then we have some spare time to display the game.
    //But if we are already late, we need to keep iterating the game (GetTickCount() > next_game_tick)
    //However if it is the case that we never are able to get some time to display the scene,
    //loops variable will end up being greater then MAX_FRAMESKIP (loops > MAX_FRAMESKIP)
    //At this time we really need to show the user how is the game going.. (He couldn't see it for 10 iterations!),
    //so the loop is 'broken' and we get to display the game
    //This is an exceptional situation where the game logic will start to slow down
    //until now game logic kept the same speed and only FPS could change
    while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) {
        update_game();

        next_game_tick += SKIP_TICKS; //We take note on when to update again
        loops++;
    }

    display_game();
}

```

You should really read the article for more detailed information, it is really good. Also, take into attention that in these code samples, update\_game() makes the game do the same amount of progress every time it is called, whereas in your code, update\_game(elapsedTime) makes the game progress more if more time has elapsed since last update. You will probably be better with the first approach if you use the model described in this answer.
> 5 votes

# Answer
Any two OS give different performance based on hardware optimization. Even between Windows 7 and Windows 8 you will see some difference in frame rates. http://www.zdnet.com/windows-8-vs-windows-7-benchmarked-7000002671/

Your game loop speed varies on each different platform for because of various reasons:

1. The JVM is implemented differently on each OS. It may be using slightly different software to compute the same game logic on a different OS and thus using your HW differently. You can narrow it down b writing generic code that only does computation and data manipulation (benchmark) to see if the issue relates specifically to the rendering or not.
2. Each one is running different processes in the background.

To see the processes running(Windows):

1. press Ctrl + Alt + Delete
2. Click on 'Start Tast Manager'
3. Click on 'Processes'

To see processes in Linux:

1. open a shell (for instance run xterm)
2. type 'ps a' and press Enter.

This issue with frame rate should not influence your game design. Why not adjust the movement of units in your game to compensate for the varying speeds?

If you mean that it is running at 140~ FPS in Windows and 120~FPS in Linux it is beyond optimization imho. You should normally stick with a lower than max fps cap, for the game to run smoothly at a steady speed. For instance if you think your game could run on speeds of 60 - 80 fps on the average user's computer, cap it at 60. Generally I try to calculate to the optimal fps for each machine my game runs on or decide, it should cap at a certain speed where anything lower means the machine is outdated.

Optimal fps is in most cases, the lowest fps during the game. Anything higher, makes the game appear less fluid.
> 3 votes

---
Tags: java, game-loop, platform
---


title: Preventing item duplication?

text:
# Question
Title: Preventing item duplication?
For my game, there's two types of items - stackable, and nonstackable.

Nonstackable items get assigned a unique ID that stays with it forever. A character ID is assosicated with the item, as is a state (CHANGED, UNCHANGED, NEW, REMOVED). The character ID and state is used for item saving purposes.

Stackable items have one unique ID, as in the entire stack has one unique ID. For example: 5 Potions (stacked ontop of each other) has one unique ID.

When dropping a nonstackable item, the state gets set to REMOVED, and the unique ID and state don't change. If picked up by another player, the state gets set to NEW, and the character ID gets changed to the new character's ID.

When dropping all items in a stack of stackable items (for example, 5 potions out of 5) - it behaves just like a nonstackable item.

When dropping some of a stack of stackable items (for example, 3 potions out of 5)... I really have no clue what to do. The 3 dropped potions have the state of REMOVED, but the same unique ID and character ID. If another player picks it up, it has no choice but to obtain a new unique ID, and its state gets changed to NEW and its character ID to the new one. If the dropping player picks it back up, they'd just be readded to the stack.

There's two issues with that though. 1. If the player who dropped the 3 potions picks it back up, there's no way to tell if they legitimately dropped the items, or if they're duped items. 2. If another player picks up the 3 potions (assuming they're duped), there's no way to know if they're duped or not.

My question is: How can I create a system that detects duplicated items for both nonstackable and stackable items?

# Answer
> 5 votes
How about having a unique itemp ID for each item, stack-able or not and then simply displaying the items that belong to the same category as a stack instead?

Solution II:

Each time the player splits a stack of items, a new unique ID is created for the stack that was dropped on the ground. When two stacks are merged, the lesser stack's ID is the destroyed and it contents are merged with the larger stack.

The destroyed stacks are indicated as such in the DB and can be used later for other items.

So each new stack with x units in the game, gets it's own ID(mentioning x units). When stacks are split, we get a new stack (y units) with a new ID and the old stack is then registered in the server as one with (x - y) units. When a stack is depleted, the server remembers it as an empty stack with 0 units.

No player can hope to reuse an empty stack.

---
Tags: mmo
---


# Question
Title: How to achieve highly accurate car physics such as Liveforspeed?
Liveforspeed is a racing simulator, there is amazing amount of realistic physics. for example, tires get warm, tire actually deforms when you turn corners. You need to play this game with a mouse at the minimum because it almost drives like the real thing.

Anyhow, how does one achieve that level of physics simulation? Are there off-the-shelf solutions out there? If not, how does one start with simulating real world physics as close as possible.

I would love to be able to work on an opensource car physics focused game. Imagine, more passionate developers, it could keep things going.

# Answer
> 5 votes
You should probably start with an open source 3d physics engine like Bullet. Remember that games that have funding can hire professionals that are well versed in kinematics that can draft models in math-lab and then have programmers implement them in the code.

So the best way to fully implement a systems like this would involve learning about cars and physics, I think that is beyond the scope of one question.

This might help you get started?

Car physics for games:

http://www.asawicki.info/Mirror/Car%20Physics%20for%20Games/Car%20Physics%20for%20Games.html

Open source 3d physics engine:

http://bulletphysics.org/wordpress/

The Disney car 2 game uses this engine.

This is just a short video that demonstrates what you could achieve with an advanced 3d physics engine like CryEngine3

http://www.youtube.com/watch?v=KppTmsNFneg&feature=related

Basically, I think this question needs to be broken down to smaller questions, some of which likely belong in SE physics. It is too broad a subject to be properly covered in the current medium.

Development of such a project is incremental in nature, you have to take a step before you can walk and walk before you can run. So I'd suggest starting with a small and rudimentary car simulator and adding features. That way you can allow the time needed for each feature, to study it in depth.

Perhaps like you suggested if you find like minded programmers, each one can focus on a different feature once you have the skeleton of the engine running.

It is sometime possible to negotiate a deal with a company to use their existing engine to make a game in exchange for a portion of the profits or a large sum in advance.

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


title: Game window systems and internal frames

text:
# Question
Title: Game window systems and internal frames
I don't know if this is a valid question, but: What kind of window manager do games use which have internal frames (Frames inside frames)? Does this differ between the programming languages (Are e.g. in Java the AWT/Swing libraries used to manage these and other graphical elements, such as buttons,or is this to restrictive (speed, graphical possibilities?))

A special example would be EVE Online, where the client can use the ingame windows like on a normal desktop.

# Answer
> 3 votes
You can actually use Swing canvas as an opengl context where you can render your game. You can use all the classic Swing components **around** your game. I say around because you cannot add components inside your game, which is what you seems to ask for.

Games usally use what we call a *GUI* (for **G** raphical **U** ser **I** nterface). A GUI will just draw windows and other composents like you would draw a character in your game.

Here are two GUI's written in Java using *LWJGL* (OpenGL port in Java) for rendering:

Since the above GUI's use OpenGL for rendering, you can render them in the OpenGL context of your game for example. A lot of others GUI's exist for many others languages and using differents technologies.

---
Tags: game-design, algorithm, rendering, graphics-programming
---


title: Programming Paradigm for Games

text:
# Question
Title: Programming Paradigm for Games
Which programming paradigm resembles or best suits the Game design or game engine programming? by paradigm I mean the Imperative, Object oriented, Functional, etc. I came to know that functional programming is more modular than object oriented and is concurrent. is it??

# Answer
Data oriented design/programming. It means that you consider your data before everything else. This does not exclude OOP *where it fits*, however this most certainly excludes "all things object oriented". Same goes for functional and just about any other paradigm.

However, there is no need to try and limit yourself to some style of programming or thinking. Try different things. See what works, check if something could work better, work on that. Repeat. The more you learn, the more you develop your coding style. Limiting yourself to some certain "best practices" is worse than shooting yourself in the foot - not only you will miss out on some of the good stuff, you'll also make programming boring to yourself that way.
> 1 votes

# Answer
Looking over your question I can't help but feel that you're going at it the wrong way around. You're trying to shoe-horn a problem into one of a number of pre-defined solutions, instead of building a solution around the needs of solving the problem.

The truth is that game programming is a multi-paradigm task. You don't need to have to choose one pizza from a (limited) selection beyond which you cannot go; you need to choose your own pizza with your own selection of toppings in the proportions that satisfy your own appetite and tastes the best.
> 1 votes

# Answer
Nowadays, most games are written in C++, with Java and C being popular alternatives. Two of these are object oriented and the third is not 'functional'.

A lot of casual games are written in AS3 which is also oop.

I am pretty confident that if you base your decision on what most experienced programmers are doing today, using object oriented would come as a first choice.

However, if you are writing a game for learning purposes or simply prefer functional programming than obviously, you can probably make decent use of it.

My answer is based on this wiki article: http://en.wikipedia.org/wiki/Game\_programming
> 0 votes

# Answer
This is an open ended question. There is no way to answer it properly as it depends on countless factors. There are exceptions, but if you want a general rule functional programming is not used for game engines. The rest depends on the projects the kind of games, the libraries and SDKs you will primarily use (on consoles, PC, mobile, and other dedicated hardware/systems)... and on the team.

Languages with functional subsets are sometimes used in the video games industry. But the successful projects I am aware of are using these languages mostly for the easy deployment across nodes to provide a distributed service (i.e. leader boards, data and metadata storage, matchmaking and game lobby management).

A game engine is usually built to provide functions which already exist but with an emphasis on performance. The use of mutable variables is key to insuring good performances which a functional language will not deliver.

The way you organize your data will mostly depend on the underlying architecture. But as a rule of thumb most data (positions, physics, models) will be stored in raw arrays of float or doubles in order to allow for fast parallelized operations (OpenGL, OpenCL, vDSP hardware acceleration libraries...).

But how you access to this data is your business. You can use objects, functions where you pass pointers, whatever.

The emerging practice in game engine is the component (or entity) based architecture where game objects are not represented by specialized objects providing functions but with entities which are no more than a key or a collection of components which are designed to interact with each other.

Factors like what is the real aim of your game engine might influence the language and paradigm used. Do you need an engine destined to one platform? Or is your engine a middleware which will abstract access to dozens of underlying OSes and SDKs (OpenGL, OpenAL, DicectX...). In the first case you will probably align your architecture around the existing SDK, in the second case you might want a good object oriented architecture to hide all the different implementations (which might be done using a non object approach).

Back on the functional programming; you might be tempted to use such an approach for a large server based game. But for the vast majority of games the client-side and server-side code are shared to some extent. And the game industry has very few experienced programmers in the field of functional programming which makes it a non obvious choice in this field.

I hope this helps.
> 0 votes

---
Tags: architecture
---


title: 2D Physics in a networked game (iOS)?

text:
# Question
Title: 2D Physics in a networked game (iOS)?
I am researching the possibilities for a new iOS game. It's going to be a run-n-gun type platformer, and I'm looking into the possibility of co-op multiplayer.

The game itself wouldn't be very physics intensive, there will most likely be 20-30 physics bodies at any given time. For the multiplayer, I think I would have one player "hosting" and up to 3 other connecting via the Internet.

Here's my first question, are there any 2D physics engines that work over a network(preferably open source)?

My second question, Does anyone have any thoughts on using a non-networked engine (like Box2D or Chipmunk) and adding the networking component? Since there would not be very much information sent, do you think it would cause a lot of lag?

# Answer
> 2 votes
Your second option is how it's done. Why would your physics engine know anything about networking? That breaks OOP principles. I suggest you use Box2D. Each mobile device has a world running, but one of them is the master. The master regularly pushes and receives game state updates from the slaves, reality-checks them, and then passes them on to other slaves if the updates passed. Ideally, you only want input sent on the slave-master channel, then you don't even have to do reality checks.

# Answer
> 1 votes
In most games the physics are not synchronized as it either requires a lot bandwidth or a completely synchronized network code.

The synchronized network approach means that at the start all data is the same for all clients, and the whole game is calculated on each client in the same time steps. Just the controls the players push are transferred. If all game logic is deterministic then all games will keep in complete synchronization.

*Upside of* this is that this approach only needs a few kbit's to work properly, no matter how complex the game is.

*Downside is* that the controls of the players are delayed by the lag and that it requires a fixed time step that is the same for every player. A fixed time step also means that if one player lags all players will notice that lag.

This approach is/was used by strategy games mostly due to the large amount of units.

A quick note about determinism, floating point implementations can differ from processor to processor, so they are deterministic as long all devices you target have the same floating point implementation, if you can't be sure of it you'll need a physics library which uses fixed point math.

# Answer
> 0 votes
Much like Bane said, a "Multiplayer(network) physics engine" is a physic engine running on the server side. Much like any game logic running on a server side(to prevent cheating).

To prevent lag, you can have a physics engine running per-frame on each client for fluid motion between server updates. Another engine instance running on the server updating the players less frequently for correctness and cheat prevention.

Note on latency or LAG:

There is no magic cure for lag, you simply have to optimize your code as much as possible and wait for technology to do the rest. Most latency isn't due to the amount of data you sent each sec. It actually has to do with number of milliseconds it takes that data to travel (could be distance related/ technology\* related). Sending more data should not affect latency much with today's tech, because you will likely still be able to send data as frequently.

In the old days, the bandwidth and the amount of data transferred were the bottleneck as far as latency goes, the connection was so slow (4Kb), it actually needed more time to send slightly more data. That is still true today only in cases where the amounts of data transferred is very large (streaming HD content on Netflix 2.3Gig per hour). The modern connection speed can handle game data pretty well, 10-40 physical objects moving around are not going to noticeably affect performance.

For instance, if for some reason we switched from Ethernet to InfiniBand, the latency would decrease dramatically even though, it may or may not affect bandwidth.

http://en.wikipedia.org/wiki/InfiniBand

---
Tags: 2d, physics, networking, ios
---


title: Huge 2d pixelized world

text:
# Question
Title: Huge 2d pixelized world
I would like to make a game field in a indie-strategic 2d game to be some a-like this popular picture.

So every "pixel"(blocks) changes it's color slowly, sometimes a bright color wave happens, etc, but the spaces beetwen this pixels should stay dark (not to count shades, lightning and other 3rd party stuff going on). Units are going to be same "pixelized" and should position them-selfs according those blocks.

I have some experience in game-developing, but this task seems not trivial for me. What approaches (shader, tons of sprites or code-render, i don't now) would you recommend me to follow? (I'm thinking of making this game using Unity Engine) Thanks everyone! :)

# Answer
> 5 votes
```
float size = 1.0 / NumTiles;

float2 Base = UV - fmod(UV, size.xx);
float2 Center = Base + (size/2.0).xx;

return tex2D(ScreenTexture, Center);

```

Make your render target be a texture called ScreenTexture, render your scene, make the rendertarget be the backbuffer again, draw a fullscreen quad with ScreenTexture and apply this shader on it. It is called Post Processing Pixel Shader. Should work fine for it.

EDIT: With in-between gaps:

```
float size = 1.0 / NumTiles;
float2 PixelSize = 1.0 / ScreenSize; //ScreenSize is a float2(ScreenWidth, ScreenHeight)
float2 Part = fmod(UV, size.xx)
if(any(Part < PixelSize) || any(Part > (size.xx - PixelSize))
    return float4(0, 0, 0, 1);
float2 Base = UV - Part;
float2 Center = Base + (size/2.0).xx;

return tex2D(ScreenTexture, Center);

```

---
Tags: unity, shaders, strategy
---