# Question
Title: what is the best way to eliminate grinding in games?
This is a very persistent question in game design, especially in games where you need to hold/retain players like MMO or social games. (On a side note grinding can easily calculated so its easy tool for engagement and timed progression).

The question other than community building/competition are there solutions that can replace grinding and still hold your audience for certain period of time (without adding large amounts of game assets and code)?

# Answer
This question avoids one of the main problems with "grinding", which is that no one agrees exactly what it is. In Everquest, grinding was fighting random mobs for XP. WoW switched the MMO format to a quest-based genre, so then grinding is doing uninteresting quests.

Is grinding any low-attention play? Then you don't want to get rid of it entirely, because low-attention play is what drives a lot of social interaction. It also serves to make high-attention (i.e. "difficult") play more exciting by highlighting it.

Is grinding what you do after you make the interesting choices, e.g. grinding is actually fighting the raid boss after speccing out your gear? Then grinding is the test of your ability to play the game, and can't be gotten rid of.

Is grinding a repetitive play pattern? Some repetition is necessary. It ensures players learn skills, and they usually feel good being able to demonstrate they have learned their skills. If players are complaining about doing something 3-5 times being "grindy", the problem is probably that it's boring to do even once.

Is grinding any boring element of a game? Not everyone is excited by the same things, so you'll never get rid of "the grind" in this case.

Are complaints of grinding just whining because you can't get the best sword in the game in the first ten minutes? Sometimes.

"Grind" is a term so abused and overloaded it's meaningless. First identify your market, then identify what they like doing, then make a game where they can do that. If people complain it's "grindy", figure out what, if anything, they are actually complaining about.
> 45 votes

# Answer
Issues of "what is grinding" aside, one obvious solution to "repeating the same content" is to add more content. Now adding content is expensive, and takes time, so how do you work around that? Well, games throughout history have found many ways to get more from their content:

**"Palette Swapping"**

Same enemy, different skin, different bullets. A technique passed down from the very early ages. Why have just one orange "Hill Orc" when you can have red "Fire Orcs" and blue "Ice Orcs" and green "Forest Orcs"?

Cons: Unless you really vary up the strategies for them, most people will see killing red orcs as largely the same to killing green orcs. So...

**Better AI**

Grinding is usually considered mindless, so add some mind to your encounters and they won't be grinding. If Fire Orcs behave in a different way from Ice Orcs, then encounters with both will feel fresh. Implementation varies from giving them different attacks to actually giving them different behaviors.

Cons: AI is a lot of work! Plus most MMOs don't have processing to spare on AI. Also...

**More Terrain**

Vary up the landscape, make encounters that actually use the terrain, then take advantage of that. Orcs in tight hallways should feel different from orcs in wide open fields. Let specialized monsters take advantage of terrain, like Fire Orcs are immune to fire so they can attack from unexpected directions in a firey landscape.

Cons: But all this stuff still requires a lot of content and players will eventually burn through any amount of content you make. WoW does all of these things AND MORE and there's still not enough content to completely eliminate repetition. Which means...

**Procedural Content Generation**

Will Wright talked heavily about this prior to Spore coming out. Unless you have a 100 person art and design team cranking out quests and assets, its very hard to have a lot of content. The solution is to have a little bit of componentized content and then to mix-and-match the pieces.

Any game with procedural content is a good example for this: Minecraft, Noctis, any roguelike, etc. Look at Nethack: that's a 30 year old game that's still popular. Yeah it gets updates pretty often, but people come back again and again because the randomized, generated content is always fresh.

This is a strategy that plays well with the above too. Nethack has a lot of predefined monsters, but the terrain varies heavily. Different mixes of monsters, in different terrains, require different strategies depending on the player's class, race, and item loadout. The number of permutations means that almost any encounter will be somewhat unique, but still building on everything the player has learned to that point.

Cons: Ahh, but the downside is that procedural content is HARD to get right, and can easily shift from awesome to boring. Who cares if you have billions of miles of generated terrain to explore, if all of it is empty and boring? Likewise look at Spore: lots and lots of monsters, including thousands generated by players and available as automatic downloads. Lots of varied and interesting worlds. But only about 3 AI routines so no matter how cool a monster looks, they all play exactly the same. Also a very limited selection of powers and abilities. Every game plays out exactly the same, just with different skins.

Procedural Content is only good when:

1) it is constrained to make sense and be playable ("I spawned in a sealed room full of lava?!")

2) it is actually varied enough to be fresh and the player's don't see the illusion that all of it is just new configurations of the same old crap

3) the rest of the game is built to support and reinforce the value you gain through procedural content generation. Your game has to build on top of the PCG assets, not just rely on PCG to provide gameplay.
> 20 votes

# Answer
First off my assumption of what grinding means is repetition of an uninteresting task that is required for advancement.

so there are three things you can address here:

1. Repetition
2. Lack of interest
3. required for advancement

**Repetition**
This one there is difficult to get around if your game is of an appreciable length. At least within your constraints of not adding a bunch of new code or assets. The best way to avoid repetition is to allow multiple avenues to achieve what the player is using the "grindy" experience for. I think player content creation systems are the best way to do this but that would not be without its own headaches.

**Lack of interest**
This ties in closely with the other points. Repetition is most problematic when what you are repeating isn't fun in the first place. I like the idea of making a toy out of your core mechanics, and then once you have a solid, fun mechanic, then add goals and direction and make it a game. I.E. League of Legends has tons of repetition but its interesting activity(usually) so the repetition is not as noticeable.

**Required for advancement**
This is a big killer for grindy-ness. The player wants X but to get it they have to do Y so many times. I think that players should have to work for rewards but this becomes a problem when this is cross-activity. If someone is a socializer and wants a purely aesthetic item to help in that regard requiring a huge combat challenge may be daunting. If they had a social avenue to get their social reward that may be much more palletable.
> 8 votes

# Answer
I think this question is particular to MMOs, but the answer lies by looking outside MMOs. What is grinding? Completing a repetitive task with a guaranteed reward. How do you eliminate it? Provide puzzles, challenges, story, character and anything that motivates and engages the player outside of the gold/items economy of the game.
> 2 votes

# Answer
These are just a couple of ideas I have regarding MMORPG's and eliminating the grind:

Write quests with differing plots. **Think of your quest plot as the plot of a short story.** Is it a mystery, action, drama, etc. Don't ever give menial tasks out as quests. Your quest should tell a story.

Let players create (and hand out) their own menial tasks. Need a caravan guard? Ask a player. Need 20 hides? Ask a player. You get the idea. **Implement an inter-player contract system for menial tasks.** So the boring "quests" are player generated and will involve some player-player interaction.

**Make encounters with NPCs as unique as possible.** Some fly, are invisible, run really fast, burrow under ground, shoot from afar, can mind-control, charge at you, sneak up to you before attacking, grab you, etc. They don't just have differing DPS. The Stalker team tried this and succeeded quite well, just a shame there aren't more types of mutants. Collectible card games (Magic The Gathering) are also good at allowing players to "bend the rules" of the game all the time by using cards with outside-the-box abilities.

See what lessons you can learn from PvP. Try to replicate the PvP feeling in the rest of the game. **It should be a test of skill, not time or patience.** How you do this is beyond me...

Any game that focuses on the player's skill instead of the in-game character's skill (or XP) will automatically be way less grindy. **Focus on strategy and tactics to get past obstacles** instead of "training" to get past an obstacle.

An element of risk always adds to the excitement. **Make defeat costly and players won't go into autopilot mode as often.** This is a difficult thing to implement and most games just go with the default "respawn with temporary negative effects" approach because it's simple and easy with less rage quits, I guess.

These are all just ideas that I've always had. Whether they are good or bad is up for the professionals to decide and it looks like most of them have decided they're bad, or too much effort.
> 2 votes

# Answer
The best way I have seen to reduce the 'grind' element is to have the **players drive** everything. The original Star Wars Galaxies did this very well even though there were some 'grind' spots in the game. There was always an **end goal** and they were very **different depending on the person playing the game**. It could be getting the best pieces of loot in order to make awesome armor or weapons for a customer, it could be gathering resources to craft various items for players, it could be building a large city, etc.

You see the great thing is that the **player creates their own entertainment** so in their mind they don't feel that it is a 'grind'.

Of course this doesn't work very well if your playerbase doesn't like sandbox games in which they are basically **generating their own content**. I would make the **decision based on what kind of game you want to have**.
> 2 votes

# Answer
One way to discourage grinding is to use diminishing rewards. Reduce the amount of gold, experience or the frequency of item drops if they keep killing the same monsters over and over again.

This can be done intelligently by comparing the player's experience points or level to that of the monster. If the player's level is lower than the monster's, the player gains more experience for killing them. Likewise, if the player's level is higher, they gain less experience.
> 2 votes

# Answer
You could always impose limits on play time, or specifically on performing the same action excessively in a certain time frame. This then leaves you needing other alternatives for players to gain acheivements/items. These alternatives need to not only be enjoyable (though just about anything is more enjoyable than grinding), they need to offer the same level-ups and rewards that grinding would do. Actually, having better rewards would be a good incentive for people to adopt them.
One idea is having a concept of 'quests', where a player needs to do a variety of different things and in different places in order to get rewards. The thing is, the rewards need to be valuable, worth forgoing grinding for a harder pursuit. The quests need to be long enough so that players couldn't repeat it over and over again in a short time (grinding), but short enough that they are still accessible and interesting. It's tough to balance, but if you do, they will be a lot more interesting for players than sitting doing the same thing over and over.

Another option is some sort of reward for achievements in multiple disciplines. For example, if your game has 'skills' like a game like Runescape has, maybe something could be given for getting to a certain level (a low to mid level) in a certain number of different skills. This encourages different activities to be explored by players.
> 1 votes

