# Question
Title: Havok physics with a wide range of object scales
So typically **Havok** works best with normal human sized objects with a gravity of **9.8m/s^2** and dealing with everything in meters.

In my Game though there will be a large variety of scales **from millimeter sized objects to meter sized objects**.

Typically this rules out running a standard Havok setup and dealing with things in a meter scale.

Would it be best to increase everything by 10x or some scalar like this and increase gravity likewise?

I understand this would also decrease how far objects can be away from the origin but for the sake of this question assume everything is relatively close to the origin, a hundred meters max.

**Issues of concern**

Object penetration - Havok usually allows some object penetration in the 2-3cm range in the meter scale.

Floating point precision - Issues dealing with distances of objects etc, typically physics breaks down at the kilometer scale in Havok.

Unseen - other unseen issues that may result with such large differences in scale.

# Answer
Havok has a few spatial constants you will want to tweak for the size of your world, but otherwise the scale of the world shouldn't matter. Rather, the scale of the objects relative to one another matters quite a bit. Below I've tried to address the issues you will need to be aware of:

Collision 'tolerance' - When rigid bodies touch they do not rest exactly touching but are kept at a separating distance. This is because Havok has a more difficult time simulating bodies that are inter-penetrating. You will need to tweak this value to be appropriate for your world, so that the separating distance is not noticeable. It is also typical to shrink the collision shapes a bit so the separating boundary aligns more closely with the visible surfaces.

Maximum velocity - When creating your world and your rigid bodies you may define a maximum linear velocity. You will want to scale this value up or down to be appropriate to the size of the world.

The bullet-through-paper problem - When you scale an object to be very small, you also want to consider of the maximum possible speed of the object relative to its size. Because havok simulates in discrete time steps a small and fast object may move several times its length in a single timestep, and so it may travel through a thin surface without detecting the collision, or worse, it will become stuck inside. To alleviate this, you can enable continuous collision for rigid bodies that are small and fast, but CCD is expensive, and causes bad performance spikes if you accidentally teleport a CCD body into another body. Another approach is set the maximum linear velocity (see above) to something ok relative to the object's size... however varying maximum linear velocities can cause problems (imagine a fast moving truck full of small objects... the small objects cannot move as fast as the truck so they will tunnel through it).

The level of detail problem - The cost of detecting a collision is generally relative to the number of polygons that are near touching on each side. When you have objects that are very large relative to the player, they tend to have many polygons to look sufficiently detailed at the player's scale. If two large high detail objects collide, you may have a 100 polygon surface collide with another 100 polygon surface, which requires 10,000 collision tests. One solution is to have multiple shapes in the rigid body with different levels of detail (two levels of detail is usually enough) and set the collision filters on those shapes so that two large colliding bodies only detect collisions between their lower detailed shapes.

Mass and momentum - Larger objects need to have much larger mass, which means that when they are moving and collide with objects of much smaller size/mass, the momentum transferred to those smaller objects will make them move very fast. Small fast moving objects cause the bullet-through-paper problem I mentioned above, and may also look undesirable, as your objects go hurtling out of the world. You can deal with the bullet-through-paper problem as I mentioned above, or you can fudge collision and explosion forces so that they are constrained to a manageable range.

Floating-point precision - If your world is very large relative to the smallest object, motion will begin to stutter visibly when viewed at the smallest scale and those objects are very far from the origin. This is because the margin of error on large floating point values (positions) will be large relative to very small floating point values (small velocities and small differences in position). One way to fix this is to only keep a relevant area of rigid bodies in the world, and occasionally translate all of those objects toward the origin when the player wanders too far away. As long as you maintain the relative positions of all the objects, the player won't notice.

Other spatial constants - Look at the parameters you can adjust when setting up the world, rigid bodies, and constraints... there are probably some other constant values in units of length that need to be adjusted to fit the scale of the world.
> 3 votes

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


# Question
Title: Computing volumetric light effects analytically
In my previous question I have asked about an effect on how to visualize light spheres. The question resulted in a very nice formulated answer which described pretty well how to achieve this by adding some fog to the scene and using some factor to weight different light samples on the rays from the camera to the scene.

However, since performance was too bad when testing it on the Xbox when taking shadows in account (`texCUBElod` lookups seem to be expensive) in split-screen multiplayer, I wanted to solve the resulting integral (which is currently approximated by a Riemann's sum) analytically **without taking shadows into account**.

I could reduce the pixel shader code to some formula, but was unable to solve it. So, I've put up another question on the mathematics stackexchange. It was answered fast, but the responder could not come up with any way I could use to solve this in an efficient way.

The question remains, how the performance could be increased without losing awesomeness of the lighting effect. (It does not have to be physically correct, so, if there are methods to increase performance but take away realism, I would like to hear about them.)

Current pixel shader code

# Answer
We solved the problem by modifying the integral using some approximations. For example, the `0.99^x` part has been approximated by a linear decay function. This produced very similar results to the original solution and was solvable analytically in one step.

```
float a = dot(lightPos - nearPlane , distance_to_wall);
a /= length_distancetowall;
if (a <= -1/dust_factor) {
    float b = length(cameraPos + direction*a - lightPos);
    float c = 1;
    float d = -0.25/30;
    float x = length_distancetowall;
    if (x > -1/dust_factor)
        x = -1/dust_factor;
    float integral = (c+a*d)/b*(atan(a/b)-atan((a-x)/b)) + d/2*(log(a*a+b*b)+log(a*a+b*b-2*a*x+x*x));
    float lightIntensity=0.0042 * lightRad;
    outColor += float4(integral*(lightColor * lightIntensity), 1);
}

```

With this method, the framerate could be improved drastically. Thanks to notabene for giving the first input and his help at this point again.
> 1 votes

# Answer
Maybe this one will help: A Practical Analytic Single Scattering Model for Real Time Rendering
> 1 votes

# Answer
There is term called "opacity correction". It enable changing number of samples without changing final result, but also can be used for solving constant density analyticaly:

\delta x is segment length, \delta x' is new segment length. So you can just define some segment length which is reference and it should provide same results(i hope)

Source: real time volume graphics book.
> 0 votes

---
Tags: xna, c#, xbox360, performance, volumetric-light
---


# Question
Title: What causes my client's painting & input thread to stop?
I recently returned to face a problem I had with a game client of mine, i.e. the client's thread responsible for input & painting becomes unable to run after some while.

I suspect that it has something to do with server sent massages. Possibly client is unable to handle old ones before new ones are arriving. But when I am printing inQueue size after dequeue it always reaches 0.

**What else could possibly be the reason of this block?**

I was debugging using NetBeans and it says there is no deadlocks?

Are there other tools which I should/might use to find the reason.

I have tried lots of things and I think the code of my client is now in a state of disaster :)

I am using the engine coded by Bret Barker which I got from the book by David Brackeen titled "Developing Games in Java".

If you guys would need some code I can paste some snippets of bits which you would suspect the problem is since the whole code is big & fat. Plus the last thing all wants to do here is read and debug someone's code, right? :) Thus I think we can do it by need basic.

*I am stuck and all your help/suggestions of stuff I should look after, even an article about similar issues, etc. is much appreciated.*

EDIT1: Here is presented a test class which combines client for server communication and GUI/frame for display & user input.

