title: Entity manager loop opinions

text:
# Question
Title: Entity manager loop opinions
This days I'm refactoring code and one of the things I want to improve is my entity manager code. More precisely, the update funcion where entities are updated. My engine is a 2D tile based engine that I'm using for an iphone game. The idea I had was to have the entity update splitted in several tasks because I'm willing to move to component based entities when I have the time. This is a Physic task, a collision detection task, AI task, etc...

For long time I have been using a simple update() function for my entity update that was called by the entity manager in a loop. Now I have come across another way to do it (in the end it is the same) but gives me some advantages like for example differnt ticks for the different tasks (Physics can run at a differnt refresh rate than collisions, etc...)

Here is the source code. I would be really happy if anyone could comment, give opinions, or improve it. Sorry ti is ObjC but I think it is pretty easy to understand:

```
//Run the update process o nall entities.
for(int i=0; i< numGameObjects;++i)
{
    GameObject* go=_entities[i];

    //If this game object was marked to be delted don't do any process with it.
    //It will be released when update loop is finished.
    if(! [go isToBeDeleted])
    {
        //Player does its physics (Movement, etc...)
                    //We save old position to let the onMapCollision know
                    //The previous position before physics were applied.
        CGPoint oldPos=[go position];
        [go doPhysics];

        if([go collisionEnabled])
        {
            //Check collisions against map
            CollisionMask collisionMask=[go collisionMask];
            if(collisionMask & MapEntity)
            {
                bool collision=[self checkEntityVsMapCollision:go];
                if(collision==true)
                    [go onMapCollision:oldPos];
            }

            //Check collisions against other entities (just the ones that have not been checked previously)
            for(int j=i+1; j < numGameObjects; ++j)
            {
                GameObject* otherGO= _entities[j];
                EntityType type=[go type];
                if( (collisionMask & type) && [go collidesWith:otherGO])
                {
                    [go onEntityCollision:otherGO];
                    [otherGO onEntityCollision:go];
                }
            }
        }

        //Execute AI for this game object
        [go doLogic];
    }
}

```

There could be some sintactical errors in the code but I just wanted to show the idea. Sorry for the long question, but I thought I had to explain everything as clear as I could.

Thanks in advance.

# Answer
> 2 votes
My entity system lib uses messages for updating. Each frame a TickMessage is sent. Entity systems can register themselves to the tick message, and can do that with a "priority": earliest, early, default, late. The registrants are called in the order of their priority. This way, the physics system can run before the rendering system but after the input system and so on. The tick message contains the time since the game started, the delta timew since the last frame and the unix timestamp.

This approach is a little more complicated than calling a virtual update method on each system, but I think it is worth it. Entity systems can deregister themselves when they have nothing to do, which saves a lot of computing power.

# Answer
> 2 votes
I would start with extracting 'entity systems' based on kind of update:

PhysicsSystem, CollisionSystem, AiSystem

After some further refactoring you might end up with a class like EntitySystemsManager which will have a method Update that loops through collection of systems updating those of them that are enabled.

---
Tags: architecture, game-loop, entity-system, physics-engine
---


# Question
Title: smooth animation following a random path in real time
So, I'm toying around with an augmented reality game. I'm using computer vision to track a particular object, which works reasonably well. I'm trying to animate something that basically follows that object around on screen.

This has proven pretty hard. The tracked location of the object is very jittery. I've tried to smooth it out by setting a threshold under which we don't bother moving the sprite, but this leads to jumpy animation rather than jittery. I want the sprite to follow the tracked object in close to real time, so aggregating movement over a lot of frames to get smooth results isn't a great option for me.

Are there any techniques I could use in this case that might help smooth things out?

# Answer
Springs using Hooke's Law can help here, they are basically a low-pass filter, filtering out the high frequency jittering. One end of the spring is connected to the *following object*, the other end is connected to its (jittering) target position.

Here is a gafferongames article about them.

---

A simpler solution might be to use an easing function to make the object follow the jittering target-position smoother.
> 1 votes

---
Tags: animation
---


# Question
Title: How do I connect circuit to PC so that I can use it to play a game?
I made a circuit, which acts like a digital dice using diodes 1N4148, IC 555, IC 4017, 8 & 16 pin IC socket, LED, push-to-on switch, resistors & connecters.

By pressing the push button, 4017 counter toggles between 0 & until released. Once released, a random number is displayed. This is determined by the clock pulse generated by IC 555, which determines the state of 4017 counter.