# Answer
One way to eliminate grinding is to allow people to write scripts that can play the game, which of course introduces other problems.
> 1 votes

# Answer
Ideally, the action should be rewarding in itself, not just the material reward that follows it. But if the game is designed such that the action needs to be performed frequently, but doesn't compensate for this by making the action deeper, then the action will become boring sooner, making it prone to becoming a grinding activity.

So the solution seems to be:

1. Identify which activities need to be performed often, and therefore are prone to becoming boring.
2. Fix, or compensate for them.

Point 2 is tricky. Whatever effort you make, there are only two possible outcomes:

1. You postpone the point at which the activity becomes boring.
2. You make the activity perpetually engaging.

A lot of solutions actually lead to outcome nr 1. Adding more content, automating the activity, reducing the reward, they all don't solve the core problem. That doesn't mean you shouldn't think about it, because its impossible to make all activities 100% engaging. But the million dollar question is what it takes to give an activity the property of being perpetually engaging, outcome nr 2. And I believe it's to enable emergent gameplay.
> 1 votes

# Answer
There are alot of ways to remove grinding, but IMHO the most important one is that it's important to make player actions and decisions count, because in WoW, f.e., no matter how amazing the quests or dungeons are, they're ultimately just an obstacle between you and the end game content, doesn't matter if you're casual or a nerd, every poster and trailer has a dragon on it and dragons are the end game content, you won't see a dragon before the last level. WoW is all about the end game content, so nothing in between matters. This means everything you do will feel like grinding.

Grinding in WoW doesn't end at 85 either, because Blizzard is constantly adding more content while making the older content completely obselete extending the grind even further. The longer into the expansion you are, the more you'll have to grind, because content you might have not seen or not completed is made easy or free, which means more work in boring, nerfed content before you get the apropriate level of gear for current content.
> 1 votes

# Answer
This question has an obvious "brute-force" answer: play test your game extensively, and where players feel an area is "boring, repetitive, but necessary to get to the part that I want" (how I currently understand "grinding"), just cut those parts or make them faster to get through.

The earliest instance of grind I could think of is when I used to make sure I had bought the silver sword from Elftown in Final Fantasy I *before* going to the earth cave. This insured I wouldn't die as much, and plus I really wanted that silver sword, in all it's silvery blueness.

I think the decision to place "grind" in games is very conscious on the part of the game designers. Yes, killing that many monsters in the same repetitive way, with the only goal of gaining gold or experience is *boring*, but that makes the pay off that much more worth it.

