# Question
Title: Help Applying SDL_Surface on an array of SDL_Surface?
I'm trying to make a 4x4 blocks (50x50 px) with SDL Surface. Added another block (50x50 px, I wrote the variable as 'flag') that can only move within the 4x4 blocks, so I can select one of the blocks with this one. The problem is when I move it (say I move it to flag\_x + 50), the previous surface (flag\_x) is still there, even though I already use blit surface. It's like taking a multiple snapshots of walking person. How can I move 'flag' normally within the 4x4 blocks? Or do I use the wrong method?

Below is the code

```
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <string>
#include <sstream>

using namespace std;

//Screen attributes
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;

//The frame rate
const int FRAMES_PER_SECOND = 20;

//The surfaces
SDL_Surface *screen = NULL;
SDL_Surface *matchbox[4][4];
SDL_Surface *flag;

....
....
....

bool load_files()
{
    flag = load_image("matchbox2.png");
    if( flag == NULL )
   {
       return false;
   }

   for(int i=0;i<4;i++){
      for(int j=0;j<4;j++){
         matchbox[i][j] = load_image("matchbox.png");
         if( matchbox[i][j] == NULL )
            return false;
      }
   }
   return true;
}

void clean_up()
{
//Free the surfaces
SDL_FreeSurface( flag );

for(int i=0;i<4;i++){
   for(int j=0;j<4;j++){
      SDL_FreeSurface(matchbox[i][j]);
      matchbox[i][j] = NULL;
   }
}
//Quit SDL
SDL_Quit();
}

int main( int argc, char* args[] )
{
   for(int i=0;i<4;i++){
      for(int j=0;i<4;i++) {
         matchbox[i][j] = NULL;
      }
}

   Timer fps;

   bool quit = false;

   //Initialize
   if( init() == false )
   {
      return 1;
   }

   //Load the files
   if( load_files() == false )
   {
      return 1;
   }

   int matchbox_x = 50;
   int matchbox_y = 50;
   int flag_x = 50;
   int flag_y = 50;

   //Fill the screen white
   SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );

   //Apply matchbox to the screen
   for(int i=0;i<4;i++){
      for(int j=0;j<4;j++){
         apply_surface( matchbox_x , matchbox_y , matchbox[i][j], screen );
         matchbox_x += 50;
      }
      matchbox_x = 50;
      matchbox_y += 50;
   }

   //key event
   while( quit == false )
   {
      fps.start();

      //While there's events to handle
      while( SDL_PollEvent( &event ) )
      {
         //If a key was pressed
         if( event.type == SDL_KEYDOWN )
         {
            switch( event.key.keysym.sym )
            {
                case SDLK_UP: flag_y -= 50; break;
                case SDLK_DOWN: flag_y += 50; break;
                case SDLK_LEFT: flag_x -= 50; break;
                case SDLK_RIGHT: flag_x += 50; break;
            }
         }
         else if( event.type == SDL_QUIT )
         {
            quit = true;
         }
     }

     //collision detection
     if(flag_x < 50)
        flag_x += 50;
     if(flag_x > 200)
        flag_x -= 50;

     if(flag_y < 50)
        flag_y += 50;
     if(flag_y > 200)
        flag_y -= 50;

     apply_surface(flag_x, flag_y, flag, screen);

     //Update the screen
     if( SDL_Flip( screen ) == -1 )
     {
        return 1;
     }
     //Cap the frame rate
     if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )
     {
        SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );
     }

  }

  //Free the surfaces and quit SDL
  clean_up();

return 0;
}

```

function examples taken from http://lazyfoo.net/SDL\_tutorials/index.php

# Answer
You need to add in a Draw( ) method that will redraw your entire map every time a player had issue an event. This is typical for game programming, because when graphics are placed onto the screen, it stays there until you instruct it to be erase or "redraw" over the existing graphics.

Within your main, add a Draw( ) method at the end of it, but before the fps.get\_ticks( ) calculation kicks in.

This allows the computer to accurately calculate your fps putting into consideration of all the game logic and draw cycle.

I hope this helps.
> 1 votes

---
Tags: c++, sdl
---


# Question
Title: Should I finish high school or teach myself?
I want to become a game developer, I am an A student in 11th grade and feel like I am wasting my time in High School. I'm thinking of switching to homeschooling so that I have more time to focus on learning game development on my own while finishing high school at home. Some people I spoke to about this say its better to stay in school and go to college, some say I can get my diploma through homeschooling and this way I can get a head start on what I love to do, and get hands on experience. I am not sure what to do and was wondering if there are any experienced programmers out there that can give me advice on what route I should take??

# Answer
> 26 votes
You're in 11th grade. I'd advocate finishing high school and attending a college or university with a decent program related to the specialization you'd like to have in the games industry -- that means computer science if you want to be a programmer, for example.