```
public class NetworkingTest2 extends GameCore implements IGameFrame
{
    private static final long serialVersionUID = 1L;
    private float _scrollSpeed = 0.35f;
    private InputManager inputManager;
    //mouse Actions
    protected GameAction leftMouseClick;
    protected GameAction rightMouseClick;
    //keyboard Actions
    protected GameAction scrollMapUpKey;
    protected GameAction scrollMapDownKey;
    protected GameAction scrollMapLeftKey;
    protected GameAction scrollMapRightKey;
    //robot moves
    protected GameAction moveForwardKey;
    protected GameAction moveBackwardKey;
    protected GameAction moveLeftKey;
    protected GameAction moveRightKey;
    private RoboClient client;
    //your/client's bot
    private IUnit unit;

    private RoboGame game = null;
    public NetworkingTest2(String playerName, String password)
    {
        addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
                System.out.println("NetworkingTest2 windowClosing");
                //used to call disconect once and then wait for it to finish
                Runnable doWork = new Runnable()
                {
                    public void run()
                    {
                        System.out.println("Stops client if it is still running.");
                        if(client.isRunning())
                            client.disconnect();
                    }
                };
                SwingUtilities.invokeLater(doWork);
            }
        });
        initializeInput();
        this.client = new RoboClient(this)
        {
            @Override
            public void onSuccessfulLogin()
            {
                System.out.println("././././onSuccessfulLogin././././");
                // 0 becaue we assume that there is only one game
                client.createAndEnqueueJoinGameEvent(0);
            }
        };
        boolean isConnected = client.connectToServer(GameConstants.SERVER_IP, playerName, password);
        System.out.println("isConnected with server (doesn't mean the player is logged)=" + isConnected);
    }

    private void initializeInput()
    {
        this.inputManager = new InputManager(this);
        // mouse
        this.leftMouseClick = new GameAction("left mouse click");//, GameAction.DETECT_INITIAL_PRESS_ONLY);
        this.rightMouseClick = new GameAction("righ mouse click", GameAction.DETECT_INITIAL_PRESS_ONLY);
        // key
        this.scrollMapDownKey = new GameAction("scrollDown", GameAction.NORMAL);
        this.scrollMapUpKey = new GameAction("scrollUp", GameAction.NORMAL);
        this.scrollMapLeftKey = new GameAction("scrollLeft", GameAction.NORMAL);
        this.scrollMapRightKey = new GameAction("scrollRight", GameAction.NORMAL);

        this.moveForwardKey = new GameAction("Move yout robot Forawrd/North");
        this.moveBackwardKey = new GameAction("Move yout robot Back/South");
        this.moveLeftKey = new GameAction("Move yout robot Left/West");
        this.moveRightKey = new GameAction("Move yout robot Right/East");
        // key mouse assigment
        inputManager.mapToMouse(leftMouseClick, InputManager.MOUSE_BUTTON_1);
        inputManager.mapToMouse(rightMouseClick, InputManager.MOUSE_BUTTON_3);
        // keybard assignment
        inputManager.mapToKey(scrollMapDownKey, KeyEvent.VK_DOWN);
        inputManager.mapToKey(scrollMapUpKey, KeyEvent.VK_UP);
        inputManager.mapToKey(scrollMapLeftKey, KeyEvent.VK_LEFT);
        inputManager.mapToKey(scrollMapRightKey, KeyEvent.VK_RIGHT);

        inputManager.mapToKey(moveForwardKey, KeyEvent.VK_W);
        inputManager.mapToKey(moveBackwardKey, KeyEvent.VK_S);
        inputManager.mapToKey(moveLeftKey, KeyEvent.VK_A);
        inputManager.mapToKey(moveRightKey, KeyEvent.VK_D);
    }

    public void setUnit(IUnit robot)
    {
        setTitle(getTitle() + " for playerName=" + robot.getPlayer().getPlayerId());
        this.unit = robot;
        //center view on the player's robot
        System.out.println("screenWidth=" + screenWidth + ";;screenHeight=" + screenHeight);
        int initialOffsetX = (int) ((robot.getCenterPoint().getX() - getFrameWidth() / 2));
        int initialOffsetY = (int) ((robot.getCenterPoint().getY() - getFrameHeight() / 2));
        game = client.getGame();
        game.getGameLevel().getMap().setMapOffsetX(-initialOffsetX);
        game.getGameLevel().getMap().setMapOffsetY(-initialOffsetY);
    }

    @Override
    public void update(long elapsedTime)
    {
        System.out.println("NetworkingTest2 public void update(long elapsedTime)");
        checkInput(elapsedTime);
        if(game != null)
        {
            GameLevel gameLevel = game.getGameLevel();
            if(gameLevel != null)
            {
                List<IShot> shotList = gameLevel.getShotList();
                //update all animated projectiles -- thus user sees their animation
                for(int i = 0; i < shotList.size(); i++)
                    if(shotList.get(i).getProjectile() instanceof IAnimatedProjectile)
                    {
                        IAnimatedProjectile ap = (IAnimatedProjectile) shotList.get(i).getProjectile();
                        ap.update(elapsedTime);
                    }
            }
        }
    }
    // for debug purpose
    private String _clickedObjectName = "None";
    private String _clickedObjectToughness = "None";
    private long drawCounter = 0;

    @Override
    public void draw(Graphics2D g2)
    {
        g2.setColor(Color.BLACK);
        g2.fillRect(0, 0, this.getWidth(), this.getHeight());

        if(game != null)
        {
            GameLevel gameLevel = game.getGameLevel();
            if(gameLevel != null)
            {
                WorldMap map = gameLevel.getMap();
                //center view on the unit -- this way arrow key are not working as map offset is set again here
                int initialOffsetX = (int) ((unit.getCenterPoint().getX() - getFrameWidth() / 2));
                int initialOffsetY = (int) ((unit.getCenterPoint().getY() - getFrameHeight() / 2));
                map.setMapOffsetX(-initialOffsetX);
                map.setMapOffsetY(-initialOffsetY);
                gameLevel.draw(g2);//, offsetX, offsetY);//(g2, map.getMapOffsetX(), map.getMapOffsetY());
                g2.setColor(Color.YELLOW);
                g2.drawString("MapOffset X: " + map.getMapOffsetX(), 10, 100);
                g2.drawString("MapOffset Y: " + map.getMapOffsetY(), 10, 120);

                g2.drawString("Mouse X: " + inputManager.getMouseX(), 10, 160);
                g2.drawString("Mouse Y: " + inputManager.getMouseY(), 10, 180);

                g2.drawString("Mouse on Map X: " + (inputManager.getMouseX() + map.getMapOffsetX()), 10, 220);
                g2.drawString("Mouse on Map Y:" + (inputManager.getMouseY() + map.getMapOffsetY()), 10, 240);
            }
            //unit display update
            g2.setColor(Color.RED);
            IShootingClipWeapon head = (IShootingClipWeapon) unit.getEquipmentAtLocation(Robot.EQUIPMENT_ON_HEAD);
            g2.drawString("Ammo on head: "
                    + head.getClip().getCurrentAmmoAmount() + "/" + head.getClip().getMaximumAmmoCapacity(), 10, 450);
            g2.drawString("Money: " + unit.getPlayer().getMoney(), 10, 480);
            g2.drawString("Hp: " + unit.getHpCurrent() + "/" + unit.getHpMax(), 10, 510);
            g2.drawString("Speed: " + unit.getSpeed(), 10, 540);
        }
        g2.setColor(Color.YELLOW);
        g2.drawString("ClickedObjectName: " + _clickedObjectName, 10, 260);
        g2.drawString("ClickedObjectToughness: " + _clickedObjectToughness, 10, 290);
        g2.drawString("drawCounter= " + (drawCounter++), 10, 320);
    }

    @Override
    public void clean()
    {
    }

    private void checkInput(long elapsedTime)
    {
        int step = Math.round(_scrollSpeed * elapsedTime);
        if(game != null)
        {
            GameLevel gameLevel = game.getGameLevel();
            if(gameLevel != null)
            {
                WorldMap map = gameLevel.getMap();

                if(scrollMapRightKey.isPressed())
                {
                    map.scroll(WorldMapDirection.EAST, step);
                    System.out.println("Pressed:" + scrollMapRightKey.getName());
                }
                if(scrollMapLeftKey.isPressed())
                {
                    map.scroll(WorldMapDirection.WEST, step);
                    System.out.println("Pressed:" + scrollMapLeftKey.getName());
                }
                if(scrollMapUpKey.isPressed())
                {
                    map.scroll(WorldMapDirection.NORTH, step);
                    System.out.println("Pressed:" + scrollMapRightKey.getName());
                }
                if(scrollMapDownKey.isPressed())
                {
                    map.scroll(WorldMapDirection.SOUTH, step);
                    System.out.println("Pressed:" + scrollMapLeftKey.getName());
                }
                if(client.isInGame() && unit != null)
                {
                    Point2D mousePoint = new Point2D.Double(
                            inputManager.getMouseX() - map.getMapOffsetX(),
                            inputManager.getMouseY() - map.getMapOffsetY());
                    double angleBetweenDirectionAndAxisX =
                            GeometricOperations.calculateAngleOfRotation(
                            unit.getCenterPoint(), mousePoint, 0.0);
                    if(unit.isAlive() && Math.abs(unit.getFaceAngle() - angleBetweenDirectionAndAxisX) >= 5.0)
                        client.createAndEnqueueTurnActionEvent(unit, mousePoint);
                    boolean isMoving = false;
                    double modX = 0;
                    double modY = 0;
                    boolean isForwardMove = false;
                    boolean isBackwardMove = false;
                    boolean isLeftMove = false;
                    boolean isRightMove = false;
                    if(moveLeftKey.isPressed())
                    {
                        isLeftMove = true;
                        isMoving = true;
                        modX = modX - 100 - unit.getSpeed();
                    }
                    if(moveRightKey.isPressed())
                    {
                        isRightMove = true;
                        isMoving = true;
                        modX = modX + 100 + unit.getSpeed();
                    }
                    if(moveForwardKey.isPressed())
                    {
                        isForwardMove = true;
                        isMoving = true;
                        modY = modY - 100 - unit.getSpeed();
                    }
                    if(moveBackwardKey.isPressed())
                    {
                        isBackwardMove = true;
                        isMoving = true;
                        modY = modY + 100 + unit.getSpeed();
                    }

                    if(isMoving && unit.isAlive())
                    {
                        if(unit.isMoving() == false || unit.isMoveFlagsStateChanged(
                                isForwardMove, isBackwardMove, isLeftMove, isRightMove))
                        {
                            unit.startMoving();
                            unit.setMoveFlags(isForwardMove, isBackwardMove, isLeftMove, isRightMove);
                            client.createAndEnqueueMoveMessageEvent(unit,
                                    isForwardMove, isBackwardMove, isLeftMove, isRightMove);
                        }
                    }//start and stop move/shoot are controlled by server
                    else if(unit.isMoving())
                    {
                        unit.stopMoving();
                        client.createAndEnqueueMoveStopEvent(unit);
                    }

                    if(leftMouseClick.isPressed())
                    {
                        if(unit.isFiring() == false && unit.isAlive())
                        {
                            Iterator<String> it = unit.getEquipmentLocationMap().keySet().iterator();
                            while(it.hasNext())
                            {
                                String key = it.next();
                                IEquipment eq = unit.getEquipmentAtLocation(key);
                                if(eq instanceof IClipWeapon)
                                {
                                    IClipWeapon cw = ((IClipWeapon) eq);
                                    if(cw.isEnoughAmmoToAttack() == true)
                                        ((IWeaponMR) cw.getMapRepresentation()).attack();
                                }
                            }

                            unit.startFiring();
                            client.createAndEnqueueFireActionEvent(unit, IUnit.EQUIPMENT_ON_ALL_SLOTS);
                        }
                    }
                    else if(unit.isFiring())
                    {
                        System.out.println("stop firing");
                        unit.stopFiring();
                        client.createAndEnqueueFireStopEvent(unit);
                    }
                }
            }
        }
    }

    public static void main(String[] args)
    {
        BasicConfigurator.configure();
        NetworkingTest2 nft = new NetworkingTest2("Alegroth2", "ElBoro");
        nft.setCoreFrameSize(600, 600);
        nft.run();
    }
}

```

# Answer
> 2 votes
I know it's hard to use the debugger to find these kinds of issues. From your question it sounds like you also have some network communication tasks inside the input and painting thread, I'd recommend pushing that functionality to a different thread. Network communication is unreliable, and having the painting and input threads possibly getting hung up on network time-outs would be bad news.

Try to figure out how to reproduce the failure, it will be much easier to solve if you can find a cause. Another way to find the offending bit of code is to try breaking the threads tasks down, or temporarily disabling some of it's functions. Then try to break it again.