A game with virtually no grinding, (as I remember it!) was really content-rich adventure games like Neverwinter Nights and the Ultima series games (Ultima 7 specifically). Notice how in Ultima 7, for example, gains from level-ups are actually of *marginal* benefit, (ie your stats don't increase that much), and most of the best items are *found* through exploration of some non-mandatory area.

So, all in all, I think the solution to level grind is to bite the bullet, your game isn't going to last forever or have infinite play time, and to play test and cut the boring bits.
> 1 votes

# Answer
I have one answer to this but only applies to console games. Instead XP for skills you attach movesets to items (way of the samurai did this). Instead of rare drops items are obtained by killing condition (monster hunter had a mix of this and random drop with it's carving system).

But I don't see this effective for an MMO setting though.
> 0 votes

---
Tags: game-design
---


# Question
Title: Moving an image by rotating and increasing y axis causes a trailing issue
Forgive me if me anything is unclear, this is a tricky thing for me to explain.

In an applet I draw a little ship gif. I have it so I can rotate the object and then increase or decrease the y axis to move the little guy around the screen. The problem it seems is that the coordinates for the ship are not in sync with those of the applet window?

For example: the boundaries for my applet window are 800 by 600. I move the ship by rotating it and then increasing or decreasing the y axis, but whenever the Y axis is exceeds 600 or is lower than 0 I get this weird trailing issue. Am I doing buffering right?

here are my "Main" and "ship" classes:

Main class:

```
    public class Main extends Applet implements Runnable, KeyListener
{
    ship player1;
    private Image i;
    private Graphics buffer;
    AffineTransform affineTransform = new AffineTransform();

    public void init()
    {
        this.setSize(800, 600);
        this.setBackground(Color.BLACK);
        addKeyListener(this);
    }

    @Override
    public void start() {
        player1 = new ship();
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void paint (Graphics g){
        Graphics2D g2d=(Graphics2D)g;
        player1.paint(g2d, this);
    }

    @Override
    public void update(Graphics g){
        Graphics2D g2d=(Graphics2D)g;
        if(i == null){
            i = createImage(this.getSize().width, this.getSize().height);
            buffer = i.getGraphics();
        }
        buffer.setColor(getBackground());
        buffer.fillRect(0, 0, this.getWidth(), this.getHeight());
        buffer.setColor(getForeground());
        paint(buffer);
        g2d.drawImage(i, 0, 0, this);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch(e.getKeyCode()){
        case KeyEvent.VK_RIGHT:
            player1.rotateRight();
            break;
        case KeyEvent.VK_LEFT:
            player1.rotateLeft();
            break;
        case KeyEvent.VK_UP:
            player1.moveUp();
            break;
        case KeyEvent.VK_DOWN:
            player1.moveDown(this);
            break;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void run() {
        while(true){
            repaint();
            try {
                Thread.sleep(17);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

```

ship class:

```
    public class ship {
    private Image sprite_ship;
    //private Image ship_engines_green;
    private int x = 300;
    private int y = 500;
    //private int dx = 10;
    private int dy = 10;
    private int my = 0;
    AffineTransform affineTransform = new AffineTransform();
    double rotation;

    public ship() {
        sprite_ship = Toolkit.getDefaultToolkit().getImage("ship.gif");
        //ship_engines_green = Toolkit.getDefaultToolkit().getImage("ship_engines_green.gif");
    }

    public void moveDown(Main M){
        y += dy;
        System.out.println("Y axis: "+y);
        System.out.println("X axis: "+x);
    }

public void moveUp(){
        y -= dy;
        System.out.println("Y axis: "+y);
        System.out.println("X axis: "+x);
    }

public void rotateRight(){
    rotation += 5;
    System.out.println("Rotation : "+rotation);
}
public void rotateLeft(){
    rotation -= 5;
    System.out.println("Rotation : "+rotation);
}
    public void paint(Graphics g, Main M){
        int spriteHeight = sprite_ship.getHeight(null);
        int spriteWidth = sprite_ship.getWidth(null);
        Graphics2D g2d=(Graphics2D)g;
        affineTransform = g2d.getTransform();
        g2d.rotate(Math.toRadians(rotation), x+spriteWidth/2, y+spriteHeight/2);
        g2d.drawImage(sprite_ship,x,y,M);
        rotation = 0;
    }
}

```

much thanks for any suggestions or if anyone can point out something I'm doing that's terribly misguided.

# Answer
> 1 votes
I ran a few tests and your ship drawing code is incorrect.

Currently you are rotating the whole Graphics2D because you get the AffineTransform from the Graphics2D.

You need to create a new AffineTransform for the ship or keep one as a variable in your ship class.

```
public void paint(Graphics2D g, Main M) {
    int spriteHeight = sprite_ship.getHeight(null);
    int spriteWidth = sprite_ship.getWidth(null);

    AffineTransform affineTransform = new AffineTransform();
    affineTransform.rotate(Math.toRadians(rotation), x + spriteWidth / 2, y
            + spriteHeight / 2);
    affineTransform.translate(x, y);

    g.drawImage(sprite_ship, affineTransform, M);
}

```

---
Tags: java, rotation, image
---


# Question
Title: Why does my Win32 call, contained in a class method, fail?
Using a Direct3D Tutorial, I took the knowledge and encapsulated it into a class. The code builds in MSVC 2010 fine, and I've handled all compiler warnings pertaining to my project with the highest warning levels. When stepping through the code from the entry point, the program fails to RegisterClassEx(&wc). After which, the program is told nicely to exit. Shortly after the unique\_ptr's destructor is run (not manually, but after the unique\_ptr goes out of scope), the program crashes w/invalid memory access.

My WinMain looks something like this:

```
std::unique_ptr<Engine> j_engine(new Engine);
j_engine->CreateD3DWindow(title, width, height, fullscreen); //public method of Engine, similar to CreateD3DWindow from the tutorial

while(message looping)
{
// etc
}

//if loop is exited, let j_engine fall out of scope (my program has never reached this point)

```

The start of my CreateD3DWindow method contains VERY standard window creation code, and does not even contain a shred of a Direct3D call prior to the crash (RegisterClassEx()).

It is essentially:

```
WNDCLASSEX wc;
hInstance = GetModuleHandle(NULL);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = "SomeName";

RegisterClassEx(&wc); // fails. GetLastError() == "Invalid Parameters". Stepping through WNDCLASSEX struct creation doesn't raise any invalid parameter flags.

```

I've also tried using ZeroMemory() after declaring WNDCLASSEX wc.

Two things register in my mind as I type this:
1. GetModuleHandle() is being called from inside the class, which exists on the heap and is referenced by a pointer from WinMain. Does this matter? Is it providing a valid handle?
2. WndProc declaration and definition is outside the class and outside the namespace of the class. Does this mean WNDCLASSEX.lpfnWndProc cannot see it? As such:

```
#includes

LRESULT CALLBACK WndProc()
{
}

namespace xyz
{
class Engine
{
}
}

```

I'm out of ideas and my problem solving capabilities are waning. Any advice? I will certainly provide more information if necessary.

Specifically, I'd like to know why RegisterClassEx() is failing.

Thank you!

\***Mentioned below that GetModuleHandle(NULL) will return a global handle for the given process, so the context of this call in this program should not matter.

# Answer
> 1 votes
From the looks of it you forgot to fill in the `cbSize` member of the `WNDCLASSEX` structure. Hence the API cannot determine what version of the structure you've got and hence returns the invalid parameter value.

# Answer
> 0 votes
You want to use `RegisterClassEx` with a `WNDCLASSEX`, I believe.

Also, `GetModuleHandle(NULL)` returns a process-global handle which will be valid for as long as your executable is loaded.

---
Tags: c++, windows
---


# Question
Title: How to hide a MMORPG backend server from the internet?
I want to create a network where the main servers IP is never exposed to the client. By going throught tunnels.

Here is a sample: http://dl.dropbox.com/u/12304631/eliteots/mc/network.jpg

## Problem

* By making tunnels through dedicated servers I hope to solve latency issues from some clients that are far away from the main server.
* But even if this does not succeed, I wish to hide my main server to avoid network attacks directly against it. So the main server only communicates with the tunnel hosts, which then communicates with the clients.

So by creating several tunnels I will be able to let customers easily access the main server by switching tunnel if their preferred tunnel is currently under attack. This is not my problem, should be easy to program, however the network configurations between tunnel and main server is the issue because of my lack of experience in this area.

## Requirements

* I am not talking about a simple http proxy, I want this to solution to operate on all ports. Or at least the configured ports. Only transmitting TCP.
* I do not wish any encryption on the traffic between the vpn and main server, I think it should be as fast as possible.
* I am working on an MMORPG, which is why I put so much effort into learning this. The worst thing that can happen to a customer is to be kicked from game server unable to login to finish their needs.
* I only operate in an linux environment server-based. (Debian/Ubuntu).

## Solution idea

I heard having an openVPN server might be what I need.

But I have problems operating it, I find it quite complex. First off, I want to know, is this even possible in OpenVPN? If so, how should I configure the network logics?

I am open to try out any free solutions you may find/recommend me!

# Answer
> 10 votes
Speaking as somebody who's been paid to do this.. In a standard MMO server network configuration, you have three main pieces:

**A point server**. This server has a public IP address, and contains nothing of value. When a client chooses to connect to the game, the first thing it does is query this server. This server provides the IP addresses (and ports, if relevant) for the available server proxies. This can be as simple as providing this data via a standard web server, if you like. In most point server implementations, the point server will do some geolocation on the requester and provide only the nearest proxy or proxies to that user. Additionally, most implementations will have the point server be in constant contact with all of those proxies to determine which ones are busy and which aren't, in an effort to balance user load between them. This server may have a static IP address, or may have a registered DNS name. **This is the only server which must maintain a single presence on the internet for the lifetime of the game; all others may be moved as desired.**

**One or more proxy servers**. These servers have two network cards: One network card has a public IP address, and faces the internet. One is on your private server farm LAN, and has an internal IP address which can't be reached by the internet. These are the "gateways" into the server farm, and ideally are widely spaced around the world, so all users will have at least one proxy near them. All outside traffic to the server farm must pass through one of these proxies. These proxies are responsible for authenticating that the end user is a real user, and (with the help of authentication servers inside the server farm) they perform login authentication. Once a user is authenticated satisfactorally, the proxy servers bundle together requests from that user with other requests from other users, and sends those bundled requests into the server farm to be handled.

**The server farm** itself. This may be one computer or many. All are on a private LAN which cannot be directly reached from the Internet. Batches of requests are received from various proxies, are split up into individual requests, and are handled by the servers in the farm. Any responses to those requests are batched up again and sent back to the originating proxies, which split up the responses and forward them out to the users.

The net effect is that your server isn't on the internet at all -- it cannot be directly reached because it has no public IP address allocated to it. This is the *only* sane way to handle a high-demand game server to keep it from being a target to DDOS and other attacks. Individual proxy servers can be attacked, but not the server itself, which is where your core data resides.

If necessary (when under attack or etc), you can move your proxy servers around, just update the data returned by the point server to point to the new locations of the proxy servers, and you're good to go; no server reboot or anything required.

And that's pretty much all there is to it!

# Answer
> 3 votes
It sounds like you just want a proxy and firewalls in front of your main server to cut down on mischief.

OpenVPN is not going to fix that, and not likely to ever decrease latency ;)

If you reduce the attack surface far enough, the attackers who are not very well-resourced will mostly become minor concerns- and you'll have bigger worries, like site perf and scaling....

# Answer
> 3 votes
Don't waste your time searching for solutions for this. Make your game, and make it work with a public server. THEN implement a solution to what you're asking for. You are wanting to build a house, but you're fixating on what the gate at the driveway is like.

# Answer
> 2 votes
Tunnels will Grow your latency, not reduce it.

Why don't you just use a frontend with failover IP:s ?

# Answer
> 0 votes
## Possible front end server solutions

OpenVPN will provide a complete protocol stack on top of the protocol stack that is already there. Therefore there is quite a bit of overhead.

If you just want to forward specific TCP ports, stunnel (with encryption) and rinetd (without encryption) are very easy to setup.

On linux, this can even be done directly in the kernel without user space applications using iptables.

## Core issues

As far as MMORPGs are concerned, I have the feeling that this whole approach might be focusing on the wrong end. For systems, that are accessed by masses of users, it is usually much more important to get the scalability on the backend server farm right.

While your approach may be able to handle stupid brute force denial of service attacks well, there are important short comings:

* If you redirect legitimate users away from a DoSed frontend server, any non trivial DoS will adapt to this redirection.
* Game actions go right through the forwarding (for example herds of bots destroying the in-game value of looted items).
* Exploits for bugs will go right through the forwarding (for example buffer overflows, integer overflows, quest logic errors, race conditions)
* Unless you move logic to the frontend servers and/or cache data on the frontend severs, latency will increase. You end up with the sum of the latency from the user to the frontend server and the latency from the frontend server to the backend.

# Answer
> 0 votes
As other answers have mentioned, using a VPN solution isn't the right choice here. Not only are you not going to solve your problem with it, you're going to make it worse. Here's why:

Tunnels are going to increase your latency, not lower it - you're not only adding some level of processing time, you're also forcing traffic to take a probably non-ideal route.

On top of that, they're not making anything any more secure. If your game client has the ability to get onto the VPN, then **anyone who has access to your game client has access to your VPN.** Attackers can again attack your server, but now they have two possible targets - the VPN servers or the game server. You still need to properly control access to the server on your VPN network as you would otherwise, with a firewall and probably a load balancer or other front-end.

This is possibly *the* most important rule in MMO development. *Never* trust the client. This isn't just for game design, and this question is a perfect example of why.

Instead, design your server architecture in a way that's both scalable and able to fail-over nicely. Commonly, this means having front-end servers (both in the sense of multiple machines, and multiple processes) that do nothing more than authenticate users and pass on or filter traffic; and having multiple actual game-running server machines/processes that can be respawned if they fail, or added to as more capacity is needed.

---
Tags: networking, server
---


# Question
Title: Any ideas on reducing lag in terrain generation?
Ok so here's the deal. I've written an isometric engine that generates terrain based on camera values using 2D perlin noise. I planned on doing 3D but first I need to work out the lag issues I'm having. I will try to explain how I am doing this so that maybe someone can spot where I am going wrong. I know it should not be this laggy.

There is the abstract class Block which right now just contains render(). BlockGrass, etc. extend this class and each has code in the render function to create a textured quad at the given position.

Then there is the class Chunk which has the function Generate() and setBlocksInArea(). Generate uses 2D perlin noise to make a height map and stores the heights in a 2D array. It stores the positions of each block it generates in blockarray\[x\]\[y\]\[z\]. The chunks are 8x8x128.

In the main game class there is a 3D array called blocksInArea. The blocks in this array are what gets rendered. When a chunk generates, it adds its blocks to this array at the correct index. It is like this so chunks can be saved to the hard drive (even though they aren't yet) but there can still be optimization with the rendering that you wouldn't have if you rendered each chunk separately.

Here's where the laggy part comes in:

When the camera moves to a new chunk, a row of chunks generates on the end of the axis that the camera moved on. But it still has to move the other chunks up/down in the blocksInArea (render) array. It does this by calculating the new position in the array and doing the Chunk.setBlocksInArea():

```
for(int x = 0; x < 8; x++){
     for(int y = 0; y < 8; y++){
         nx = x+(coordX - camCoordX)*8
         ny = y+(coordY - camCoordY)*8
         for(int z = 0; z < height[x][y]; z++){
             blockarray[x][y][z] = Game.blocksInArea[nx][ny][z];
          }
       }
}

```

My reasoning was that this would be much faster than doing the perlin noise all over again, but there are still little spikes of lag when you move in between chunks.

Edit: Would it be possible to create a 3 dimensional array list so that shifting of chunks within the array would not be neccessary?

# Answer
> 2 votes
Chunk your map - at least in the z,x dimensons (longitude and latitude NOT height) if it's an isometric game, make the chunks as big as can be fit on the screen at one time - and maintain the 9 chunks around the camera in memory.

build a structure for each chunk, be it an octree, or quad or whatever, but try to store it as a 1D array.

it should have methods along the lines of: generate(), load(), save()

only generate once - as the character moves around, cache chunks to the disk, as they're simple arrays, loading and saving them should be very efficient.

Try to steer clear of nested objects, building a huge array of objects isn't terribly efficient when you can do the same thing with a well ordered array.

If this is a minecraft style map, where there is depth to tiles, then a 3 dimensional dataset (converted into a 1D array) is ok, if you're just storing the height and type of tiles, you can do that in a single number using bitwise operators, with 128 levels, and 128 tiles your tile data can be stored in a single byte. Meaning your entire map can be stored as series of bytes.

# Answer
> 0 votes
It sounds like you're maintaining an array of blocks currently visible on screen, with indices based on the camera position. This requires you to shuffle things around the array whenever the camera moves. Instead, your array indices should be based on position in the world, and the drawing routine should loop through a range of indices based on the camera position. This way you do not need to copy anything around; when the camera moves you just index into a different spot in the array.

You can still load and unload chunks as the camera moves around, but this way when a chunk loads it always goes to the same spot in the array regardless of where the camera is. Parts of the world array that are off-screen may be empty, with no tiles loaded.

Also, why do you have 3D arrays of tiles instead of 2D arrays? And why is the height dimension 128? Maybe I'm misunderstanding how your system works, but terrain would typically only have one tile at each horizontal position. If you have 1 valid tile and 127 empty tiles in each column, you're wasting a lot of time and memory on the empty ones. If that's the case, you should get rid of the empty tiles - just store a 2D array of tiles and their heights (as integers).

# Answer
> 0 votes
Don't copy all the data; just collect the visible chunks and render each one. It sounds like you considered this:

> but there can still be optimization with the rendering that you wouldn't have if you rendered each chunk separately.

I think you are probably wrong here. Rendering chunks separately creates many opportunities for saving effort, and doing what you're doing has the cost of shifting large amounts of data around. Could you explain **what optimization you are trying to make possible**?

---

It sounds like you're writing a Minecraft-style engine (infinite random voxel terrain, height limit w/ terrain at halfway point, chunks). So am I: here's my code. My world is not infinite, but the rendering subsystem doesn't care about that — it breaks things into chunks itself and never looks at the entirety of the world (other than for fast indexing). Rendering chunks individually means that when a block is updated and needs to be rerendered, only the one chunk's geometry needs to be recalculated (for new hidden surface removal, etc.).

If I were to try to render the entire visible world together, I would have to rebuild the entire vertex array whenever the camera moved (at great expense) because the newly-visible terrain doesn't necessarily have the same number of vertices as the newly-hidden (opposite camera motion direction) terrain. Furthermore, per-frame I test each chunk's bounding box against the view frustum, which is a cheap test which greatly reduces the cost of the invisible parts of a complex scene.

(Note: I am working in JavaScript (and WebGL), so my work is somewhat more CPU-bound than yours probably is.)

---
Tags: java, isometric, terrain, terrain-rendering, voxels
---


# Question
Title: XNA Drawing Glitches (maybe Viewfrustum related?)
I'm drawing a simple Voxel world. When I naively render all the vertices, things look fine. But when I change my code to include a ViewFrustum check, I start getting strange visual glitches like this:

glitch http://www.phillipwei.com/game/glitch.png

The large square block is meant to be there; the strange triangles on the bottom left are not. These glitches appear all over the screen, and intermittently appear/vanish as I move my camera around. The draw code looks something like this:

```
basicEffect.World = Matrix.Identity;
basicEffect.View = Matrix.CreateLookAt(
    camera.Position,
    camera.Position + camera.GetForward(),
    camera.GetUp()
);
basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(
    camera.FieldOfView,
    camera.AspectRatio,
    1.0f,
    1000.0f
);

BoundingFrustum viewFrustum = new BoundingFrustum(basicEffect.View * basicEffect.Projection);

List<VertexPositionTexture> vertices = new List<VertexPositionTexture>();
foreach (Voxel voxel in voxelWorld.GetAllVoxels())
{
    if (viewFrustum.Intersects(voxel.Cube.BoundingBox))
    {
        vertices.AddRange(voxel.Cube.GetVertices());
    }
}

if (vertices.Count != 0)
{
    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Apply();
        using (VertexBuffer buffer = new VertexBuffer(
            graphicsDevice,
            VertexPositionTexture.VertexDeclaration,
            vertices.Count,
            BufferUsage.WriteOnly))
        {
            buffer.SetData(vertices.ToArray());
            graphicsDevice.SetVertexBuffer(buffer);
        }
        graphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, vertices.Count);
    }
}

```

So if I remove the viewFrustum.Intersects() check everything is fine. It seems unlikely to me that the viewFrustum check itself is causing the error, but I can't figure out where the problem is coming from. Any suggestions?

# Answer
> 2 votes
DrawPrimitives takes the triangle count, not the vertex count. You should pass verticies.Count / 3.

---
Tags: xna, frustum
---


# Question
Title: Making mouse pos realtive to a moving object
I'm coding my first actual game, trying without following tutorials, just trying to use my knowledge so far to make something playable. I'm creating (attempting) a simple side-scrolling shooter. I have a reticle drawn on screen that follows the mouse position, relative to where the player is. I.e. my update method for the reticle

```
mouse = Mouse.GetState();

reticlePostion.X = mouse.X + (player.position.X + (player.texture.Width /2));
reticlePostion.Y = mouse.Y + (player.position.Y + (player.texture.Height /2));

```

The only problem is that the windows cursor, ends up being about 300-400 pixels away from where the actual reticle is. What I'm trying to accomplish is a reticle that moves with the player (when the player jumps the reticle moves up with him in relative position), but still have it follow the mouse. I hope this makes sense, just lemme know if I need to post more.

# Answer
Is this for providing an aiming guide for your player? If that's the case, then I suppose you want to draw the reticle so that it remains at a fixed distance *around* the player, but always facing in the mouse's direction. Here's how I would do it, based on what you currently have:

```
// Distance to draw the reticle from the player
float distance = 100f;

// Calculate mouse and player position
Vector2 mousePosition = new Vector2(mouse.X, mouse.Y);
Vector2 playerCenter = player.position + new Vector2(player.texture.Width/2f, player.texture.Height/2f);

// Find direction from player to mouse
Vector2 direction = Vector2.Normalize(mousePosition - playerCenter);

// Calculate final reticle position
reticlePosition = playerCenter  + direction * distance;

```

Then just tweak the `distance` variable to your liking. And of course you can inline all of those calculations in a single line of code if you wanted. I just presented the steps separatedly so I could comment each of them, and for clarity.

If this is not what you meant, then I don't see how you can have an object that is following *both* the player and the mouse at the same time, unless it's always drawn half way between them or something similar. Or perhaps the reticle's X coordinate follows the mouse, while the reticle's Y coordinate is fixed relative to the player? That's another possibility.
> 4 votes

# Answer
Off the top of my head -

calculate the vector between the character and the mouse

normalize and multiply the vector to however far you want the reticle and use that point to draw it.

```
reticlePosition = Vector2.Normalize((mouse.x - player.x, mouse.y - player.y)) * 100

```

Or similar

You could also provide a subtle mouse cursor so the player can see where they've left the mouse.
> 0 votes

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


# Question
Title: In a component/entity system, what's the correct way to implement entity-specific components?
I'm trying to create a basic C/E game engine for Android, and I'm trying to re-create pong as a basic warm-up. I currently have a `EntityManager` class that contains a list of all the UUIDs for its Entities, and has a render() function that calls render() on all Components that implement `RenderableComponent` (a basic interface with a render() function itself), and the same for update().

Stop me if I'm already doing something incorrectly...

My question is, should I be creating specific components that only apply to each entity? (E.g. a `BallMovement`, `BallDraw`, etc. component for the ball) or what is the correct way to create components for Entities?

Thanks in advance! (:

# Answer
> 5 votes
No, I think your components should be as generic and reusable as possible. And the examples you gave certainly don't need specific components. Here's an *example* of the type of components you could be thinking about:

* **TransformComponent** \- Has as `Position` in the world.
* **SpriteComponent** \- Has a `Sprite` and renders it at TransformComponent.Position
* **MovableComponent** \- Has a `Velocity` and updates TransformComponent.Position
* **BoxComponent** \- Has a `Rectangle` and detects collisions with other BoxComponents

Then, all of these have *parameters* that will vary from entity to entity.

For example, and still thinking about the ball:

* The `TransformComponent` could store the ball's initial position
* The `SpriteComponent` could keep a reference to the ball sprite
* The `MovableComponent` could store the ball's initial velocity.
* The `BoxComponent` could store the ball size and have a special handler for its collision event

Then your paddles might also have *some* of these components, but they will probably have different initial parameters for each of them, and this is what will make them unique and different from the ball entity. A good component for them might be an `InputComponent` that handles user input and updates the `TransformComponent` when the player presses the up or down keys.

*PS: If you have never tried Unity3D, I think it's a good place to start wrapping your head around these concepts!*

---
Tags: java, android, architecture, component-based, entity-system
---


# Question
Title: Graphic hardware texture formats shaders relational speed
I'm interested to know, is there a direct correlation to the speed that a shader will run based on the bit depth of a texture upon which it is running. For example: If I have a 2 bit stencil texture and I'm accessing data from this, will the access time be 16 times \*'FASTER' than accessing the data in a 32 bit texture or is it primarily used for the memory saving capabilities.

\*\[SEE EDIT\]

# Answer
First of all, I think you meant to ask whether a 2-bit texture will be 16 times *faster* than a 32-bit texture, not slower.

The answer is: sometimes. Performance of graphics hardware is a complex topic. It is a concurrent, pipelined system that contains many different processes operating simultaneously and passing data to one another.

In general, the speed of the whole system is controlled by the speed of the slowest component. At different times and under different circumstances, different components may be the bottleneck. For instance, we often render triangles by running a vertex shader followed by a pixel shader. If the vertex shader is slower than the pixel shader, the speed of the whole rendering will be determined by how fast the vertices can be done, and we say the system is "vertex-bound" or "vertex-limited". Or if the pixel shader is slower, we say it's "pixel-bound", etc.

Within shaders we can also look at computation versus memory access. Sometimes a shader may be compute-bound, meaning it has enough math operations to hide the latency of memory reads (texture sampling) and writes (output to a render target). In other cases the shader may be bandwidth-bound, meaning that it needs to wait for memory access to complete, so memory bandwidth (how fast you can read and write memory) is the bottleneck. Within bandwidth-bound cases we can distinguish being bound by input bandwidth (texture bound), or by output bandwidth.

The texture-bound case is the one you're asking about. If a shader is texture-bound, then switching to a texture format twice as wide will make it render approximately half as fast. However, switching to a thinner texture format might not make it go much faster, if it moves the bottleneck somewhere else.

Conversely, if the shader is *not* texture-bound, switching to a thinner format will have no effect on the overall speed, since the bottleneck is somewhere else. But switching to a wider format might cause the shader to become texture-bound and slow it down.

In conclusion, there's no fixed relationship between texture format and rendering speed. Thinner texture formats will be no slower than wider ones, but they might not be faster either - it depends on details of the shader and the scene.
> 5 votes

---
Tags: opengl, textures, shaders, gpu, fragment-shader
---


# Question
Title: How to efficiently handle registration/anchor points for graphics?
I am currently working on an iPhone project, but most of my work has been in Flash. Flash has a feature where you can place a bitmap into a MovieClip, set its registration point with the mouse and it's automatically adopted. It's one of the lovelier Flash features.

Now I'm doing iPhone stuff, using TexturePacker for importing the graphics, and I'm having to write code like this:

```
if(graphic == "spikes1") setAnchorPoint(ccp(1, 0));
if(graphic == "spikes2") setAnchorPoint(ccp(.5f, 0));
if(graphic == "spikes3") setAnchorPoint(ccp(.5f, 0));
if(graphic == "spikes4") setAnchorPoint(ccp(.5f, 0));

if(graphic == "bush-a") setAnchorPoint(ccp(.5f, .25f));
if(graphic == "bush-b") setAnchorPoint(ccp(.5f, .25f));

if(graphic == "tree1") setAnchorPoint(ccp((float)134/209, (float)34/202));
if(graphic == "tree2") setAnchorPoint(ccp((float)96/236, (float)31/184));

```

I can obviously use macros or functions to shorten this a little, but is there a more intelligent way to go about this?

How do professional platformer games (on consoles and PC) handle this?

# Answer
> 2 votes
If you're referring about not having to hardcode all of of those anchor points, you could move them to an external file, and after loading all of the images, just read and iterate through your anchor file and set the values. The file could look like:

```
spikes1 1 0
spikes2 0.5 0
spikes3 0.5 0
spikes4 0.5 0
bush-a 0.5 0.25
bush-b 0.5 0.25

```

And for easier access, after loading the images you cold store them in some hashtable or dictionary using the name of the graphic as a key. Then to assign the anchor points it would be something like (in pseudocode because I'm not familiar with Objective-C):

```
foreach(entry in anchorFile)
{
    string[] data = entry.split(' ');
    string name = data[0];
    float x = parseFloat(data[1]);
    float y = parseFloat(data[2]);
    imageDictionary[name].setAnchorPoint(cpp(x, y));
}

```

To help you generate the file, you could also create a simple offline tool where you'd load all of your images, click once on each of them, and then it would generate the data file for you with all the anchor points recorded. Should be fairly trivial to implement.

# Answer
> 0 votes
While you could create some meta-data file that contains the anchor points for all your sprites, you should generally avoid having different anchor points for different sprites.

There are some reasons for this:

* You might create a collision shape in another editor, after changing the anchor-point, the shape will suddenly no longer match the sprite.
* Maybe you use a level-editor that doesn't support anchor-point offsets. So while your level looks fine in the editor, it will no longer work in your game (where you use offsets).

Things like this can cause strange issues that can become hard to debug. I strongly suggest you don't alter the anchor points at all, unless there's a very good reason to do so.

# Answer
> 0 votes
Usually artists manage their assets folder where they create their graphics in .psd format or something else with layers. By convention a specific layer named *anchor* is created which contains a single opaque pixel (other pixels are ignored), and the artists define that pixel as the rotation point for the sprite. Then, in your conversion process from .psd to your own formats you split the layers and convert the coordinate to a text file which you can later load like David Gouveia mentioned.

If you are dealing with a layer-less art pipeline, you can then use the convention of storing several files for the same graphic, like `sprite1.png` and `sprite1_anchor.png`, where the anchor point has already been split by the artist into a separate graphic. This puts pressure on the artists to remember to update the anchor files, though anchors don't tend to change that much.

---
Tags: 2d, iphone, graphics
---


# Question
Title: Creating lots of sprites dynamically in libgdx
I´m creating Groups that contains Sprites and adding bodies with box2D, but when I create many of this my animation gets very slow. How can I handle it?

# Answer
> 2 votes
Have a look at this if you're using spritebatch http://code.google.com/p/libgdx/wiki/SpriteBatch#Performance\_tuning

And also if your bodies are static terrain and don't animate, then you should be using SpriteCache. Ex. you are building tile based terrain

---
Tags: sprites, box2d, libgdx
---


title: Starting off in game development

text:
# Question
Title: Starting off in game development
Recently I acquired a myriad of free time and have decided that I want to learn how to program. My question is what language should a newbie start off in? I understand that each language has its own pros and cons, but were could someone who is interested in making games start off?

# Answer
Many choose to start with a simpler managed language such as C# or Java. If you really seriously want to go into large-scale 3d games you will almost certainly need to learn C++, but this is a difficult language and has a high learning curve.

The good thing about C# and Java is that they share a mostly C style syntax, so you can become more familiar with the syntax in a more forgiving environment for things such as memory management. If you choose C#, I have found Microsoft's XNA an excellent learning tool for beginners.
> 2 votes

# Answer
Each language has it's ups and downs, I'd probably suggest you grab something like Unity3D where you'll still have to program, but you're going to see something much faster, as it worries about all the tedious stuff like drawing polygons, input and asset management.

When picking a language in Unity, I'd go for Javascript, it's easy, seems to be the most prominent in the community, and there's lots of people who understand it.

My personal preference was Boo (a python derivative) next to no one used it so support was pretty much my own work.
> 0 votes

---
Tags: game-design
---


title: I have to make a game in 9 days. AHHH!

text:
# Question
Title: I have to make a game in 9 days. AHHH!
If you just want to get to the question and skip the background, go to the next paragraph if not, keep reading. O.k., so, I'm 13 and I make games in my spare time. They've never really been shared with anyone or anything so I decided I would enter the STEM Video Game Challenge for middle schoolers. I decided to use Stencyl to make the game and it was January so I figured I would work on it at some point. After that I joined a play at my school which takes up a ton of my time and today I realized its March 3rd which means I have 9 days to make a game-gah!

So, I have to make a game in 9 days and I'm probably going to use stencylworks. I just need an idea that I could execute in 9 days and just general tips for efficient game development. Sorry that this is kind of a loose question and thanks in advance!

# Answer
> 49 votes
9 days? No sweat, man! I've made over a dozen games in one week each, with a 48-hour limit a few times.

So, here's what you've got to know.

First off, you need an idea. Now, you might think that the best way to get an idea is to *not* restrict yourself. Oddly, you'd be wrong. Humans seem to be better off exploring ideas within the confines of a stricter concept.

That means we need some concepts. Luckily, there are tons of concepts available for easy pickings. Here, for example, are a ton of historical concepts from the Experimental Gameplay Project (which I highly recommend taking on, by the way.)

Pick one. I recommend picking the most recent one. Tada, you're making a game about economy. What does that mean? I dunno! That's where it's up to you. Maybe that's a business sim. Maybe it's about recycling. Maybe it's about making careful use of resources. You've got a word - "economy" - and now it's up to you to make a game.

Write down a bunch of ideas. Throw out the bad ones. Pick the idea you're most interested in. Start writing code.

Now, keep in mind this is going to be a bit of a crapshoot. It's possible you'll pick a brilliant idea. It's possible you'll get seven days in and say "well, that idea was pretty crummy actually". If the latter happens, *finish the game anyway* and chalk it off as a learning experience.

Now, how do you make a game in nine days?

First: ruthless cutting of features. You don't need a title screen. You don't need an escape menu. You don't need good art or good music. If you get in five days and your game is done, yeah, sure, go back and flesh things out, but for now your goal is to get your gameplay working. Sit down and work until your basic gameplay exists. Then work until it's done. Don't waste time on finicky details, don't worry about making things look perfect. If you find a bug, think about whether it's worth fixing or not. If your character has a graphics glitch when he fires a gun, congratulations, you've just invented a weird kind of muzzle flash. If you're designing a clock and the face looks wrong, awesome, you've got a weird art deco clock. KEEP WORKING ON THE IMPORTANT THINGS.

Second: get rid of distractions. Yeah, I know you want to read Reddit. Don't do that. Stop reading Reddit. I've found that streaming my development as a video keeps me on-track - if I get distracted, *everyone will know* \- but you probably don't want to set that up right now, you've got a game to write.

Third: Keep a list of goals. Again, cull it ruthlessly. Anytime you find yourself unsure of what to do next, that means you need to consult your list. If your list doesn't tell you, that means you need to *improve* your list.

Fourth: Make sure everything is worth the time. Yeah, you could download a good sound design package and spend five days learning how to make good sound effects. NOPE. You'll have time for that once the competition is done! Grab SFXR. You have five minutes per sound effect. GO. Are you an awesome artist? Can you make a great character sprite in a day? NOPE. Your main character is a square, your enemies are triangles. GO.

Good luck! This kind of a challenge is very difficult but it's also incredibly rewarding. If you really want to get into the games industry, I can promise you that releasing twelve games, one every month, looks *miles* better on a resume than a four-year college diploma.

As an example, here are a bunch of games I made under similar constraints. Yours probably won't be that developed - you just don't have the time or the experience - but it's certainly doable.

Are you playing those games?

STOP. GET TO WORK. YOU DON'T HAVE TIME TO PLAY GAMES. GO GO GO

# Answer
> 4 votes
if you need ideas you can look at boardgames, most of them have an easy rules and there are easy to copy. you can make an 2dplattformer like the mario games or an simple puzzle game. be sure you make it simple, you need time for graphics and tweaking everything.

---
Tags: game-design
---


# Question
Title: How to make leg bones children of torso bone in Blender?
I'm a complete Blender novice and I'm trying to create a humanoid skeleton. I'm having problems figuring out how to make my leg bones children of the torso bone. Here's how my skeleton looks like:

As you can see from the bone hierarchy, the legs are not children of the torso. This is because I extruded them from the lower part of the torso bone. Is there any way I can fix this?

Also, on another note, would this be a good skeleton for 2D animations?

# Answer
> 3 votes
Just parent them to the "Torso" (using `Ctrl P` and keep the offset).

It doesn't look like a very flexible skeleton, especially the rotation on the leg bones is bad (they are twisted) .. that's something you should definitely avoid. Other than that, it really depends on the type of animation you want to do. You could also search the web for some human-rigs or tutorials, that might give you some inspiration.

# Answer
> 3 votes
**The bummzack's answer is right and technically the good one.**

But I will add this answer to encourage you and anybody else to try changing your point of view every time you encounter a problem. Too much often, peoples (including me indeed) doesn't step back (in their mind ^^) to have a better view of the problem.

Here is a very simple example; if you can't link the legs to the torso because you can't (in fact you can as Bummzack said) or don't know how to link them, step back and try step forward another way: can you construct you model from another bone?

I don't know if you tried, but obviously yes you can if you start from the head.

This skeleton isn't perfect nor it does necessary fits your animations needs (I didn't rotated bones the right way etc...) but that's just a bone linking example and I'm a Blender Rookie too, so I might be wrong. But the important idea is that we need to try others perspective when encountering a problem.

---
Tags: 2d, blender, skeletal-animation
---


# Question
Title: Why does my game not update unless I'm moving the mouse?
I'm pretty confused by what's happening. Now that I've finally put something moving on my screen, I notice it doesn't update unless I move the mouse, or press a key, or trigger other events.

Using PIX, the "Frame: #" counter only goes up when I fire these events. This is all that happens in my game loop:

```
while(GetMessage(&msg, NULL, 0, 0) > 0 && m_isRunning)
{
        TranslateMessage(&msg);
        DispatchMessage(&msg);

        m_gameGraphics->BeginRender();
        m_gameGraphics->EndRender();
}

```

BeginRender clears the screen, and EndRender presents to the swap chain. I thought maybe it was a problem with WndProc, but comparing it to other DirectX 11 game WndProcs, I don't see any major differences. I'm pretty confused, never seen this problem before, and I have no idea what causes it. I'm just hoping maybe someone will have some insight on why this might be happening.

# Answer
Actually that "while loop" that you wrote there is the source of your problem. GetMessage puts your application to sleep until a message arrives. This is good for GUI applications but obviously is not good for games.

The right way of doing the game loop is using PeekMessage instead so that your application is not put to sleep and can just keep spinning.

Here is the loop that you can see in DXUT and in most DirectX samples:

```
while( WM_QUIT != msg.message )
{
    // Use PeekMessage() so we can use idle time to render the scene.
    bGotMsg = ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0 );

    if( bGotMsg )
    {
        // Translate and dispatch the message
        if( hAccel == NULL || hWnd == NULL ||
            0 == TranslateAccelerator( hWnd, hAccel, &msg ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
    }
    else
    {
        // Render a frame during idle time (no messages are waiting)
        DXUTRender3DEnvironment();
    }
}

```

Here is a link that explains it in more detail.
> 9 votes

---
Tags: directx11, winapi
---


# Question
Title: Game 30% done on HTML5. Maybe it was a bad idea. Should I change to Unity3d?
I'm creating a 3d game on HTML5. It's 30% complete and the hard part is already coded. The server is on node.js.Now I'm realizing that maybe it was not a wise choice. This is because I realized:

1. Three.js still has many bugs. I don't see the same thing on every machine. Each browser, OS, can give different results. I'm afraid my clients will have a great stress installing my game properly.
2. I have tons of sprites and models on my game. I wonder if my clients will have to load all them again everytime they want to play?
3. I wonder if a Node.js server will be fast enough to handle it, and I'm afraid it won't be scalable.

What would you advise me? Should I continue and finish the game on HTML5 or is it better to remake it on something else, like Unity3d for the client and (what?) for the server?

# Answer
> 5 votes
#1: I can't comment on Three.js as I haven't used it. Two thoughts: (a) A lot of the variation is going to be due to graphics hardware. There are certain things you should avoid doing to be consistent across GPUs, which will be the case no matter *what* 3D engine you use. (b) You can always use raw WebGL instead of any framework, which will get you better performance (due to reduction in abstraction) and might help you detect and work around inconsistencies.

#2 should not be a problem as long as your sprite and model resources are served with proper caching information — make sure your web server is configured appropriately. Check your server logs and your browser's request inspector, and perhaps use RED.

#3: Using HTML5 etc. on the client side does not mean your server has to be in JavaScript. Interoperation is part of the whole idea of the Web. (If you're shoving JSON around, well, there are libraries for that everywhere, not just in JavaScript.) Choose the best platform for the client, and for the server, independently.

---
Tags: unity, html5
---


title: Implementing Power-Ups in a game

text:
# Question
Title: Implementing Power-Ups in a game
I'm making an Arkanoid or Brick Breaker game, but I got confused when I wanted to implement power-ups. The idea is that when you destroy a brick, a powerup-block falls down, and if you catch it you'll get the powerup. -for example:

* Wider Paddle (change dimensions of the quad)
* Change ball speed (variable)
* Ball goes through blocks (no reflection on hittest)
* Shoot lasers from the paddle (change in input handling)

Now I pretty much know how to affect the code to achieve these effects, however not in a clean, flexible way. I have my ie my ball and paddle hard-coded in java (GameObjects), and my Levels/BlockTypes in xml.

One terrible way to do it is to have like a flag telling which powerup is active, and by that alter the code with loads of if- statements.

Could anyone help me with how this is done?

# Answer
The simplest solution I can think of to solve this problem would be to add accessors to whatever objects you would to be modified by power ups. For instance, your paddle would be an instance of the `paddle` class and have the accessors:

```
public void setPaddleWidth(int aWidth);
public int paddleWidth();

```

The accessors would define the public interface that your power ups will have access to. To your power ups class, you would have this method:

```
public void pickedUp(Paddle targetPaddle);

```

However you go about detecting that a power up is picked up, you call that instance method on the appropriate power up. The purpose is to put your effects code in that method; so a power up that doubles the width of the paddle would have this in its pickedUp method:

```
targetPaddle.setPaddleWidth(targetPaddle.paddleWidth() * 2.0);

```

If the effects of the power up are loaded from an XML or other data file, instead of being hardcoded to the power up, you can do this (psuedocode):

```
/* Data File Example */
<powerup>
    <name>Double Paddle Width</name>
    <effect>
        <target>PaddleWidth</target>
        <value>2.0</value>
        <operator>*</operator>
    </effect>
</powerup>

public void loadFromFile(String aFilePath)
{
    /* Do whatever you need to load your data here;
    assume we store the list of effects loaded in an instance variable
    PowerUpEffects */
}

public void pickedUp(Paddle targetPaddle)
{
    for (Effect anEffect : PowerUpEffects)
    {
        /* Modify targetPaddle based off the effect
        name, value and operator. In this case, we would change
        the paddle width, by multiplying by a value of 2.0 */
    }
}

```
> 3 votes

# Answer
I implemented sth similar for an open source MORPG, where we needed infrastructure to make any attribute of players or creatures temporary modifiable, while avoiding to persist the actual modified value to the database.

The basic idea, we had in mind, was to store the modifying values in objects that are separate from the actual modified objects. For instance a player that gets a health points (HP) boost would get added a Modifier-object that tells on HP-calculation on how much to adjust the HP (i.e. HP raises by 50%).

Out of this we came to the following class structure: class diagram of draft for modifiers

The yellow classes denote the actual game entity hierarchy. In blue we have the full infrastructure for handling the modifiers. (You can ignore the TurnNotifier)

The ModifierHandler classes and the AttributeModifier help with managing those modifying objects. The Handler is delegated to whenever a possibly modified attribute's actual value is needed and the handler then calculates the actual value based on the "normal" value and the modifiers that are known to him.
> 2 votes

---
Tags: game-design, architecture
---


# Question
Title: Scripting language with class instance support
I have come across the need to use a scripting engine for my C++ game, but after experimenting with many languages since the last few days, nothing has truly stood out as the obvious choice for a language and/or binding library.

I would like have the ability to

1. call methods of a specific Game instance from within the scripting language,
2. call arbitrary functions in the scripts from C++, and
3. test for function existence in the scripts using strings.

Lua looks nice, but I'm unsure of its ability to do 1 and 3. Python and Boost::Python are great, but the same applies. Regardless, here's an example of an ideal implementation.

**C++**

```
class Game
{
    ...
    void printNumber(int arg);
};

int main( )
{
    Game *game = new Game();

    // Make method available to script
    functionRegister("printNumber", game->printNumber);

    // Test and call function in script
    if ( functionExists("greet") )
        functionCall("greet", "Hello world");
}

```

**Script pseudocode**

```
function greet( greeting )
    print( greeting )
    game.printNumber( 42 )
end

```

The output may be

```
Hello world
42

```

Is there a language and library that will pull this off?

# Answer
> 6 votes
I'm fairly sure Lua can do everything you need relatively simply. I use Lua and C++ in my game. I looked at various wrappers like LuaBind, or using a generator like Swig, but I decided I didn't want any of that stuff and I wrote my own wrapper which I ended up making open source in case other people found it useful.

Using my little library you can do stuff like this in C++:

```
// Wrap a C++ function
static int Widget_AddChild(lua_State* L)
{
    // Typesafe way to extract userdata from Lua
    Widget* parent = luaW_check<Widget>(L, 1);
    Widget* child = luaW_check<Widget>(L, 2);
    lua_pushboolean(L, parent->AddChild(child));
}

static luaL_reg Widget_Metatable[] =
{
    // Register the function you wrote above
    { "AddChild", Widget_AddChild },

    // Widgets also have some getter and setter functions,
    // Using these templates you can automatically generate
    // wrapper functions for them
    { "GetStyle", luaU_get<Widget, Style, &Widget::GetStyle> },
    { "SetStyle", luaU_set<Widget, Style, &Widget::SetStyle> },
    { "Style", luaU_getset<Widget, Style, &Widget::GetStyle, &Widget::SetStyle> },

    { NULL, NULL }
};

int luaopen_Widget(lua_State* L)
{
    luaW_register<Widget>(L, "Widget", NULL, Widget_Metatable);
    return 1;
}

```

In lua you could now do something like this:

```
local w = Widget.new()
w.foo = 10 -- Foo is stored on w, it's not accessible to other instances
-- You can also add values accessible to all Widgets
function Widget.metatable:newfunction()
    print(self:GetWidth())
end
w:newfunction()

```

With all that, you can fairly easily call C++ function from Lua (and vice versa, but I didn't illustrate that here). Once you know how to interact with the Lua API, writing a function to 'safely' call (i.e. call a function only if it exists) a Lua function should be easy as well.

Edit:

If you want to check for the existence of a function before calling it, like I said, just check that the value is a function before calling it.

```
lua_getglobal(L, "myFunc"); // You can get your function from anywhere, this is just for example
if (lua_isfunction(L, -1)) // Check the top of the stack, make sure it's a function
{
    lua_call(L, 0, 0);
}

```

# Answer
> 2 votes
Personally, I am a fan of AngelScript.

It does exactly the things you want, it has a close to C++ syntax.

You can easily create different scripting contexts, and for some types of scripts, have functionality x, for others, y. For example if you want to have a game loop in a script, and AI specific functions in other, while hiding the other one's API.

You can call functions by their name, you can export global functions and class members easily. You can define global properties as well.

So you could basically configure your script to know a Game object, which is your actual Game instance. Then call functions exported on it.

Its really straightforward, but if you want I can add little snippets of how it could be done. Though, we re talking about 1-line setups !

---
Tags: scripting
---


# Question
Title: How to get started in Java Game Programming?
As I try to program a game, I can't do virtually anything(because I really don't know what do do although I know the basics in Java), except if I look at tutorials. I'd like to ask you, professional game programmers, how to actually learn game development without reading tutorials because those don't really teach a lot. Thanks.

# Answer
> 2 votes
First great step is to finish learning Java. You want to know more than just basics. After that (or while you're learning) you should get around to coding your first easy game like Tetris, Breakout or Pong. Don't look for more information about how to do it, these games are recommended for a reason, they're easy to program (relatively speaking) and you should be able to code them yourself.

You probably want to read this.

After that, there are general resource sites availible.

And books like **Game Engine Architecture** by Jason Gregory. Most books about making games deal in C++. But if you can code in Java, you'll be able to take most out of them anyway.

---
Tags: java
---


# Question
Title: Translating local to global coordinates in ARToolkit / OpenGL
Ok, so I've tried reading over the other questions and something's just not clicking for me. I am working on an augmented reality application using ARToolkit, however it should just be straight OpenGL matrix math.

So, one of my fiducial markers is considered to be my global coordinate base. So I have an x,y,z that I pull out of the ARToolkit transform matrix (this would be something like trans\[0\]\[3\], trans\[1\]\[3\], trans\[2\]\[3\]). I am feeding that into a glTranslated() call in order to move my objects around, relative to the origin.

Now, when I use another marker, those are recognized with their own local coordinates. I need to transform them into the coordinates of the original marker, and that is where I'm having issues. I can pull out the x,y,z coordinates easy enough, but taking that relative to the origin is my issue.

So my understanding was that I could somehow create my global coordinates, take the inverse, multiply those by the new coordinates, and that would give me the coordinates of the new object relative to the origin. I think my issue is in figuring out how to add those in properly to a matrix, since I'm dealing with x,y,z coords separately.

Any help would be appreciated...I'm doing this all in C as well, so no nifty STL functionality for me.

# Answer
A small correction first.

x, y and z translation in a 4x4 OpenGL matrix is not

```
trans[0][3], trans[1][3], trans[2][3]

```

but

```
trans[3][0], trans[3][1], trans[3][2]

```

since OpenGL matrices are in column-major form, the translation being in the last column.

This code-snippet demonstrates it:

```
    glLoadIdentity();
    glTranslatef(1.0, 2.0, 3.0);
    float m[4][4];
    glGetFloatv(GL_MODELVIEW_MATRIX, (float*)m);
    printf("%3.1f, %3.1f, %3.1f\n", m[3][0], m[3][1], m[3][2]);

```

The output is: 1.0, 2.0, 3.0

---

Now here is the answer to your question. Let

```
  mA be the transformation matrix of marker A
  mB be the transformation matrix of marker B
  mA^-1 be the inverse matrix of mA

```

Now to get the matrix that transforms mB-space into mA-space -\> `m = mA^-1 * mB`

`m[3][0]` and `m[3][1]` and `m[3][2]` will be the position of marker B in the local space of marker A

Btw. you dont need to pull out x, y and z to pass it to glTranslated, just upload the entire matrix using glMultMatrixd, in order to not only apply the position but also the correct orientation.
> 2 votes

---
Tags: opengl, matrix, c, artoolkit, transformation
---


title: Collision Detection Result Theory?

text:
# Question
Title: Collision Detection Result Theory?
To be clear because the title is slightly ambiguous: I understand that to check for collision detection it's (box.x \> otherBox.x && box.x \< otherBox.x + otherBox.w) etc.

However I'm curious about things to do after this, how can I sort of keep the player from entering the other object that they're supposedly colliding with without fully stopping them and therefore suspending them from movement?

# Answer
You would only restrict movement in that direction. In other words, let the player move left only he has not collided with a wall to his left. Let him move right only if there is no wall to his right. This way, if there is a wall on one side, the player can still back away.

You would do this by checking multiple collision points, so instead of box.x, you would check both `box.x+(box.width/2)` `and box.x-(box.width/2)`.
> 2 votes

---
Tags: collision-detection
---


# Question
Title: Box2D + Love2D (Lua) - Assertion fail with polygon meshes
When I try to create a triangle collider for my game it sometimes leads to an assertion fail. I use the physics engine that comes with love2d (Box2D). That's the error message that appears when the assertion fails:

```
love: modules/physics/box2d/Source/Collision/Shapes/b2PolygonShape.cpp:85: b2Vec2 ComputeCentroid(const b2Vec2*, int32): Assertion `area > 1.19209289550781250000e-7F' failed.

```

Here's an example of a triangle that doesn't cause the error (represented by a table with 3 points): {{258,451},{740,767},{284,597}}

And this one leads to a crash: {{258,450},{222,569},{306,723}}

The bodies of both shapes lie at {0, 0} (upper-left corner of the screen)

Does anyone know a possible reason and/or solution for the problem?

Edit: I'm not allowed to answer my question right now for some reason so I'll post the answer here before I've forgotten it: In Box2D, the order of placement of vertices seems to play an important role, since I was able to avoid the crash with the "problematic" triangle in my example from my question just by placing the first vertex between the second and the third one. Maybe I'll repost the answer when I'm able to provide more information (and am also allowed to do so)

# Answer
> 3 votes
You have to create polygons with a counter clockwise winding in box2d. Have a look at the box2d manual, section 4.4 http://www.box2d.org/manual.html#\_Toc258082970

---
Tags: physics, box2d, lua, love2d
---


# Question
Title: Ensure house map maze with lifts can be solved?
In my game we see the floors of a house from the side, and the hero can take lifts -- a lift either goes up (to the next lift upwards), or down (to the next lift downwards), depending on the arrow as shown, and there's always a pair of exactly two lifts connected. That's the only way the hero can move vertically, though he can freely move horizontally. The house map is a randomized 11x5 grid with different items, and unpassable walls to the far left, far right, and sometimes in one of the two middle positions:

My question: How can I ensure the map is always randomized yet always solvable and that the hero, starting at the left side of the bottom floor, can always leave it via any upwards-pointing lift at the top floor?

For what it's worth I'm using the Lua language for development. Thanks so much!

# Answer
> 14 votes
What you want to do is create a Graph such that every node is an elevator position, and the edges between them means you can walk/lift there. Once you made the graph you can use dfs/bfs to see if you can get from the start node to the end node.

Using you example above I made a picture of how the graph would look like. Green circles means there is an elevator there, and the green lines means you can travel from node to node.

# Answer
> 5 votes
The difference between what you have and a normal maze is simply that it has non-adjacent connections vertically. I think that what you should be looking at are **graph-based maze generation algorithms**. You simply need to have a larger set of "adjacent rooms" or "possible walls" than an ordinary 2D maze does, in that *every vertically aligned pair of floor-grid-cells which does not already have an intervening lift* is adjacent. You could model this as a graph where adding definite lift edges incidentally deletes other possible lift edges; some algorithms might be confused by this, but not others.

---
Tags: 2d, maze
---


# Question
Title: Where to start for implementing vehicle physics?
A little background for myself. I am relatively experienced with 3rd part physics engines such as Havok, Box2D, Bullet and have successfully integrated them in custom engine(s). I have also made a simple physics engine by following a few known books.

Now I am interested in diving into vehicle physics. There are a couple of books that skim over the topic but do not go over in enough detail for me to grasp anything useful. So I would like to know of good books/resources that are not too heavy (by that I mean a book that is pure vehicles and made for engineers rather than game developers) that help me get started on vehicle physics. Here `get started` = at least guide me through creating a simple vehicle in 3D with modern features found in most games (suspension/transmission etc.)

**Note:** I searched for a similar question but did not find one, but if one exists, please post the link and feel free to close the question.

# Answer
> 9 votes
This blog has four links (the third is broken), the first of which seems like an amazing resource, the others seem pretty great too. I'm probably going to read over this just for funsies, should be a good read.

You could take a look at the Rigs of Rods engine, it's an open source soft-body vehicule simulator, it may give you some insight into how it's done, but could be too complex for what you want to do. Also, reading though other people's code may not be what you want to do; nevertheless it could be inspiring.

Digital Rune gives some simple info on their implementation of car physics.

# Answer
> 4 votes
If you want to just get something reasonable going, I can't more heartily recommend the talk by the physics programmer on rallycross. (a shipped game on the PS1 back in 1997, so it's very quick on modern hardware and arguably implementable in higher-level languages that aren't as efficient at math as they could be).

# Answer
> 2 votes
I know this is an old question, but if I stumbled upon it so might others.

While it is a walkthrough for getting a car setup in the Unity3D engine, this tutorial goes through a lot of what is necessary and the concepts should be transferable enough.

http://unity3d.com/support/resources/tutorials/car-tutorial.html

---
Tags: physics, books, racing
---


# Question
Title: What AI technique should I use to control a car in a bumpy environment?
What kind of AI can you recommend controlling a car in a level where there are hills, sharp turns, straight parts, et cetera?

There is AI in the game already. It uses points on the road to which the car accelerates and when it gets closer, the next points is taken. These points are predefined. The problem is AI-controlled car are not fast enough compared to a human controlled car. The difference is about 14 seconds, so what methods can you recommend to speed up cars?

Increasing just maximum speed of the cars does not help, because then, they do not take turns fast enough. Do you know a solution for this? Do you know a resource where this problem is looked at and solved?

# Answer
> 3 votes
You want to look into steering behavious. So that, rather than following points, the AI sees the track and the other cars on it and drives itself based on the information. The site I linked above is a great resource for information and examples.

You might want to check out OpenSteer, a C++ library developed by same author.

There's a C# version too if you're using that: OpenSteerDotNet

That should get you started. If you build and open the OpenSteer demo application (in C++, not sure about .Net), there's a example that shows a car navigating through a path by using... I guess you could call them "feelers." Basically, it has about 10 parallel lines come from the front of the car and are about 3 or 4 times the length of the car. The lines represent the path that the car will travel and can curve if the car is turning. If these lines hit something, the car knows there's something in it's path and it steers in such a way that it will miss it. There's another version that just uses a simple rectangle in front of the car, but it's not as robust as the lines.

Here's an image of what I'm describing:

# Answer
> 1 votes
You can make the AI-controlled cars turn faster, you make the computer slow down while turning and speed up while going in a straight line. Don't be afraid to make the AI cheat, as long as the player doesn't notice.

---
Tags: game-design, physics, ai
---


title: What's the best head-bob formula?

text:
# Question
Title: What's the best head-bob formula?
Given a point in space, a direction of travel, and a time since start, what's a convincing, non-sickening formula to simulate head bob? What's been successful in previous games? Has there been any research on what bobs induce sickness the least?

An example naive head bob formula, applied to the up axis:

http://www.wolframalpha.com/input/?i=abs%28sin%28x%29%29

# Answer
Gah! Don't change pitch. At all. Unless you want the player to feel like they're playing a drunk, and fighting the camera. Your focal point is set by the player's control, don't change it.

I'm not even sure it warrants a 'formula' - I think you'd be better served with some predictably random motion. Look into low frequency Perlin noise to generation your offset curves. Any simple formula you can think of will be predictable enough that it defeats the whole point of the bob - to give the impression that the avatar isn't moving in an artificial way. You can combine trig functions to get a pseudo-random smoothed curve, but you're far better off using Perlin noise which is perfect for this sort of work.

I'm not aware of any research on 'good' head bobbing, but I'd say if you're going to do it, you need to do some serious cold testing and iteration. You (the implementer) are not in a good position to judge the effectiveness of your implementation, because very quickly after you start, you'll become hyper-sensitised to the amount and manner of the bob. What others might find good, you'll obsess over and reject.

Most of all, keep the motion subtle. The temptation when implementing is to crank up the 'bob' factor until it's noticeable, because you want to see it taking effect. That's no good. Ideally the player doesn't even notice the bobbing - if you ask them after the testing whether they noticed their viewpoint bobbing when they ran, I think they should say no. The purpose of a bobbing motion in the viewpoint is to make the motion feel natural, so that you don't feel like you're sliding around as a camera on top of a wheeled dolly. The player's hind-brain will pick up on the artificial nature of a naive implementation, but it only takes small subtle variations from that to fool the perception.
> 20 votes

# Answer
There are many causes of nausea. Here are the environmental factors to consider:

1. The larger the screen, the more likely to cause nausea.
2. The closer the user is sitting to the screen, the more likely to cause nausea.
3. The darker the room, the more likely to cause nausea.
4. Third-party viewers -- non-interactive passengers -- are more likely to experience nausea than someone who has some form of control over the game.
5. A slightly skewed viewing position will typically cause more nausea than a straight-on viewing position or a sharply skewed viewing position. (This typically interacts with #4, above, making things even worse for non-interactive viewers)

(You normally don't have control over these environmental factors, unless you're making a gaming installation. In which case, you absolutely should be considering them.)

Remember that nausea is caused by a disagreement between what's being seen by the eyes and what's being experienced by your body's internal motion sensors in the inner ears; the more context that your brain gets that motion being seen by the eyes is not an actual motion (say, by being in a well-lit room with plenty of stationary objects visible behind the screen), the less nausea will be experienced.

In terms of the camera behaviour itself, any sort of automatic rhythmic motion can easily cause nausea. Rotations are worst (particularly tilting), but even rhythmic translations from side to side or up and down will cause nausea for many (but not all!) players.

For this reason, if you use camera bob, it's important to always include an option to disable it. Otherwise, many players will be unable to play your game for more than a few minutes at a time.

As a rule of thumb, the slower the cycle and the smaller the motion of the camera along that cycle, the less nausea will be caused for the players who are susceptible to it.

Additionally, sudden changes in velocity are **particularly bad** for nausea; any rhythmic motion you choose to use should be smooth through its whole arc, rather than 'bouncing' along any axis, the way that your example graph does.

It's also worth noting that most players do not have nausea responses immediately; those responses build up over a few minutes duration. Some games therefore only perform these sorts of camera movements periodically; for example, when the player is performing a duration-limited "sprint" move, rather than all the time when the player is running normally. It's still probably important to allow those who are susceptible to nausea to disable the effect entirely, but more users will be able to tolerate the effect if it's infrequent than if it's constant.
> 8 votes

# Answer
I'll just drop two additional ideas to the table.

First of all, have you ever seen Mirror's Edge first person camera in action? See this link if you haven't. I'm not sure about pitch, but there's quite a bit of *roll* changes taking place, and I think it looks very dynamic and fresh. So that's just a possibility for you to consider incorporating in your formula too, if you like the feel it gives.

Another idea which I don't know if any game uses, is to take a simplified animated 3D model of a character walking, and even if you won't be rendering, you can still gather head position information from it, or even attach your camera to the head's bone. And if the character has eye movement independent from his head, you could even incorporate *both*. I don't know how that would look in action, but I figure it should behave very realistically. But there's also a chance it could look extremely sickening too :-)
> 5 votes

# Answer
The human vision system includes some (pretty sophisticated) feedback control to allow the eyes to track the relative motion of objects. The ultimate effect of this is that, when you focus on a particular point, the image of that point will continue to be projected to roughly the same location on the retina despite motion of the point and your head. (As a simple demonstration: focus on a word on this page. Move your head around. Note how violently you have to move your head before the word begins to blur and displace from the centre of your field of view.)

To emulate this effect, when you displace the camera, you should also adjust the view direction so that whatever the player's eye is focusing on stays in the same location on the screen. Since you don't have any information about where the player is looking, the best you can do is to make the not-unreasonable guess that they're probably looking at the centre of the screen. This will produce an effect more similar to what you 'expect', which is subtly changing parallax as the viewpoint moves.

It's probably impossible to completely eliminate nausea. Motion sickness is typically a response to inconsistent sensory input. In a vehicle, the inconsistency is that the inertial information from the inner ear indicates motion, while visual cues indicate that you are stationary. With head bob, the converse will be true.
> 2 votes

# Answer
I definitely recommend against changing the pitch of the camera, since the camera's facing is under the player's control. Just using a sine function to subtly deflect along the vertical/Y axis usually works well.
> 0 votes

---
Tags: animation, camera, first-person-shooter
---


title: Cellbased maps explanation?

text:
# Question
Title: Cellbased maps explanation?
I've been trying to understand cellbased maps and how they work, i have googled alot but can't seem to find any explanation for it.

With cell based maps i mean the ones where you do height and everything like walls roof floor in each cell. If possible i would appreciate an explanation from a Javascript perspective, but only a theoretical explanation can do.

So why do we use them? how do they work? Is it just like a normal array with more information?

# Answer
> 6 votes
Most commonly tile based games mix two types of data to make the game world.

1. A tile grid with information that every tile needs to have like texturing, accessibility, height, two of the four adjacent possible walls and depending on the game perhaps some other stuff.
2. All the stuff that can move, or is complex to represent. This is usually made as individual objects containing all their own properties, including position coordinates. You store these objects on one or multiple lists. Often it will be advantageous to have links from the tiles to the objects occupying it.

A small sketch:

```
grid=[]
for(a=0;a<100;a++){
    grid[a]=[]
    for(b=0;b<100;b++){
        grid[a][b]={} //one object for every tile, stuff in all the info you need
    }
}
character={}
character.x=3
character.y=4
misc=[] //list of case 2 objects
misc[misc.length]=character
grid[character.x][character.y].occupant=character //backwards reference

```

---
Tags: javascript
---