I don't see a lot of advantages to being "homeschooled" for your last year-and-change of high school. Everybody feels like they are wasting their time in high school -- you'll probably have bouts of that exact same feeling in college (and you'll probably be just as wrong then as you are now).

Sure, you can devote *more* time to focusing on your immediate interests if you don't finish high school, but it might be harder to get into the best college you're otherwise capable of with only a GED, because those factors sometimes matter (regardless of whether or not they *should* matter). The danger is that by self-directing your education you are running, potentially, a much larger risk of *misguiding* your education. More so, I feel, should you choose to eschew college as well. You also narrow your focus, potentially prematurely, which might make you less desirable than others who are more generally educated.

I strongly and repeatedly advocate making games and practicing the craft you intend as a career to students, interns, and potential hires. You should do that regardless of the educational path you are on -- with that in mind, the fact that the strongest candidates for a job are usually those who practice game development to some extent as a hobby, the "head start" you get won't really be that terribly advantageous and it certainly won't count as applicable work experience to a potential employer.

If you feel that not finishing high school is the right thing for you to do for *other* reasons, then I encourage you to consider those. But my professional opinion is that it's not as advantageous for your future career as you might be assuming.

# Answer
> 14 votes
First I will admit to some bias, I am a PhD student in computer science at a large research institution (Clemson University), so I'm all about getting some education :-)

Short answer, if you want to have a good chance of becoming a game developer (and by this I assume you mean working for a AAA company like Blizzard?), you need to finish strong in high school (take the AP computer science exam), go to college for a degree in computer science, and try to specialize in some aspect of the game development process (game engine design and architecture, resource management, tooling, particle systems and FX, physics engines, simulation etc).

The value of your education is not in learning the tricks of the trade or preparing for a specific career, its learning the underlying concepts and understanding how to make good decisions based on thoughtful analysis and critical thinking; your confusing two things your *education* and your *career*. Your education can never be taken from you, while you can always lose your job.

In a practical sense, being self taught will definitely hinder your development as a programmer, you wont have the resources available to your average college student such as computer labs, high powered clusters, an army of people with similar interests, and professors hired to help you, there is a wealth of information on the internet, but it never beats hearing it straight from the mouth of an expert.

Another angle of this is the amount of *stuff* you need to know to be an effective programmer. Modern game development is extremely technical no matter how you approach it, knowledge of advanced data structures, a keen understanding of the inner workings of C++, and a strong grasp of linear algebra and physics is nearly universally required for a industry job. This is why the majority of entry level and lead software engineer jobs on Blizzard's jobs website require a bachelors degree. These concepts are hard to learn well unless you're *forced* to learn them.

In short, why get in the way of yourself? If you are making straight A's then you will definitely get in the college of your choice and probably get some merit scholarships. The game industry will still be here after taking the time to get a four year degree, and if you pursue attending a school with good connections to the game industry, then summer internships and job offers are a definite possibility. As a last good read, I would highly recommend this treatise on becoming an expert. It has some good insights into why computer science is not to be taken lightly.

# Answer
> 8 votes
My advice: Finish High School for sure, but don't waste your time on a CS degree. It will get you very little that you'll need to get a job. I say this having interviewed many CS grads who know little or nothing about what they need to know about: Software development.

Instead, I'd spend my time writing the exact kind of code that you want to get paid to write. Do that via:

* Your own imagination and ideas
* Read every book on game development you can find.
* Study all the gaming code you can get your hands on.
* Participate in an open source gaming project.
* Any other way that you can develop a body of gaming code.

Once you have a body of code that you can show (much like a photographer's portfolio) then use that to apply for jobs. Don't be afraid of the fact that you don't have a degree (even if they ask for one). Let your code do the talking. Ultimately, whether you can code or not is what potential employers want to see. If they care that you've got a CS degree, then you probably don't want to work there.

"Stay in School" is all great and good -- do finish High School -- but CS degrees are way, way overblown. Many famous developers don't have them.

ADDED: If you want to see why CS degrees are dubious at best, read the part about "Take programming-intensive courses" in this article (http://www.joelonsoftware.com/articles/CollegeAdvice.html) by the great Joel Spolsky.

# Answer
> 6 votes
I agree with everyone else about not switching to home schooling in the last year, I only see it either doing noting at all or hurting your chances in the long run.

On the topic of going to collage, be aware that **MANY** "game schools" are scams to just rip people off for money. Think the tighten up the graphics on level 3 kind of guys.

The guys over at Extra-Credits did a very good presentation on Game Schools, showing you what to look for in a good school and what warning signs to look for in a bad school.

# Answer
> 5 votes
*Should I finish high school or teach myself?* \- those two aren't mutually exclusive. I'm both finishing school and teaching myself.

And there's not much "game development knowledge" that is exclusive to game development. It's mostly just mathematics, computer science and physics, all of which you learn about in school.

I know it's a very unpopular opinion around people of our age, but school has actually been quite beneficial to me.

If you have to sacrifice anything in order to get more time for your own hobbies, there are much better candidates than education: sports, social life, TV (didn't watch it in years), procrastination...

The definitive answer is that you should definitely stay in school. It will give you knowledge that is not only applicable to game development, but other fields too, because you cannot predict your future.

# Answer
> 1 votes
**Financial** When I went to college the surveys indicated that after four years the experience you gained working made you as valuable as a new college grad. After that the college grad got raises faster and surpassed the non graduate. This may not be true any longer but I suspect it still is.

**Personal** You will meet a lot of great people at college. It's important to learn about, and from, them.

**My recommendation** It worked out better for one guy (zuckerberg). It didn't work out better for the other 89,999,999 drop outs.

# Answer
> 0 votes
For sure finish High School. However, I'm going to differ on what everyone else says, because I'm a bit biased.

While a CS/equivalent degree can help you get your foot in the door at companies, it may or may not teach you a lot, depending on the college. I'm sure everyone learns a lot that goes to MIT.. but also pays \>$10K a semester, if they can even get in.

I have to ask you a few things though.

1. Have you made any projects/games before to the point that you can call them "complete"? (and something beyond the basic hello-world)
2. Are you constantly learning about game development via the appropriate mediums(stackoverflow, forums, blogs, books etc)
3. Do you enjoy creating games, even if you don't get paid for it?
4. Do you feel comfortable teaching yourself and learning through the internet?

If you answered no to any of those questions, you're probably better off getting a degree because you're not experienced enough. However, if you answered yes to all of those, then a degree will only serve one purpose: getting your foot in the door.

That being said, I'm a (non game) programmer. I graduated high school, and took a few college courses, but never got a degree. I'm now 21(with almost no debt to my name!) and working in an entry level(ie, junior) position at a respectable, though small company. Here's how I did it and what you need to be doing:

1. Contribute to and create open source projects! This is the absolute best way to get real-life experience working in a team
2. Graduate high school. If you don't, many companies will see this and think "he has no discipline", because it takes quite a bit of discipline to finish. If you don't finish something tedious like high school, how will you deal with getting a game to complete when all the "fun" stuff is already done?
3. Create a project. It can be open source, or not. But, this project needs to be the most polished game you can possibly make. If it's an app-store game, publish it. This will be the key part of your resume to future employers. Because you have no degree, you have to really wow them to get them to consider you. They have to know, without a doubt, that you know what you are doing.
4. Create a nice resume and start applying for entry level or internship jobs! Make sure your resume points out that you are motivated enough to be self-taught, shows off all of your previous projects and contributions, etc.

Now, the hardest part about this path, is getting that first job, and leaving a good impression. Your first job probably won't be anything exciting, and you'll probably be underpaid and god knows what else. But, get the job! Make sure to be completely honest about what you lack though. If they're a Java shop and you know C# make sure to say something like "I've learned many languages and can pick them up easily. It'll take me a little while to get up to speed with Java, but I also know C# which is quite similar". The number one thing you don't want to do is get the first job and then they figure out that you don't know anything they expected of you.

After the first job, things are significantly easier. Most companies care much more for prior work experience than a college degree. Make sure to stick out your first job though for at least 2 years, maybe longer. When you feel comfortable, start sending out applications to other "better" entry level jobs. Basically, your first job will serve as your replacement for a degree. It'll be bad, but the next job will know that you have the know how and won't worry so much about lacking a degree.

This worked for me, and hopefully it works for you. Of course no guarantees, but I'm speaking from real-world experience. I got a programming job literally 2 months after graduating from High School. It wasn't the best job and it was practically slave wages, but 2 years later, here I am at a much better job, getting paid decently, and I wake up every morning and actually enjoy what I do. And many people have left this company to work at Microsoft and other big names.

In summary:

1. Make personal games
2. Get (any) game-dev related job
3. Profit!

**Note:** You may still want to take a few college courses depending on what you want to be doing(graphic designer, programmer, modeller, etc). For instance, having a thorough understanding of geometry can help you program 3D games. Also, if you're a bit of an introvert, you may want to take a public speaking class, just to pick up that skill. That's one of the classes I plan on taking sometime because I suck at public speaking, yet it's useful even for programmers.

Also, I began programming very young. In 7th grade, and got to a point that I could learn just about any new language and had a few "good" projects by my senior year. If you started later, this path may be more difficult.

# Answer
> 0 votes
That's good to hear that you are in grade 11 with an ambition to do great things. I started out learning C programming in grade 11 as well. I would highly suggest finishing off High School and during your spare time learn a programming language and start building console games and read up as much about the game industry as you can. Of course, play a lot of games.

Jumping the gun to college or university doesn't actually help in my opinion, I have done that and I got burn. Because the video game industry looks for people beyond academic background, they need people that are on top of things in the industry. If you are aiming for giant game developers like Blizzard, Capcom or SquareEnix. You need to know quite a few things and they expect you to know it well. Simply having a degree would not get you in their door, but the combination of experience and academic credential can increases your chances significantly.

Of course, there is a lot more to consider than simply going to school and getting the job. You have to factor into the educational cost, supplies and living expense while you are taking this road. Lifestyle also plays a big part within the gaming business, because they are not your typical 9-5 jobs, if family comes first, then perhaps video gaming might not be the best suit.

Degrees are great, they reinforces your knowledge and make you more competent and what not. They are great and make you more versatile and open for any type of programming job. As your knowledge grows in development, you'll realize how much school doesn't teach you and those are the things that you needed the most.

My golden rules for the new age of student is to work first, get hands on experience, then go to school. Because if you really don't like it, at least you haven't spend a dollar in it. But if you do take the road to school first and graduate just to find that you hated your job. Then you are in the world of pain.

Hope you find your answer!

---
Tags: game-industry
---


# Question
Title: Variable height jumping in side scrollers
How can I have the player jump higher if the jump key is held down longer? I am currently just reducing gravity as long as the key is held and the player is jumping, but this looks odd.

# Answer
First you need to decide what you want the jump to look like.

In real life, the jump height is decided at the moment that you leave the ground. You can't keep jumping higher while you're already in mid-air.

So if you can control your jump height while you're already in the air, you're going to get some sort of "jet-pack"-like effect.

I seem to remember a sidescroller that had two different jump heights, I think it was one of the super mario games. The higher jump occured when you held the jump button, and the jump was then actually a two part jump, starting with the initial regular jump, followed by a second impulse that took you higher.

So, what do you want your jump to look like? What sort of control do you want the player to have over the jump?

What I would start with is this:

Leave gravity alone (i.e. never change it). When a player presses the jump button, apply the jump force as long as the player is pressing the jump button (up to some time limit). Then when the player releases the jump button, he cannot apply any jump force again (i.e. he can't initiate a jump again) until he touches the ground first, at which point jumps are re-enabled.
> 9 votes

# Answer
I have seen some people do this:

1. Create a variable (I'll call it `jumpTime`) (number/double/float). When the jump key is pressed, set `jumpTime` to some number (i.e. `0.5`. This will be the number of seconds that holding the jump key will have affect).
2. Then, for every step, set the velocity to `jumpTime` multiplied by some other number, and decrease `jumpTime` by `delta` (the time difference between each step).
3. Repeat that until `jumpTime` reaches zero or below, or when the player releases the jump key. After that happens, use normal physics (apply a constant negative acceleration until the player reaches the ground).

You may need to use trial and error (or "logical guessing") to find suitable values for those "some number"s, unless you know how to do it.

---

**UPDATE:** I found the trick that makes the jump a bit more realistic (since it is originally slow going up but then fast going down). Infinite Mario also uses the following line (293 of Character.js of JavaScript version)... `this.Ya *= 0.85;` This is simply like "air drag", and limits/slows down the velocity of the character when in mid-air. So every frame, multiply the y-velocity (vertical speed) by a number less than one so that it slows down when falling back down (and therefore both *going upwards* and *going downwards* during a jump will be similar and more realistic). I know, I'm bad at explaining...

When the character jumps using the method I originally described above, it "rises up" faster then "falling back downwards". The drag, however, slows down the vertical speed. Since we set the vertical speed to be proportional to the `jumpTime` every frame, this drag doesn't have much affect on the first half of the jumping. However in the next half (falling back downwards), the vertical speed is not set every frame, but simply added by another number (in this case it is the gravitational constant). Therefore, the drag takes effect in the falling, and since it decreases the speed (in any direction), it slows down the fall, making it similar to the first half.

There are other ways to solve this problem though, like decreasing the affect of gravity on the character as it falls. However, we need to find how much we should reduce the gravity.

---

### Case Study: Infinite Mario

This is what I found (from line 206 of Mario.java by Markus Persson (Notch)):

```
    if (keys[KEY_JUMP] || (jumpTime < 0 && !onGround && !sliding))
    {
        if (jumpTime < 0)
        {
            xa = xJumpSpeed;
            ya = -jumpTime * yJumpSpeed;
            jumpTime++;
        }
        else if (onGround && mayJump)
        {
            world.sound.play(Art.samples[Art.SAMPLE_MARIO_JUMP], this, 1, 1, 1);
            xJumpSpeed = 0;
            yJumpSpeed = -1.9f;
            jumpTime = 7;
            ya = jumpTime * yJumpSpeed;
            onGround = false;
            sliding = false;
        }
        else if (sliding && mayJump)
        {
            world.sound.play(Art.samples[Art.SAMPLE_MARIO_JUMP], this, 1, 1, 1);
            xJumpSpeed = -facing * 6.0f;
            yJumpSpeed = -2.0f;
            jumpTime = -6;
            xa = xJumpSpeed;
            ya = -jumpTime * yJumpSpeed;
            onGround = false;
            sliding = false;

            facing = -facing;
        }
        else if (jumpTime > 0)
        {
            xa += xJumpSpeed;
            ya = jumpTime * yJumpSpeed;
            jumpTime--;
        }
    }
    else
    {
        jumpTime = 0;
    }

```

The javascript version is basically the same https://github.com/robertkleffner/mariohtml5/blob/master/code/character.js

This is similar to the suggestion from Olhovsky, but in this case the force will be proportional to the amount of time passed after the player pressed the jump key.

### My javascript version:

```
    if ( onGround && jump && !jumped ) {
        jumpTime = maxJumpTime;
        onGround = false;
        jumped = true;
        this.vel.y = jumpTime * jumpConstant;
        A = true;
    } else if ( !onGround && jump && jumpTime > 0 && !released ) {
        jumpTime -= evt.delta;
        this.vel.y = jumpTime * jumpConstant;
        B = true;
    } else if ( !onGround && ( !jump || jumpTime <= 0 ) ) {
        this.vel.y -= gravityConstant * evt.delta;
        jumpTime = 0
        released = true;
    } if ( this.pos.y < 0 && !A && !B ) {
        onGround = true;
        released = false;
        this.pos.y = 0;
        this.vel.y = 0;
    }
    if ( !jump && onGround ) jumped = false;

```

However, some values for the constants (e.g. "gravityConstant" and "jumpConstant") will give an unrealistic jump though. But sometimes games don't have to be realistic! (**update** see the update section above)

This question is more than a year old already, but I hope this helps!
> 7 votes

# Answer
As Olhovsky has said, the jump height is decided the moment you leave the ground, not after that.

If you really want to avoid the jetpack effect, I only see two ways: a key *combination* to jump higher, or fundamentally changing the way the jump key works:

Instead of making the player jump as soon as the key is pressed, delay the jump until the key is *released*. So basically the duration of the key press controls how much spring tension in the player’s legs is built up, and subsequently released.

Of course, this fundamentally alters the game mechanics and may be unfamiliar for the player. But the effect could be quite interesting and may well be worth the unfamiliarity.
> 2 votes

# Answer
I've found another solution in David Gouveia's answer to the question " How to make a character jump?"

### Summary:

His idea was to set a velocity when the player pushes down the jump button. In every frame it only computes the gravity. However, when the player releases the button, it sets the velocity to a smaller value if the velocity is greater than it. The velocity is only decremented each frame by the gravity.

I shouldn't steal his answer, so go ahead and read his post. His solution is under the "*Variable Height Jump*" section.

So really people came up with many different ways to solve this problem...
> 2 votes

---
Tags: side-scroller
---


title: Smooth Voxel Terrain

text:
# Question
Title: Smooth Voxel Terrain
As a personal project, I'm trying to make a terrain generator that will create terrain looking something like the Castle Story smooth terrain.

If you haven't seen it before, here:

So as you can see, it's combination of blocks and "smooth" blocks.

What I've tried to do to emulate this look is to give each surface block a mini heightmap. This generally works, but there are some issues, yielding a terrain like this:

The problem is is that each block is 1x1x1, but sometimes the height at a particular location is negative or \> 1. In that case, I clip it and set the height to 0 or 1.

To better illustrate what I mean, here's a diagram:

To generate the height, I basically do:

```
genColumn(int x, int z)
{
    int highestBlockY = (int)noise2d(x, z);

    bool is_surface = true;

    for(int y = max_height - 1; y >= 0; y--)
    {
        Block b;

        if(is_surface)
        {
            b = Block.Grass;
            b.HasHeightMap = true;

            // generate heightmap
            for(int ix = 0; ix < 5; ix++)
            {
                for(int iz = 0; iz < 5; iz++)
                {
                    float heightHere = noise2d(x + ix / 4, z + iz / 4) - y;

                    // clip heights
                    if(heightHere > 1)
                        heightHere = 1;

                    if(heightHere < 0)
                        heightHere = 0;

                    b.HeightMap[ix][iz] = heightHere;
                }
            }

            is_surface = false;
        }
        else
        {
            b = Block.Dirt;
        }

        setBlock(x, y, z, b);
    }
}

```

Perhaps I'm approaching this incorrectly by using the "true" perlin noise value?

Any help would be greatly appreciated!

# Answer
Castle Story looks like this due to technical constraints: Were there to be a heightmap per each voxel in the entire volume, rather than only a heightmap per each *surface* voxel, storage cost would be vastly greater, on the order of O(n^3) which can be prohibitive, as opposed to a more favourable O(n^2), where n is the side length of a cubic voxel space representing your world. Bear in mind that heightmap information for subterranean voxels is implicit in the grid structure, so heightmap info need only be *explicitly* stored for those voxels which lie on the surface. So the Castle Story guys have snapped vertices to grid interstices to save on storage cost and mesh-construction complexity... read on.

First off, let's look at your options:

**(1)** is going to make things difficult for you, since in a single voxel column you only want mini-heightmap information for the *topmost* voxel -- refer back to the first paragraph for the reasons why. Looking at (1), the column on the right has heightmap information for both the topmost and the second-from-top (and this could apply to the third-from-top and so on, if the slope were extreme enough.). This is no good.

**(2)** Is probably a better option then; that is, ensuring that corner vertices snap to voxel grid interstices. But how then do we address the extreme slope issue? Well, we need to pick some gradient where we simply snap to a vertical column and thus ensure we have no gradients than can crosscut through n topmost voxels. A 45 degree gradient is the natural cutoff for reasons I explain below. So instead of (3), we'd have (4):

**(4)** Snapping the voxel's corner vertex to the nearest grid interstice is the solution. The visual effect -- diagonal aliasing -- can be seen in your screenshot of Castle Story. The cutoff slope for the voxels is a 1:1 gradient, or 45 degrees (as viewed orthogonally). Working backward from the solution, let's look at the reasons:

* The only way we could have an unbroken, extreme slope, is if a voxel were vertically elongated...
* .... But no voxel's mesh can exceed it's bounding area, irrespective of it's actual smoothed shape; a voxel needs to sit in a defined space in a 3D grid which accounts, if not for it's exact form, then at least for it's axis-aligned bounding box.

Another reason to approach it this way is that, as you've already discovered, not using snapping (discretization) leads to a range of geometrically complex surface smoothing scenarios, which are best avoided altogether... games of this sort generally do not require the degree of accuracy that a proper CSG algorithm would provide, which is the whole reason we are using voxels in the first place: Voxels make it far easier to work incrementally with volumes, than floating-point (continuous) polygon intersection / CSG algorithms do.
> 11 votes

---
Tags: xna, procedural-generation, terrain, voxels, perlin-noise
---


title: Multisampled Texture

text:
# Question
Title: Multisampled Texture
i have some doubts with multisampled textures.

In fragment shader, how to pass multiple samples?

We use glTexImage2DMultisample instead of glTeximage2D. so, how to upload texture data?

I want to use default FBO for this.

# Answer
It is not possible to directly use a multisampled texture. You have to resolve it to another texture (same format, same size) first.

You can do that by binding the non-multisampled texture and blitting the multisampled one to it with glBlitFramebuffer (you might need to append EXT to function name - use glBlitFramebufferEXT - if you use OpenGL 2).
> 0 votes

---
Tags: opengl, textures, glsl
---


# Question
Title: Is jButton in Java suitable for a Game GUI?
Recently I have encountered the issue of trying to add a GUI into my game using Swing. The game will randomly & infrequently flash the jButton or Swing component when I add it to my jFrame. I'm not sure if this is because Swing is not double buffered like the rest of my graphics or something is interfering with Swing (The game is in a barebone state, so I'm not sure what in the game would cause this).

I noticed that Minecraft has it's own custom GUI components, should I do a similar system, or is there an alternative to Swing?

EDIT: Figured I should add the initialization code for the component.

```
@Override
public void init(Main main) {
    playButton = new JButton("Test", new ImageIcon(this.getClass().getResource("gui/BlankButton.png")));
    playButton.setLocation(main.getW() / 2, main.getH() / 2);
    main.add(playButton);
}

```

# Answer
> 2 votes
No. Swing components wont render nicely in custom drawing. Actually the layout manager stores the coordinates of the object (component) and renders it by translating the graphics object. When in custom rendering, you do

```
@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    // Original graphics
}

```

This overwrites the original rendering of the components. Instead you could translate the coordinates yourself but the rendering will be the default face, no mouse over effects and all other stuff since you will be calling `repaint` several times.

This has another backdrop also i.e improper functioning since you may be in another thread (i.e the game thread). You may do this with synchronization, but it so time ridden.

You can download and try the chapter 3 of `Developing games in Java` source but it didn't work for me exceeding version JDK 1.5.

You can make your own Button class if you want.

---
Tags: java, gui, swing
---


title: Non Updated Paint Graphics in Java

text:
# Question
Title: Non Updated Paint Graphics in Java
I want the tank to move in the screen but it doesn't update at all. If I am going to draw a ball...an oval...it does move in the screen, but since I want a picture to do so, I used the image method, but why does it stay on the window and does not even move even with the key listener method? Here is what I did:

```
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
 import javax.swing.ImageIcon;

import javax.swing.JPanel;
import javax.swing.JFrame;

public class Main extends JFrame{

Image tank;
 int x, y;
public class ActionListener extends KeyAdapter{

    public void keyPressed (KeyEvent e) {
        int key = e.getKeyCode();
            if (key == e.VK_LEFT) {
                x--;
            }
            if (key == e.VK_RIGHT) {
                x++;
            }
            if (key == e.VK_UP) {
                y--;
            }
            if (key == e.VK_DOWN) {
                y++;
            }
    }
    public void keyReleased (KeyEvent e) {

    }
}
public Main () {
    x = 300;
    y = 320;
    addKeyListener(new ActionListener());

    setSize(500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setVisible(true);

}

public void paint (Graphics g) {

    Graphics gr = (Graphics2D) g;
    gr.drawImage(tank,0,0, null);
    tank = new ImageIcon (this.getClass().getResource("tank.png")).getImage();

    repaint ();
}

public static void main (String args []) {

    new Main ();
}
}

```

how can i fix this so it updates and moves the picture as I wanted it to? I even plan on making separate pictures for each direction, but with this problem I can't move on. Thanks.

# Answer
> -1 votes
This is the error

```
public void paint (Graphics g) {
    Graphics gr = (Graphics2D) g;
    gr.drawImage(tank,0,0, null);
    tank = new ImageIcon (this.getClass().getResource("tank.png")).getImage();
    repaint ();
}

```

Change it to

```
public void paint (Graphics g) {
    Graphics gr = (Graphics2D) g;
    if (tank==null){
        tank = new ImageIcon (this.getClass().getResource("tank.png")).getImage();
    }
    gr.drawImage(tank,0,0, null);
    repaint ();
}

```

Though calling `repaint` from `paint` could blow out your program.

---
Tags: java
---


# Question
Title: XNA 4.0 - Normal mapping shader - strange texture artifacts
I recently started using custom shader. Shader can do diffuse and specular lighting and normal mapping. But normal mapping is causing really ugly artifacts (some sort of pixeling noise) for textures in greater distance.

It looks like this:
This is HLSL code:

```
// Matrix
float4x4 World : World;
float4x4 View : View;
float4x4 Projection : Projection;

//Textury
texture2D ColorMap;
sampler2D ColorMapSampler = sampler_state
{
    Texture = <ColorMap>;
    MinFilter = Anisotropic;
    MagFilter = Linear;
    MipFilter = Linear;
    MaxAnisotropy = 16;
};

texture2D NormalMap;
sampler2D NormalMapSampler = sampler_state
{
    Texture = <NormalMap>;
    MinFilter = Anisotropic;
    MagFilter = Linear;
    MipFilter = Linear;
    MaxAnisotropy = 16;
};

// Light
float4 AmbientColor : Color;
float AmbientIntensity;

float3 DiffuseDirection : LightPosition;
float4 DiffuseColor : Color;
float DiffuseIntensity;

float4 SpecularColor : Color;
float3 CameraPosition : CameraPosition;
float Shininess;

// The input for the VertexShader
struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
    float3 Normal : NORMAL0;
    float3 Binormal : BINORMAL0;
    float3 Tangent : TANGENT0;
};

// The output from the vertex shader, used for later processing
struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
    float3 View : TEXCOORD1;
    float3x3 WorldToTangentSpace : TEXCOORD2;
};

// The VertexShader.
VertexShaderOutput VertexShaderFunction(VertexShaderInput input, float3 Normal : NORMAL)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    output.TexCoord = input.TexCoord;

    output.WorldToTangentSpace[0] = mul(normalize(input.Tangent), World);
    output.WorldToTangentSpace[1] = mul(normalize(input.Binormal), World);
    output.WorldToTangentSpace[2] = mul(normalize(input.Normal), World);

    output.View = normalize(float4(CameraPosition,1.0) - worldPosition);
    return output;
}
// The Pixel Shader
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 color = tex2D(ColorMapSampler, input.TexCoord);

    float3 normalMap = 2.0 *(tex2D(NormalMapSampler, input.TexCoord)) - 1.0;
    normalMap = normalize(mul(normalMap, input.WorldToTangentSpace));
    float4 normal = float4(normalMap,1.0);

    float4 diffuse = saturate(dot(-DiffuseDirection,normal));
    float4 reflect = normalize(2*diffuse*normal-float4(DiffuseDirection,1.0));
    float4 specular = pow(saturate(dot(reflect,input.View)), Shininess);

    return  color * AmbientColor * AmbientIntensity +
            color * DiffuseIntensity * DiffuseColor * diffuse +
            color * SpecularColor * specular;
}

// Techniques
technique Lighting
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

Any advice? Thanks!

# Answer
It looks like you have mipmapping disabled for at least the normal map texture.

Select your image file in the Content project. In the Properties, expand the Content Processor, and set "Generate Mipmaps" to "True".

I can't spot any issues with your shader at a glance, but I don't normally deal with graphics programming so I'm not sure what my opinion is worth on that subject.
> 1 votes

# Answer
I suspect that those artifacts may be specular highlights because when I tried your shader in place of my normal map' shader, the specualar shading was imitating a light shining at a 90 degree angle about the model to where the diffuse shader's light was shining from. So yeah, hopefully it's just spec highlights, so try this:

```
float4x4 World : World;
float4x4 View : View;
float4x4 Projection : Projection;

//Textury
texture2D ColorMap;
sampler2D ColorMapSampler = sampler_state
{
    Texture = <ColorMap>;
    MinFilter = Anisotropic;
    MagFilter = Linear;
    MipFilter = Linear;
    MaxAnisotropy = 16;
};

texture2D NormalMap;
sampler2D NormalMapSampler = sampler_state
{
    Texture = <NormalMap>;
    MinFilter = Anisotropic;
    MagFilter = Linear;
    MipFilter = Linear;
    MaxAnisotropy = 16;
};

// Light
float4 AmbientColor : Color;
float AmbientIntensity;

float3 DiffuseDirection : LightPosition;
float4 DiffuseColor : Color;
float DiffuseIntensity;

float4 SpecularColor : Color;
float3 CameraPosition : CameraPosition;
float Shininess;

// The input for the VertexShader
struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
    float3 Normal : NORMAL0;
    float3 Binormal : BINORMAL0;
    float3 Tangent : TANGENT0;
};

// The output from the vertex shader, used for later processing
struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
    float3 View : TEXCOORD1;
    float3x3 WorldToTangentSpace : TEXCOORD2;
};

// The VertexShader.
VertexShaderOutput VertexShaderFunction(VertexShaderInput input, float3 Normal : NORMAL)
{
    VertexShaderOutput output;

    float4x4 WVP = mul(World, mul(View, Projection)); //A Preshader

    output.Position = mul(input.Position, WVP);

    output.TexCoord = input.TexCoord;

    output.WorldToTangentSpace[0] = mul(normalize(input.Tangent), World);
    output.WorldToTangentSpace[1] = mul(normalize(input.Binormal), World);
    output.WorldToTangentSpace[2] = mul(normalize(input.Normal), World);

    output.View = normalize(float4(CameraPosition,1.0) - mul(input.Position, World));
    return output;
}
// The Pixel Shader
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 color = tex2D(ColorMapSampler, input.TexCoord);

    float3 normalMap = 2.0 *(tex2D(NormalMapSampler, input.TexCoord)) - 1.0;
    normalMap = normalize(mul(normalMap, input.WorldToTangentSpace));
    float3 normal = normalize(normalMap);

    float diffuse = saturate(dot(normalize(-DiffuseDirection),normal));
    float3 reflection = reflect(DiffuseDirection,normal);
    float specular = pow(saturate(dot(reflection,input.View)), Shininess);

    return  color * AmbientColor * AmbientIntensity +
            color * DiffuseIntensity * DiffuseColor * diffuse +
            color * SpecularColor * specular;
}

// Techniques
technique Lighting
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

Everything up until the Vertex Shader is the same. The VS does exactly the same thing, but I added a pre-shader just because I can. The Pixel Shader is where it's at. I cleaned it up a little, but the big changes are:

```
float4 reflect = normalize(2*diffuse*normal-float4(DiffuseDirection,1.0));

```

is now

```
float3 reflection = reflect(DiffuseDirection,normal);

```

Apart from the float4 to float3, I replaced the variable name 'reflect' with 'reflection' so I could use the HLSL function: reflect. This cool function means you don't have to write out the equation, just pass the 'incident ray' and the normal and it'll do the rest. It also makes sure that it's done correctly, unlike here. You used `diffuse` instead of `dot(-DiffuseDirection, normal)` and in `diffuse`, you normalized `-DiffuseDirection`.

It should go without saying that `reflect` has been changed to `reflection` in the line below as well.

This code worked for the model I used it on, so I'm hoping this is the fix you're after.
> 1 votes

---
Tags: xna, shaders, hlsl, lighting, normal-mapping
---


# Question
Title: Implementing simple proportional navigation for a homing missile
I'm trying to implement the simplest possible form of proportional navigation, i.e, the missile turns in the direction that its bearing-to-target is changing, and once its bearing-to-target is unchanging, it's on an intercept course.

So, I have a 2d missile moving at a constant speed in the direction it is facing, which can turn at a constant rate, and every interval I update the missile with something like:

```
Position += VectorProduct (Direction * Speed * TimePassed)

PreviousTargetBearing = TargetBearing
TargetBearing = AngleBetween(TargetPosition, Position)
TargetBearingDelta = TargetBearing - PreviousTargetBearing

If TargetBearingDelta > 0: MissileDirection += TurnRate * TimePassed
If TargetBearingDelta < 0: MissileDirection -= TurnRate * TimePassed

```

Problem is, the missile always oscillates around its launch direction, because as soon as the missile turns the first time, this reverses the sign of TargetBearingDelta, making it then turn in the opposite direction, and so on...

What is the simplest way I can resolve this problem? I'm sure I'm missing something simple.

Related StackOverflow question: How to create an “intercept missile” for a game?

**To reiterate, I am interested specifically in implementing the proportional navigation algorithm, not in homing algorithms in general.**

---

Update: I guess the obvious answer is to not check bearing *and* adjust heading every turn, but to alternate between the two. I'll try that.

# Answer
Step 1)Calculate time to target if going in a straight line

Step 2)Calculate where the target will be with it's current heading at that time.