Lastly, try posting the code you think is at fault so we can look at it.

**Edit** That code is a bit much to look at. Try placing break points at all your exit points for the thread, see if the thread is ending prematurely. Step through the thread a few times with the debugger, to make sure it's following the path you think it should. Make sure it's not getting hung up on network issues.

---
Tags: java, multiplayer, multithreading
---


# Question
Title: Stretching textures for CCSprites in Cocos2D
I'm making a game for iPhone and iPad w/ Cocos2D and Box2D. I scale the size of square objects ("blocks") using a pixel-to-meters ratio depending on the particular device. **Can I stretch or shrink the textures and CCSprites as well**? I was considering having just one "blockImage.png" file and scaling it up/down depending on the device.

The alternative is having 2-3 sets of images for iPhone, iPhone 4, iPad etc.

Cheers!

# Answer
I'd recommend offline creating your assets at the highest resolution possible, then for your purposes create a PNG for each target platform requirements separately. It'll be more efficient on memory and it'll also be faster for the graphics hardware not having to scale things down (and process unnecessary texels). It seems a relatively trivial amount of work to create a couple of different sized versions and having the loading code look for and load a version that matches the platform your running on.

You can more than likely just get away with just scaling down however (scaling up would just look blocky), I don't think if you're just doing 2D you'd probably see any artefacts that 3D would suffer with when using a large texture for a small area of the screen (the way the hardware samples from the texture isn't consistent as a polygon moves and you can see weird sampling issues - problems improved by more complex filtering algorithms and mipmaps).
> 1 votes

---
Tags: graphics, textures, box2d, cocos2d-iphone, ccsprite
---


title: Real Time Dynamic Pathfinding?

text:
# Question
Title: Real Time Dynamic Pathfinding?
I'm currently doing some pathfinding research and my simulation is the following: I have a 3d scene with a start and end point represented, I'm capable of creating navigational meshes, waypoints and polygons to aid with pathfinding.

I've tried an A\* algorithm and some of its variants and they work perfectly. However, now I'm more interested in 'dynamic' pathfinding. For example, while finding a path from point A to point B, if a new obstacle suddenly appears, i want my algorithm to immediately be able to re-plan a path and not start searching from scratch again.

I've done some reading on the D\* algorithm and wondering if this would be appropriate for what I need or would this seem like an overkill.

So my questions basically are: What algorithm would be best for Real Time Dynamic Pathfinding? OR what combination of techniques could I use instead?

# Answer
D\* is quite involved -- I don't recommend trying to implement it. Even when projects that are well funded, and being developed by smart/experienced people, D\* lite is used, because D\* is such a pain to get right.

You may be interested in this presentation, which includes discussion of Left 4 Dead's pathfinding:

http://www.valvesoftware.com/publications/2009/ai\_systems\_of\_l4d\_mike\_booth.pdf

One approach is to use a coarse level A\* search to get a general path for an agent, and then to do a fine detail level A\* search for an agent's local environment. This way, you can quickly recompute the course detail A\* search if the terrain changes, and then quickly recompute the fine detail A\* search for a small segment of the environment. This is not perfect. It works as long as your obstacles cannot block out multiple course detail graph nodes, which is fine for most games. This is the method I recommend if you have less than 100 agents.

If you want to support hundreds, or thousands of agents, then you can implement something like continuum crowds. See this research: http://grail.cs.washington.edu/projects/crowd-flows/ That discusses a purely CPU based method that can support thousands of actors in a dynamic environment.

If you want to support tens of thousands, or hundreds of thousands of agents, then you can implement something like continuum crowds, with GPU assistance. See here for the relevant research: https://a248.e.akamai.net/f/674/9206/0/www2.ati.com/misc/siggraph\_asia\_08/GPUCrowdSimulation\_SLIDES.pdf

Here is a video demonstrating continuum crowds in action: http://www.youtube.com/watch?v=lGOvYyJ6r1c (Skip to 4:10 to see large dynamic obstacles like cars and stoplights affecting hundreds of people walking around a city.)
> 19 votes

# Answer
Have you looked at simple steering behaviors?

http://www.red3d.com/cwr/steer/

You can use them to veer from your A\* path in order to do local obstacle avoidance, and then steer back onto your path once you are done.

Its also fairly easy to combine multiple behaviors.
> 9 votes

# Answer
Since your post is in the "Game Development" part of stack exchange, here's what most game programmers would answer you: It's not about Real Time Dynamic Pathfinding, it's about Real Time Dynamic Path\**following*\*!

Some edge cases where an edge on your navigation graph is totally obstructed would require the pathfinder to recompute another path, but most of the time you can simply steer your entities around the obstacles, doing position prediction and avoid in the right direction. For most games, it would be too heavyweight to have to predict over time the position of dynamic agents, especially since you can't predict accurately player actions or agent decisions.