Now I am thinking of making an application so as to capture this value(LED's lit) so that it can be used in a game like **monopoly**.

Is there any way I can achieve this ?

# Answer
> 4 votes
You have several options, each has advantages and disadvantages:

* You can connect each of your wires directly to a parallel port if your PC has one as these typically use TTL logic levels. Note that it's a good idea to use ribbon cables or some tape / elastic bands as lots of wires here can be a pain.
* You can send data over a Serial port fairly easily with any AVR or programmable chip. These typically have serial libraries in C that you can use that can read the output from your dice and write it to the serial port in the form of an ascii symbol. Note that serial RS-232 serial uses different logic levels to your 74 series circuits (rather than 0v and 5v they use somewhere between -3 and -25v for logic 1 and 3v and 25v for logic 0. You need to specify the baud rate of transmission in both your transmitter and your receiving software. Assuming you have a power supply capable of negative voltages you can use something like a MAX232 to convert the levels for you nice and easily.
* There's several commercial systems that make this easier if you don't have access to output to serial manually. For instance the Arduino doesn't need any of that, it has it's own FTDI chip and can send serial data straight over USB which you can read via a virtual serial port on any modern computer. It's a bit more expensive than doing it manually (AVRs are very cheap) but very simple to do, they provide a C-like library to program them and you do everything over USB. There's even a programs that show you how to use serial. You would simply read the the logic values from your dice, convert them to a number and write them to serial.
* There's some very expensive options such as using infra-red (if you have a receiver) or bluetooth (very expensive, and requires an AVR or similar device to use it).

For reading data on the other side, there's some nice libraries such as PySerial which allow you to read serial data in Python, or you can do it directly from C/C++ on Linux as there's usually a serial port defined as `/dev/ttyS*` (`/dev/ttyUSB*` in the case of Arduino's virtual serial ports). The GNU screen program allows two way communication with any device as well, and in Windows MATLAB also has the ability to read in serial data, and I'm sure it's possible in other languages - I've just never tried it.

If you're not too experienced with the systems I'd recommend the Arduino. It has many more uses than the fairly simple circuit you're after and might be a little overkill, but you can do a lot of awesome things with it and it's an all in one solution that doesn't require any extras.

Edit: The serial port options I described all allow data to be sent both ways very easily, you should note that you'll need to add some extra circuitry to your dice circuit in order to use this with a parallel port.

# Answer
> 2 votes
Am I missing something? If your goal is a "digital dice" hardware for use with physical games, then no pc is required. On the other hand, if your goal is a PC game, it already has a perfectly good random number generator, and has no need of your hardware, and even if your hardware were somehow useful, no existing application will know how to use it.

So, assuming this is just a cool science fair project, not a serious attempt to build hardware to be bought, sold, and used, I would think about packaging it as a USB device. www.usb.org has exact specs for what is acceptable electrical properties.

# Answer
> 1 votes
I'm quite sure you can connect a device like that on the Parallel port of a PC.

The program would read the value of the 4017 and the button.

Or you could connect a button and 6 diodes to the port and let the computer do the rolling and lighting.

# Answer
> 1 votes
You'll have to build an additional or different circuit to communicate with the PC. Something you make yourself would likely be over the Parallel port.

However, I'd recommend using a micro controller for communication. Something like the Arduino. Many have USB connections and will allow you to interface with your existing circuit with a few changes. Arduino also has plenty of helpful tutorials. Additionally, a micro controller will allow you to easily expand to other types of control inputs and hardware outputs.

# Answer
> 1 votes
You could do an arms-length integration by using a web cam and image recognition to decide what number was rolled. Get fancy and call it an "optical air interface" to make it sound official.

FYI this is how those lava lamp random number generators work, so there is good precedent. http://en.wikipedia.org/wiki/Lavarand

# Answer
> 0 votes
Easiest methods I know are:

1. USB experiment boards. These are relatively cheap and give a bunch of I/o pins you can control through some API on pc.
2. USB connectivity kits such as PSoC can be used to make your device look like a keyboard or joystick.

Parallel port is nice, but hard to find on a modern pc, and windows has made its programming rather difficult since XP or so.

---
Tags: hardware
---


title: How to detect collisions in AS3?

text:
# Question
Title: How to detect collisions in AS3?
I'm trying to make a simple game, when the ball falls into certain block, you win.

**Mechanics:** The ball falls through several obstacles, in the end there are two blocks, if the ball touches the left block you win, the next level will contain more blocks and less space between them.

**Test the movie** (click on the screen to drop the ball): http://gabrielmeono.com/downloads/Lucky\_Hit\_Alpha.swf

**These are the main variables:**

```
    var winBox:QuickObject;//You win
    var looseBox:QuickObject;//You loose
    var gameBall:QuickObject;//Ball dropped

```

**Question:**

*How do I trigger a collision function if the ball hits the winBox? (Win message/Next level)*

Thanks, here is the full code:

```
    package  {

    import flash.display.MovieClip;
    import com.actionsnippet.qbox.*;
    import flash.events.MouseEvent;

    [SWF(width = 600, height = 600, frameRate = 60)]

    public class LuckyHit extends MovieClip {

        public var sim:QuickBox2D;
        var winBox:QuickObject;
        var looseBox:QuickObject;
        var gameBall:QuickObject;

        /**
         * Constructor
         */
        public function LuckyHit()
        {
            sim = new QuickBox2D(this);
            //sim.createStageWalls();
            winBox = sim.addBox({x:5,y:600/30, width:300/30, height:10/30, density:0});
            looseBox = sim.addBox({x:15,y:600/30, width:300/30, height:10/30, density:0});

            // make obstacles
            for (var i:int = 0; i<(stage.stageWidth/50); i++){
            //End
                 sim.addCircle({x:1 + i * 1.5, y:16, radius:0.1, density:0});
                 sim.addCircle({x:2 + i * 1.5, y:15, radius:0.1, density:0});

            //Mid End

                  sim.addCircle({x:0 + i * 2, y:14, radius:0.1, density:0});
                  sim.addCircle({x:0 + i * 2, y:13, radius:0.1, density:0});
                  sim.addCircle({x:0 + i * 2, y:12, radius:0.1, density:0});
                  sim.addCircle({x:0 + i * 2, y:11, radius:0.1, density:0});
                  sim.addCircle({x:0 + i * 2, y:10, radius:0.1, density:0});

            //Middle Start
                 sim.addCircle({x:0 + i * 1.5, y:09, radius:0.1, density:0});
                 sim.addCircle({x:1 + i * 1.5, y:08, radius:0.1, density:0});
                 sim.addCircle({x:0 + i * 1.5, y:07, radius:0.1, density:0});
                 sim.addCircle({x:1 + i * 1.5, y:06, radius:0.1, density:0});

            }

            sim.start();

            stage.addEventListener(MouseEvent.CLICK, _clicked);
        }

        /**
         * ..
         * @param e MouseEvent.CLICK
         */

        private function _clicked(e:MouseEvent)
        {
            gameBall = sim.addCircle({x:(mouseX/30), y:(1), radius:0.25, density:5});

        }
    }

}

```

# Answer
> 1 votes
Got help from atomparker at stackexchange, The class needed is QuickContacts inside BOX2D library.

Here's the code for future reference:

```
   var simContacts:QuickContacts;

public function LuckyHit()
{
    ...
    simContacts = sim.addContactListener();
    simContacts.addEventListener(QuickContacts.ADD, contactListener);
}

...

private function contactListener(event:Event)
{
    if (simContacts.isCurrentContact(winBox, gameBall))
    {
        // They won.
    }
}

```

The relevant class in the QuickBox2D documentation is **QuickContacts**.

---
Tags: collision-detection, actionscript-3, box2d
---


# Question
Title: Can't change the textures of a .FBX or an .X exported from 3dsmax
I created a model (real simple) in 3DSMax 2010, exported it to FBX format and loaded it in an XNA 4.0 content project. I also tried with .X files using kW X-port and it has the same behavior.

I can load the model in a game, and it has it's 3DSMax texture. I can't however change the texture of a face (or all) at runtime. When I do this, it doesn't crash or anything, it just doesn't apply the textures.

I've tried with a sample model from a microsoft creative tutorial (the famous spaceship one) and on that model, with my texture, it works. This is why I think my model isn't working properly.

Anyone care to comment/help?

Note: Even though I don't think the problem is there since I've made it work with another model, here is my LoadContent method to load the model and change the texture of all mesh :

```
protected override void LoadContent()
{
    base.LoadContent();

    ContentManager contentManager = new ContentManager(Game.Services, "Content");

    Model = (Model)contentManager.Load<Model>(ModelName);
    Texture = (Texture2D)contentManager.Load<Texture2D>(TextureName);

    foreach (ModelMesh mesh in Model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.Texture = Texture;
        }
    }
}

```

# Answer
> 2 votes
Ok, so yes the problem is in your model. You haven't set:

1. UVW mapping for your geometry
2. A diffuse map for your material.

In 3ds max, when you use the `Standard` material on your model and change the `Diffuse Color` the material doesn't actually have a texture, and so it doesn't use one even if you give it one later.

Basically, here are the steps to make it work (sorry if you don't need such a specific list, but I'll make it usable by anyone):

1. Make the diffuse color of your material grey.
2. Click the little box next to the diffuse channel to give it a map, and choose bitmap.
3. Navigate to your initial texture.
4. Choose it.
5. UVW map your geometry, there are so many tutorials about this on the internet that it's pointless to put one here.
6. Export it again, and, depending on the exporter, choose 'Copy textures to output' or the equivalent.

If you do all of this it should work, as I've made it work on my computer

---
Tags: xna, c#, textures, 3dsmax
---


# Question
Title: How to create a 2D region where sprites are automatically wrapped?
**Edit**

Finally managed to get this to work, after two separate questions! Here's a video demonstration:

http://www.youtube.com/watch?v=nZ7e0jegvs0

Will write an article about it later when I have a chance since there's a lot of little tricks involved. Thanks to everyone who helped figure this out. Meanwhile, the solution for the rendering part is described on this question, while for the physics part of the solution, check this other question.

---

**Disclaimer**

I'm looking for intelligent solutions that encapsulate this behavior in a way that is transparent to the user. Don't simply answer "draw the sprite four times". For instance, something that could be packed up in a class like:

```
class Sprite
{
    Vector2 Position;
    float Rotation;
    float Scale;

    Texture2D Texture;

    Rectangle? WrapRegion;

    void Draw(SpriteBatch spriteBatch);
    bool IsColliding(Sprite other);
}

```

By the way, there's no need to post any code, just a description of how to solve each of the problems will do.

**Problem**

**1 -** By wrapped I mean that when they leave the borders of that region, they continuously appear on the opposite side, i.e:

So simply changing the sprite's position clearly is not enough. The sprite might have to be drawn either 2 or 4 times depending on its position in relation to the region.

And despite needing to draw it several times, I should still be able to do, for instance:

```
sprite.Position += Vector2.One; // Every frame

```

And the sprite's Position would automatically wrap within the area.

**2 -** Another problem would be how to handle collisions between wrapped sprites properly. For instance:

This should trigger *only one* collision (okay, consider that they are overlapping a bit although the drawing might not suggest it).

Checking for the collision manually shouldn't be too hard.

But the bigger problem arises when using this **together with a physics engine** (which is what I tried to do before and failed). How would I coerce the physics engine into handling this problem correctly, since there's usually a 1 to 1 correspondence between the physics body and the sprite representation?

**Edit**

You can see the solution to this particular point here. I create 9 bodies attached to each other using the joint described in that question, like so:

**3 -** Finally, and being more specific about XNA in this case, if the wrap region happens to be smaller than the Viewport, what would be the best way to clip the sprite so that it does't show outside the region anywhere?

Take into consideration that the sprite may be rotated or scaled too.

# Answer
> 3 votes
**Problem 1**: I solved this by using a render target that was larger than the area. It should be able to encompass the halfwidth/halfheight of your biggest sprite. In my example, I just decided to use a size three times as high and wide as the game render area. I cut the render target into nine pieces, and render them all on top of each other. Here's the code:

```
private const Int32 WIDTH = 320;
private const Int32 HEIGHT = 240;
private RenderTarget2D wrapTarget;

protected override void LoadContent()
{
    this.wrapTarget = new RenderTarget2D(this.GraphicsDevice, WIDTH * 3, HEIGHT * 3);
}

protected override void Draw(GameTime gameTime)
{
    this.GraphicsDevice.SetRenderTarget(this.wrapTarget);
    this.GraphicsDevice.Clear(Color.Transparent); // has to be transparent, to allow all segments to overlap properly.

    // the translation matrix saves you from offsetting all coordinates, since we want to draw at the center segment of the wrapTarget rendertarget.
    this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, Matrix.CreateTranslation(WIDTH, HEIGHT, 0.00f));

    this.spriteBatch.Draw(this.circle, this.circlePosition, null, Color.White, 0.00f, new Vector2(this.circle.Width / 2.00f, this.circle.Height / 2.00f), Vector2.One, SpriteEffects.None, 0);
    this.spriteBatch.Draw(this.square, this.squarePosition, null, Color.White, 0.00f, new Vector2(this.square.Width / 2.00f, this.square.Height / 2.00f), Vector2.One, SpriteEffects.None, 0);

    this.spriteBatch.End();

    this.GraphicsDevice.SetRenderTarget(null);
    this.GraphicsDevice.Clear(Color.LightYellow); // this is the actual background color you want.

    this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

    this.spriteBatch.Draw(this.wrapTarget, Vector2.Zero, new Rectangle(0, 0, WIDTH, HEIGHT), Color.White);
    this.spriteBatch.Draw(this.wrapTarget, Vector2.Zero, new Rectangle(WIDTH, 0, WIDTH, HEIGHT), Color.White);
    this.spriteBatch.Draw(this.wrapTarget, Vector2.Zero, new Rectangle(WIDTH * 2, 0, WIDTH, HEIGHT), Color.White);
    this.spriteBatch.Draw(this.wrapTarget, Vector2.Zero, new Rectangle(0, HEIGHT, WIDTH, HEIGHT), Color.White);
    this.spriteBatch.Draw(this.wrapTarget, Vector2.Zero, new Rectangle(WIDTH, HEIGHT, WIDTH, HEIGHT), Color.White);
    this.spriteBatch.Draw(this.wrapTarget, Vector2.Zero, new Rectangle(WIDTH * 2, HEIGHT, WIDTH, HEIGHT), Color.White);
    this.spriteBatch.Draw(this.wrapTarget, Vector2.Zero, new Rectangle(0, HEIGHT * 2, WIDTH, HEIGHT), Color.White);
    this.spriteBatch.Draw(this.wrapTarget, Vector2.Zero, new Rectangle(WIDTH, HEIGHT * 2, WIDTH, HEIGHT), Color.White);
    this.spriteBatch.Draw(this.wrapTarget, Vector2.Zero, new Rectangle(WIDTH * 2, HEIGHT * 2, WIDTH, HEIGHT), Color.White);

    this.spriteBatch.End();

    base.Draw(gameTime);
}

```

**Problem 2**: This I have no idea how to solve.

**Problem 3**: This method automatically does that. You can replace the Vector2.Zero in the nine SpriteBatch.Draw inside the second SpriteBatch.Begin/End block to draw it wherever you'd like.

---
Tags: xna, 2d, sprites
---


title: XNA - Incorrect Mouse Ray?

text:
# Question
Title: XNA - Incorrect Mouse Ray?
I have the following code:

```
Vector3 nearSource = new Vector3(mState.X, mState.Y, 0.0f);
Vector3 farSource = new Vector3(mState.X, mState.Y, 3.0f);
Vector3 nearPoint = Main.main.GraphicsDevice.Viewport.Unproject(nearSource, Main.main.projection, Main.main.view, Matrix.Identity);
Vector3 farPoint = Main.main.GraphicsDevice.Viewport.Unproject(farSource, Main.main.projection, Main.main.view, Matrix.Identity);
Vector3 direction = farPoint - nearPoint;
direction.Normalize();

Ray ray = new Ray(nearPoint, direction);

```

When my camera is facing direction DOWN, it still says that farPoint.Y is greater than nearPoint.Y

Why would it be doing this? The farpoint should be futher down if that is the direction I am facing.

# Answer
> 2 votes
You can't use 3 as the Z value for your farSource variable. Change it to 1 instead:

```
Vector3 nearSource = new Vector3(mState.X, mState.Y, 0f);
Vector3 farSource = new Vector3(mState.X, mState.Y, 1f);

```

Viewport.Unproject expects a source position in **screen space**, where the Z value varies between 0 at the near clip plane and 1 at the far clip plane.

---
Tags: xna, vector, raycasting
---


# Question
Title: How do I install SDL.NET in Visual Studio 2010? (Or any other .NET library)
I'm trying to get SDL.NET to work in Visual Studio 2010, but am really not sure how to go about installing the library (or creating a custom project or something), and any basic instructions would be appreciated. :)

(Im also trying to install the Farseer Physics library and later MOGRE)

Thanks!

# Answer
For whatever project you want to add the requirement to. Right click the References folder then go to browse and find the .dll you want to add.

To add a source project such as Farseer so that you can look though it while using it. Right click the solution and add the project to the solution. Then right click the References folder for your project then click the projects tab and add Farseer.
> 3 votes

---
Tags: visual-studio
---


title: Should I learn 3DS Max or Maya?

text:
# Question
Title: Should I learn 3DS Max or Maya?
I have two options to choose from: 3DS Max or Maya. I am not going into the commercial line.

I need to get advice from users on which thing I should choose provided I am really not going in to character animation. I just want building, landscapes, moving objects, et cetera.

I have to start, so I think its better to ask.

# Answer
Judging by the fact that you can arbitrarily choose between two $3500 tools to work with, I guess the price doesn't really matter. I don't really think it matters which of the two you use -- I'm sure some UIs/workflows will just click better with some than others.

It seems like you're asking for advice between using a mechanical pencil or a wooden pencil for sketching. I'm sure there are advocates for both who will give you contradictory opinions on why one is better suited than the other for the task. There isn't really a strong reason that I've seen to prefer either of these tools over the other for the task of "just modeling". You can probably use any number of other tools: Milkshape, Wings3D, Blender, etc.

Why don't you find tutorials on how to use one tool and follow them -- get a feel for each program. There are trials available from Autodesk for both. In other words, if 10,000 people tell you here "Use 3DS Max" but it just doesn't click with you the way that Maya does, why use 3DS Max? Vice versa for any tools listed. Do what works, and master your tool. Any of them are sufficient to do what you want.
> 7 votes

# Answer
Well, I would like to add my opinions to this discussion thread. I am a self learner & hobbyist in the field of CG not as much learned as you guys. I started by learning Maya only but have tried every software out there even 3ds Max as well. I simply want to mention that it doesn't matter which piece of package you are using to create your own stuffs as far as they are appealing and looks good, the only thing which matters is the comfort in using that software which differs from user to user. I prefer Maya for most of my works coz I find it more user friendly and easy however, some people may find MAX easier than Maya just because they are familiar with it. Both of them are beasts in their respective areas and you will find most of the tools available in both the suites, but its personal preference only. Moreover, the CG industry looks for professionals only and not amateur, so its better to learn only one of them to the full though its not possible to touch every aspect of any of these suites still try to grab as much as you can rather trying to put your hands on each one of them ...

Now a days, Maya has been incorporated in every field like MOVIES, GAMING etc, which was earlier dominated mostly by MAX. So, you can start your career with any one & can switch to a different suite at a later point of time & ofcourse, sometimes it depends upon the requirements of the studio where you are working as per their pipeline structure. So, if you take my suggestion I would prefer Maya ( or if you wish can start with MAX as well ) reason being I find it pretty easy for a beginner to understand the tools as they are pretty much straight forward. I find the UI of MAX a lil bit weird & the most exciting thing about MAYA is its shortcut keys & you can perform a single task in Maya in atleast more than 3 ways :D, so choice is yours, make your decision and put your first step in the industry ..

Wishing you all the best .. !!
> 1 votes

# Answer
Have you tried Google Sketchup? I think you should try this as well
> 1 votes

# Answer
Neither is really better than the other, so try both and use whichever you prefer. Or rather, go with whichever is most convenient to learn on (eg. one is already installed on computers at your school) because it doesn't make a whole lot of difference.

For the record, I learned on 3ds Max but later switched to Maya when that became available on Macs. I still consider them about the same however and actually at my current job I use 3ds Max occasionally because that's what they have.
> 0 votes

---
Tags: 3dsmax, maya
---


# Question
Title: What to look for when searching an artist for doing graphics?
I was wondering which skills I should ask for when I need someone to make the graphical part for a 2D game intended for iOS or Android.

Not really looking for someone right now, but working on a project and don't really know what to ask for, equally I want to avoid thinking only in experienced artists working for iOS or Android developments, but I would want to ask for necessary similar skills.

---

Thank u all by the answers, very useful.

As I said before I would be interested in 2D graphics, but speaking about what to ask to a friend of mine, who's very skilled, he's traditional painter, but i don't know what should i ask him to learn related with the computer artwork, for doing the 2D artwork on the computer.

# Answer
Make sure they are able to commit the number of hours you expect -- get it in writing if you possibly can.

Make sure they are capable in regards to the art style you want. It is *not* the same to take someone who "thinks they can" do a certain style, because it will take them some time to get familiar with execution, and their time is your money -- even if they are just volunteers.

And be as sure as you can possibly be that this is really, truly what they want to be doing at the present time. That way you will get much better commitment out of them.
> 5 votes

# Answer
If you're looking for just one person, then there are a lot of skills this person should have!

* Good illustration skills (eg. for character-design)
* Good knowledge of computer based creative-tools, preferably knowing technical requirements for games (you don't want to scan and crop some drawings, do you?)
* Person should have a feeling for good UI-Design
* Good knowledge of typography and readability
* Must also be able to create animations and effects
* Able to create icons (logo) for a game (note, that this is an entirely different skill-set sometimes)
* Should be able to produce a consistent look and feel within given requirements

I think these are some common requirements. Each one of these requirements could be filled by a single person, so finding one that excels at all of them will be near impossible. You should therefore set some priorities what's most important to you.

In addition to the above, there's also the usual skills that should be there, like good communication and teamwork skills etc.

**Update:** Since you extended your question, here's an updated answer. So you have a skilled friend and you would like to give him advice on what to learn, so that he can participate in your game-project.

I'd say it highly depends on the art-style you're going for. If he's a painter and you're creating a game with painted assets, even better. Then the main thing he has to learn is to scan the paintings and mask them (eg. apply define the transparent and opaque areas of the sprite). Also he should pay attention to scale. It doesn't make sense to paint lots of details when the assets are going to be shown with only a few pixels in size.

Knowing tools like Photoshop/GIMP and Illustrator/Inkscape is a must and something he/she should learn first.
> 2 votes

# Answer
I think nobody mentioned this yet. It's not really on the technical skills side, more the personal aspect of it:

Make sure you get an artist who has either already successfully participated in gaming projects or at least someone who you know of has the right attitude to do art.

One thing that many artists have in common is that they view whatever they create as finished pieces of art that has some kind of value. In game development it's often required for them to draw something for hours on end just to completely abandon it in the end because it doesn't work for the game and needs to be redrawn. A lot of artists will get very upset upon getting told this by you, the programmer, and you need someone who can deal with this with no problem.

This is an attitude problem that programmers, for example, don't have, because we learn very early on that most code is rewritten 5 times before it's an acceptable version.
> 2 votes

# Answer
Decide what kind of graphics you need: vector, high-res raster, pixel-art, 3D rendered.

Decide what kind of style you need: casual-cartoonish, hardcore-realistic etc.

Look/ask for portfolios based on those preferences and pick the one you like the most. They should have some game art (sprites, not concept-art) in their portfolios.
> 1 votes

---
Tags: graphics, art, human-resources
---


# Question
Title: Collision detection in a 3D heightmap-based world
I'm creating a simple engine to increase my knowledge, and have a Minecraft like world, but the height is only one block.

How would you suggest I detect for collision? AABB would be good, but I have no clue. My map is stored in a 2 dimensional byte array, and I have the current location of the "player"/camera in X, Y and Z as well as the yaw (0-360 degrees).

I'm using LWJGL if that makes a difference, any ideas?

# Answer
You world is a 2 dimensional byte array storing what? Height? Tile type? You won't be able to have caves if it's only 2 dimensional, only hills. But anyway, the general idea would be something like:

**Vertical Collision (Floor)**

Divide the player's (X,Z) by the block's size to know which block he's currently on top of. Find the height of the floor in that block (by checking your array at that position). If it's lower than the player's Y apply gravity, in order to make the player fall. Otherwise, set the player's Y to be the height at that spot, in order to ground him.

**Horizontal Collision (Walls)**

When moving the player, check the block he's on *before and after* the movement. If he crossed a block boundary by moving (i.e. the current block changed) check the height of the new block. If it's higher than his current height, cancel the movement because he must have hit a wall (or clamp his position against the edge of the block).
> 7 votes

---
Tags: collision-detection
---


# Question
Title: What is a fair latency, to cut off game connection at?
I'm currently coding a realtime game. I'm doing alot of technical operations with the physics world (resimulations of old world states etc.) to prevent game lag. I save the world state every physics update, so I can re simulate it later if needed.

Of course this consumes alot of memory, so I'm trying to decide after what period will I remove old world states. For example, if a world state is *250 milliseconds* old, remove it from memory. Then, if any player movements are received from players, that occurred more than 250 milliseconds old, discard them.

This would theoretically discontinue any physics movements of players with a latency of 250+. This is to improve the performance/experience for other players, and to maintain low memory usage.

My question is, what is a fair latency to cut off players at (for the good of other players)?

# Answer
It depends on how fast things happen in your game, and what typical latency you expect from your players.

My gut feeling is that 0.25 seconds is too little. World of Tides, a game I worked on that used this approach, stored several seconds worth of history.

**Added** Also, you most probably do not need to save a snapshot of a whole world for every frame. Save only some key values and interpolate between them - this would save you a lot of memory.
> 2 votes

# Answer
You don't need to save the entire world state, only the things that are relevant to the players. Particles, static actors, shaders etc. is irrelevant. Maybe even animations depending on your game. If only relevant information is stored, it shouldn't take that much memory.

I would recommend saving like a full second of gameplay. Remember to clear old data when you recieve a correction from the server. All data stored before the correction timestamp (not the current time) can be cleared. If it was more than a second the game would be unplayable anyway with the correction happening sooner than the recieved package.
> 1 votes

---
Tags: physics, networking, optimization, simulations
---


# Question
Title: Project development in a long distance Indie Dev environment
Myself and 4 other coders have been working as a modding team for the past 7 months. We all have a very good grasp on our preferred language (C#), and also use versioning (GitHub / BitBucket / Assembler) to organize our code, and updates.

We want to now get into developing our own game. We have an idea, and have a very basic engine in place.

How do we project manage from here?

Obviously we dont want to dive into adding content, but how do we manage the project from here? Should we assign tasks to each person? How do we manage the project do that each person gets a fair share of work? Once we have a game, how should profits be split?

Any advice on this is welcome.

Thanks Twitchy

# Answer
> 8 votes
## How to manage a project remotely

### Establish communication channels

and routines for how to communicate so that information is never lost, and so that it is shared between everyone who wishes to partake in that flow of information.

*Communication is the pillar your project will stand on, if it isn't rigid and sturdy, your project's downfall is inevitable.*

**Suggestions:**

* IRC - setup a channel for your communication and let the words flow.
* Skype - weekly conversations among yourselves, get to know each other!
* Forums/Bulletin Boards - this is good to keep information stored for future reference.
* GitHub's issue tracker - I love this feature, you can discuss/vote/peer-review everything.

### Use a project management tool

to keep a transparent view of your roadmap, how it's going, what needs to be done and what is planned for the future.

**Pick a development methodology**
There are several different methodologies for how to manage your project, I'm personally in favor of Agile/XP. Here are some moar.

**Suggestions:**

I personally like Trello the most, you can assign work there based on the tasks you create, and it's very versatile, so you can use it for lots of different needs!

## How to handle the profits

If you are serious about your passion and project, you should create a company, but this is a bit over my head, so I can't give you more advice on this except that it will be easier to determine ownership at the end of the month if everyone have their ownership stated and signed on paper witnessed by lawyers.

---
Tags: project-management
---


title: How to debug pyglet/opengl bus errors

text:
# Question
Title: How to debug pyglet/opengl bus errors
I'm using pyglet for game development, and sometimes encounter "bus errors". They are not consistently repeatable, and whenever I try to do simple debugging (eg move/remove variables, etc), the errors will eventually disappear entirely. I feel like I am encountering the notorious "heisenbug" class of errors.

Intuitively, I feel like the problem is likely due to pyglet/opengl/video card interaction, but of course this is only a hunch. So my question is: how do I debug this kind of problem?

# Answer
The most straightforward thing to do is to run your game through a debugger. `pdb` is python's default debugger, but IIRC there are good alternatives, such as `bpython`. Once an error happens, you'll be in the python's console and be able to debug the problem.

Since a "bus error" is, unless I'm not mistaken, something similar to a good old "segmentation fault", I *guess* you could instead somehow have it drop a core dump and analyze that, which is a less invasive method than running through a debugger... but unless you find quick and easy instruction about how to do that, I wouldn't bother.
> 0 votes

---
Tags: opengl, debugging, pyglet
---


title: gluLookAt on OpenGLES2

text:
# Question
Title: gluLookAt on OpenGLES2
`gluLookAt` is not available in OpenGLES 2. OpenGLES 2 is also using floats not doubles.

Taking the description on the `gluLookAt` man-page, I have implemented it like this:

```
void graphics_t::set_mvp_look_at(const vec_t& eye,const vec_t& centre,const vec_t& up) {
#if !defined(GL2) && !defined(NDEBUG)
    matrix_t check;
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixf(pimpl->mvp.f);
    gluLookAt(eye.x,eye.y,eye.z,centre.x,centre.y,centre.z,up.x,up.y,up.z);
    glGetFloatv(GL_PROJECTION_MATRIX,check.f);
#endif
    const vec_t f((centre-eye).normalised()),
        s(f.cross(up.normalised())),
        u(s.cross(f));
    const matrix_t m = {{
        s.x, s.y, s.z, 0,
        u.x, u.y, u.z, 0,
        -f.x, -f.y, -f.z, 0,
        0, 0, 0, 1
    }};
    set_mvp_matrix(matrix_t::translation(-eye).transposition() * (m.transposition() * pimpl->mvp)); // setter notifies shader
#if !defined(GL2) && !defined(NDEBUG)
    if(pimpl->mvp != check)
        std::cout << "WARNING! Error setting look-up: " << std::endl << pimpl->mvp << std::endl << " != " << std::endl << check << std::endl;
#endif
}

```

As you can see I have some inline unit-testing when building for a non-OpenGLES 2 target (that's my own GL2 define).

Now the code seems to work, although it feels somehow slightly wrong depth but I can't put my fingers on that.

However, the code is printing warnings all the time, e.g.:

> WARNING! Error setting look-up: matrix\_t\<\[4.79627,0,0.424102,-261.019\],\[0.243815,5.79255,-2.75737,51.5329\],\[0.158943,-0.862347,-1.79752,269.079\],\[0.0794715,-0.431174,-0.898762,350.119\]\> != matrix\_t\<\[5.31579,0,0.470039,-289.291\],\[0.270225,6.41998,-3.05604,57.1149\],\[0.158943,-0.862347,-1.79752,269.079\],\[0.0794715,-0.431174,-0.898762,350.119\]\>

As you can see, the numbers are very nearly the same but not-quite.

My comparision function for my matrix class is fuzzy with `if(fabs(f[i]-rhs.f[i])>0.001) return false;`.

Is this error within expected bounds when using float precision instead of doubles? Or is there a bigger bug in my translation?

# Answer
You need to normalise all base vectors. The purpose of the cross products is to get a direction, so there is no need to normalise before the cross product, but you need to do it afterwards. You can skip the step if you know the arguments were normalised *and* orthogonal to each other.

The following:

```
const vec_t f((centre-eye).normalised()),
            s(f.cross(up.normalised())),
            u(s.cross(f))

```

should instead be:

```
const vec_t f((centre-eye).normalised()),
            s(f.cross(up).normalised()), /* <- only this line changes */
            u(s.cross(f))

```

As for your question regarding floats instead of doubles, floats have a mantissa of 24 bits (32 minus 1 for the sign and 8 for the exponent, plus the implicit top mantissa value), which is approximately 7 decimal digits. So *in general* you should not get any precision loss before the 6th decimal, unless of course you do things like subtracting two very close numbers.

**Edit:** by construction, `u` doesn't need to be normalised; I removed the useless call.
> 4 votes

---
Tags: opengl-es2
---


title: GLM: Euler Angles to Quaternion

text:
# Question
Title: GLM: Euler Angles to Quaternion
I hope you know **GL Mathematics** (GLM) because I've got a problem, I can not break:

I have a set of **Euler Angles** and I need to perform **smooth interpolation** between them. The best way is converting them to **Quaternions** and applying **SLERP** alrogirthm.

The issue I have is how to **initialize** glm::quaternion with Euler Angles, please?

I read GLM Documentation over and over, but I can not find appropriate `Quaternion constructor signature`, that would take three Euler Angles. The closest one I found is angleAxis() function, taking angle value and an axis for that angle. Note, please, what I am looking for si a way, how to parse `RotX, RotY, RotZ`.

---

For your information, this is the above metnioned angleAxis() **function signature**:

```
detail::tquat< valType > angleAxis (valType const &angle, valType const &x, valType const &y, valType const &z)

```

# Answer
> 15 votes
I'm not familiar with GLM, but in the absence of a function to directly convert from Euler angles into quaternions, you can use the "rotation around an axis" functions (such as "angleAxis") to it yourself.

Here's how (pseudocode):

```
Quaternion QuatAroundX = Quaternion( Vector3(1.0,0.0,0.0), EulerAngle.x );
Quaternion QuatAroundY = Quaternion( Vector3(0.0,1.0,0.0), EulerAngle.y );
Quaternion QuatAroundZ = Quaternion( Vector3(0.0,0.0,1.0), EulerAngle.z );
Quaternion finalOrientation = QuatAroundX * QuatAroundY * QuatAroundZ;

```

(Or you may need to switch those quaternion multiplies around, depending on the order in which your euler angle rotations are intended to be applied)

Alternately, from looking through GLM's documentation, it appears that you may be able to convert euler angles -\> matrix3 -\> quaternion like this:

```
toQuat( orient3( EulerAngles ) )

```

# Answer
> 21 votes
```
glm::quat myquaternion = glm::quat(glm::vec3(angle.x, angle.y, angle.z));

```

Where `angle` is a `glm::vec3` containing *pitch, yaw, roll* respectively.

PS. If in doubt, just go to the headers and look. The definition can be found in glm/gtc/quaternion.hpp:

```
explicit tquat(tvec3<T> const & eulerAngles) {
        tvec3<T> c = glm::cos(eulerAngle * value_type(0.5));
    tvec3<T> s = glm::sin(eulerAngle * value_type(0.5));

    this->w = c.x * c.y * c.z + s.x * s.y * s.z;
    this->x = s.x * c.y * c.z - c.x * s.y * s.z;
    this->y = c.x * s.y * c.z + s.x * c.y * s.z;
    this->z = c.x * c.y * s.z - s.x * s.y * c.z;
}

```

Where `quat` is a float typedef for `tquat`.

# Answer
> 9 votes
Solution is in wikipedia: http://en.wikipedia.org/wiki/Conversion\_between\_quaternions\_and\_Euler\_angles

using that:

```
sx = sin(x/2); sy = sin(y/2); sz = sin(z/2);
cx = cos(x/2); cy = cos(y/2); cz = cos(z/2);

q( cx*cy*cz + sx*sy*sz,
   sx*cy*cz - cx*sy*sz,
   cx*sy*cz + sx*cy*sz,
   cx*cy*sz - sx*sy*cz ) // for XYZ application order

q( cx*cy*cz - sx*sy*sz,
   sx*cy*cz + cx*sy*sz,
   cx*sy*cz - sx*cy*sz,
   cx*cy*sz + sx*sy*cz ) // for ZYX application order

```

Constructors for a quaternion, given an Euler (where application of rotation is XYZ or ZYX). However, it's only two of six possible combinations of Euler angles. You really need to find out what order the Euler angles are constructed when converting to transform matrix. Only then can the solution be defined.

In the old company I worked at, we had Z as forwards (like most graphics cards) so the application order was ZYX, and at my current company the Y axis is forwards and Z is up, so our application order is YZX. This order is the order you multiply your quaternions together in to generate your final transform, and the order matters for rotations are the multiplications are not commutative.

# Answer
> 1 votes
```
vec3 myEuler (fAngle[0],fAngle[1],fAngle[2]);
glm::quat myQuat (myEuler);

```

fAngle must be in radians!

---
Tags: opengl, mathematics, opengl-es, rotation, glm
---


# Question
Title: Help me to fine tune my diamond-square algorithm
Check this map i generated:

I seeded a sine wave to act as a mountain range. The lower portion of the sine wave looks fine, but the upper side is thin, the algorithm did not do its magic there (expanding with some noise the seeded values to generate wider mountain ranges and then some hills (brown and light brown)).

Also, the whole continent shape is not affected by the sine wave. Ideally, it should be like a "S" as the mountain range pretends to be.

I bet this is how the diamond square algorithm takes the values it uses to make the average.

If not seed the center point of the map, i can not generate a continent, it just makes a pelinesque noise of random hills.

Basically, i'm having some hard time trying to control the noise with seeds and toying with amplitude and randomness reduction values.

I need some experienced people in world generation and noise to help me out!

Thanks!

(PS: red dots are rivers).

# Answer
> 1 votes
Try giving more central (or along your sine wave) points on the graph a higher-than-average chance to grow in height and the edges (or farthest points from the sine wave) a hight-than-average chance to shrink.

Instead of hills, you'll end up with craggy mountains in the middle that fade off to slopes and into a sea bed. You can mess with the DS to smooth it if you are looking for more Appalachian mountains than Rockies. Or, and this is my preferred method, use a CA to weather the mountain by eroding away peaks and filling valleys.

You can create ranges of mountains by slapping a bunch of random points in the map rather than just one central one. The math is just a matter of scaling to the distance to the nearest point.

Same concepts can be used to create a chain of islands much like Hawaii. Start by making a curved line across your map, randomly along the line place points, then offset the points perpendicular to the line by some random value. Now do the original process of scaling the offsets in Diamond Square to the distances away from the points. And Voila. Hawaii.

---
Tags: algorithm, maps, heightmap
---


title: Good game engine to fork?

text:
# Question
Title: Good game engine to fork?
I am a student C++ developer, and while I like game development, I don't like making games. Instead, I like developing the "tech" behind the games, like game engines, tools etc. The reason for this is because it enables me to code without having to worry about creating art resources, sounds, storylines, etc.

I started working on a game engine, but I am having a hard time starting from scratch. I would much rather be given a template to work off of and modify/add as I go. What are some good open source game engine I can fork?

I would rather fork an engine, as I truly want to make it my own, but I need a base to start from.

Please let me know.

Thanks

# Answer
In my experience the people who are capable of writing their own engine from scratch are likely more technical than the people who can't. That being said, you may be hard pressed to find features that you can add to their code on your own and be of any use.

I would take one of two approaches to this:

1. Join their open source project. This seems obvious, but instead of forking and adding random features to someone else's architecture which can be tough. Look at their issues they have listed and offer to help on them. Submit small fixes and eventually work into doing new features.
2. Work on small elements of a game engine. Instead of writing the rendering, scene, ai, physics, etc. Just work on small projects that are separate from a central engine. If you want to expand your expertise, get one of the Game Development Gems books and work on implementing one of the gems and blog about it. Or find a research paper on a topic and implement it, then blog about it.

I think either or both of these are the common approach to preparing to be a core team developing one from scratch.
> 8 votes

# Answer
Pick OGRE if your not afraid of digging through large code base or just a rendering engine. I would also suggest jMonkeyEngine if Java is not a problem for you. Horde3d is pretty well known for its high profile code base. You can try to look that one too. ID Tech engines has been released open source, you can fork those too.

I would stay away from those engines that has been abandoned by the developers, i.e. Irrlicht

Most importantly, rather then looking into one and recreating/cloning one for yourself, its better to contribute to one of these open source project. I think that way you'll learn more and everybody will be happy. :)
> 4 votes

---
Tags: open-source
---


# Question
Title: Why do my sprites have a dark shadow/line/frame surrounding the texture?
I'm starting OpenGL with Apple's GLKit hand I'm having some trouble to get my sprites displayed properly. The Problem is that they all are surrounded with thin dark lines. The screen shot below shows two rectangles with a png image textures containing transparency (obviously).

The black shadows, surrounding them are definitely not part of the pngS. The green png is done without anti-aliasing the blue one has an anti-aliased border. The black border is also apparent if I draw only one sprite.

Te relevant part (hope so...) of code is:

```
//render the scene
-(void)render
{
    glClearColor(69./255., 115./255., 213./255., 1.);
    glClear(GL_COLOR_BUFFER_BIT);
    [shapes enumerateObjectsUsingBlock:^(AAAShape *shape, NSUInteger idx, BOOL *stop)
     {
         [shape renderInScene:self];
     }];
}

//creating and storing the effect inside shape class
-(GLKBaseEffect *)effect
{
    if(!effect)
    {
        effect = [[GLKBaseEffect alloc] init];
    }
    return effect;
}

//rendering the shape (including effect configuration)
-(void)renderInScene:(AAAScene *)scene
{
    //TODO: Storing vertices in Buffer
    self.effect.transform.projectionMatrix = scene.projectionMatrix;
    self.effect.transform.modelviewMatrix = self.objectMatrix;
    if(texture)
    {
        self.effect.texture2d0.enabled = GL_TRUE;
        self.effect.texture2d0.envMode = GLKTextureEnvModeReplace;
        self.effect.texture2d0.target = GLKTextureTarget2D;
        self.effect.texture2d0.name = texture.name;
    }
    [self.effect prepareToDraw];

    if(texture)
    {
        glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
        glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 0, self.textureCoordinates);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 2, GL_FLOAT, GL_FALSE, 0, self.vertices);
    glDrawArrays(GL_TRIANGLE_FAN, 0, self.vertexCount);
    glDisableVertexAttribArray(GLKVertexAttribPosition);

    if(texture)
    {
        glDisableVertexAttribArray(GLKVertexAttribTexCoord0);
        glDisable(GL_BLEND);
    }
}

```

Any ideas anyone? Thank you.

# Answer
> 11 votes
This looks like a case of not drawing with a premultiplied alpha texture correctly. Here's a few helpful links on the subject:

If you search for "premultiplied alpha" and iOS you might find a direct solution to your problem. I suspect it will have something to do with the way you're setting up the glBlendFunc call. Here's my take at it:

In Shawn's XNA code he mentions that where before you would do:

```
RenderState.SourceBlend = Blend.SourceAlpha;
RenderState.DestinationBlend = Blend.InverseSourceAlpha;

```

You should do this instead:

```
RenderState.SourceBlend = Blend.One;
RenderState.DestinationBlend = Blend.InverseSourceAlpha;

```

I'm not too familiar with OpenGL, but my intuition tells me it should be something like replacing:

```
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

With:

```
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

```

**Edit**

Trevor mentioned that this conversion of textures into the pre-multiplied format is done automatically at build time by XCode, even if they were not originally in that format. Thanks for the tip.

---
Tags: textures, opengl-es, ios, transparency
---


title: How to create a map by coding in OpenGL

text:
# Question
Title: How to create a map by coding in OpenGL
I have a very good knowledge about Java, C++, Qt, C# etc... and I wanted to start making a game... most the engine that the game per se since I don't like the "design" part of making a game..

I have read a lot of tutorials and learn the basics of OpenGL since this was the API I choosed. To start I wanted to create a simple 2D game like mario and then create the same but in 3D with a map like ine Minecraft composed of cubes (as it seems more funnier to code).

But I just don't know How video game developers create those maps ! I just know that for 2D games for example, we can use tiles (I think this is the right name), and then create an array that stores numbers and then match the number with the pixel position of the tile so that the game appears in front of the user....

But that is not very easy to code when we want a big map (even for a 2D game)...

So my question is :

Could someone tell me how they archive that ? Just the idea, the rest I will try to develop myself and learn by myself.. I really just want the idea to understand how they easily create those big maps in 3D and 2D.

Thanks in Advance, And sorry for my horrible english.

Luis Da Costa

# Answer
> 2 votes
Your question is too vague. You should start by deciding if you want 2D or 3D, and what sort of world you're trying to create. Since you already know that many 2D games are built with tiles (not all though) I'll talk a bit about 3D instead. For 2D maps check this other topic for many variations. And for a Minecraft-like 3D world read this. I'll talk about the general case.

Most 3D maps are built with pieces (where each piece will usually be a separate 3D model), and if it's an outdoor scene, most of these pieces will be placed on top of a height map that serves as the ground. Then there's other systems that can add further detail to the world, such as decals (which is basically applying textured quads on top of existing geometry to give variation), animated billboards to create vegetation, a water rendering system (which involves using a water shader with reflection and refraction), etc...

Take a look at one of the The Elder's Scrolls Construction Sets to see a bit of how this might work in practice.

Following the guys at Wolfire as they develop their new game is also pretty inspiring. They've showed a lot about map construction before, just browse their blog and youtube channel.

But that's really just touching the surface. There's *a lot* to learn, so you should just pick one topic and start learning it. For instance, start learning how to create and render an height map. Make it more efficient. Then look into rendering 3D models and organizing them using a Quadtree or Octree. Decals. Billboards. Water. Skybox. Night and day cycles... The list is almost endless.

When you have a more specific question, feel free to ask again.

---
Tags: opengl, 2d, 3d, maps
---


# Question
Title: How should I develop my Android game efficiently?
I have attached a image of a flow chart that I made in paint.

The image shows how I want to develop my game. I want a game that runs great with smart coding that is easy to update and ad features over time. My target platform is the Android smartphone and all code will be written in java with XML inflated resources, if that matters. I am not looking for hard code,although pseudo code will help, I would more so prefer suggestions and advise from the pros.

My questions are :

Is this a good way to program a game or are there better ways to do this? Are there any modifications that need to be made? Any suggestions would be useful because I am not experienced in game programming so I would prefer the advice from someone who has written several games and knows from experience how one should go about setting their code up to run efficiently.

# Answer
> 12 votes
A lot of android games are not even large enough in scope to justify save/load or options/preferences, never mind custom characters and the like simply because they are played offhand for 10 minutes on the train home.

Don't make the mistake I did of embarking on something with a large scope for a first android game. Make a bunch of smaller games then go for something larger

Android specifics wise:

**Structure:**

I would recommend having almost all the game in one activity class. Android works on the idea that each activity is like a mini-app, semi-independent of the other activities in the app. The app is essentially a stack of activities, with the user seeing which ever is on the top.

When you pop one off the top, it generally gets destroyed and will be recreated next time the user starts a new activity (startActivity intent). This makes it hard to maintain states between activities and leads to a single activity architecture

You may want to have a Home screen type activity with a "New Game/Load Game/Options" menu on it, and make that the launch activity. However, you will end up having to have an in-game menu as well in your game activity, which will have most of the same functions in it

My own app, I made a "MenuActivity" that has the functions that launch a new game, save, load, change options. Then my HomeActivity extends that, as does my GameActivity.

Since everything is in one Activity class, I would recommend making a heirarchy of activity classes and using private, protected and default scope lots. Doing it this way, you at least can split things up into different file to stop from having one unmanageable Activity file. E.g. for my own app:

`GraphicsEngine extends MenuActivity`.

`PhysicsEngine extends GraphicsEngine`.

`GameLogicActivity extends PhysicsEngine`.

`UIActivity extends GameLogicActivity`.

Since my app is 3D opengl-es, a lot of stuff I do doesn't work cross-activities so everything is in the same activity, so maybe I'm biased towards using one activity architecture

--

**Threading**

For the game activity, You have two threads (or 3 if you are doing 3D opengl stuff). One thread is the UI/main thread. This is the thread the activity gets started and runs in and is given to you by android.

This UI thread is the only one you can update UI elements (views, layouts etc) in. It is also the one where any listeners for user input will run. You don't see any of the mechanics of the UI thread, just that it runs in a loop in the background somewhere.

The second thread, you make yourself (I would recommend using AsyncTask, despite all its shortcomings). This does all the non-UI things you do in a normal game loop, such as updating movement, calculating collisions, combat calculations and so on.

You make this AsyncTask thread/class as an inner class of your activity. That way, you can have some activity-wide-scope objects (`Vector<Spaceship>`) that can be accessed by both UI thread and game loop thread.

Since the game logic is going on in the game loop thread, that is the only thread that will need to actually change the values of variables (update tank speed, reduce player HP). The UI thread just reads values, so there should be minimal concurrency issues.

The tricky bit is getting the UI thread to do updates on request of the game loop thread. There are a couple of ways to do this. If you read the AsyncTask documentation, it has publishProgress()/onProgressUpdate() method. This is actually adding stuff to the UI thread's queue of things to do next loop.

Handler does exactly the same thing, where you implement handleMessage() method and that method is actually executed by the UI thread next loop.

Finally, any user-input, being in the UI thread, you can update UI elements immediately from it (so inside the implementation of any onClick / onTouch listeners). If you need to update the game objects, you can either use things like synchronise, or you can implement your own queue of updates into AsyncTask that like the UI thread, it goes through next time it executes the game loop

Android Threading Guide.

--

**UI**

As for the actual UI structure within the single activity, I recommend having a frame layout as your base layout. The child elements in a frame layout work like a queue. First element gets drawn first, second gets drawn on top of first, third on top of second.

This way, you can have multiple XML layout files and by managing the frame layout's children, can easily swap sets of views in and out.

If you always have the SurfaceView at the bottom (first child in the frame layout), then you can use all the usual android views/widgets (buttons, text views, scroll views) etc over the top of the surface view, which just does the graphics part of the game.

So for example, if something is loading, you can pause the game loop / just get it to skip everything, add an opaque 'loading' screen as the last child to the frame layout and the user will see 'loading' appear on their screen, quite unaware that other views are behind it. This way you don't have to remove views that take a long time to set up or cause complications each time they are added / removed.

I would also recommend using View.setVisibility lots. You could for example, add a whole 'inventory' layout to your base frame layout and then just setVisibility(View.Visible) on it when the user clicks to view their inventory, and setVisibility(View.Gone) when they close it again. That way, you aren't even managing the children of the frame layout so much as just adding everything and making things visible/invisible as and when the user does different things

This helps with threading again; as the user clicks to open their inventory, the onCLickListener is handled in the UI thread, the inventory is made visible therein, and the updateInventory method is called, again from the UI thread, with just getters on all the game objects being called

Here's the diagram I made for an earlier question about the single activity / frame layout idea:

# Answer
> 11 votes
A lot of what I see in your diagram is UI related, and that much seems fairly reasonable. There is only a small portion of your diagram reserved for actual game logic, and it is very vague.

I think you are trying too hard. I would suggest you just start writing code. Pick a particular problem and start solving it. You will learn so much that by the time you have a better idea of what your problem space is that you will have a completely different (ane more useful) perspective.

---
Tags: java, android, architecture
---


# Question
Title: LPD3DX10FONT::DrawTextA/W messes up the depth buffer!
why does calling this function mess up the depth buffer? I read somewhere that it cheekily changes the blend state, but to be totally honest I don't even know what that means. What is it doing, why is it doing it and what should I do about it?

Here is my code... instantiation:

```
RECT rct;
D3DXCOLOR fontColor = D3DXCOLOR(255,0,0,255);
LPD3DX10FONT m_font;
LPD3DX10SPRITE m_sprite;

```

and then...

```
rct.left=200;
rct.right=780;
rct.top=200;
rct.bottom=rct.top+20;

D3DX10CreateFont(device, 16, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_TT_ONLY_PRECIS,     ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Verdana", &m_font);
D3DX10CreateSprite(device, 256, &m_sprite);

```

and THEN...

```
m_sprite->Begin(D3DX10_SPRITE_SAVE_STATE);

std::ostringstream oss;

oss << "This ruins the depth buffer!!!" << agents[0].State();

std::string test = oss.str();

m_font->DrawTextA(m_sprite, test.c_str(), -1, &rct, DT_LEFT|DT_NOCLIP , fontColor);

m_sprite->End();

```

as a side question, is there a more succinct way I can append variables to the string being written?

# Answer
Let's think what the ID3DX10FONT will need.

To draw texts, you need to use alpha blend(mixing the color you will use with the background color). Drawing letters with white or black background will be odd.

Secondly, where should those letters be placed in the world space? It is a hard question. For texts to be shown in front of your window, DirectX 10 changes the depth buffer state. I cannot say for sure, but I guess DX disables it.

To solve this problem, you should change your blend state and depth stencil state back after you drew texts.

First of all, you should create depth stencil state and blend state for your application.

Secondly, draw texts.

Finally, use ID3D10Device::OMSetDepthStencilState/OMSetBlendState to change back.
> 1 votes

---
Tags: c++, directx, directx10
---


title: Player icon auto generator

text:
# Question
Title: Player icon auto generator
Hi I am searching for an open library (preferred in java) to generate user icons / badges for representing an user in an mmpg, rather than by his player name. The user does not need to take any actions to manipulate the icon by him self, but the system is auto generating the icon when the user is registering. Is there any library / script out there to achieve that? Thanks!

# Answer
> 6 votes
If abstract icons are fine, you could somewhat use gravatar.

If you want to have human-like icons instead, not allowing the user to customize them is a bad bad bad idea.

Another option is to use facebook login and use player's avatar.

---
Tags: java, avatar
---


title: How to make a market test for the game?

text:
# Question
Title: How to make a market test for the game?
I'm making a casual game on iOS platform. But I'm not sure Do the consumers like my game. How can I make a market test for my game?

# Answer
That is a very nice question! I have been thinking about the same thing lately.

I don't know how are you doing your development. But you always need beta testers. If you don't have any. I would start there. Beta testers could give you great hints about your game. What is wrong / what is right / what should be changed. Beta testers are players as we all are. They know what entertains them. They will help you make the game better. In my opinion it is far better then releasing the game as **ClassicThunder** mentioned.

If you released the game as a demo. You could get very bad ratings and it would ruin your game awareness. Just because you want to test if public likes it.

If you have beta testers and / or you feel very confident about your game. You might want to release a preview of your game to Youtube and then post it to Reddit and such. It will take some time, but you will see just from the comments if the game is looking good or bad for potential customers. This is again to avoid bad ratings.

Then you might want to release a demo. But I would not recommend it.
> 4 votes

# Answer
I've only done stuff with the WP7 market place but if apple allows it I would suggest releasing a free demo, posting a link to it at places such as Reddit's IndieGaming subreddit, and then seeing how the reviews go. Plus you can get direct feed back in the comments. Also no blow back in reputation if it doesn't go over well (No bad reviews sitting there forever keeping customers away).
> 3 votes

---
Tags: game-design, marketing, testing
---


# Question
Title: What is an efficient 2D line-segment-versus-triangle intersection test?
In a 2D plane, I have a line segment (P0 and P1) and a triangle, defined by three points (t0, t1 and t2).

My goal is to test, as efficiently as possible ( in terms of computational time), whether the line touches, or cuts through, or overlaps with one of the edge of the triangle.

Everything is in 2D, so I can't expect the usual ray-triangle intersection test (3D version) to work.

Edit: Same question is asked on math.SE, but I think asking here is also appropriate as this is as much mathematics as game development, and the approach may be different also.

# Answer
Here is an algorithm for intersection only (doesn't cover touching) that I believe is fast.

* if `t0`, `t1` and `t2` are all on the same side of line `P0P1`, return NOT INTERSECTING
* if `P0` AND `P1` are on the other side of line `t0t1` as `t2`, return NOT INTERSECTING
* if `P0` AND `P1` are on the other side of line `t1t2` as `t0`, return NOT INTERSECTING
* if `P0` AND `P1` are on the other side of line `t2t0` as `t1`, return NOT INTERSECTING
* otherwise, return INTERSECTING

To check whether point `P` and point `Q` are on the same side of line `AB`, compare the signs of the Z coordinates of `AB^AP` and `AB^AQ` where `^` is the cross product.

The following code should work:

```
/* Check whether P and Q lie on the same side of line AB */
float Side(vec2 p, vec2 q, vec2 a, vec2 b)
{
    float z1 = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y);
    float z2 = (b.x - a.x) * (q.y - a.y) - (q.x - a.x) * (b.y - a.y);
    return z1 * z2;
}

/* Check whether segment P0P1 intersects with triangle t0t1t2 */
int Intersecting(vec2 p0, vec2 p1, vec2 t0, vec2 t1, vec2 t2)
{
    /* Check whether segment is outside one of the three half-planes
     * delimited by the triangle. */
    float f1 = Side(p0, t2, t0, t1), f2 = Side(p1, t2, t0, t1);
    float f3 = Side(p0, t0, t1, t2), f4 = Side(p1, t0, t1, t2);
    float f5 = Side(p0, t1, t2, t0), f6 = Side(p1, t1, t2, t0);
    /* Check whether triangle is totally inside one of the two half-planes
     * delimited by the segment. */
    float f7 = Side(t0, t1, p0, p1);
    float f8 = Side(t1, t2, p0, p1);

    /* If segment is strictly outside triangle, or triangle is strictly
     * apart from the line, we're not intersecting */
    if ((f1 < 0 && f2 < 0) || (f3 < 0 && f4 < 0) || (f5 < 0 && f6 < 0)
          || (f7 > 0 && f8 > 0))
        return NOT_INTERSECTING;

    /* If segment is aligned with one of the edges, we're overlapping */
    if ((f1 == 0 && f2 == 0) || (f3 == 0 && f4 == 0) || (f5 == 0 && f6 == 0))
        return OVERLAPPING;

    /* If segment is outside but not strictly, or triangle is apart but
     * not strictly, we're touching */
    if ((f1 <= 0 && f2 <= 0) || (f3 <= 0 && f4 <= 0) || (f5 <= 0 && f6 <= 0)
          || (f7 >= 0 && f8 >= 0))
        return TOUCHING;

    /* If both segment points are strictly inside the triangle, we
     * are not intersecting either */
    if (f1 > 0 && f2 > 0 && f3 > 0 && f4 > 0 && f5 > 0 && f6 > 0)
        return NOT_INTERSECTING;

    /* Otherwise we're intersecting with at least one edge */
    return INTERSECTING;
}

```

There is a lot of factoring possible here; it's possible the compiler will cleverly reuse partial results across calls to `Side` if it's inlined.

**Edit**: implement test for touching *and* overlapping in addition to intersecting.
> 8 votes

# Answer
The bIg question here is what does your outer loop look like? I.e. Are you intersecting many lines with many triangles, one line to many triangles or many lines to one triangle? Or is it just N pairs of a triangle and a line? Only the last case (which sounds to be the most unlikely case) will best be accelerated by a faster segment to triangle intersection test.

Depending on what the scenario is, you may want to put your triangles OR your line segments into a spatial tree structure of some kind (if your segments are very long (relatively speaking), you can consider a spatial wtructure built on a duality mapping of gradient and offset). E.g. A grid, quad-tree or kd-tree will allow you to test multiple triangles or multiple line segments simultaneously.

If you really do have just one triangle and one line segment, performance shouldn't matter.

I should add, that the above will also dictate what type of primitive intersection test is the most efficient. If after traversal you know that the line segment intersects the bounding box of a triangle, then it also implies that an intersection is likely, which means that early out segment or edge sideness tests are likely wasted computation.
> 4 votes

# Answer
AFAIK you can check collision of each edge of triangle and even if one of the was true, the line segment collides the triangle. according to wikipage you can easily compute intersection point of two lines, in the rare case that you have divisor is zero it means two lines are parralel so they can't collide at all!

then you have to check if the collision point is a part of both line segments, it's also easily done:

```
// assume we want to check if I (intersection point) is
// between p0 and p1

if (dotproduct(P0-I,p1-I) > 0)
    return false;
else
    return true;

```
> 3 votes

# Answer
here is a routine that we use in our game engine. It can check if two line segments are not intersecting, intersecting or just parallel to each other. If they are intersecting, it will return the intersection XY position. It is used in our PolyPoint Collision System where it can auto trace a sprite image and put a polygon outline around it, then using this routine we walk the line segments of the colliding sprite outlines checking for intersection.

```
TLineIntersection = (
  liNone,
  liTrue,
  liParallel
);

function  LineIntersection(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer; var X, Y: Integer): TLineIntersection;
var
  Ax,Bx,Cx,Ay,By,Cy,d,e, f, num: Integer;
  offset: Integer;
  x1lo,x1hi,y1lo,y1hi: Integer;
begin

  Result := liNone;

  Ax := x2-x1;
  Bx := x3-x4;

  if (Ax<0) then      // X bound box test
  begin
    x1lo := x2;
    x1hi := x1;
  end else
  begin
    x1hi := x2;
    x1lo := x1;
  end;

  if(Bx>0) then
  begin
    if (x1hi < x4) or (x3 < x1lo) then Exit;
  end else
  begin
    if (x1hi < x3)  or (x4 < x1lo) then Exit;
  end;

  Ay := y2-y1;
  By := y3-y4;

  if (Ay<0) then // Y bound box test
  begin
    y1lo := y2;
    y1hi := y1;
  end else
  begin
    y1hi := y2;
    y1lo := y1;
  end;

  if (By>0) then
  begin
    if (y1hi < y4) or (y3 < y1lo) then Exit;
  end else
  begin
    if (y1hi < y3) or (y4 < y1lo) then Exit;
  end;

  Cx := x1-x3;
  Cy := y1-y3;
  d  := By*Cx - Bx*Cy;          // alpha numerator
  f  := Ay*Bx - Ax*By;          // both denominator

  if(f>0) then                  // alpha tests
  begin
    if (d<0) or (d>f) then Exit;
  end else
  begin
    if (d>0) or (d<f) then Exit
  end;

  e := Ax*Cy - Ay*Cx;                    // beta numerator
  if (f>0) then                // beta tests
  begin
    if (e<0) or (e>f) then Exit;
  end else
  begin
    if (e>0) or (e<f) then Exit;
  end;

  // compute intersection coordinates

  if(f=0) then
  begin
    Result := liParallel;
    Exit;
  end;

  num := d*Ax;                // numerator
  if SameSignInt(num, f) then
    offset := f div 2
  else
    offset := -f div 2;
  x := x1 + (num+offset) div f;                       // intersection x

  num := d*Ay;
  if SameSignInt(num, f) then
    offset := f div 2
  else
    offset := -f div 2;

  y := y1 + (num+offset) div f;                          // intersection y

  Result := liTrue;
end;

```
> 0 votes

---
Tags: mathematics, linear-algebra, computational-geometry
---


# Question
Title: How should I handle functions, where two classes have equal use?
I'm working on a few features for a strategy engine I'm making. I'm trying to figure out the best spots to separate the components, as either option will provide the same amount of coupling, with the same effectiveness.

---

For example, all players have a `Damage` component, a `Player` component, and a `HealthBar` component:

```
abstract class Damage
{
    protected abstract void sendDamage(Player targetPlayer, int rawDamage);
    public abstract int calculateRawDamage(Attack attackUsed);
    public abstract void receiveDamage(int rawDamage);
}

class Player
{
    List<Armor> equippedArmor;
    List<Buffs> currentBuffs;
    public Damage damageComponent;
    public List<HealthBars> healthBarComponents;
}

abstract class HealthBar //can be inherited for mana or health bar
{
    protected Color color;
    public float percent; //0.0 - 1.0
}

```

When a player receives damage, I need to show a red number floating up from their head, indicating the amount of damage. This can either be implemented in `HealthBar`, or in `Damage`. It fits damage better, but then healing works in the same way, and wouldn't be called from damage. I could abstract damage into something like `ChangeValue`, which would change mana, health, etc in any direction, or I could use the abstract `HealthBar` class to show this number being changed.

---

I'm trying to think of a general rule that would solve this and other problems, where two classes use the same function equally. This is an oversimplified version of my classes, but it makes more sense this way.

How should I handle functions, where two classes have equal use?

# Answer
> 4 votes
I think you kinda just answered you own question. The number needs to appear not only on damage but also on heals, i.e. it appears whenever your health changes. And your `Damage` component has no connection with heals. So they don't *really* use the same functionality equally.

Because of that I think I would make it a part of your `HealthBar`. Make it react automatically to *any* variation in the health bar, and show that variation as a number in green or red depending on whether it increased or decreased. Besides, the `HealthBar` is by nature a GUI component, and so is the damage number you want to show. On the other hand `Damage` is conceptual.

But your `HealthBar` seems to be only holding a `percent` value at the moment. This would make it harder to know which number to show since there's no absolute range. Because of that I would also change it into a `value + max` pair instead, and keep it synced with the player's health.

Nonetheless, you might still want to generalize your `Damage` component a bit further too, to enable applying any sort of stat variation like you mentioned.

**The bottomline is...**

If and when both options **really** provide the *same* amount of coupling, then it doesn't matter where you add the functionality. Just pick the one and move on, since none of them will have a benefit over the other. Try to choose the one at the closest level of abstraction though.

---
Tags: software-engineering, component-based
---


# Question
Title: Is using XNA title storage for level/config files a Bad Idea?
I've reached the point in development where my Game Engine can actually do stuff, and it's time to start thinking about how to store / load the various bits and pieces where they need to be.

I've decided to go with file storage (rather than a database), which means I'm probably going to be using .xml, .json, or .csv files. The only remaining question is how to actually store them within the game's binaries (so that any players won't be able to edit levels willy nilly).

XNA's Title Storage, being read-only, seemed as good a starting place as any, but when I loaded up the MSDN page, there's this warning on the top:

> This topic describes how to add files to title storage that the game will access through stream I/O. **This is the exceptional case, and is not recommended for most XNA Game Studio games.** Instead, consider using the Content Pipeline to manage your game data most efficiently.

Emphasis mine.

So is it a bad idea to use Title Storage for level/config files, or is that warning intended to stop people from using it to store things like Texture2Ds and SpriteFonts ?

# Answer
`TitleContainer.OpenStream` just opens an I/O stream in the same folder as the current executable resides. There isn't anything wrong on using it, the warning you see in the MSDN pages is because on XNA the rule of thumb is to preprocess all the content you will use via the Content Processors so you don't have to waste any CPU converting data on load.

Note that this doesn't prevent tampering of the original files if your game targets the Windows platform, as the file resides in the same directory as the binaries but is merely copied by the compiling process. Your best option is to embed them in a Resources file, and apply some kind of encryption to prevent being edited by existing tools.
> 4 votes

---
Tags: xna, xna-content-pipeline
---


# Question
Title: Generating spherical world from heightmapped terrain
I am using a standard heightmapped procedural terrain in my project. However, I want the terrain to appear spherical when the user zooms out. This is an attempt to simulate the appearance of a spherical planet. Here is my current algorithm:

```
        //get the direction from the "planet" center to this vert
        Vector3 sphereCentertoVertPosition = vert.Position - SphereCenter;
        sphereCentertoVertPosition.Normalize();

        //our rotation axis is the cross between the direction from this vert to the planet center and the root (center of the terrain) to the planet center
        RotationAxis = Vector3.Cross(sphereCentertoVertPosition, sphereCenterToRootPosition);

        //the amount we rotate is based on the distance of this vert from the center of the terrain
        Vector3 fromCenter = vert.Position - Root.Position;
        float amount = (fromCenter.Length() / ((myTextureWidth / Scale) / 2)) * (float)Math.PI;

        Quaternion rot = Quaternion.CreateFromAxisAngle(RotationAxis, amount);

        Vector3.Transform(ref vert.Position, ref rot, out vert.Position);

```

My main concern is that the rotation axis is not correct. Theoretically, should it be the cross between the vert-to-planet-center and the terrain-center-to-planet-center?

# Answer
> 5 votes
Hmm, I'm not so sure about rotating the vertices. Perhaps this is not the answer you're looking for, but I can suggest an alternate method.

I've done something similar with maps in my game. I wrote a shader to wrap terrain into a sphere, but it can easily be done outside the graphics card too. It's as simple as mapping the Cartesian coordinates to spherical coordinates. The code would look something like:

```
public static Vector3f MapToSphere(Vector3f coords, WorldMap MAP) {
    float pi = 3.14159265f;
    float thetaDelta = ((2 * pi) / (MAP.XSize - 1));
    float phiDelta = ((pi) / (MAP.ZSize - .5f));
    float RadiusBase = ((MAP.XSize) / pi / 2f);
    float theta = (coords.z * thetaDelta);
    float phi = (coords.x * phiDelta);

    //Limit the map to half a sphere
    if(theta > pi) {theta = theta - (pi);}

    if(theta < 0.0)    {theta = theta + (pi);}

    if (phi > 2*pi) {phi = phi - (2*pi);}

    if (phi < 0.0) {phi = phi + (2*pi);}

    Vector3f coords2 = new Vector3f();
    coords2.x = (float) (((RadiusBase) * Math.sin(theta) * Math.cos(phi)) + MAP.XSize / 2f);
    coords2.y = (float) ((RadiusBase) * Math.sin(theta) * Math.sin(phi));
    coords2.z = (float) (((RadiusBase) * Math.cos(theta)) + MAP.ZSize / 2f);
    return coords2;
}

```

This maybe "too spherical" for you. If so, you can try padding the edges of your map so that the portion turned into a sphere only represents a portion of the surface of the sphere.

Below is an example of the spherical mapping results.

A "flat" map:

And a spherical world, created by wrapping the vertices into a sphere:

Note that there will be a large amount of distortion at the poles if you don't follow the suggestion above to limit the surface area of the sphere this map is stretched over.

---
Tags: xna, procedural-generation, geometry, coordinates
---


title: Pricing an application

text:
# Question
Title: Pricing an application
I decided to make my application for free but introduce donation button. For this I would use paypal. What are the advantages of this monetization model and what are other models to consider? My application is kinda educational so that's why I am thinking to make it free as I will try to send it to schools.

# Answer
Nothing wrong with a donate button, but don't forget ads. You should include other options than Paypal like Amazon or Google Checkout since some people don't use Paypal.
Good answer of ads in android applications:
https://stackoverflow.com/questions/2471417/embedding-ads-on-android-app
> 8 votes

# Answer
I'd include ads and make sure they're in a part of the screen where you don't have controls, as well as a "Do you hate ads?" Button where they can download a full version without adds for maybe 2$ or so. Donations work too, it's rare that people will donate, but when they do I can guarentee you'll be happier to see the "well I've got 10$ to spare" people than 4 sets of $2. ($2 less only,) When it's a larger number it makes a bigger difference. It's all about whether you want the app to cost money to begin with or not though.
> 2 votes

# Answer
I would recommend using ZooZ, it's an In-App payment SDK for iOS and Android. ZooZ offer excellent conversion rate and variety of payments methods.
> 0 votes

---
Tags: android, marketing
---


title: android game development dilemma

text:
# Question
Title: android game development dilemma
I'm doing a android game project that has a character that can do basic movements like step, turn left, turn right, raise left arm etc. When combining those moves together, the character can do some complicated movements like a dance routine or so.

I'm banging my head to figure out what to do about the graphics. I can do a 3D model with animation then export it to the format of Bones library that displays the character movements. Like shows in this video. I wish to have different characters with different characteristics like height, clothes colour and such. However, that means I have to stock pile more 3D models that have different settings.

Alternatively, I can attempt to code from scratch that have bones system, meshes, skinning, animation. More control and flexibility but the appearance won't be as good as 3D model and it takes alot more afford (as it appears to me). The character will be in 2D if I go down this route. I will use Android OpenGL library for this.

I thought of 2D but then I realize that it's pretty similar to 3D option.

My question is that what can I do here? What else I can do to make the best of this situation?

Edit: thanks for the comments and answer but I have sorted my "dilemma" now. Im using jpct-ae and bones library for my project. The downside is that I need to use a 3D model to make use of those library. They are actually very good and suitable for my need when working with a 3D model. Cheers.

# Answer
> 1 votes
You could make ever changeable feature a model, nose 1 nose 2 hair 1 hair 2... have a list of textures that fit with every model, nose 1 color red texture, nose 1 blue texture... and have the models a different piece that moves on its own and animate the movement. Making 3D games and games for that matter takes time. To have a good game, you need a lot of effort. For example of what i'm talking about, look at Mount and Blade Warband, Sims 3, and Spore. (all computer games)

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