Step 3)Set heading of missile to be that spot.

Step 4)Update as necessary

At first, this won't be very accurate, but as the distance closes it will become more accurate; as the time to travel goes to zero, the target spot for the missile gets closer to the target.

Give that a whirl. It's simple enough to implement. Let me know how it works because I want to put homing missiles in my game and this was my first thought.

And for this part:

```
If TargetBearingDelta > 0: MissileDirection += TurnRate * TimePassed
If TargetBearingDelta < 0: MissileDirection -= TurnRate * TimePassed

```

I would instead have two missileDirection variables. One for what it really is, and one for what it should be in the future. Then, the missile move's its' heading towards the desired heading by it's turn rate. If the desired heading is bigger than the current heading, add the turn rate. If it's smaller, subtract. If you go past, set it equal.
> 1 votes

# Answer
As Nailer says, you can cap the movement change in some way.

Check out PID, a nice way to make things move to a certain 'value' fast but without overshooting it, it might give you some ideas.

You can also check out this question, a bit down is an explanation of the 'dog curve', a very accurate homing algorithm used by dogs.
> 4 votes

# Answer
For my opinion, there would be another method involving two vectors, one for direction for a missile to hit, and another one is for itself lerping (or say transitioning its direction to match the first vector).

This way, we can produce a lag time allowing a missile to smoothly changes its direction according of a change in a first vector. I believe it will remove out the problem in "sign" of math operation.