So, my advice would be to start by implementing Steering Behaviors (http://red3d.com/cwr/steer/), handle cases where the path becomes impossible and then add a layer on top of it to handle edge cases that aren't handled by the two previous solutions.

Hope this helps
> 4 votes

---
Tags: algorithm, path-finding
---


title: MVC or Components, or both?

text:
# Question
Title: MVC or Components, or both?
I'm an experienced developer but recently I've been wanting to get into game programming but as you know game development is an entirely different beast from most other forms of programming (perhaps only bested by operating system development).

That being said I've been reading Game Coding Complete (ISBN 978-1-58450-680-5) by Mike McShaffry.

Originally I was going to try developing with a component model with the assortment of usual components (e.g. SpacialComponent, VisualComponent, EntityLogicComponent, etc..) however Mr. McShaffry recommends using the MVC model which looks very attractive but I'm not sure how I can make it work with the component model if at all possible, but, without components, the MVC model looks sort of the evil monolithic inheritance monster and not very flexible, which I'm not really interested in.

I'm really confused about where to go from this point.

Do you more experienced game coding voodoo experts have any thoughts or recommendations?

Thank you so much!

# Answer
Useful questions:

MVC (Model-View-Controller) Game Engine Architecture - Yes or No?

Why are MVC & TDD not employed more in game architecture?

MVC-like compartmentalization in games?

For me, I have a RenderComponent base class and then a few that inherit from that (GameSprite, UISprite, or if you're doing 3d StaticModel, DynamicModel, BillboardModel, etc.) and if the object wants itself rendered, the object submits its RenderComponent member to the rendering system. No need for the rendering system to know what kind of object submitted the RenderComponent. It just knows it's got something to render and it better do it, or else!

Keep it basic and centered around composition rather than inheritance. Separating logic, data, and representation isn't incompatible with a component system.
> 6 votes

# Answer
I'd recommend ignoring components for your first game because they solve some types of complexity by adding more complexity in other areas, and if you've not already made a game you have no idea whether this trade-off is worth it or not.

For the most part though, don't get bogged down in programming paradigms and just code a game. There are no right or wrong ways, otherwise nobody would need to ask this sort of question. Work it out as you go along.
> 6 votes

# Answer
I wouldn't use a strict MVC pattern, but I would separate your rendering from your simulation, and stick it on another thread.

I think components are very useful actually, but I often see people just ignore them and write their code directly into the "main" component whatever that may be. You have to remember that games are full of hacks because the are often written on a deadline with the assumption that code wont be re-used.

I'm a little confused as to why you think these approaches are incompatible. What game code have you looked at?

Personally, I think games do require some up front design. I've seen a couple of code bases that were nightmares because of the "just code it mentality".

That said, I think that you should just jump in and code a game. You'll make so many mistakes writing your first game that these kinds of problems wont matter much. Once you have a better grasp of whats required, then you can go back and start looking at architecture and seeing how it solves the problems you encountered.
> 2 votes

---
Tags: architecture, component-based, design-patterns
---


# Question
Title: 2d Collision detecton axis aligned boxes
I have recently run into some trouble with my collision detection. My game is composed of a map made out of axis aligned squares. The player has an x and y velocity, and I want to know how I can find out with which side the player is colliding. So if they move left, I want to know that if they collide with a square, and with which side they collide with it.

Edit: Basically, what I want to know is how to find out which face the player is colliding with.

# Answer
> 2 votes
The "right" way to do this is probably with swept collisions.

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

Was the result of 5 seconds of googling, but if you look for swept and AABB, you should be able to find a lot of resources.

# Answer
> 0 votes
If you're ok with using c# example code, here is an example of 2d polygon detection. It may get you started, there's a lot to put into a QA answer.

http://www.codeproject.com/KB/GDI-plus/PolygonCollision.aspx

Otherwise, just google polygon detection. Once you know which ones are colliding, finding out on which face should be easy.

# Answer
> 0 votes
There are solutions for this all over the internet, stackoverflow and gamedev.SE.

Here are a couple of random ones:

---
Tags: collision-detection, physics
---


# Question
Title: in Unity3d, how to automatically create fixed joints in a wall of cubes?
I want to create a wall:
width 6 cubes
height 7 cubes
therefore I have 22 cubes on the margins and 20 cubes inside. For each of the margins cubes(except the corners) I have to set 3 fixed joints, and for the cubes inside the wall I have to set 4 fixed joints - all this to have good physics behavior.
**Pretty much I have to create a fixed joint between a cube and all his neighbors =\> and that's a lot!
Is there a way to automatically create these fixed joints?

Is there another way to create a physics friendly wall? I want to simulate a wall of bricks hited by a projectile.**

# Answer
I usually don't write code for these questions, but I'm bored. I don't have unity on this computer so I'm just guessing, it should give you an idea even if it doesn't compile. I just added each blocks right and top joint as long as it's not on the top row or far right column. In a real situation you would add the parent transforms x and y position and do all positioning in local space so it can accept the parents transform, but you get the idea I hope.

```
int x = 6;
int y = 7;
float hSpacing = 0.5f;
float vSpacing = 0.5f;
GameObject[,] wall = new GameObject[x,y];

for(int i = 0;i<width;i++)
{
    for(int j = 0;j<height;j++)
    {
         //Add the Cube
         wall[i,j] = (GameObject)Instantiate(cube,
                     new Vector3(i*(cube.lossyScale.x+hSpacing),
                     j*(cube.lossyScale.y+vSpacing),0);

         //Add right joint
         if(i+1<width)
         {
              FixedJoint fjR = wall[i,j].AddComponent("FixedJoint") as FixedJoint;
              fjR.connectedBody = wall[i+1,j].rigidbody;
         }

         //Add top joint
         if(j+1<height)
         {
              FixedJoint fjT = wall[i,j].AddComponent("FixedJoint") as FixedJoint;
              fjT.connectedBody = wall[i,j+1].rigidbody;
         }
    }
}

```
> 2 votes

---
Tags: physics, unity
---


# Question
Title: How to test a network game on a mobile device
I am looking to test a network game with say, 10 or more users, on a mobile device. Think of it like an MMO with a lot less users. (Assuming I can get 10 running, I'd test for more users later)

The test is for two reasons :

1. To see if and how the server will handle that many users
2. To see the performance on the client side (seeing how it has to update/render all these objects on a mobile device)

How would I go about testing 10 or more users? Unfortunately I do not have 10 devices to test on, only one. I've seen a few MMOs available on Android/iPhone. How do these developers go about test their game on devices?

# Answer
> 3 votes
I'm not sure about the Android platform as I have no experience with it. However, for the iOS you may be able to use something like TestFlight. You can also generate ad hoc distributions to beta users manually (you need their device UUIDs, I believe).

Also, since you're testing the server, you should be able to do load/stress/packet loss testing with fake clients that run on desktops (and thus you can run multiple clients per desktop machine to get a higher stress level). You can build packet loss simulation into those fake clients as well.

You could also implement game state recording/playback, play the game yourself for a little while, and then play back that session over multiple connections (starting each new connection at an offset time).

Artificial methods of testing are, of course, not going to reveal the same problems as real users. But they can still help and they're much easier to do as early phase testing since you don't need to involve so many real people.

---
Tags: iphone, android, networking, mmo
---


title: Flash Custom Events

text:
# Question
Title: Flash Custom Events
I am working on a Flash Tower Defense game. I have a main game loop which is an eventListener for each frame. Whenever you gain money or lose a life, I want the GameUI to be updated to display this change. Right now, it checks every frame for a change. How can I create an event to only change this information whenever the lives or money changes?

# Answer
> 1 votes
While Valke answered your question regarding custom events perfectly, I usually try to avoid Events in Flash for game-development. Robert Penner lists some good points why Events are bad.

Custom events are especially bad, when you're dispatching them very frequently (a common scenario in games), because every time you dispatch the event a new `Event` object will be allocated and also has to be garbage-collected later on.

I found the signal/slot pattern to be a very good replacement for most event-related stuff. There's the excellent as3-signals library or the fast turbosignals library for flash.

With as3-signals, your game class could look something like this (I omitted any irrelevant stuff):

```
public class Game
{
    // the signal that will dispatch whenever the money changes
    public var moneyChanged:Signal = new Signal(int);

    // ENTER_FRAME listener
    private function handleEnterFrame(e:Event):void {
        // the player collected money.. we can dispatch an "event"
        if(player.hasCollectedMoney){
            // dispatch the collected money amount
            moneyChanged.dispatch(player.collectedMoneyAmount);
        }
    }
}

```

Your GameUI class would simply have a method to update the money:

```
public class GameUI
{
    public function updateMoney(amount:int):void {
        // .. update money...
    }
}

```

All that is left to do, is to connect the signal to the update method (slot). You usually do this somewhere at initialization time, but you can also add/remove listeners/slots during runtime. eg.

```
var game:Game = new Game();
var gui:GameUI = new GameUI();
game.moneyChanged.add(gui.updateMoney);

```

Done! Whenever the game dispatches "moneyChanged", the gui will be updated. This also works nicely with multiple listeners, so you could also have a `ScoreManager`class, that also listens to `moneyChanged` updates.

# Answer
> 1 votes
you can create a custom event class this way:

1 / In a new .as file (say GUIEvent.as) create the following class

```
package {

    import flash.events.*;

    public class GUIEvent extends Event {

        public static const DEFAULT_NAME:String = "GUIEvent";
        public var _params:*;

        // your events types
        public static const GET_LIFE:String = "getLife";
        public static const GET_MONEY:String = "getMoney";
        public static const GET_GLOBAL:String = "getGlobal";
        public static const GET_ETCETERA:String = "getEtc";

        public function GUIEvent($type:String, $params=null , $bubbles:Boolean=false, $cancelable:Boolean = false){
            super($type, $bubbles, $cancelable);
            this._params = $params;
        }

        public override function clone():Event{
            return new GUIEvent(type, this._params, bubbles, cancelable);
        }

        public override function toString():String{
            return formatToString("GUIEvent", "_params", "type", "bubbles", "cancelable");
        }
    }
}

```

2/ In the place you want to register for the events (probably your MainClass.as)

```
import GUIEvent;

YourGuiObjectWaitingForTheUpdates.addEventListener(GUIEvent.GET_LIFE, GUIupdateHandler);
YourGuiObjectWaitingForTheUpdates.addEventListener(GUIEvent.GET_MONEY, GUIupdateHandler);
YourGuiObjectWaitingForTheUpdates.addEventListener(GUIEvent.GET_GLOBAL, GUIupdateHandler);

```

3/ Place the function provided to the addEventListener where it should be (still probably in your MainClass.as)

```
private function GUIupdateHandler(evt:GUIEvent):void
{
    switch(evt.type) {
        case GUIEvent.GET_LIFE:
            //modify lives on the GUI using evt._params.life
            break;
        case GUIEvent.GET_MONEY:
            //modify money value on the GUI using evt._params.money
            break;
        case GUIEvent.GET_GLOBAL:
            //modify lives AND money value on the GUI using evt._params.life and evt._params.money
            break;
        default:
            //nothing ?
}

```

4/ Finally, dispatch the events when you need to update you GUI...

```
this.dispatchEvent(new GUIEvent(GUIEvent.GET_LIFE, {life:3}, true));
//or
this.dispatchEvent(new GUIEvent(GUIEvent.GET_MONEY, {money:333}, true));
//or
this.dispatchEvent(new GUIEvent(GUIEvent.GET_GLOBAL, {life:3, money:333}, true));

```

I do not practice AS3 anymore, but I have played with it for years so it should be almost OK... but I could have forgotten something through.

---
Tags: flash, actionscript-3, game-loop, events
---


title: Simple Terrain Grid (not working)

text:
# Question
Title: Simple Terrain Grid (not working)
I know yall are probably going to hate me.....but I can't figure out what im doing wrong, im trying to make a SIMPLE Vertex Grid (for Terrain) but I get a black screen for some reason And I can't figure out why. It does run, but I just get a black screen afterwards....I hate posting such huge code on this site but I figure if anyone can explain what the heck I did wrong i'd be able to understand a little bit better.

I think the problem....may be in the matrix, but my code is simple and im 100% sure im doing the Grid right because I took it from a working tutorial that does grids (but it's large and VERY confusing for a beginner, so I just took the appropriate code).

I know it's alot to look at (vars.h is very small) and main.cpp is pretty small too but I know it's still alot.....but im just completely stuck.

vars.h http://pastebin.com/SupcqB8N

main.cpp http://pastebin.com/vAnSUTpp

shaders.hlsl

```
cbuffer ConstantBuffer
{
    float4x4 matFinal;
}

struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VOut VShader(float4 position : POSITION, float4 color : COLOR)
{
    VOut output;

    output.position = mul(matFinal, position);
    output.color = color;

    return output;
}

float4 PShader(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
    return color;
}

```

# Answer
> 2 votes
Have you tried building up from example code you know works? Incrementally adding to it? I think that's your best solution. Start with drawing a triangle and make sure that shows up, then add textures, then make it two triangles drawn from a loop, then make it into your whole grid.

For your current code, I can only suggest the basic 3D troubleshooting stuff.

* Make sure your camera is pointing the right direction
* Disable lighting, depth buffer, clipping, textures and special effects
* Check that your objects are properly formed
* Make sure your camera has it's bounds set up correctly

Good luck!

---
Tags: terrain-rendering, directx11
---


# Question
Title: Deleting Objects Before Export from Maya Causes .PSK to Crash UDK on Import
I'm using Maya 2008 Complete and 03/11 build of UDK as well as 07/10 build (haven't got around to installing newer version on other computer). I am using ActorX to export.

I have a character that I have rigged and animated (I'm not using UDK rigs).

**Here was my process:**

* Early on in the process, I had other objects skinned to the character's skeleton.
* I hid those objects while weighting the character
* I decided later that I wanted to delete them.
* I tested my .psk in both UDK builds with those objects hidden and noticed that they still showed up (in UDK)
* So, I went back into Maya, detached the skin on those objects and deleted history, then deleted them.
* I then re-exported my .psk and now when I try and import, udk crashes.

Here are my input/output connections for one of the objects before detaching the skin.

https://i.stack.imgur.com/hoDdv.jpg

**Here is my log:**

```
0002.77] Log: >>>>>>>>>>>>>> Initial startup: 2.77s <<<<<<<<<<<<<<<
[0002.81] Cmd: MODE MAPEXT=udk
[0002.87] SourceControl: Source Control disabled in GAMEEditorUserSettings.ini.  [SourceControl] has Disabled=False
[0005.61] Log: TIMER ALL OF INIT : [5.028131]
[0070.42] Log: FactoryCreateBinary: SkeletalMesh with SkeletalMeshFactory (0 0 Z:\websterProject2\EXPORTTESTING\SK_snailMesh01.PSK)
[0070.42] Log:  * Skeletal skin VPoints            : 812
[0070.42] Log:  * Skeletal skin VVertices          : 1166
[0070.42] Log:  * Skeletal skin VTriangles         : 1596
[0070.42] Log:  * Skeletal skin VMaterials         : 1
[0070.42] Log:  * Skeletal skin VBones             : 73
[0070.42] Log:  * Skeletal skin VRawBoneInfluences : 1520
[0070.42] Log:  * Skeletal skin VertexColors          : 0
[0070.42] Log:  * Skeletal skin Num Tex Coords    : 1
[0070.42] Log:  Mesh material not found among currently loaded ones: lambert3SG
[0070.42] Log: Bones digested - 73  Depth of hierarchy - 15
[0070.49] Critical: appError called: Assertion failed: Wedges.Num() == WedgeInfluenceIndices.Num() [File:c:\depot\UnrealEngine3\Development\Src\Engine\Src\UnSkeletalTools.cpp] [Line: 301]
Stack: Address = 0x402228f9 (filename not found) [in C:\UDK\UDK-2010-07\Binaries\Win64\UDK.exe]
Address = 0x40924bb1 (filename not found) [in C:\UDK\UDK-2010-07\Binaries\Win64\UDK.exe]
Address = 0x412bfbc8 (filename not found) [in C:\UDK\UDK-2010-07\Binaries\Win64\UDK.exe]
Address = 0x401a178d (filename not found) [in C:\UDK\UDK-2010-07\Binaries\Win64\UDK.exe]
Address = 0x412964a4 (filename not found) [in C:\UDK\UDK-2010-07\Binaries\Win64\UDK.exe]
Address = 0x412823a4 (filename not found) [in C:\UDK\UDK-2010-07\Binaries\Win64\UDK.exe]
Address = 0x983633   (filename not found) [in C:\UDK\UDK-2010-07\Binaries\Win64\wxmsw28u_vc_custom_64.dll]
Address = 0x983d73   (filename not found) [in C:\UDK\UDK-2010-07\Binaries\Win64\wxmsw28u_vc_custom_64.dll]
Address = 0x983e30   (filename not found) [in C:\UDK\UDK-2010-07\Binaries\Win64\wxmsw28u_vc_custom_64.dll]
Address = 0x800a34c6 (filename not found) [in C:\UDK\UDK-2010-07\Binaries\Win64\wxmsw28u_core_vc_custom_64.dll]
Address = 0x800aec65 (filename not found) [in C

```

I would like to know why deleting these objects is causing the .psk to crash on import and how I can fix it.

Thanks very much for your time.

# Answer
I wasn't sure if this was something to do with UDK or ActorX but the problem ended up being some extra inputs on the character in Maya.

I had a blend shape on the character that must have had a connection with those objects. I deleted all inputs except for the skin cluster on the character and everything works fine now.
> 0 votes

---
Tags: udk, unreal, maya
---


# Question
Title: How to generate slopes that meet the plane, is using collision detection a good idea?
I have a terrain, which is defined by mesh. And there are a lot of other polygonal faces scattered throughout the terrain, they can be located above, or below or cutting through the terrain. You can think of those faces as platforms.

A screenshot below should clarify what I mean. Despite looking smooth, all the mesh are actually consist of small elements (number\> 10k) combined together, giving the false appearance of smoothness. The obvious disconnected area are platforms.

My question is, how can I generate slopes that connect between the platforms and other platforms/ terrain? The slope plane is defined as a series of piecemeal planes, starting from the edge of platforms, going down or up, depending on where is the nearest platforms or terrain elements.

I would need to generate he slope planes so that I can compute the volume difference between the slopes and the terrains, it's not just for visualization purpose.

I'm thinking about using collision detection engines to do things like this, but

1. I'm not too sure whether this is the right idea
2. if this was the right idea, any open source collision detection engines ( C or C++ or C#) I can use?

Edit: Any open source framework that can do this is desired.

# Answer
> 1 votes
I'm not sure I know exactly what you want to do, but I'm fairly sure you don't need a collision detection engine. You'll want to use some of the principles of a collision detection engine, but don't need a full blown engine. I assume that after you find these slopes they won't change? This terrain is going to be static?

You've got a few problems here.

1. Find out where and what the closest surface to "connect" to is. This can probably be solved following the normal of the edge out (like a ray) to see what is out there (up first then down?). If you bump into a platform, find the top edge that's closest (the edge you bumped into) and move to problem 2. If it's terrain, move to problem 2.
2. How to connect to two surfaces. Likely this can be done almost the same way as problem 1. You found the direction you need to go in problem 1, now create a normal on each end of the edge in that direction. Now the ends where you started and the points where those normals bump into something else are your 4 points for a quad.
3. Finding how when you bump into something. I'm assuming you have some height map you can reference. Hopefully you'd be able to use that along with your ray to find if something exists at that point in 3D space. Otherwise you'll have to check all the primitives (triangles? quads?) in the area to see if there was a intersection.

Not sure that's really clear, but it's somewhat difficult to explain. Good luck!

# Answer
> 0 votes
This seems to me to be the type of problem that you would solve by using the current mesh as the rendering mesh, and creating a separate mesh for collisions where you connect the appropriate surfaces inside of the modeling application. I'm not sure investing the time into coming up with an algorithm would be worthwhile unless you're going to continually run into this problem over and over.

---
Tags: collision-detection, geometry, computational-geometry
---


# Question
Title: How do 3D game engines render 3D environments to a 2D screen?
For 2D sprite games, I can understand that sprites move on the X and Y axis. However, for 3D games, how do game engines calculate how to render a 3D environment on to a flat 2D computer monitor?

# Answer
> 10 votes
**3D sprites get a new Z axis that stores depth, scaling size and movements in the X/Y plane.** A sprite that is farther away has a bigger Z value. Now, divide sprite's size and X/Y axis movements by the Z axis. As others have noted, this is a 3D perspective projection. Here is the best illustration I could find:

This makes sense conceptually because things that are farther away look smaller. Their apparent movements also look smaller.

In addition, near objects need to be drawn on top of far objects. Again, this makes sense conceptually because near objects occlude the view of objects behind them.

These techniques can be implemented at the sprite level. However, for the most realistic projection each sprite has a 3D model and is rendered at the pixel level.

# Answer
> 17 votes
It's similar to how you can capture 2D pictures of our world on camera. The 3D environment is described in terms of X, Y, and Z coordinates, but ultimately you need to map that to a 2D screen with only X and Y axis. This is done by projection, where each 3D point is projected onto a 2D view plane.

To put it simply, you can imagine projection lines going from the virtual camera in 3D space to each 3D point by passing through the view plane. The point where a projection line intersects the 2D plane is the projection of the 3D point. In orthographic projection these projection lines are all parallel; the distance between the object and the camera doesn't make any difference for the projected shape. This type of projection isn't realistic but is useful in certain instances such as drawing 2D graphics using a 3D engine (the HUD for example). The other type of projection is perspective projection where these lines converge making more distant objects appear smaller and giving more realistic results. This page has some figures that could help you visualize the process.

Projection is one of several transformation objects undergo in the graphics pipeline, and is usually done using a projection matrix. Note that although projection implies discarding the Z coordinate, in reality a transformed Z value is still used a measure of screen depth so that we can tell which objects are visible and which ones are occluded by other objects. This is known as z-buffering.

# Answer
> 5 votes
It's all about projection, a geometric operation that lets you define a space from another space of superior dimension (basically, in your case, you're describing a 2D image from a 3D environment).

Simply put, this is how 3D rendering engines generate an image (given a 3D scene & a projection) :

For each pixel of the resulting image

* Compute the looking direction (according to the projection), it's basically a 3D vector
* Find the nearest object in your scene that is "seen" in this direction (simply guess what objects are intersected with the vector, and keep the nearest one)
* Compute the color of this object, you have the color of the pixel !

Of course this is a simple model, I'm not talking about reflective/refractive/translucent objects of special effects such as smoke...

# Answer
> 2 votes
**The Matrix**. Or rather, lots of matrix math.

It's scary stuff for the uninitiated. There's typically three 4x4 matrices involved in turning a bunch of 3D coordinates in space into 2D coordinates on the screen (including the depth into the screen as Z).

3D matrices are a set of 16 floating point values arranged in a 4x4 grid. Algorithms are used to generate the required values and then using matrix-vector multiplication, these numbers transform a 3-dimensional vector (X, Y, Z).

```
[ 1, 0, 0, 0 ]
[ 0, 1, 0, 0 ]
[ 0, 0, 1, 0 ]
[ 0, 0, 0, 1 ]

```

This is the **identity** matrix. It essentially *does nothing* to a vector's coordinates.

---

## Model

The first is the **world** or **model** matrix. This matrix takes the vertices in an individual model (such as a crate) modelled around the origin (0, 0, 0) and transforms them into world vertex coordinates. This might include scaling the object, rotating it around it's origin and finally translating it across to where it's located in the scene.

---

## View

The second matrix is the **view** matrix. This takes the world coordinates and transforms them so that they are within the context of the view. The concept of a camera is typically used to generate this matrix.

The camera usually contains a **position** vector, a **direction** or **target** vector, and an **up** vector. This **up** vector describes the 'spin' of the camera.

These vectors are used to generate what's called a **look at** matrix.

The affect this has is similar to the **world** matrix in the fact that it is essentially rotating and translating the world *around the camera* to "position" the camera.

A camera that is 10 units along the X axis will translate world coordinates 10 units in the other direction.

---

## Projection

The final piece of the puzzle is the **projection** matrix. In a camera-like perspective projection, the matrix transforms the *almost* screen coordinates to give the illusion of a perspective with a field of view of x degrees.

If you think in terms of corners of the screen (for a 640x480 game), this is how projection "aligns" the coordinates along the Z axis within the 2D coordinates of the screen. For orthographic projection, no scaling takes place along the Z axis into the screen. For perspective, the further away the object, the smaller it becomes in relation to the screen's extents.

---
Tags: 3d, graphics
---


# Question
Title: Is there a memory read/write or performance difference when applying affine transformations on a movieclip rather basic elementary math
I am using Actionscript 3.0 to make games and I fall into the category of programmers who use `ball.x+=5;` `ball.y+=5;` in order to move a ball by 5 pixels horizontally and vertically.

Well, now i seem to have an issue with a game I am making, it has a 3-body vehicle and each has its own translation and rotation. The three bodies: front, back1,back2 exist inside the top movieclip called vehicle. So each of them has a different coordinate system compared to the top movieclip. Well, when the vehicle crashes onto an obstacle in my game, I have to reset the movieclip, this is done by taking apart all the x,y,rotation of each movieclip into an array at the beginning of the game and restoring it to the beginning position after crash.

Well , but ,now I have stumbled upon this

> transform.matrix

feature in flash, which allows me to perform mathematical transformations on the movieclip's transformation matrix, and now on applying mathematical transformations on the top level movieclip, all the inside movieclips are affected, It is a huge advantage to me.

*But, I would like to know, IF i use this technique by breaking apart my whole code written as of now and re-writing it into using transformation matrices for every single horizontal, vertical or rotation of the vehicle. Will it affect my performance?*

Thank you.

# Answer
Using matrices for transformation isn't exclusive to using `x`, `y` and `rotation` properties. These actually all map to the same thing. If you update `x`, `y` or `rotation`, the matrix will also change.

So you can freely mix these things. You can store the initial position matrix somewhere, to easily restore it later on, but you can also still do things like `ball.x += 5`

There's no negative impact in using the matrix for transforms. I guess it's probably even faster, since you set all transformations at once instead of setting each property individually.
> 1 votes

---
Tags: flash, mathematics, actionscript-3, matrix, coordinates
---


title: Flash High Scores

text:
# Question
Title: Flash High Scores
I have a Flash game running on a Google Sites web page right now. My main goal is to eventually convert it to an Android app. For testing and for my friends to play though, I want to store high scores on the Google Sites version.

Right now I am using SharedObjects but that is only local. What is the best way to store high scores so I can see other's scores. I've been searching for a while and I found some stuff about PHP and MySQL but I don't know a lot about that or if its possible with Google Sites.

I am not really worried about people hacking the scores, I just want something quick and simple, especially since it probably won't be used when I convert it to an Android app.

# Answer
> 2 votes
Take a look at http://playtomic.com/ or http://gamersafe.com/

Both of them offer online leaderboards and are very simple to integrate with a Flash game (both require registration though, but it's free).

# Answer
> 0 votes
Simply put, you need some sort of server side scripting support to be able to handle a 'true' high score table like you're talking about. A bit of research turned up that google sites does **not** support any server side languages.

However, depending on the abilities of flash, and google docs spreadsheets, you might be able to hack something together where your game 'submits' a form to google docs, and then reads it back. This is a completely untested idea, and if it is possible, it's almost certainly a really hacky solution, and might be more complex than simply getting a web server to handle the scores.

Alternate option: set up a web server on your local machine, and use that for the high score list. There's other potential issues if you do this, but it would work if your game doesn't get found by something like reddit.

# Answer
> 0 votes
I will add a vote for mochi and kongregate. They both have very simple to integrate highscore lists, and are both free.

---
Tags: flash, actionscript-3, leaderboards
---


# Question
Title: Determine position of a rotated element in Tetris
Tetris-Tiles are stored as a 4x4 boolean matrix. Each rotation step has it's own matrix, the representation of the **T**-Block would look like this:

```
[
    0, 0, 0, 0,
    0, 1, 1, 1,
    0, 0, 1, 0,
    0, 0, 0, 0
],
[
    0, 0, 1, 0,
    0, 0, 1, 1,
    0, 0, 1, 0,
    0, 0, 0, 0
],
[
    0, 0, 1, 0,
    0, 1, 1, 1,
    0, 0, 0, 0,
    0, 0, 0, 0
],
[
    0, 0, 1, 0,
    0, 1, 1, 0,
    0, 0, 1, 0,
    0, 0, 0, 0
]

```

I'm trying to find a way to calculate the position of the block when it's being rotated and collides with the board (the board is also a matrix). The original Tetris would simply not allow rotation of a block when the rotation would result in a collision. Modern variants of the game will resolve the collision and move the block to a valid position.

Here are some situations that should be solved. The board is 6x6, **red** = active block, **grey** = placed/occupied blocks. Each time, a counter-clockwise rotation should be performed. The green overlay indicates the matrix for the block. The arrow indicates the resulting correction to resolve the rotation:

1. Block is at the left side of the board. Since the block cannot leave the board, it should be moved back inside after a rotation.
2. Block hits "ground", but isn't placed/committed yet. In this case, the tile must be moved up to resolve the collision (in case of a "I"-Block, the movement would be 2 cells up).
3. Tile would hit occupied blocks, must be moved left to resolve collision.
4. Tile cannot be rotated.

What would be the best approach to tackle this problem? Optimally, the solution should be generic, eg. work with arbitrary 4x4 matrix blocks on an arbitrarily sized and populated board.

# Answer
The situation you describe is called a "wall kick".

> A wall kick happens when a player rotates a piece when no space exists in the squares where that tetromino would normally occupy after the rotation.

...

> The simplest wall kick algorithm ... is to try moving the tetromino one space to the right, and then one space to the left, and fail if neither can be done.

There are various Tetris rotation systems, all documented on Wikia: Rotation Systems

SRS is the "official" Tetris specification, and it has quite a complex algorithm for wall kicks involving tables. The final piece may not even overlap the original piece at all!

The DTET rotation system extends the simplest algorithm by checking five other wall kicks besides just right and left. All pieces follow the same rules.
> 16 votes

---
Tags: software-engineering, algorithm, puzzle
---


# Question
Title: What are the most commonly used programming languages?
When I took my Java courses a year ago, I was told that Java is used mostly in the overseas gaming companies while C++ is used here in the US. What languages should I focus on learning in-depth?

# Answer
Common programming languages can be broken up by "type" of game development.

Large, triple-A games that are pushing the envelope when it comes to graphics typically utilized a mixture of straight C and C++ for the majority of the project. Often, a scripting language will be involved--though, this isn't necessarily true of all engines.

Gameplay code is often written in a proprietary language (UnrealScript), Python, Lua (CryTek, Spark Engine), or, in some cases, C# (The Sims 2). A few game engines are starting to support JavaScript (Unity, etc.).

Shader languages are also utilized, of course.

In the mobile realm, iPhones are dominated by objective-C while most other cellphones utilize Java (Android, Brew-based, etc.).

As for indies or small companies, they can be utilizing pretty much anything depending on their target platforms. For instance, C# is common with small time Live developers. Flash developers obviously use ActionScript.

So, there you go. Hope that helps.
> 27 votes

# Answer
C++ is the lingua franca of the console game industry. C# is used pretty heavily for tools and pipelines.
> 33 votes

# Answer
C++ is fairly prominent in the current gaming market. Thought C is still widely used.

When making games, your main focus should not be language but the end product. Never start a project thinking "How can we make this in language X?" but "How can we make this in the best way possible?"
> 15 votes

# Answer
The *ultimate* source is the **TIOBE Index**. Granted it won't tell you what each language is being used for...
> 8 votes

# Answer
As already mentioned, C++ is essentially *the* language to learn; the major consoles all host a C++ development environment, for better or worse. C# is starting to take off, in XNA-powered games, but is most often also used for tools development.

Lua is also one of the most commonly used scripting languages in games; it's helpful to have at least a passing familiarity with it.

Often the build chain used to build the game will contain scripts written in Python or Perl; it's helpful to be familiar with those too (though it's not a requirement).
> 6 votes

# Answer
It is best not to learn one language, but to learn different programming concepts and how to apply them in a few different languages, frameworks and enviroments.
> 4 votes

# Answer
Don't forget PHP. It is very popular in MMORGP played via WWW development. In Poland f.g. there is very large number of MMORPG based on Vallheru engine, written entirely in PHP.
> 3 votes

# Answer
Maybe you shouldn't focus on learning one specific language. You should how to develop.

Yesterday, i downloaded the iOS SDK and Xcode. And i took it right away and made a little tetris. I'm an as3 guy, and i haven't even bother about learning Objective-C. But i was able to make a simple game because i understand how to develop.

So, my point here is that you maybe should spend more time learning new concepts, than a specific language. Or Learn X languages and port your knowledge to other languages.
> 0 votes

# Answer
Game development is a different ball game form application programming.

In the world of games it is all about speed. When pushing the envelope with 1080p HD graphics, high sampling sound and nex gen AI every last processor cycle counts.

Historically C and C++ have been the fasts but java is now comparable to c++ in terms of speed in some circumstances.

C++ allows you greater control over the architectural you design on than any other language.

Most senior game developer are well senior meaning they were taught the old school way as they were invented an as such are very proficient in older technologies.

But the most major reason that commercial game development favours C++ is that it has been used for over 15 years in the games industry and there are literally billions of in house and public access library's for it. If you want it chances are someone has built it in c++.

Having said that java is becoming more and more popular as it makes it easier to develop on the wide spread and constantly changing mobile architectural but bleeding edge games will continue to have there core written in c++ for some time to come.
> 0 votes

# Answer
Objective-C for iOS devices of course. https://developer.apple.com/library/ios/#referencelibrary/GettingStarted/RoadMapiOS/chapters/Languages.html And most OS X programs are coded in it as well : https://developer.apple.com/technologies/mac/cocoa.html
> -1 votes

---
Tags: software-engineering
---


# Question
Title: OpenGL ES 2.0: Moving Camera in Orthogonal (2D) Projection
I have quite **large 2D game scene**. The scene is much larger than the screen of the LCD. Therefore, I have to move the camera (view) in desired directions, to display particular parts of the scene.

**What is the correct way of moving viewport over the scene, in Orthogonal (2D) projection, please?**

*There are two solutions coming to my mind:*

1. Using **GluLookAt()**, which is designed to move camera moslty in Perspective Projection, but it could work well for 2D as well. However, not all of the GluLookAt() parameters would be utilized in Ortho configuration.
2. Using **opposite View Translate transformation**. This would mean, if I need to move my 2D camera 10 units to the right(positive x axis), I would apply opposite Translate transformation to every scene vertex (negative x axis). This way, I would create illusion, the camera moves to the right.

These are the solutions coming from my mind. However, because, i am self taught, is there any **correct and recommended way of moving camera over the 2D scene**, please?

# Answer
There are several correct ways -- both of the methods you described are fine. I would suggest the first method, using gluLookAt or otherwise directly manipulating the view transformation matrix to transform it sideways. All parameters to gluLookAt are still going to be used.

GL combines the world and view matrices into one, so depending on the level to which you abstract that yourself it may not matter if you manipulate the "view" matrix or the "object" matrix (since they're the same). If you do maintain a separation of these concepts in your own code, I would say that it's more readable to manipulate the view matrix (via gluLookAt or more direct transformation) than the object matrix, even the math would end up being equivalent.
> 6 votes

---
Tags: opengl, opengl-es, camera
---


# Question
Title: Circled plus math symbol - Direct sum of triangles?
I'm reading a paper on terrain rendering LOD and there's some math notation there I'm not clear on.

When talking about how triangles are split into pairs of smaller triangles where more detail is needed on the mesh they have an equation along the lines of

large triangle = left triangle ⊕ right triangle

From the context of the rest of the paragraph, I get that they're saying that the bigger triangle contains/is made up of the two smaller triangle. But what specifically does that symbol mean in terms of triangles & trigonometry?

Should that be interpreted as the direct sum of two triangles? If so, what does that operation actually entail? Performing a direct sum of the matrices of the triangle vertices?

Paper in question is here btw, page 4, section 4.1 has the notation I'm talking about.

# Answer
> 5 votes
Probably referring to Minkowski Addition?:

http://www.cut-the-knot.org/do\_you\_know/add\_shape.shtml

(Scroll down a little ways to find where they use the same symbol.)

"Every element of A added to every element of B," meaning that if A had 4 vertices and B and 3 vertices, the resulting shape would have 12 vertices.

---
Tags: mathematics
---


title: Designing a component based game

text:
# Question
Title: Designing a component based game
I'm writing a shooter (like 1942, classic 2D graphics) and I'd like to use a component based approch. So far I thought about the following design:

1. Each game element (airship, projectile, powerup, enemy) is an Entity
2. Each Entity is a set of components which can added or removed at run-time. Examples are Position, Sprite, Health, IA, Damage, BoundingBox etc.

The idea is that Airship, Projectile, Enemy, Powerup are NOT game classes. An entity is only defined by the components it owns (and that can change during time). So the player Airship starts with Sprite, Position, Health and Input components. A powerup has the Sprite, Position, BoundingBox. And so on.

The main loop manages the game "physics", i.e. how the components interact each other:

```
foreach(entity (let it be entity1) with a Damage component)
    foreach(entity (let it be entity2) with a Health component)
    if(the entity1.BoundingBox collides with entity2.BoundingBox)
    {
        entity2.Health.decrease(entity1.Damage.amount());
    }

foreach(entity with a IA component)
    entity.IA.update();

foreach(entity with a Sprite component)
    draw(entity.Sprite.surface());

...

```

Components are hardcoded in the main C++ application. Entities can be defined in an XML file (the IA part in a lua or python file).

The main loop doesn't care a lot about entities: it only manages components. The software design should allow to:

1. Given a component, get the entity it belongs to
2. Given an entity, get the component of type "type"
3. For all entities, do something
4. For all entity's component, do something (e.g: serialize)

I was thinking about the following:

```
class Entity;
class Component { Entity* entity; ... virtual void serialize(filestream, op) = 0; ...}
class Sprite : public Component {...};
class Position : public Component {...};
class IA : public Component {... virtual void update() = 0; };

// I don't remember exactly the boost::fusion map syntax right now, sorry.
class Entity
{
   int id; // entity id
   boost::fusion::map< pair<Sprite, Sprite*>, pair<Position, Position*> > components;
   template <class C> bool has_component() { return components.at<C>() != 0; }
   template <class C> C* get_component() { return components.at<C>(); }
   template <class C> void add_component(C* c) { components.at<C>() = c; }
   template <class C> void remove_component(C* c) { components.at<C>() = 0; }
   void serialize(filestream, op) { /* Serialize all componets*/ }
...
};

std::list<Entity*> entity_list;

```

With this design I can get #1, #2, #3 (thanks to boost::fusion::map algorithms) and #4. Also everything is O(1) (ok, not exactly, but it's still very fast).

There is also a more "common" approch:

```
class Entity;
class Component { Entity* entity; ... virtual void serialize(filestream, op) = 0; ...}
class Sprite : public Component { static const int type_id = 0; };
class Position : public Component { static const int type_id = 1; };

class Entity
{
   int id; // entity id
   std::vector<Component*> components;
   bool has_component() { return components[i] != 0; }
   template <class C> C* get_component() { return dynamic_cast<C> components[C::id](); } // It's actually quite safe
...
};

```

Another approch is to get rid of the Entity class: each Component type lives in its own list. So there is a Sprite list, a Health list, a Damage list etc. I know they belong to the same logic entity because of the entity id. This is simpler, but slower: the IA components needs access basically to all other entity's components and that would require searching each other component's list at each step.

Which approch do you think is better? is boost::fusion map suited to be used in that way?

# Answer
I've found that component-based design and data-oriented design go hand in hand. You say that having homogeneous lists of components and eliminating the first-class entity object (instead opting for an entity ID on components themselves) will be "slower", but that's neither here nor there since you haven't actually profiled any real code that implements both approaches to arrive at that conclusion. As a matter of fact, I can almost guarantee you that homogenizing your components and avoiding the traditional heavy virtualization will be *faster* due to the various advantages of data-oriented design -- easier parallelization, cache utilization, modularity, etc.

I'm not saying this approach is ideal for everything, but component systems which are basically collections of data that need the same transformations performed upon them every frame, simply scream to be data-oriented. There will be times when components need to communicate with other components of different types, but this is going to be a necessary evil either way. It shouldn't drive the design, however, since there are ways to solve this issue even in the extreme case that all components are processed in parallel such as message queues and futures.

Definitely Google around for data-oriented design as it relates to component-based systems, because this topic comes up a lot and there is quite a bit of discussion and anecdotal data out there.
> 6 votes

# Answer
if i were to write such a code i would rather ot use this approch (and i'm not using any boost if it's important for you), since it can do all the thing you want but the problem is when there are too many enteties which do not share some componnet, finding those which have it will consume some time. other than that there is no other problem i can thing of :

```
// declare components here------------------------------
class component
{
};

class health:public component
{
public:
    int value;
};

class boundingbox:public component
{
public :
    int left,right,top,bottom;
    bool collision(boundingbox& other)
    {
        if (left < other.right || right > other.left)
            if (top < other.bottom || bottom > other.top)
                return true;
        return false;
    }
};

class damage : public component
{
public:
    int value;
};

// declare enteties here------------------------------

class entity
{
    virtual int id() = 0;
    virtual int size() = 0;
};

class aircraft :public entity, public health,public boundingbox
{
    virtual int id(){return 1;}
    virtual int size() {return sizeof(*this);};
};

class bullet :public entity, public damage, public boundingbox
{
    virtual int id(){return 2;}
    virtual int size() {return sizeof(*this);};
};

int main()
{
    entity* gameobjects[3];
    gameobjects[0] = new aircraft;
    gameobjects[1] = new bullet;
    gameobjects[2] = new bullet;
    for (int i=0;i<3;i++)
        for(int j=0;j<3;j++)
            if (dynamic_cast<boundingbox*>(gameobjects[i]) && dynamic_cast<boundingbox*>(gameobjects[j]) &&
                dynamic_cast<boundingbox*>(gameobjects[i])->collision(*dynamic_cast<boundingbox*>(gameobjects[j])))
                if (dynamic_cast<health*>(gameobjects[i]) && dynamic_cast<damage*>(gameobjects[j]))
                    dynamic_cast<health*>(gameobjects[i])->value -= dynamic_cast<damage*>(gameobjects[j])->value;
}

```

in this approch every component is a base for an entity so given the component it's pointer is also an entity! the second thing you ask for is to have a direct access to some entity's components eg. when i need to access damage in one of my entities i use `dynamic_cast<damage*>(entity)->value`, so if `entity` has damage component it will return the value. if you are not sure whether `entity` has component damage or not you can easily check `if (dynamic_cast<damage*> (entity))` return value of `dynamic_cast` is always NULL if the cast is not valid and a same pointer but with the requested type if it's valid. so to do something with all the `entities` which has some `component` you can do it like below

```
for (int i=0;i<enteties.size();i++)
    if (dynamic_cast<component*>(enteties[i]))
        //do somthing here

```

if there any other questions i'll be glad to answer.
> -1 votes

---
Tags: c++, design-patterns, component-based
---


title: Voxel heightmap terrain editor

text:
# Question
Title: Voxel heightmap terrain editor
I've recently been experimenting with a simple Voxel-based 3d engine (think Minecraft) which uses heightmaps to define terrain in the following format:

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

Does anyone know of the best software for producing these kind of maps? Preferably with the ability to define a texturemap also. Are terrogen and picogen the only real alternatives?

# Answer
Rolling your own is nice, since then you can just create maps, without needing to supply an image, or at least make the image optional. I use Perlin noise in my voxel game for terrain generation. It works pretty well, but is fairly plain compared to the maps that Minecraft produces. I imagine Notch does a lot more than just Perlin noise.

In my game I use 2D Perlin noise to generate the basic flow of the landscape. Then do some carving with another grid of 2D Perlin noise to make a more rugged look. Then I carve tunnels using a wandering path through the terrain.

Perlin noise is a pretty standard way to go:

https://stackoverflow.com/questions/4753055/perlin-noise-generation-for-terrain

Then this guy Paul Martz has an application that makes such maps, and the source code for doing so.

http://www.gameprogrammer.com/fractal.html

There's also a nice article in Game Developer that goes into procedurally generating voxel terrain. It goes into 2D height maps, and 3D noise for generating maps.

There is an article in the April issue on page 21 (Creator of Worlds) That's rather good, however it looks like it's paid access if you don't already have a subscription.
> 2 votes

# Answer
I'm a little confused about what you're trying to do. If you represent your terrain as a single 2D heightmap, then you won't be able to form the same kind of terrain as minecraft, as it is a 3D voxel terrain (i.e. arbitrary placement of cubes anywhere in 3D).

One benefit of voxels is that you can have overhangs and tunnels and floating blocks, which are all impossible with a heightmap like you describe.

In terms of minecraft, a single 2D texture can only provide you with information about a single layer of blocks.

If you really do want to create a 2D heightmap, Vue has excellent tools for doing so. (Although it is quite expensive.)

If you want to generate an interesting 3D terrain from scratch consider this often quoted GPU Gems article: Generating Complex Procedural Terrains Using the GPU, and simply ignore all the hard parts of generating a mesh from the voxels, and just use the voxel generation method by itself (just a combination of trig functions).

Texture colors can be generated based on slope and height.
> 2 votes

# Answer
## World Machine

http://www.world-machine.com/

World Machine has a non-commercial free version which only has a few limitations compared to the commercial version. I can't speak highly enough about this software.

Produces both a heightmap and texturemap procedurally.

I used it to create the island and texturemap for this techdemo

> Forget what you know about editing terrains. Unlike many other terrain editors that function like paint programs, World Machine operates on a procedural level. A World Machine world file is not the terrain, but the steps that creates the terrain. This is the source of both its power and its complexity.
>
> When working in World Machine, your role is to determine the overall appearance and characteristics of the terrain, and then allow the generators and effects to create and detail the appearance of your world. This way of working and thinking at a higher level takes some getting used to, but the rewards are huge: You can create impressive terrains with relatively little work, and once you have created a terrain that you like, you can use the same world file with different random "seeds" to produce a different terrain with the same feel.
> 2 votes

---
Tags: level-design, terrain-rendering, voxels, minecraft-modding, heightmap
---


# Question
Title: OpenGL ES 2.0: Converting GL_TRIANGLES into GL_TRIANGLE_STRIP
I **export my 3D geometry** from a 3D authoring application. It is possible to export the vertex coordinates as full triangle arrays.

On ther other hand, **triangle strips are more efficient** for the OpengGL to render. This is especially true for OpenGL ES, which is very sensitive for performance.

**Is it therefore possible to convert GL\_TRIANGLES arrays into GL\_TRIANGLE\_STRIP, please?**

Could anybody provide me with working algorithm? Thank you.

# Answer
> 2 votes
Looks like you may have an answer here: http://www.gamedev.net/topic/456455-convert-triangle-list-to-triangle-strip/

---
Tags: opengl, opengl-es
---


# Question
Title: Should I have an upper limit to the number of update cycles per second in a JS game?
I'm making a JavaScript game engine for fun and one thing I noticed was that my laptop runs super hot with the simplest game mechanics and that my game is doing about 600 updates per second.

The graphics is already capped at 60 fps, but I'm wondering if I should limit the update cycles so my processor doesn't get owned on the simplest games.

I think the answer is yes, it is just that I've never heard of anyone doing this before, so I wanted others opinions.

# Answer
> 4 votes
You may want to look at some of the common javascript game loop patterns that exist. Most folks use a timer to schedule the game loop. This resource is excellent: http://codeofrob.com/archive/2011/03/17/a-javascript-game-loop-for-multiplayer-webgl.aspx

If your game isn't multiplayer you can likely use what the author calls "another naive game loop".

# Answer
> 3 votes
600 updates per second is far too much for any game I can think of. Some games require a very intensive update rate, but most of the games can do all they need to be done, with a 25-30 update rate per second. (We speak about the game state updates, not about the display updates)

There is different methods to limit the number of game state update per second... and as *Koen Witters* wrote a very interesting, clear and simple paper on this question I recommend you the following article ( http://www.koonsolo.com/news/dewitters-gameloop/ ) instead of trying to explain myself the same ideas with my approximative English ;)

This paper will present you four approaches of game loops, and for each one it will expose the pros, the cons and explain how it can be done.

---
Tags: javascript, game-loop
---


# Question
Title: What good books are there on level design?
I am trying to learn a bit of level design. The type of game I am most interested is 2D puzzle games similar to Cut The Rope for iPad. However, literature on general level-design for different genres would be very welcomed.

A internet quick search brings.

http://www.amazon.com/Art-Game-Design-book-lenses/dp/0123694965/ref=pd\_sim\_b\_5

http://www.amazon.com/Game-Level-Design-Development/dp/1584503696

Anyone can recommend those or any other resources? books, recorded conferences, examples, tutorials, slides..

# Answer
I agree with what Clinton Freeman suggested. I haven't read Hourences' book, but I have gone through some of his video tutorials and his website is highly informative so I would bet his book is excellent.

The Art of Game Design:A Book of Lenses is a great book and takes you through the game design process but doesn't delve too much into level design specifically as I recall. It covers how to get started designing a game all the way through pitching your ideas to a publisher.

Scott Roger's book Level Up is another fantastic book in my opinion. This book has a a section specific to level design. That section includes things like hand drawn level maps that were used to concept actual levels, what makes a level fun/boring, how to draw the attention of the player, and the different types of level layouts. There are a lot of other interesting topics in the book as well and it was entertaining to read.

Hope that helps. Good luck!
> 3 votes

# Answer
Although I realize you're looking for literature on the subject, in the meantime I would recommend trying to find a discussion community that most closely aligns to the particular game you're trying to design for. If none exist specifically for level design, find one where players of the game congregate. One of the best ways to learn level design for any game, IMO, is to do the following:

1. Actually begin creating levels for the game
2. Get critical feedback about what could be improved from players and other designers
3. Respond to the feedback with improvements to your level
4. Repeat

In terms of books on the subject, one you might be interested in looking at is Hourences' book, The Hows and Whys of Level Design.
> 2 votes

# Answer
I'm an immense fan of the Jesse Schell book (A Book Of Lenses), though as noted it's not the best book specifically for level design (it does have some discussion on that front, though, particularly on how to force player paths without making them feel forced).

You should note that puzzle design (for games like Cut The Rope and arguably Angry Birds-style games) is a drastically different thing than level design; level design often concerns itself with the *physical* space of a level, and while games like Cut The Rope have some elements of this, if what you're looking for is puzzles, that's really a different topic (and sadly, one that doesn't have a lot of literature on it!).
> 0 votes

# Answer
Jesse Schell's book is good, though it doesn't work for me strictly as a 'level design' book. What really helps is reading breakdowns of the level design of famous games; for example, try reading some articles about Super Mario's level design. In addition, a good thing I always remember from Schell's book and almost every game I've ever loved is to remember to give the player visual/auditory rewards for progress which don't need to impact the goal of the game (score). This just seems to increase the game's fun. :)
> 0 votes

---
Tags: books, level-design
---


title: How to handle input from user

text:
# Question
Title: How to handle input from user
I am making an iphone opengl es 1.0 game. I am using a fixed timestep with interpolation on the end. One thread only. I am using CADisplayLink to fire the game loop.

First question: is it okay to use CADisplayLink to fire the game loop? i am targeting \> 3.1 so that's not an issue.

Real question: What's the proper way to handle user touch input as it relates to my gameloop and adding state to my game. For example lets say when the user touches the screen i want to fire a bullet. I've read that I don't want to actually update my game state in my touch handler function. But I should instead record that touch in an array or something and then on the next gameloop update(dt) i go through the array and updated my game state based on the array items.

is this correct? shouldn't i be storing a timestamp of each touch so i know exactly how to inject it into my game?

# Answer
> 1 votes
First answer: AFAIK using the CADisplayLink should work just fine (I use it and haven't had a problem with it yet). The CADisplayLink simply makes sure that your OpenGL view only receives update calls when the hardware is ready for a new frame. Based on your assumptions, however, this may make your game skip or lag at some points. You may consider moving to a variable-step time-based approach to smoothly update your game between frames (example can be found here).

Real answer: This is a tough one to answer directly, as everyone has their own opinion on how this works. In general, I would say yes: place the input events into a queue that is processed at the end of every frame. This ensures a few things: 1) user input is processed in the same order it was received; 2) input processing is executed at a known point in time, making mutation of iterated arrays and other potential hazards a non-issue; 3) significantly cuts down on input-related bugs as you now have a single point in your update loop that you can easily step through to see what's happening.

I'm sure there are some who disagree, but this approach has worked well for me in the past, especially for keystrokes and other state-based input. Please let me know what approach you decide to take and if this answer helped out. Until then, good luck!

---
Tags: iphone, input, game-loop
---


# Question
Title: How should I display ping in a client-server-client multiplayer?
Say I'm having a multiplayer RTS game. There's a main server for each individual game and several clients connected to it. All packets are sent to server first and then server retransmits them back to specified clients.

I'm thinking of 2 ways:

* List of **Client-Server** pings, which will be the same, no matter which Client asked for it
* List of **Client-Client** pings, which will vary for every Client

My question is how should I calculate and display ping info to players?

*I will add more details to my question if necessary*

# Answer
Client to Server ping: This one's pretty easy. Simply timestamp your packets and find the difference between the times when the packets arrive. Take the average of these times over some period (say 1 second) and that's your lag from Client to Server. As far as display, that's totally up to you and your game layout. In general, it's a good idea to display lag as part of the "score breakdown" screen, where each player's public information can be accessed. Also, you may consider color-coding lag levels; such as green for \<100ms, yellow for \<200ms, and red for 200ms+.

Client to Client ping: I'm not sure this is implemented very often, and probably for good reason: it's unimportant. Actually, ideally, there is no Client to Client ping because there is no Client to Client interaction; all interaction takes place on the Server. If you did have Clients connecting to each other, you would probably display that information in much the same way you would as a Client to Server connection. However, if you wanted to display ALL of the pings between ALL of the Clients, a table would work.

Hope that helps!
> 5 votes

---
Tags: multiplayer, client-server
---