PS. The main point is that we lerp a missle's own vector to a directional vector (to hit) with regard to some small lag in time.
> 1 votes

# Answer
Porportional navigation is simple to implement in games.

An example of implementation in game is:

**Required Acceleration = LOS * LOS\_Rate * NC + APN\_bias**

LOS = Vector3( TargetPosition ) - Vector3( MissilePosition )

NC = Navigation Constant multiplier (depending on frame rate run)

APN\_bias = LOS\_Rate/delta\_T * ( NC/2 )

LOS\_Rate = LOS Rotation Rate is the angular rate of change in sightline between the missile and the target. This is measured by recording both the missile and the target vector positions every frame at delta\_T, and subtracting each to get the difference. Delta\_T is the timing reference (i.e. frame rate) at which your homing missile is running in game.

To obtain LOS\_Rate, simply have your missile guidance loop do the following at each frame (delta\_T):

```
// New LOS rate

LOS_Delta = Vector3( LOS ) - Vector3( LOS_previous_frame )

LOS_Rate = LOS_Delta.Vector3Length()

// Update LOS before we finish

LOS_previous_frame = Vector3( LOS )

```

You can find more information about how we implemented PN for World in Conflict game at the following URLs below. Hope you find these helpful.

http://www.moddb.com/mods/wicmw/features/flint-lead-pursuit-guidance-principles

http://download.wicmwmod.com/Fun\_Mod/presentations/FLINT%20Jul%202012.pdf

-blahdy
> 1 votes

# Answer
Can´t you just cap the turn rate so that it can never turn past TargetBearing in one frame?

If a turn would make the missile turn past it´s target bearing you just set the new bearing equal to target bearing.

Does that make sense?
> 0 votes

---
Tags: ai
---


# Question
Title: I would need an idea on how to animate a player in a board game that is top-down and 2D?
I'm planing a 2D board game and I cannot figure out how to make the animation of the player from tile to tile. Note that tiles are not in a grid, they are flexible (x, y) points in the map.

The ways I found until now:

* Just move the player from (xi, yi) to (xf, yf) with nothing special
* An helicopter comes from an edge an transport the player (a circle) to the next tile
* A little man walking by making it in a wrong perspective (side)

Do you have any better ideas, thanks alot?

# Answer
Without any knowledge of what your game is, the theme of the game, or what kind of things you want to be moving, all we could possibly do is throw out random ideas hoping you like one. So... here's a rampant brain dump of ways I can think of to get from `A` to `B`:

* Land
    + Walk/jump/skip to the destination
    + Pull out a sled and slide to the destination
    + Jeep/Car/Tank/etc.
    + Burrow through the ground
    + Ride a horse/camel/dog/caterpillar/etc.
* Air
* Sea
    + Boat/Sea-Doo/etc.
    + Summon a wave and ride/surf it
    + Swim
    + Submarine
    + Ride a shark/whale/jellyfish/floating piece of trash/etc.
* Magic/Scifi
    + Magic carpet
    + Space ship/rocket/etc.
    + Teleportation/wormhole/etc.
    + Folding space
    + Riding a unicorn/pegasus/Luck dragon/etc.
* Other
    + Mailed in an envelope/box/etc.
    + Being eaten and regurgitated/"passed"
    + The ground you're on gets up and moves
> 2 votes

# Answer
You can use a sprite sheet of the character walking to their destination from a top-down perspective until they get to water (I'm assuming these islands have water around them). When they get to the water, you can use a sprite sheet of them swimming freestyle or backstroke, etc, again from the top-down perspective. If the islands are about the size of the player, just have him dive in and swim, no walking required.

As an alternative to swimming, you can have him picked up by a submarine that just so happens to surface at the right place and time and have that carry the character to the next island while still on the surface. Sub reaches the island, the character disembarks and the submarine submerges again.

I do like the idea of something like a jetpack, or flying carpet as well. Hell, you can even mix it up a bit: submarine this turn, jetpack the next, followed by a giant slingshot, etc.

However you wish to do it, I reckon sprite sheets would be the way to go. Just be prepared to do a lot of editing (unless you're crazy talented).
> 1 votes

---
Tags: movement
---


title: Mesh manipulation on GPU vs CPU

text:
# Question
Title: Mesh manipulation on GPU vs CPU
Just a bit curious - where do you perform mesh manipulations, on the CPU or in the shader? I've been doing everything on the CPU and a friend suggested moving things on to the GPU side.

If you're doing things like bone animations... on the GPU, how do you get back the mesh? (since I'm doing collision detection...)

# Answer
This commonly happens on the GPU, but there are trade offs for both and it's up to you to decide which will work best for you.

Doing the manipulation on the GPU means you only need to send the mesh data once, then you can just send the matrix transforms to deform it. This is great because it greatly reduces the bandwith required between CPU-\>GPU. It also means you can upload just *one* copy of the mesh to the GPU and apply transforms for many different instances of the mesh. However, it's more difficult to have "mesh accurate" collisions. Since the transforms are done on the GPU, you don't have them available to test with on the CPU.

Doing the manipulation on the CPU means you have access to the transformed mesh. You can access everything you need to know about it. However, it means you need to upload that entire mesh to the GPU each frame. It also means you have to upload a transformed mesh *for each* instance of that mesh. In summary here's a no where near exhaustive list of pros and cons.

* **Pros for GPU**

+ Upload the mesh data once
    + Transform it for multiple instances
    + Only need to send the matrix transforms
    + The GPU is very good at parallelizing these types of things
* **Cons for GPU**

+ Transformed meshes are not available for testing on CPU
* **Pros for CPU**

+ Transformed meshes are available for collision tests and anything else needed.
* **Cons for CPU**

+ Need to upload the entire transformed mesh each frame
    + Need to upload an entire mesh for each instance of the mesh

There are ways to get around the cons for the GPU however.

* **Don't have mesh accurate collisions**. Use something "close enough" like a bounding box for the entire mesh or have bounding boxes for each bone of the mesh. The below is using on the GPU transforms for the mesh, and on the CPU transforms for axis aligned bounding boxes that represent the mesh. You could get even more accurate bounds by using non-AABBs.

* **Transform a copy of the mesh on the CPU if and only if mesh accurate collisions are needed**. After a bounding box collision has returned true, transform a mesh to match the transforms on the GPU, then check the collisions against that to get more accurate collision data.

All-in-all I assume you can see why it's more common to transform on the GPU
> 14 votes

---
Tags: opengl, 3d
---


# Question
Title: Does using LWJGL and Slick2D yield promise for the future of my project?
I've been looking around the net for months now in an attempt to find the most appropriate tool for my needs. I haven't had a lot of time to devote to the creation of systems that could possibly already exist, however, now I do.

That being said, I've been drawn to 2 or 3 APIs/Engines thus far. The bulk of my experience lays with Java due to the exposure during my time in high school and college (of which I am currently a senior in, if any of you are wondering!) but I have used Python, C, C++, C#, and even a little Ruby and PHP for site needs.

Now, I've sought the power of OpenGL and LWJGL because of the platform independence and the obvious success of things such as Minecraft being used in a Web, Linux, Mac, and Windows environment. This is all due to Java, LWJGL, and a very interesting game concept. I've used the Slick2D API which is built upon LWJGL and I would like to continue with it if there is promise of no limitations on what I intend to create. I need a powerful, platform-independent 2D/3D graphics library, an input-monitoring system with perhaps even controller support, and networking capabilities beyond that of the standard (Java, or other language) library.

I've also looked into both the Torque Game Engine as well as the UDK and, to be honest, the UDK looks quite perfect. However, my goal for the end of this project is for the user to be able to host a multiplayer session which other players can join via IP or hostname, the world be a unique generation for each "new game", but still not limit the game in such a way that would not allow complex system to be implemented. Now, nothing would be limited if I simply used the UDK source, but I will not make such a commitment without first consulting the experts.

**TL;DR** \- This is not intended to be a, "Which engine should I use? I like Java but wahhh I'm scared to write real code!" I have written my own engine (2D) and it has not been as successful as current ones, but it's done what I wanted it to. My only question is: Is the UDK sufficient for my needs; if not, I believe that the Slick2D API could be. I'm an aspiring Computer Science major from Michigan Tech, so learning and developing something new would not crush my world, haha. I would just like to hear what the beating heart of SE has to say on such topics. My plan for this project was 2D purely to control scope creep and not overwhelm myself.

Thanks!

PS - Also, I've done research on all programming topics associated with this development: creating standalone listening servers, PCG, complex item/inventory/reward systems, advanced dynamic RPG level systems and dynamic storyline systems. I'm not a super-noob. Just a curious individual.

# Answer
> 1 votes
If you're looking to develop your game development skills with a 2D game, I highly recommend using LWJGL/Slick2D. Slick2D is a great library that makes making games really easy, and allows you to get experience with putting together all the other aspects of the game instead of just wrapping your head around graphics (which is a huge task). Additionally, I feel that (in my humble opinion), Java is a really good language for Networking. However, if your game is highly physics-based you might have some trouble since Java isn't really a targeted environment for that kind of development. There are some libraries like JBox2D, but they generally lag behind their C/C++ counterparts by quite a bit. Also know that Slick2D is SOLELY a 2D library - don't expect to do a 3D game with it (note you can use LWJGL with the slick\_util library to do this though).

The Unreal engine, on the other hand, is going to be a serious leap up in difficulty. If you haven't developed at least a medium-size game before, I would steer you away from this choice. This engine offers high-end features intended for a high-class game. Learning all of these features for graphics/physics are probably beyond a beginner at game development. Also, this isn't really intended to be a 2D development platform, since it's aimed at high-end development (just look at the showcase - if your game doesn't really fit in with those games, UDK probably packs more punch than you need). However, programming with UDK would give you good experience programming a high-end game engine, and definitely stretch your skills - just be ready.

I'd propose a third option, and that's to use a C/C++ solution that really fits your game needs. I'd suggest checking out libraries like SDL and SFML which offer a lot of Java-like functionality and rather mimic what you'd be getting with Slick2D, but also allow for 3D options, C++ physics engines, and good experience programming in C/C++.

Hope that helps!

---
Tags: java, udk, lwjgl, slick
---


title: Quaternion Camera

text:
# Question
Title: Quaternion Camera
Can someone help me figure out how to use a `Quaternion` with the `PerspectiveCamera` in libGDX or in general? I am trying to rotate my camera around a sphere that is being drawn at (0,0,0). I am not sure how to go about setting up the quaternion correctly, manipulating it, and then applying it to the camera.

**Edit:** Here is what I have tried to do so far.

```
// This is how I set it up
Quaternion orientation = new Quaternion();
orientation.setFromAxis(Vector3.Y, 45);

// This is how I am trying to update the rotations
public void rotateX(float amount)
{
    Quaternion temp = new Quaternion();
    temp.set(Vector3.X, amount);

    orientation.mul(temp);
}

public void rotateY(float amount)
{
    Quaternion temp = new Quaternion();
    temp.set(Vector3.Y, amount);

    orientation.mul(temp);
}

public void updateCamera()
{
    // This is where I am unsure how to apply the rotations to the camera
    // I think I should update the view and projection matrices?
    camera.view.mul(orientation);
    ...
}

```

# Answer
I used 2 Quaternions.
The first rotation quaternion is used to rotate the camera up vector according to the pointer delta movement angle.
The second rotation quaternion is rotating the camera around the new camera up vector.
Note: initialX & initialY are the pointers values in touchDown(), origCameraDirection & origCameraPosition are camera.direction.cpy() & camera.position.cpy()

```
@Override
public boolean touchDragged(Ray unused, int x, int y, int pointerIndex) {
    super.touchDragged(unused, x, y, pointerIndex);
    float deltaX  = (initialX - x);
    float deltaY  = (initialY - y);
    float rotationAngle = 360.0f * (float)(Math.sqrt(deltaX * deltaX + deltaY * deltaY)/screenDst);
    while (rotationAngle < 0) {
        rotationAngle += 360;
    }
    while (rotationAngle > 360) {
        rotationAngle -= 360;
    }

    float alpha = (float)Math.atan2(deltaY,deltaX) * MathUtils.radiansToDegrees;

    Quaternion q = new Quaternion(origCameraDirection, alpha);
    Vector3 rotatedUp = origCameraUp.cpy();
    q.transform(rotatedUp);

    // rotatedUp is our actual rotation vector
    Quaternion actualQ = new Quaternion(rotatedUp, rotationAngle);

    Vector3 newCameraPosition = origCameraPosition.cpy();
    actualQ.transform(newCameraPosition);
    camera.position.set(newCameraPosition);

    Vector3 newCameraDirection = origCameraDirection.cpy();
    actualQ.transform(newCameraDirection);
    camera.direction.set(newCameraDirection);

    Vector3 newCameraUp = origCameraUp.cpy();
    actualQ.transform(newCameraUp);
    camera.up.set(newCameraUp);
    return true;
}

```
> 3 votes

# Answer
Rotate will turn the camera around the axis of the camera! When you rotate the camera around another object, you need to translate the camera, pointing it to the object. To translate the camera around an object, you need use the distance from the object e the angle to rotate. So, you must add sin(angle) in X and cos(angle) in Y.

```
double distance = DistanceBetween(camera, sphere);
camera.x += distance * sin(angle);
camera.y += distance * cos(angle);

```
> 0 votes

---
Tags: java, android, opengl-es, libgdx, quaternion
---


# Question
Title: OpenGL Depth Buffer/Coordinate issue with SFML
For some reason, my coordinate system in OpenGL is getting all messed up with depth. When I put something more than 1 unit away from zero (in terms of the Z coordinate), I can't see the object. Furthermore, it seems as if the GL coordinate (-1, -1, 0) is in the lower left corner no matter what I do (and (1, 1, 0) is upper right). I've used OpenGL in Java and in C++ with GLUT before and am now trying out SFML, and haven't had these issues before, so maybe someone can tell me what I'm doing wrong?

A minimal example as best I can do:

```
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>

#include <iostream>

int main()
{
    sf::ContextSettings settings;
    sf::RenderWindow window(sf::VideoMode(800, 600), "OpenGL Test", sf::Style::Default, sf::ContextSettings(24));

    settings = window.getSettings();

    std::cout << "depth bits:" << settings.depthBits << std::endl;
    std::cout << "stencil bits:" << settings.stencilBits << std::endl;
    std::cout << "antialiasing level:" << settings.antialiasingLevel << std::endl;
    std::cout << "version:" << settings.majorVersion << "." << settings.minorVersion << std::endl;

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);    // Black Background
    glDepthRange(-1, 1000);

    // run the main loop
    bool running = true;
    while (running)
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                // end the program
                running = false;
            }
            else if (event.type == sf::Event::Resized)
            {
                // adjust the viewport when the window is resized
                glViewport(0, 0, event.size.width, event.size.height);
            }
        }
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glLoadIdentity();

        // Comment this line to fix it!!?
        glTranslatef(-1.5f,0.0f,-6.0f);

        glBegin(GL_TRIANGLES);                      // Drawing Using Triangles
            glVertex3f( 0.0f, 1.0f, 0.0f);              // Top
            glVertex3f(-1.0f,-1.0f, 0.0f);              // Bottom Left
            glVertex3f( 1.0f,-1.0f, 0.0f);              // Bottom Right
        glEnd();                            // Finished Drawing The Triangle

        window.display();
    }

    return 0;
}

```

Update: The glDepthRange() call was to make sure that wasn't the source of the problem. Also I added the following code to the initialization, and I haven't seen any change in behavior:

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, 800, 600);

glMatrixMode(GL_MODELVIEW);
...

```

Also, I'm using the 2.0RC version of SFML, and my OpenGL version is 4.3 (running on an ATI card).

# Answer
It appears that the issue was a combination of setting the perspective matrix correctly, ensuring a proper coordinate system, and getting the right number of depth bits/ensuring the depth buffer was properly enabled. It looks like sf::RenderWindow is intended for 2D rendering, so I should be using sf::Window instead as well. Still having issues with gluLookAt(), but that's a different problem.

Update: I believe a big part of the problem was coming from 'glEnable(GL\_CULL\_FACE)' and then proceeding to use the wrong winding... whoops.
> 0 votes

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


# Question
Title: Reusing entities across screens: game data vs. object modelling
I'm working on a 2D RPG. I currently have a `MainWorldScreen` which has a `Player` entity, and some `MapObjects` that he can collide against. The player has a few components (sprite, keyboard input) etc. that implement specific logic for it to work in the main world screen.

The problem now arises when I start working on a "battle" screen. The crux of it is, **should I reuse/extend my Player entity or create one entity per screen?**

Up to now, components are all behaviour based -- sprites to display something on-screen, input components to capture and expose events to handle input, etc. My entities are a composition of components that implement game logic (eg. move on keyboard click).

If I did this as "pure" object-oriented, I would probably have a larger `Player` class which had all the combined attributes needed for all screens -- list of equipment, health, etc. and each screen would only take what it needs.

However, since I have components, if I reuse my player entity, it doesn't make much sense to reuse it; I will have to remove and re-add new components, since screens use completely different data, and I don't really know where the player state should go (eg. equipment).

What's the right way to handle this? Should I go with one `Player` entity per screen (at least with these two screens)? Should I keep player state in the entity, and just add/remove components depending on the screen when I pass it from screen to screen?

# Answer
> 1 votes
Disclaimer: My entity/component system is a bit unique. Components are very low-level (eg. track input state by keyboard, or draw a sprite); entities combine entities and contain game logic (analogous to systems in other EC systems).

For me, it turned out that the simplest solution that worked well was to **treat components and entities as view-specific.** For example, I would have a "world map" view (entity) for my player, and an "in battle" view (entity) for my player.

The "traditional" model of the player (eg. inventory, health) **became a shared object across each player\* entity.** When switching screens, I simply take the player "model" out of the current screen and hand it off to the new screen.

# Answer
> 2 votes
Use one core entity for all game screens.

Overall, though, your issue is one of decoupling the correct classes in the correct places.

**Method 1: Per-Entity renderer class, separate from core Entity controller**

Here you have a different `IEntityView` (let's call it) component per screen AND per entity, so if you had two game screens and 100 entities, you'd have a total of 200 entity view components. Each of these would reference a core Entity model or model-controller, such that this core class need not be tainted by view-specifics; you then simply select the right one for the current gamestate and the current entity being rendered, either in your root controller or root view for that state, and say `entityViewForThisSpecificGameStateAndThisParticularEntity.render()` (a Javaesque name if ever you saw one). So if you have one `IEntityView` component for a minimap, and another for your main game viewport, then each of these holds a reference to the core model or model-controller for that entity, meaning you are indeed sharing key data.

**Method 2: Monolithic renderer class, separate from core Entity controller**

Here you use a "raw" renderer based approach as common with e.g. OpenGL. Each monolithic renderer pertains to a particular game screen, and will typically be the root view for that screen. You will, inside this monolithic renderer, run through a massive list of entity models or model-controllers (again, nothing view-specific should really be in there!) and render directly inside a single monolithic update function. Again you are sharing key data, but in this case you do not have additional components for every entity; instead the monolithic renderer know everything it needs to know about how to render any entity for this particular screen, given only that entity's data model.

**Method 3: Monolithic renderer with pure memory efficiency (TL; DR)** This applies not only to rendering, but to everything. The best possible way to access memory is in large, contiguous blocks where data accesses are, if possible, aligned to the cache width of the system in question. This is often lost in OO, as objects are allocated all over the heap. Refer to the final part of Mick West's Evolve Your Hierarchy... If you ignore all OO structure and aim simply for massive chunks of data, you avoid additional pointer references, which accesses cache, which if there is a cache miss, results in a callout to the heap. This is a serious approach for power users only, as it largely foregoes the nice, human-readable structure which OO provides. As the Tao of Programming reminds us,

> You must understand the Tao before transcending structure.

---

Pros, cons to each? The first approach is easiest to conceptualise as it is a nicely encapsulated system and obeys OO principles nicely; however, it is less efficient as more object references bouncing around means (a) more 32-bit pointers and (b) more potential calls out to heap memory, and furthermore it can be restrictive when you need to play tricks with render order and can also introduce issues when comparing stateful vs stateless rendering subsystems (eg. Flash DisplayObject vs Flash BitmapData, if you know those). In deferred rendering on the GPU, the monolithic approach is preferred, as controlling rendering order is a matter of critical importance. Obviously the third approach is only for if you are trying to milk serious performance out of your system, yet for any VM-based platform (Java, Flash, Unity) performance gains are not as cut and dried as we might like, since both the OS and the VM implementations will muddy the water in terms of what might, in native code, be a clear performance gain.

# Answer
> 1 votes
**Use the same entity and components**. What will change is the systems you have operating on the entities. When you load a new screen, use a different set of systems to process your entities. For example, something like this:

```
if(gamestate == MainWorld) {
    inputSystem.process();
    movementSystem.process();
} else if (gamestate == BattleState) {
    inputSystem.process();
    movementSystem.process();
    battleSystem.process();
    healthSystem.process();
}

```

Or even better, just have you screens implement a screen class that has a `process` function and stick all your system updates in there, so it's handled inside the screen class.

This way you maintain the data for your player in one place, the only thing that changes is how it's processed and what is processed. The systems doing the processing don't care what other components your entity has, they're only interested in the components they operate on. There's no need to add or remove any components.

Using multiple entities would mean you'd need to sync data, or have multiple copies of components. Sounds like a mess.

# Answer
> 0 votes
I guess you're talking about player stats like attributes, health, and such? If so, I'd keep these things outside your player in some global "save state" (which will make loading and saving easier as well). In your player entity just refer to the right "position" (e.g. player x or character x as some kind of index or offset).

I assume you're talking about separate combat screens similar to the older Final Fantasy games. As such I'd create a separate game state for this (so separate entities). This allows you to just "push" the combat scene on your game state stack and it's easy to return back to map screen without issues. Once combat ends, you just pop that state and you're back at your world map.

---
Tags: component-based
---


# Question
Title: Abstract games that are hard to play for AI/computer?
Do you know any abstract multi- or single-player game that is hard to play for AI/computer but not so hard for humans?

Being simple and popular is better.

# Answer
> 9 votes
Probably your best bet is **arimaa** which is specifically designed to be hard for AI's.

> Arimaa (pronounced Ah-REE-ma) is a very deep strategy game with simple rules. It was designed to be: Playable with a standard chess set. Easy to learn. Difficult for computers (the $10,000 programming challenge is still available). Fun and interesting for humans.
>
> The creation of Arimaa was inspired by the Deep Blue vs Gary Kasparov match in which the computer defeated the world chess champion. Arimaa was created to show that humans can still outplay computers using a chess set and provide the next challenge to the AI community.
>
> Why is Arimaa hard for computers?
>
> * On average there are over 17,000 possible moves compared to about 30 for chess; this significantly limits how deep computers can think, but does not seem to affect humans.
> * Opening books are useless since the starting position is not fixed. There are over 64 million ways to start the game.
> * End game databases are not helpful since a game can end with all pieces still on the board.
> * Research papers on Arimaa suggest it is more of a strategic and positional game with less emphasis on tactics.
> * Arimaa is proposed as a more difficult challenge for AI than chess.
> * A challenge prize invites AI researchers to develop a program that can defeat the top human players.
> * A yearly challenge match is held to give teams a chance to win the challenge prize.
> * Humans have decisively won each year. A yearly computer championship tournament is held to select the best Arimaa playing program.

# Answer
> 4 votes
Go is famous for being extraordinarily hard to create a decent AI for. It's perhaps one of the most abstract and elegant games ever created; you place stones on a grid in an effort to capture territory from your opponent.

Early Go AI research was driven by competitions which offered prizes as large as 1.4 million dollars. The best achievement in the field to-date is a program which reached 6 dan (I'm not sure how that rank fits into the grand scheme of things, but it sounds impressive) on a major Go server. Most Go AIs are beaten by lower - though still very skilled - players, even with significant handicaps.

Go is by no means easy to master for a human, but it fits what you're looking for, for this reason: were a person to spend some amount of time learning the game, and an equivalent amount of time put into developing a Go AI, the human player would surely win.

# Answer
> 3 votes
Arimaa and Go are hard for computers, but good progress is being made. My candidate for a game that will remain difficult for computers is "Volo" which you can play at Boardspace.net.

In addition to the "vast number of moves" problem, Volo has the property that most moves have to be obviously a step backward from the goal of the game, which is to unite all your pieces.

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


# Question
Title: Is there any game engine using a functional programming language?
Is there any game engine using a functional programming language similar to Scheme, Common Lisp, Clojure or JavaScript?

I've tried Unity3D but their "JavaScript" is not actually JavaScript, is strongly typed and is not functional.

# Answer
> 7 votes
There is LambdaCube which is written in Haskell (it's not exactly game engine but more like graphics engine).

# Answer
> 2 votes
You can always use f# or iron python (yes i do know, python isn't functional) or any other .netified language with XNA on .net platform.

http://fsharpgamedev.codeplex.com/ http://www.ironpython.info/index.php/XNA\_Example\_with\_a\_Bouncing\_Sprite

edit: One more engine, written in Lisp: http://code.google.com/p/blackthorn-engine/

# Answer
> 2 votes
I don't have an answer to the question as written, but I believe you are possibly trying to ask "why aren't there more functional game engines" rather than looking for a specific one to use. If that's correct, you should rephrase the question. If not... ignore me. :)

A pure functional approach is not a good fit for games. Games (and graphics, and physics, and AI) and basically all about state changes. The correct functional approach to these problems would be to compute an entire new state once per loop, which will have a very severe performance penalty compared to coding more directly to how actual hardware works.

It is for that reason that you don't see any functional-style game engines in production. It is simply the wrong programming paradigm for the majority of problems a game engine is meant to solve. It is the wrong programming paradigm for the majority of problems that need to be solved in higher-level scripting and game logic code, too. While it is almost certainly possible to make a functional game engine, it would be slow, difficult and cumbersome to use, and would serve no real purpose other than being a neat demo/toy to show off.

That's not to say that functional programming doesn't have a place somewhere in games. I use a very functional style of coding (where appropriate) in C#, Unity JavaScript, and even C++11. Some very specific problems are best or at least most easily solved with a functional style, and most of the popular languages today support that form of programming, albeit in a more cumbersome manner than "real" functional languages. Usually these problems solved with functional approaches are not in the core engine code, nor in code that runs in the game itself. Functional coding can be quite beneficial for tools and offline data processing (baking models and other assets, for instance). It's also arguable that GPU programming is vaguely functional in how algorithms are written, even though the actual coding is done in a hardware-efficient procedural manner.

Of course it can still be best to avoid functional approaches outside very specific circumstances since you want these offline tools to be as fast as possible. Functional languages excel at parallelism, which is good for some problems, but the abstractions from the hardware tend to lead to very inefficient single-threaded performance. (Languages like LISP do well here because they are not pure functional, and in fact Common LISP is multi-paradigm.) The absolute single worst thing for a game engine or related toolkit is to be a bottleneck for content iteration. A fancy engine with a lot of features that takes artists or level designers hours to do what could be done in 5 minutes (or ideally, near-instantly) will just lead to low quality games or cancellation due to budget escalation.

# Answer
> 0 votes
The Naugthy Dog company used List on its Game Engines and it was called Game Oriented Assembly Lisp.

Some information can be found here: http://en.wikipedia.org/wiki/Game\_Oriented\_Assembly\_Lisp

Some code samples: http://web.archive.org/web/20070127022728/http://lists.midnightryder.com/pipermail/sweng-gamedev-midnightryder.com/2005-August/003804.html

It is not available for public usage.

---
Tags: functional
---


title: OOP in cocos2d for ios

text:
# Question
Title: OOP in cocos2d for ios
I have been pulling my hair out trying to make an object in cocos 2d that is a CCSprite (with an image) and a CCLabelBMFont.

I tried making a CCNode object and I tried making a custom CCSprite object but none of it worked!

Can someone show me how to do this?

Thanks.

# Answer
Add a new file to your project and use Objective C class as the file type. It will ask you what you want it to inherit from when you create the file, so enter CCSprite.

Your new class will inherit all methods of CCSprite, including the ability to init with an image. In your class's implementation file (the one that ends in .m), create a method called init:

```
- (id) init {
   if ( self = [super init] ) {
      // add your custom code here

   }
   return self;
}

```

What this is doing is overwriting the CCSprite's init method, which is called during the creation of all CCSprites. Because we are overwriting the CCSprite init method, we must call \[super init\] to make sure all of the CCSprites init stuff gets done. In this method, we can also add the label you spoke of.

```
- (id) init {
   if ( self = [super init] ) {
      CCLabelBMFont *label = [[[CCLabelBMFont alloc] initWithString:@"hello world" fntFile:@"somefont"] autorelease];
      [self addChild: label];
   }
   return self;
}

```

So we created a label and added it as a child of the sprite. You can of course modify the labels position and all that here as well. Now when you create an object from your custom class, you will of course have to add it to one of your scene layers before it will become visible. Note that adding a child to a node will automatically retain it, so you can create the label as an autorelease object.
> 2 votes

# Answer
In order to use OOP in Cocos2d, you can utilize the following library

For exact solution utilize the learning

And for a nice introduction, please read this
> 0 votes

# Answer
Subclassing a CCNode and adding CCSprite and CCLabelBMFont as its properties will do the job. You can do this manually (by adding a CCLabelBMFont on your CCSprite) but if you're gonna use this across your project then this is way more efficient.

I don't get your main question though. Cocos2d is already in OOP. Maybe you're talking about MVC???
> 0 votes

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


# Question
Title: Issues with background coordinate configuration in objective c with runAction?
In my game I want to have two backgrounds going one after the other creating a continuous loop moving to the left. However, right now one goes, and the other does not follow it.

Here's what I currently have, which isn't working.

```
if((self = [super init]))
{

    self.isTouchEnabled = YES;

    background=[CCSprite spriteWithFile:@"testbackground88.png"];
    [self addChild:background z:1];
    background.position=ccp(500,240);
    id repeat1 =[CCRepeatForever actionWithAction:[CCSequence actions:
                                                         [CCMoveTo actionWithDuration:7 position:ccp(-300,240)],
                                                         [CCPlace actionWithPosition:ccp(800,240)],nil]];
   [background runAction:repeat1];

    background2=[CCSprite spriteWithFile:@"testbackground92.png"];
    [self addChild:background2 z:1];
    background2.position=ccp(500,240);
    id repeat2 =[CCRepeatForever actionWithAction:[CCSequence actions:
                                                         [CCMoveTo actionWithDuration:7 position:ccp(-300,240)],
                                                         [CCPlace actionWithPosition:ccp(800,240)],nil]];
   [background2 runAction:repeat2];
}

```

# Answer
> 1 votes
Basically you are running both actions at the same exact time. Your code does not "wait" for an action to end before continuing, it simply starts both animations. If you want to wait for one action to end before calling the next animation, you will have to look in to the CCCallFunc or CCCallBlock classes, which basically allow you to insert a function or block into your action sequence.

Then again, you may not want to be using actions for something like this at all. You could just as easily control the background movement manually inside of an update method.

---
Tags: iphone, sprites, cocos2d-iphone
---


title: CCTMXTiledMap continuous scrolling;

text:
# Question
Title: CCTMXTiledMap continuous scrolling;
I have a vertical shooter, the game scrolls TMXTiledMap, and when it runs out I want it to load next map and scroll them seamlessly without interruption. How do I achieve that?

Here is my scrolling method, if I load another map it stops, I need to add scrolling to another map, is there a way around that?

```
- (void) update: (ccTime) delta

{
    CGPoint tempPos = myMap.position;
    tempPos.y -= 2;
    myMap.position = tempPos;
}

```

How do I load next map so they are scrolling seamlessly and connected to each other?

# Answer
you will need two variables, one for oldmap and one for newmap. you will scroll them both. when newmap's right side reaches the right edge of the screen, you will create a another map and add it at screen width (for its y). You will then move newmap into the oldmap, and place the newly created map into newmap. once oldmap's right side has reached the screen's left side, you will remove it all together. The cycle repeats.
> 1 votes

---
Tags: cocos2d-iphone
---


title: Player sprite moving slower on iPhone 4

text:
# Question
Title: Player sprite moving slower on iPhone 4
I just finished getting movement/jump animation for a player sprite in Xcode using Cocos2D. The basic movement algorithm is a timer that updates every 0.01 sec, changing the sprite position to `(sprite.position.x + xVel, sprite.position.y + yVel)`. Each time a movement button is tapped, the appropriate velocity (initialized to 0) is changed to whatever speed I choose, then a stop movement button returns the velocity to 0. It's not an ideal solution but I'm very new at this and **stoked** to at least have that working with little help from the internet.

So I may not have explained that perfectly, but it *is* in fact working to my satisfaction in Xcode's iPhone Simulator, however when I build it for my device and run it on my phone, the sprite's movement speed is noticeably slower than in Xcode. At first I thought it must have to do with the resolution of the iPhone 4, making the sprite's movement path twice as long, but I found that if I pull up the multitask bar, then return to the app the speed will sometimes jump back to normal. My second theory was that the code is just inefficient and is bogging the processes down, but I would see this reflected in the frame rate wouldn't I? It stays at 59-60 the whole time, and the spritesheet animation runs at the correct speed.

Has anyone experienced this? Is this a really obvious issue that I'm completely missing? Any help (or tips for optimizing my approach to movement) would be much appreciated!

# Answer
> 1 votes
The reason it is different speeds is because you are not calculating/using a delta time. Basically the frame rate could be any number at any time slowing or speeding up your animations. To counteract this, programmers calculate a delta time:

```
delta = currentTime - previousFramesTime; // time difference between this frame and the last frame

```

Then use this in their animation:

```
position.y = position.y + (velocity * delta);

```

This way no matter what the framerate is, your animations will remain the same speed.

---
Tags: animation, sprites, cocos2d-iphone, movement, xcode
---


title: OpenGL glMatrixMode rotation

text:
# Question
Title: OpenGL glMatrixMode rotation
I'm stuck on trying to figure out how to rotate the viewport(or camera). So far I've figured out I need to use the function `glRotatef` and `glMatrixMode(GL_MODELVIEW)`. But I have no idea how to apply the rotations to the model view. I'm sorry I have no code to show because I have no idea how to get started. Any help would be greatly appreciated!

# Answer
glRotatef should apply to whatever matrix is currently selected by glMatrixMode. Just execute it after glMatrixMode.

It's worth nothing that glMatrixMode is a deprecated command. The new way of doing things involves using shaders, binding a matrix to them and multiplying them together with the vertex coordinates.
> 1 votes

---
Tags: opengl, java, camera, lwjgl
---


# Question
Title: Handling increasing numbers of users (server)
For this post, we'll assume my game is multiplayer chess as it essentially requires the same functions. User logs in to the server and requests a game - the server provides a simple matching service and once done, they start the game. They get 30 seconds timed by the server per turn with 6 players in each game and however many spectators (probably very limited).

I would like to know how you would scale this.

I've considered two options:

Option 1

1) Main server to handle login / match making (which regardless of user numbers should be a fairly easy task)

2) Start new Node servers for each game that close when the game ends.

I'm not entirely sure how this could be implemented yet. (i.e. would the user connect to the main server still and the requests just be passed to the new server or would the user change connection to the new server and then back again when done? changing connection would reduce the load even further and as the two servers won't require communication between them, should be fairly simple)

Option 2

Have 1 Node server and somehow scale it.

--

Suggestions / input?

I'm planning on hosting on Amazon AWS and am well aware that the chances of my game even warranting this level of detail are probably nil but I'm taking this as a learning opportunity.

Thanks.

# Answer
General way to handle this is to allow multiple game servers to be spun up, and whenever a new game is started, one is chosen and the client is told to connect to that server. You can then add and remove game servers as necessary to scale horizontally, essentially limited by only by hardware/bandwidth capacities.

Scaling up the login servers can be done by using round-robin load-balancing on your servers, which can be achieved at the DNS level, or via a hardware load balancer (generally not cheap, though some data centers offer use of a shared load balancer for a price). The same can be done with the match making servers.

You can also deal with this per region. That is, your customers in China might be using a different set of servers in a Chinese data center while your customers in North America might be using a set of servers in a data center there. Or if NA is where most of your customers are, you can split up the data centers between the east and west halves of the continent.

Things get tricky when it comes to sharing data between your servers. In these cases, it is generally better to have a middle layer between the main game/logic servers and the backend storage. That is, don't have your game servers access a database to look up player information. Instead, create an internal API (using REST over HTTP, or an AMPQ infrastructure, or what have you) that servers use to communicate with backend services. The advantage of this approach is that it makes physically distributing your services easier. You might want those match making and game servers split between China and NA, but you might want all account information to be centralized so players in each region can friend each other and start direct matches with each other (of course one of the two players will be using a non-ideal game server for their location, but no way around that). With an API, you can have your Chinese data center game servers talk to a local API proxy that caches requests made to the "authoritative" servers in NA, allowing distributed operation with good horizontal scalability and a single primary data store for user accounts.

Keep in mind that you'll want to limit that as much as possible to infrequently changing data, since you'll need to do all writes to the primary data center to avoid collisions. That is, you can't share user accounts between a NA and a Chinese datacenter is both can create accounts locally, since two users might try to create a user account with the same name in both regions. Since you'll be forced to use one data center as the authoritative master for this data, that means creating accounts in other regions will be a tad bit slower. Account creation is generally not something that needs fast response times, so that's not a huge deal; if you're trying to track play stats for every move in your game, though, it might become an issue. For cases like that, you'll want to aim towards a data design that allows merging data later in bulk, rather than needing to keep a real-time data set in an authoritative server.

All that said, you probably don't need to worry too much. A simple turn-based board game style of thing is not going to be particularly data intensive, and your odds of getting lucky and being successful enough to have so many users that one server can't handle the load is pretty small.
> 2 votes

---
Tags: multiplayer, server, node.js
---


# Question
Title: What are some good books which detail the fundamentals of graphics processing?
The best book on the nitty gritty of graphics that I've found is Computer Graphics: Principles and Practice http://www.amazon.com/Computer-Graphics-Principles-James-Foley/dp/0201121107

However, as this was written in the early 90s, it is a little out of date.

Are there some similar books which go over the more recent developments?

# Answer
Pick one from each of these and work your way up.

# 1. CG Fundamentals

<sup>† these aren't OpenGL books, they just use OpenGL to teach rudimentary CG concepts</sup>

Of these, my personal favourites are the last two. More practical and hence engrossing for the beginner; the explanations aren't very cryptic, unlike the other, more academic books in the list.

> Reason *Real-Time Rendering* is omitted is it's not a *get your hands dirty* book; it's a broad survey of techniques used in the industry than on fundamentals of CG; theory-heavy than workout-heavy: something beginners need to understand basics well. Even the theory covered is fairly high-level at many points.

# 2. Math Basics

To be proficient in computer graphics or even to understand the basics, a decent amount of mathematical concepts needs to be grasped; it requires one to be comfortable in using trigonometry and linear algebra. For this I recommend

* Vector Math for 3D Computer Graphics is by far the best beginner tutorial for vectors and matrices. It is also interactive in that at the end of each section there's a test question to verify and seal the understanding of that topic.

## Books

Out of these math books, the most intuitive is the first with lot of funny anecdotes in between. The last is for hard core math fanatics (if you're afraid of symbol vomit, steer clear of it); it's a good book for experienced CG programmers who need a reference. The one in between is really good in that it details out some things which the other two -- or many books for that matter -- omit, and in the spectrum of intuitiveness and hard core math it's in between.

# 3. Tutorials

Just reading doesn't seal the concepts so working out is definitely recommended. For that I found these tutorials very good; most give a decent explanation of the theory too.

Don't get too attached to a specific library or tool (e.g. OpenGL, Direct3D, Metal, Vulkan, WebGL, SDL, Quartz, etc.) Once you understand the basic concepts (math behind them), implementing them in any language, framework or library wouldn't be a big deal. Just syntax/compiler would change, but the techniques themselves remain the same.
> 35 votes

# Answer
## Real-Time Rendering

*Not for the faint of heart.*
> 23 votes

# Answer
I've heard that the GPU Gems series of books are a really great read. You can purchase them (a quick search on amazon.com will bring up some results), but they are also free to read online:

http://http.developer.nvidia.com/GPUGems/gpugems\_pref02.html
> 2 votes

# Answer
We used Computer Graphics with OpenGL (Hearn & Baker) when I was in university and I liked it a lot. Despite its name, it gives the fundamentals of 2D and 3D graphics and rendering. OpenGL is used as example when doing 3D graphics, but only after the fundamental maths and algorithms have been presented.

http://www.amazon.com/Computer-Graphics-OpenGL-Donald-Hearn/dp/0130153907

After that, Real Time Rendering as already suggested.
> 2 votes

---
Tags: graphics, books
---


# Question
Title: Suggest a simple Java math library for matrix operations for use with OpenGL (lwjgl)
I'm writing an OpenGL app with Java. I need to do some math for camera and frustum culling (for AABB). Could you suggest a simple and fast Java math library for that?

# Answer
> 3 votes
Vecmath from Java3d http://java.net/projects/vecmath is useful for standard 3d geometry stuff.

Not sure camera and frustum culling would really be a bottleneck, but if you use this heavily you should try to reuse things like Vector3f rather than calling `new` the whole time which can lead to costly garbage collection.

# Answer
> 1 votes
I'am the author of la4j library (Linar Algebra for Java). I've just released verion 0.3.0. Try to look at it. la4j works pretty fine now with sparse and dense matrices.

# Answer
> 0 votes
JAMA math.nist.gov/javanumerics/jama

Colt acs.lbl.gov/software/colt

jblas jblas.org

These come to mind first. jblas, thanks to the natives, seems to be a lot faster than the other though. Keep in mind the applet loader from LWJGL allow you to easily use natives in an applet.

see https://stackoverflow.com/questions/529457/performance-of-java-matrix-math-libraries

---
Tags: opengl, java, mathematics, lwjgl, frustum
---