# Question
Title: Your mobile device as controller for webapps
I'm creating a multiplayer game just for fun and exploring different techniques like isometric games, node.js and socket.io. The point is that I've tried to make an alternative approach on multiplayer gaming in a browser. Have a look here; http://ny.scsterallure.nl/ The second player connects to the game by going on his mobile device to http://ny.scsterallure.nl/index.mobile.html All though I'm not finished with the game and controls, I think the mobile device controller shouldn't be a webpage but an app. Since the webpage doesn't handle double taps and other events well. So my question is; are there already some generic (virtual) mobile gamepad apps or is this something new? Also what are your opinions on the whole controller interaction.

# Answer
> 1 votes
Such a thing already exists -- see Google's ChannelConnect API. I built a game for a client using this technology to do exactly what you're suggesting. I'd post a link, but unfortunately it was a 1-day banner ad game on Youtube. It was hooked up for iOS and Android, using a browser-based controller.

And TBH, I don't think it's the world's greatest idea, mainly for reasons of latency. As far as I -- and I think most networked game developers -- are concerned, a game isn't playable when the delay between your manipulating a controller and seeing the effect of that manipulation onscreen is more than a tenth of a second, let alone half a second. So the mobile network had better be damned reliable -- which you cannot guarantee with your players on so many different providers, at different times of day.

---
Tags: isometric, web, controllers
---


# Question
Title: Try-catch or ifs for error handling in C++
Are exceptions used widely in game engine design or it is more preferable using pure if statements? For example with exceptions:

```
try {
    m_fpsTextId = m_statistics->createText( "FPS: 0", 16, 20, 20, 1.0f, 1.0f, 1.0f );
    m_cpuTextId = m_statistics->createText( "CPU: 0%", 16, 20, 40, 1.0f, 1.0f, 1.0f );
    m_frameTimeTextId = m_statistics->createText( "Frame time: 0", 20, 20, 60, 1.0f, 1.0f, 1.0f );
    m_mouseCoordTextId = m_statistics->createText( "Mouse: (0, 0)", 20, 20, 80, 1.0f, 1.0f, 1.0f );
    m_cameraPosTextId = m_statistics->createText( "Camera pos: (0, 0, 0)", 40, 20, 100, 1.0f, 1.0f, 1.0f );
    m_cameraRotTextId = m_statistics->createText( "Camera rot: (0, 0, 0)", 40, 20, 120, 1.0f, 1.0f, 1.0f );
} catch ... {
    // some info about error
}

```

and with ifs:

```
m_fpsTextId = m_statistics->createText( "FPS: 0", 16, 20, 20, 1.0f, 1.0f, 1.0f );
if( m_fpsTextId == -1 ) {
    // show error
}
m_cpuTextId = m_statistics->createText( "CPU: 0%", 16, 20, 40, 1.0f, 1.0f, 1.0f );
if( m_cpuTextId == -1 ) {
    // show error
}
m_frameTimeTextId = m_statistics->createText( "Frame time: 0", 20, 20, 60, 1.0f, 1.0f, 1.0f );
if( m_frameTimeTextId == -1 ) {
    // show error
}
m_mouseCoordTextId = m_statistics->createText( "Mouse: (0, 0)", 20, 20, 80, 1.0f, 1.0f, 1.0f );
if( m_mouseCoordTextId == -1 ) {
    // show error
}
m_cameraPosTextId = m_statistics->createText( "Camera pos: (0, 0, 0)", 40, 20, 100, 1.0f, 1.0f, 1.0f );
if( m_cameraPosTextId == -1 ) {
    // show error
}
m_cameraRotTextId = m_statistics->createText( "Camera rot: (0, 0, 0)", 40, 20, 120, 1.0f, 1.0f, 1.0f );
if( m_cameraRotTextId == -1 ) {
    // show error
}

```

I heard that the exceptions are a bit slower than ifs and I shouldn't mix exceptions with if-checking method. However with exceptions I have more readable code than with tons of ifs after every initialize() method or something similar, though they are sometimes too heavy for just one method in my opinion. Are they ok for game development or better to stick with simple ifs?

# Answer
Short answer: read Sensible Error Handling 1, Sensible Error Handling 2, and Sensible Error Handling 3 by Niklas Frykholm. Actually, read all the articles on that blog, while you're at it. Won't say I agree with everything, but most of it is gold.

Don't use exceptions. There are a plethora of reasons. I will list the major ones.

They can indeed be slower, though that is minimized quite a bit on newer compilers. Some compilers support "zero overhead exceptions" for code paths that don't actually trigger exception (although that's a bit of a lie, since there's still extra data that exception handling requires, bloating your executable/dll size). The end result though is that yes, using exceptions is slower, and in any *performance critical* code paths, you should absolutely avoid them. Depending on your compiler, having them enabled at all may add overhead. They always always bloat code size, rather significantly in many cases, which can severely affect performance on today's hardware.

Exceptions make code *much* more fragile. There's an infamous graphic (which I sadly can't find right now) that basically just shows on a chart the difficulty of writing exception-safe code vs exception-unsafe code, and the former is a significantly larger bar. There are simply a lot of little gotchas with exceptions, and many *many* ways to write code that *looks* exception safe but really isn't. Even the entire C++11 committee goofed on this one and forgot to add an important helper functions for using std::unique\_ptr correctly, and even with those helper functions, it takes more typing to use them than not to and most programmers won't even realize what's wrong if they don't.

More specifically for the games industry, some consoles' vendor-supplied compilers/runtimes outright don't support exceptions fully, or even don't support them at all. If your code uses exceptions, may you still in this day and age have to rewrite portions of your code to port it to new platforms. (Unsure if that's changed in the 7 years since said consoles were released; we just don't use exceptions, have them disabled in the compiler settings even, so I don't know that anyone I talk to has even checked recently.)

The general line of thinking is pretty clear: use exceptions for *exceptional* circumstances. Use them when your program gets into a "I have no idea what to do, maybe hopefully someone else does, so I'll throw an exception and see what happens." Use them when no other option makes sense. Use them when you don't care if you accidentally leak a little memory or fail to clean up a resource because you messed up the use of proper smart handles. In all other cases, don't use them.

Regarding code like your example, you have several other ways to fix the problem. One of the more robust -- though not necessarily most ideal in your simple example -- is to lean towards monadic error types. That is, createText() can return a custom handle type rather than an integer. This handle type has accessors for updating or controlling the text. If the handle is put into an error state (because createText() failed) then further calls to the handle simply fail silently. You can also query the handle to see if it has errored, and if so, what the last error was. This approach has more overhead than other options, but it's fairly solid. Use it in cases when you need to perform a long string of operations in some context where any single operation could fail in production, but where you don't/can't/won't check for errors after every call.

An alternative to implementing monadic error handling is to, rather than using custom handle objects, make the methods on the context object gracefully deal with invalid handle ids. For example, if createText() returns -1 when it fails, then any other calls to m\_statistics that take one of those handles should gracefully exit if -1 is passed in.

You can likewise put the error printing inside the function that is actually failing. In your example, createText() likely has way more information about what went wrong, so it'll be able to dump a more meaningful error to the log. There's little benefit in this case to pushing the error handling/printing out to callers. Do that when the callers have need to customize the handling (or use dependency injection). Note that having an in-game console that can pop up whenever an error is logged is a good idea and helps here, too.

The best option (already presented in the linked series of articles above) for calls that you don't expect to fail in any sane environment -- like the simple act of creating text blobs for a statistics system -- is to just have the function that failed (createText in your example) abort. You can be reasonably sure that createText() is not going to fail in production unless something is totally wonked out (e.g., the user deleted font data files, or for some reason only has 256MB of memory, etc.). In many of these cases, there isn't even a good thing to do when failure does happen. Out of memory? You might not even be able to make an allocation necessary to create a nice GUI panel to show the user the OOM error. Missing fonts? Makes it hard to display errors to the user. Whatever's wrong, a crash handler can pop up a message to the user, offer to send the log file in to the developer, and hint that the user should probably reinstall the software since it's quite possibly missing some important component.

Just crashing is totally fine so long as you (a) log the error to a log file and (b) only do it on errors that aren't caused by regular user actions.

I wouldn't say the same thing at all for many server apps, where availability is critical and watchdog monitoring is not sufficient, but that is quite different than game *client* development. I would also strongly steer you clear of using C/C++ there as the exception handling facilities of other languages tend not to bite like C++'s since they are managed environments and don't have all the exception-safety problems that C++ has. Any performance concerns are also mitigated as servers tend to be focusing more on parallelism and throughput than minimum latency guarantees like the game clients. Even action game servers for shooters and the like can function quite well when written in C#, for example, since they're rarely pushing the hardware to its limits like FPS clients tend to do.
> 51 votes

# Answer
The old wisdom of Donald Knuth himself is:

> "We should forget about small inefficiencies, say about 97% of the time: premature optimization is the root of all evil."

Print this as a big poster and hang it out anywhere you do serious programming.

So even *if* try/catch is a little slower then I would use it by default:

* The code must be as readable and understandable as possible. You *might* write the code once but you *will* read it many more times for debugging this code, for debugging other code, for understanding, for improvement, ...
* Correctness over performance. Doing the if/else stuff *correctly* is not trivial. In your example it is done incorrectly, because not one error can be shown but multiple. You have to use cascaded if/then/else.
* Easier to use consistently: Try/catch embraces a style where you don't need to check for errors every line. On the other hand: *One* missing if/else and your code might wreck havoc. Of course only in unreproducible circumstances.

So the last point:

> I heard that the exceptions are a bit slower than ifs

I heard that about 15 years ago, haven't heard that from any credible sources recently. Compilers may have improved or whatever.

The main point is: Do no premature optimization. Do it only when you can prove by benchmark that the code at hand is the tight inner loop of some heavily used code *and* that switching style improves performance *considerably*. This is the 3% case.
> 13 votes

# Answer
There has already been a really great answer to this question but I would like to add some thoughts about code readability and error recovery in your particular case.

I believe your code could actually look like this:

```
m_fpsTextId = m_statistics->createText( "FPS: 0", 16, 20, 20, 1.0f, 1.0f, 1.0f );
m_cpuTextId = m_statistics->createText( "CPU: 0%", 16, 20, 40, 1.0f, 1.0f, 1.0f );
m_frameTimeTextId = m_statistics->createText( "Frame time: 0", 20, 20, 60, 1.0f, 1.0f, 1.0f );
m_mouseCoordTextId = m_statistics->createText( "Mouse: (0, 0)", 20, 20, 80, 1.0f, 1.0f, 1.0f );
m_cameraPosTextId = m_statistics->createText( "Camera pos: (0, 0, 0)", 40, 20, 100, 1.0f, 1.0f, 1.0f );
m_cameraRotTextId = m_statistics->createText( "Camera rot: (0, 0, 0)", 40, 20, 120, 1.0f, 1.0f, 1.0f );

```

No exceptions, no ifs. The error reporting can be done in `createText`. And `createText` can return a default texture ID that doesn’t require you to check the return value, so that the rest of the code works just as well.
> 10 votes

---
Tags: c++, software-engineering, exceptions
---


title: Rolling my own scene graph

text:
# Question
Title: Rolling my own scene graph
Hello Game Development SE!

I'm crawling my way through OpenGL with the hopes of creating a *simple* and very lightweight game engine. I view the project as a learning experience that might make a little money in the end, but will be fun either way.

So far I've used GLFW to gain some basic I/O, a window (with a oh so fancy F11 fullscreen key) and of course an OpenGL context. I've also used GLEW to expose the rest of the OpenGL extensions because I'm using Windows and I want to use all of OpenGL 3.0+.

Which brings me to the scene graph. In short, I'd like to roll my own. This decision came after looking at OSG and reading a few articles on how the concept of a scene graph has become twisted, bent and broken. One such article described how scene graphs have developed as...

> Then we added in all this extra stuff, like hanging ornaments on a Christmas tree, except that some of the ornaments are nice juicy steaks and some are whole live cows.

Following the analogy, I'd like the steak, the meat of what a scene graph should be, without having to strap on piles of extra code, or any whole cows.

So with that in mind, I find myself wondering exactly what a scene graph should be and how a simple scene graph should be implemented? Here's what I have so far...

A one parent, n-children tree or DAG which...

* Should keep track of game object transformations (position, rotation, scale)
* Should hold render states for optimizations
* Should provide a means of culling objects not within the view frustum

With the following properties...

* All nodes should be treated as renderable (even if they don't render) This means they...

+ Should all have cull(), state() and draw() methods (return 0 if non-visible)
    + cull() recursively calls cull() on all children, thus generating a complete cull mesh for the entire node, and all children. Another method, hasChanged() could allow so-called static meshes to not need to have their culling geometry computed each frame. This would work such that if any node in the sub-tree has changed then all geometry down to root is rebuilt.
* Render states will be held in a simple enumeration, each node will select from this enumeration an OpenGL state set that it requires and that state will be setup before draw() is called on that node. This allows for batching, all nodes of a given state set will be rendered together, then the next state set is setup and so on.
* No node should directly hold geometry/shader/texture data, instead nodes should point to shared objects (perhaps managed by some singleton object like a resource manager).
* Scene graphs should be able to reference other scene graphs (maybe using a proxy node) to allow situations like this, thus allowing complex multi-mesh models/objects to be copied around the scene graph without adding a ton of data.

I'm hoping to get some valuable feedback on my current design. Is it missing functionality? Is there a vastly better way/design pattern? Am I missing some larger concept that will be necessary to include in this design for a somewhat simple 3D game? Etc.

Thanks, -Cody

# Answer
> 15 votes
**The Concept**

Fundamentally, a scene graph is nothing more than a bi-directed acyclic graph which serves to represent a hierarchically-structured set of spatial relationships.

Engines in the wild tend to include other goodies into the scene graph, as noted. Whether you see that as the meat or the cow probably depends on your experience with engines and libraries out there.

**Keeping it Lightweight**

I favour the Unity3D style of having your scene graph node (which at it's heart is a topological rather than a spatial / topographical structure) inherently include spatial parameters and functionality. In my engine, my nodes are even lighter-weight than Unity3D, where they inherit a lot of unncessary junk members from superclasses / implemented interfaces: Here's what I have -- about as light as you can get:

* parent / child pointer members.
* pre-transform spatial parameter members: xyz position, pitch, yaw and roll.
* a transform matrix; the matrices in a hierarchical chain can very quickly & easily multiply out by walking recursively up/down the tree, giving you the hierarchical spatial transformations which are a scene graph's main feature;
* an `updateLocal()` method which updates *only this* node's transform matrices
* an `updateAll()` method which updates *this and all descendant* nodes' transform matrices

...I also include equations-of-motion logic and thus velocity / acceleration members (linear & angular) in my node class. You can forego that, and handle it in your main controller instead if you wish. But that is it -- very lightweight indeed. Remember, you could have these on thousands of entities. So as you've suggested, keep it light.

**Constructing Hierarchies**

What you say about a scene graph referencing other scene graphs... I'm waiting for the punchline? Of course they do. That's their main use. You can add any node to any other node, and transformations should automatically occur within the new transform's local space. All you're doing is changing a pointer, it's not like you're copying data around! By changing a pointer, you then have a deeper scene graph. If using Proxies makes things more efficient then by all means, but I've never seen the need.

**Avoid Render-related Logic**

Forget about rendering as you write your scene graph node class, or you will confound things for yourself. All that matters is that you have a data model -- whether it's the scene graph or not doesn't matter -- and that some renderer is going to inspect that data model and render objects in the world accordingly, whether it's in 1, 2, 3 or 7 dimensions. The point I am making is: Do not contaminate your scene graph with render logic. A scene graph is about topology and topography -- i.e. connectivity and spatial characteristics. These are the true state of the simulation and exist even in the absence of rendering (which can take any form under the sun from a first person view to a statistical graph to a textual description). Nodes don't point to rendering-related objects -- however the reverse may well be true. Also consider this: Not every scene graph node in your entire tree will be renderable. Many will be just containers. So why even allocate memory for a pointer-to-render-object? Even a pointer member that is never used, is still taking up memory. So reverse the pointer direction: Render-related instance references the data model (which might be, or include, your scene graph node), NOT vice versa. And if you want an easy way to do run through your list of controller yet get access to the related view, then use a dictionary / hashtable, which approaches O(1) read access time. That way there is no contamination, and your simulation logic doesn't care what renderers are in place, which makes your days and nights of coding *worlds* easier.

As for culling, refer back to the above. Area-of-interest culling is a simulation logic concept. That is, you don't process the world outside of this (usually boxed, circular or spherical) area. This takes place in the main controller / game loop, before rendering happens. On the other hand, frustum culling is *purely* render-related. So forget about culling right now. It has nothing to do with scene graphs, and by focusing on it you will be obscuring the true purpose of what you are trying to achieve.

**A Final Note...**

I get the strong feeling you are coming from a Flash (specifically AS3) background, given all the details about rendering included here. Yes, Flash Stage/DisplayObject paradigm includes all the render logic as part of the scenegraph. But Flash makes a lot of assumptions that you don't necessarily want to make. For a fully-fledged game engine, it is better not to mix the two, for reasons of performance, convenience and controlling code complexity through proper SoC.

---
Tags: opengl, 3d, scene-graph
---


title: Min/Max of two vectors?

text:
# Question
Title: Min/Max of two vectors?
This seems like a simple question, but i'm having trouble searching the internet for it.

In XNA, during a collision detecting method, I would determin the minimum of some vectors.

```
// Get the minimum top point
Vector2 minTopPoint1 = Vector2.Min(topLeft1, topRight1);
// Get the minimum bottom point
Vector2 minBottomPoint1 = Vector2.Min(bottomLeft1, bottomRight1);
// Get the minimum of both the top and bottom points.
Vector2 minPoint1 = Vector2.Min(minTopPoint1, minBottomPoint1);

```

I switched over to making a C++ engine, and am trying to replicate the collision formula (Honestly, it's confusing enough, I just need to replicate it from XNA) I made my own Vector2, and now I need to make this Min function.

So, what is the minimum or maximum of two vectors? Is it just the magnitude of the two vectors measured against eatchother? Is it the x and y values min/maxed somehow?

# Answer
> 6 votes
The code behind all the methods in Xna are available with reflection (I use red gate's reflector application but there are probably free ones). here's the code behind `Vector2.Min`

```
public static Vector2 Min(Vector2 value1, Vector2 value2)
{
    Vector2 vector;
    vector.X = (value1.X < value2.X) ? value1.X : value2.X;
    vector.Y = (value1.Y < value2.Y) ? value1.Y : value2.Y;
    return vector;
}

```

---
Tags: xna, c++, collision-detection, mathematics, vector
---


# Question
Title: simple escape algorithm: enemy escapes when hero approches
I need some clues on a "escape" algorithm. My scene a 2D rectangle (0,0,1000,1000)

I have enemy sprites on this scene. They are immobile until distance from hero \<100. If distance\<100, enemy tries to escape from here, so hero tries to chase it.

When distance\>100, enemy has escaped and becomes immobile again. The rule is of course that enemy cannot go outside the scene. And a enemy cannot overflow enemy bonus.

Any clues ? Regards

# Answer
> 4 votes
I suggest you took a look at steering behaviors, which can provide a lot of simple but very flexible ways to control how actors respond to other actors on the map.

In particular, on that link, **flee** and **evasion** are good behaviors to look into. Their goal is to cause an enemy to either move away from the position and direction of the player, or to even try to avoid the *future* position of the player (so they don't act like a certain idiot in Prometheus).

In order to ensure that the enemies do not get stuck in the corners of your map, you can also add in the **obstacle avoidance** behavior, which will push the enemies away from walls as they close in.

I'm also unsure of what you mean by "overflow the enemy bonus," but it sounds from your comments (please update your question to clarify!) that the bonus is an enemy the player is meant to catch, and by overflow possibly you mean that you don't want fleeing enemies to sit on top of that enemy. You can handle this with the **separation** steering behavior, which incidentally is a good one to know since it's a part of the common and quite popular flocking algorithm.

---
Tags: collision-detection, algorithm, movement
---


# Question
Title: Can't add rectangles into rectangle list
When I run this code, it gives me "Object reference not set to an instance of an object." here

```
clickableArea.Add(temp);

```

here is the entire class

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ScreenManager
{
class Menu
{
    public List<string> MenuItems;
    private List<Vector2> Position;
    private int iterator;
    public string InfoText { get; set; }
    public string Title { get; set; }
    public List<Rectangle> clickableArea;

    public int Iterator
    {
        get
        {
            return iterator;
        }
        set
        {
            iterator = value;
            if (iterator > MenuItems.Count - 1) iterator = MenuItems.Count - 1;
            if (iterator < 0) iterator = 0;
        }
    }

    public Menu()
    {
        Title = "Title";
        MenuItems = new List<string>();
        MenuItems.Add("New Game");
        MenuItems.Add("Options");
        MenuItems.Add("Exit Game");
        Iterator = 0;
        InfoText = string.Empty;
    }

    public int GetNumberOfOptions()
    {
        return MenuItems.Count;
    }

    public string GetItem(int index)
    {
        return MenuItems[index];
    }

    public void DrawMenu(SpriteBatch batch, int screenWidth, SpriteFont arial)
    {
        batch.Begin();

        Vector2 FontOrigin = arial.MeasureString(Title) / 2;

        batch.DrawString(arial, Title, new Vector2(screenWidth / 2 - arial.MeasureString(Title).X / 2, 20), Color.LightGreen, 0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);

        int yPos = 100;
        for (int i = 0; i < GetNumberOfOptions(); i++)
        {
            Rectangle temp;

            Color colour = Color.White;
            if (i == Iterator)
            {
                colour = Color.Gray;
            }

            batch.DrawString(arial, GetItem(i), new Vector2(screenWidth / 2 - arial.MeasureString(GetItem(i)).X / 2, yPos), colour);

            int reclengthX = (int)arial.MeasureString(MenuItems[i]).X;
            int reclengthY = (int)arial.MeasureString(MenuItems[i]).Y;

            int recposX = (int)(screenWidth / 2 - arial.MeasureString(MenuItems[i]).X / 2);

            temp = new Rectangle(reclengthX, reclengthY, recposX, yPos);

            clickableArea.Add(temp);

            yPos += 50;
        }
        batch.End();
    }

    public void DrawEndScreen(SpriteBatch batch, int screenWidth, SpriteFont arial)
    {
        batch.DrawString(arial, InfoText, new Vector2(screenWidth / 2 - arial.MeasureString(InfoText).X / 2, 300), Color.White);
        string prompt = "Press Enter to Continue";
        batch.DrawString(arial, prompt, new Vector2(screenWidth / 2 - arial.MeasureString(prompt).X / 2, 400), Color.White);
    }

}

}

```

# Answer
`clickableArea = new List<Rectangle>();`

...needs to come first. Your list is not yet instantiated, so you cannot add anything to it. All you have there at the moment is an empty reference.
> 3 votes

---
Tags: xna, xna-4.0
---


# Question
Title: Problem loading content in WinForms using XNA
I'm currently having trouble implementing loading content with the content pipeline into my WinForm application. I'm using the "WinForms Series 1: Graphics Device" sample provided by microsoft.

By simply creating a project, copying over the classes, creating a both content projects like in the sample worked all fine. But what I really want is use my XNA Game Project and it's Content Project to be used so I can run simple simulations inside my editor with it's code and graphics.

I thought it would be really simple since it appears to be the same structure except this time the games project has some code in it. But it seems like it doesn't, if I try to load some font or a sprite it gives me the classic red cross and a console entry telling me it can't load my asset. However, it's clearly on the Content directory in the build.

# Answer
The WinFormGraphicsDevice sample's classes uses the **Reach profile**, while my game project's sources get compiled for the HiDef profile, which are are obviously incompatible with each other.

The solution is to simply set your game's "**Game profile**" to "Reach" by **right-clicking** on the project in your VS and select **Properties**. Then go to the "XNA Game Studio" tab and click the "Use Reach to access a limited API set supported by Windows Phone, Xbox 360 and Windows".

**Remember!** as said Reach is a limited API and thus has its differences with the HiDef profile. More information about the differences can be found on Shawn Hargreaves Blog.
> 2 votes

# Answer
Open GraphicsDeviceService.cs file and edit the line below;

```
graphicsDevice = new Microsoft.Xna.Framework.Graphics.GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile.Reach, parameters);

```

as

```
graphicsDevice = new Microsoft.Xna.Framework.Graphics.GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile.HiDef, parameters);

```

and you'll be able to compile your assets within HiDef profile and still use in winforms-xna control.
> 2 votes

# Answer
**Edit**

I see you already found your answer, and that it was related to the assets being built in a different profile than your game. I thought you were having problems setting up the build process, so I'm leaving my answer anyway for future reference because it might apply to other people arriving on this question.

---

I've also had problems with this before but managed to get it working. The easiest way is really to start from the Microsoft sample, rename the project and namespace, and then import your own code into that project.

In order to do it manually, first you need to make sure you have *all three* necessary projects. I'll call them:

1. **Main** \- The main *Windows Forms Application*.
2. **Content** \- The *Empty Content Project* where you'll add all your assets.
3. **ContentLibrary** \- The empty *Windows Game Library* project used to build your assets.

And you need to make sure of the following:

* **ContentLibrary** must have a *Content Reference* to **Content**.
* **Main** must have a *Reference* to **ContentLibrary**. I also add a *Project Dependency* to it to guarantee the correct build order.

These are all done through the right-click context menu of the project tree.
> 1 votes

---
Tags: xna-4.0
---


title: Platform slope angle detection

text:
# Question
Title: Platform slope angle detection
> **Possible Duplicate:**
> How do I calculate the angle of the slope at a point on a 2D bitmap terrain?

I am planning to make a platform game with my own little engine and I need to know how to detect the angle of a slope. Any help is appreciated.

# Answer
You need to know 2 points to calculate a slope, in this example you have `p1` and `p2` as the two points. You use the Pythagorean theorem to calculate it.

```
// Delta X and Y
dx = p1.x - p2.x;
dy = p1.y - p2.y;

// Calculate the angle
slope = Math.atan2(dy,dx);

// Convert the angle to degrees
slope = slope * 180 / Math.PI;

```
> 1 votes

# Answer
You have two options, and it depends on how you plan to go about your game's collision detection.

If the collision data for your levels can be represented as line segments (or other shapes that can be broken down into line segments), you can use atan2 to find the angle between the endpoints of each line segment as suggested by Thomas.

If your game is tile-based, each tile would likely hold collision data that you've created manually. (E.g. tile type, angle of slope, etc.)
> 1 votes

---
Tags: flash, platform
---


title: Dynamic cubes for cube engine

text:
# Question
Title: Dynamic cubes for cube engine
I had an idea for a cube world (i'm writing in C#) that would make creating new types of cubes simple and dynamic. Here is how I imagine it:

1.Text file stores everything including block name, texture path, 'hp',light output, and simple scripting for events. Here's an example:

```
BlockName=<block name>

Texture=<Texture Image Path>
SeeThrough=<True/False>

Element=<Normal/Fire/Ice/Water/Light/Dark/Earth/Quintessence/Void>
State=<Solid/Liquid/Gas>

Inventory=<slots for inventory>

MaxHP=<0 = Infinite>
Armor=<armor level>

EnergyIn=<amount of energy required>
EnergyInDirection=<[Top/Bottom/Front/Back/Left/Right/All]
EnergyStorage=<amount of energy that can be stored>

EnergyOut=<amount of energy given>
EnergyOutDirection=<[Top/Bottom/Front/Back/Left/Right/All]

LightIntensity=<level of light output>
LightDirection=[Top/Bottom/Front/Back/Left/Right/All]

[Events]

onTouch{
     Damage.Give(10);
}

onClick{
}

onBreak{
}

onTimer(Time-in-ms){
}

switchOn{
}

switchOff{
}

```
1. An internal class would read all valid block files from the folder and create a list of block types, internally assigning ID numbers for each type of block. The specific world would store a dictionary of ID values and block names so that no matter how the block files are read, the saved world will always attribute the same ID number to the same block.
2. A look-ahead system in the CubeCaching service would identify all block types in existing chunks and in cached chunks and store only those cubes in memory. When a new chunk enters the cache, it will run through the types of blocks in its structure and the world class would then push all chunk blocktype amounts to the cache, where it would determine if a new type of block needed to be cached or not. Likewise, at that point the cubecache would also determine if all currently stored blocktypes still exist, and erase from memory any that no longer exist.

My goal is to chew as little memory as possible on block information and only make available the information that is necessary.

Here's my question: am I worrying about memory use too much? Is step 3 a good idea, or should I go ahead and just load and store all block types found without worrying about its memory use?

To clarify, i'm trying to figure out if it makes more sense to either load all block information and store it in a block-type list, or if I should include logic to only load the block information that exists?

Also to be clear: I am not storing all of this information for every single block. The information is only stored for the block TYPE, and would then be referenced for action based on an integer array in the chunk.

# Answer
It depends on how many block types you will have. But yea, no need to load a block type that you are not using.

I would not generate the ids inside your internal class, I would have the id stored in your block type file. This will make sure that a block type will always have the same id.

Also, I suggest you look at the Flyweight Pattern.
> 1 votes

---
Tags: c#, minecraft-modding, memory-efficiency
---


# Question
Title: Game Development at iOS, Android and PC with OpenGL ES
I'm beginning iOS apps development, and my aim is to make games to launch on App Store. But I want to know if it's possible to program a game on Xcode with OpenGL ES (C++ game logic), integrate it on iOS with ObjC, and with that same game code (OpenGL ES + C++), implement it for Android with Java and to PC.

I have great interest to publish the same game on App Store, Google Play and specially Steam, and intent to build my personal 2D engine/API when I have more experience on graphic programming.

Do you know where can I find material to learn this?

# Answer
You can use OpenGL ES 2.0 in C/C++ code in both platforms - Android and iOS. No need to use Java or Objective-C for calling OpenGL functions. As long as you don't use vendor/hardware specific OpenGL extensions your drawing code can stay exactly same for both platforms.

* iOS has OpenGL ES 2.0 in C++ support natively
* Android supports OpenGL ES 2.0 in C++ through NDK
* To utilize the same OpenGL ES 2.0 in C++ code in PC, give a try to ANGLE which translates OpenGL-ES calls to Direct3D.

For, C++ OpenGL Resources
> 4 votes

---
Tags: android, ios, opengl-es, cross-platform, pc
---


# Question
Title: problem with bullets shooting in FPS game
Please check out my game here: http://still-escarpment-3701.herokuapp.com

The problem is with shooting. The bullets keep on moving with the First person controller instead of moving from the same position and direction from which they were shot.

```
///////////////////code for shooting from fps///////////////////////////////////
         ///////////////////////////////////////////////////////////////////////////////////
        // the bullet to be thrown and shoot ......

        bulletTemplate = new J3D.Transform();
        bulletTemplate.geometry = J3D.Primitive.Sphere(0.5, 4, 4);
        bulletTemplate.renderer = J3D.BuiltinShaders.fetch("Normal2Color");

        // bullet holder bullets ko apni gun main rakhe ga ....
        bulletHolder = new J3D.Transform();

         engine.scene.add(bulletHolder);
        ////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////

document.onmousemove = onMouseMove;

        document.onmouseup = function(e) {
        var b = bulletTemplate.clone();

            var fz = first_person_controller.forward();
            b.direction = new v3();
            b.direction.fromArray(fz);

            b.position.fromArray(fz).mult(3);
            b.progress = 0;
            b.ttl = 300;

            b.animate = function() {
                b.position = b.direction.cp().mult(3 + b.progress);
                b.progress += 1;
                b.ttl--;

                if(b.ttl == 0) {
                    bulletHolder.remove(b);
                }
            }

            bulletHolder.add(b);

        };

```

The code below is being called in the game loop function's `draw()`.

```
bulletHolder.position.x =first_person_controller.position.x;
bulletHolder.position.y =first_person_controller.position.y;
bulletHolder.position.z =first_person_controller.position.z;

first_person_controller.rotation.y = mx;

for(var i = 0; i < bulletHolder.numChildren; i++) {
    bulletHolder.childAt(i).animate();
}

```

# Answer
*Assuming you are using J3D.js.*

Add your bullets to the `bulletHolder` at the position of the `first_person_controller`.

```
// Instead of:
b.position.fromArray(fz).mult(3);
// Do:
b.position.fromArray(first_person_controller.position);
// Or, if you want the bullet to start a few units in front of the player:
b.position = v3.add(first_person_controller.position, fz.mul(3));

```

And don't move your `bulletHolder` around in `draw()`. Remove these lines:

```
bulletHolder.position.x =first_person_controller.position.x;
bulletHolder.position.y =first_person_controller.position.y;
bulletHolder.position.z =first_person_controller.position.z;

```

You'll save yourself a lot of time if you keep each scene graph "holder" object like this at the world coordinate system origin.
> 0 votes

---
Tags: 3d, javascript, first-person-shooter
---


# Question
Title: Pathfinding with Less Desirable Squares that are still passable
I have been looking at different path-finding algorithms for my game. I have almost settled upon D\* Lite, but have a question. (perhaps I missed it in the documentation) - Are there any algorithms, D\* included, that allow for squares that are less desirable to pass over, but still possible, should there be no other way? I believe that I saw this in A\* but I believe that I need it dynamic, as I will be having objects placed and removed from the map.

UPDATE: Is it possible to have levels of undesirable squares? Eg. Some still arent desirable, but are better than really undesirable ones

# Answer
See Collaborative Diffusion. This approach is computationally cost-effective and implictly addresses the issue of dynamic obstruction.
> 2 votes

# Answer
I do not know the algorithm but wikipedia writes:

> The original D\* was introduced by Anthony Stentz in 1994. The name D\* comes from the term "Dynamic A\*", because the algorithm behaves like A\* except that the arc costs can change as the algorithm runs.

Isn't it enough to put a high cost on the squares that are less desirable to pass over ? This way if there are no cheap squares the expensive one are chosen.

Answer to your **"Update"**: This is just a question of cost, the higher the cost of a square is the less desirable the square is.

*disclaimer: my answers are based on my knowledge of A\*.*
> 2 votes

---
Tags: java
---


# Question
Title: How can I use multiple meshes per entity without breaking one component of a single type per entity?
We are just switching from a hierarchy based game engine to a component based game engine. My problem is that when I load a model which has a hierarchy of meshes, and the way I understand, is that an entity in a component based system can not have multiple components of the same type, but I need a "meshComponent" for each mesh in a model. So how could I solve this problem.

On this site they implemented a Component based game engine: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/

# Answer
> 13 votes
Your Position component could have a "parent/children" logic, where any Entity with a Position may have a parent and their position is relative to their parent. Instead of having several meshs on the same entity, you can make more than one entity, each with its own mesh and link them together. You can even make the children entities listen to their parent events (or whatever system you have for communication between entities) and react accordingly.

# Answer
> 8 votes
Your meshComponent may contain a list of meshes. I'm not sure how you are implementing your engine, but a system could easily iterate over all meshes and simply draw them.

# Answer
> 4 votes
I would create my mesh component with a list of mesh objects. Each mesh object has the mesh data along with an offset. When drawing, the drawing system takes the position from the position component, then draws each mesh in the mesh component at position + offset.

You can have multiple meshes inside your mesh component, while still saying with a single mesh component per entity.

# Answer
> 1 votes
**TLDR: By making the *component* consist of multiple meshes to begin with.**

I agree with Asakeron/Byte56/Laurent in that another level of indirection is needed between the mesh/material pairs, and the entity itself. Instead of looking at the GraphicsComponent as vertices and materials, think of it as a blob of pixels on the final raster - how it/they get there is an implementation detail and nothing more.

I thought about this a lot for my project and I think the optimal solution is to make the GraphicsComponent a much higher level component, encompassing much of the functionality of the traditional 'Model' object - because this functionality isn't optional! To render those polygons a lot more than just the buffer data and the shader is needed, such as:

* Position which you have mentioned
* Skinning/Animation data
* The Current Pass (e.g. if using two pass alpha)
* Shadow casting information (if you are doing it)
* Information on *how* and when to update the material
* Culling functionality

And thats just for 3D assets, without considering particle systems, billboards, etc. But all of it is pertinent only to the graphics/rendering code - it doesn't affect the physics, sound or scripting, so it makes sense it should sit in the Graphics/Rendering component.

I ended up with:

```
Model : Entity, IHasGraphicsComponent, IHasSkeleton, IHasAnimationStore     //This is the 'game object' - it is passed to the GraphicsController
    ModelComponent : GraphicsComponent                      //This is the actual graphics component, used by the GraphicsController in the context of the game object.
        ModelComponentPart : GraphicsComponent              //This is also a graphics component
            Mesh                                        //These are implementation details
            Material
        ModelComponentPart : GraphicsComponent
            Mesh
            Material
    Skeleton
    Animations

```

In this:

* Model is any game asset that has a graphics component.
* The ModelComponent is analogous to the traditional Model and in fact, is, for 3D assets. The GraphicsComponent controller (if you use the Model-View-Controller pattern) is responsible for figuring out what type of graphics asset it is and drawing it correctly (note that ModelComponent is a subclass of GraphicsComponent).

There were also a couple of compromises in mine for simplicity and backwards compatabilitys sake, such as each GraphicsComponent is also an Entity, and Entity stores Position data directly so its only calculated in one place, but the idea is the same: **GraphicsComponent handles what is needed to draw the item - all of what is needed - not just what comes from the modeller.**

---
Tags: architecture, component-based
---


# Question
Title: Dealing with edges on spherical heightmapped terrain
This is the problem I'm having: where the height has been applied to the vertex, the edge of each face has been pushed apart. I was wondering how I can best deal with this issue?

I read elsewhere that calculating the mean between the two adjacent edge vertices and applying to both will seal the gap, but wouldn't that cause some UV stretching?

Any advice would be great, Caius.

# Answer
It looks like when you apply the displacement map, you're pushing vertices out along the face normal of the underlying mesh? Instead of using the face normal, you should use the smooth vertex normal - which means you will need to interpolate across the face from its vertex normals. Smooth normals will match across edges automatically, so displacements along them should not generate cracks.

For more discussion of this issue, see the GDC talk My Tessellation Has Cracks (pdf).
> 2 votes

---
Tags: terrain, heightmap
---


title: Mixing Bump mapping and Detail mapping

text:
# Question
Title: Mixing Bump mapping and Detail mapping
I wonder if I create bump mapping for my terrain is it good to add detail mapping too? Does such mix improve realism or make it even worse (because there is "too much" of it)? If this improve realism, is it even worth doing that? Maybe it takes a lot of resources for small improvement?

# Answer
> 2 votes
If you plan to make good looking Terrain, then using Detail Maps will improve your scene a lot, so to answer your first question, yes.

Although only one question should be asked, I will go on. I don't think you should be worried about performance just yet, you will have to try out a few things to find out. Depending on the type of terrain, different games have different solutions that fit them that are balanced between use of resources and enhancing the scene.

Some games might do just fine using a few pretty bigger textures (probably not), some will look ugly and blurry unless they use a combination multiple blended textures, mip-maps, bump or normal maps, detail maps or even decals.

You can either test for yourself, or if you need more advice look at some more terrain tutorials. Wolfire games have a really good Youtube channel where they tell you what technique and why they used it.

---
Tags: terrain-rendering
---


# Question
Title: Sharing a texture resource from DX11 to DX9 to WPF, need to wait for DeviceContext.Flush() to finish
I'm following these instructions on TheCodeProject for rendering from DirectX to WPF using D3DImage.

The trouble is that now that I have no swap chain to call Present() on -- which according to the article shouldn't be a problem, but it definitely wasn't copying my back buffer.

An additional step that I have to take before I can copy the texture to WPF is to share it with a second D3D9Ex device, since D3DImage only works with DX9 (which is understandable, as WPF is built on DX9). To that end, I've modified some SlimDX code to work with DirectX 11.

I tried calling `DeviceContext.Flush()` (the Immediate one) at the end of each render cycle, which kind of works -- most of the time it'll show my renderings, but maybe for maybe 3 or 4 out of 60 frames each second, it'll draw my clear color instead. This makes sense -- Flush() is non-blocking; it doesn't wait for the GPU to do its thing the way `SwapChain.Present` does.

Any idea what the proper solution is?

I have a feeling it has something to do with my texture parameters for the back buffer, but I don't know.

# Answer
> 7 votes
```
First:
// Create a Query to be able to wait for the completion of the drawing:
D3D11_QUERY_DESC qd;
ZeroMemory(&qd, sizeof(qd));
qd.Query = D3D11_QUERY_EVENT;
hr = m_U->m_pd3dDevice->CreateQuery(&qd, &m_U->m_pEventQuery);
if( FAILED( hr ) )
    return hr;

```

---

```
After the flush put the query in the queue (there is no call like begin in this case):
// Draw!
m_U->m_pImmediateContext->DrawInstanced( 3* numTrianglesPerInstance, numInstances, 0, 0);
m_U->m_pImmediateContext->Flush();
m_U->m_pImmediateContext->End(m_U->m_pEventQuery);

```

---

```
Wait for the paint/flush/query to end:
// wait for drawing to come to an end:
while (S_FALSE == m_U->m_pImmediateContext->GetData(m_U->m_pEventQuery, NULL /*&GPUfinished*/, 0 /*sizeof(GPUfinished)*/, 0));

```

---

```
Tidy up later:
if( m_U->m_pEventQuery) m_U->m_pEventQuery->Release();

```

# Answer
> 4 votes
I think the proper way of syncronising the surfaces is using "Direct3D9Ex and DXGI Shared Surface Queue":

More info:

---
Tags: directx, slimdx, wpf
---


title: Font outline in OpenGL, FTGL

text:
# Question
Title: Font outline in OpenGL, FTGL
I'm using FTGL library to render fonts in my game, but I have completely no idea how to create an outline around text. Achieving a shadow could be easy, because I can simply do it like this:

(pseudo code)

```
font.render(Color::BLACK, position.x + 1, position.y + 1); // Shadow
font.render(Color::WHITE, position.x, position.y)          // Normal text

```

But how to create an outline? Unfortunately I haven't found any interesting solutions for it over internet which seemed to me a bit strange, because I thought it's quite popular problem.

Drawing outline with just a bigger font is not a right way, because as I found out, letters just don't match in this case:

So is there any simple way to create an outline for fonts? How do they do it in real games?

Thanks in advance for any answer

# Answer
**Flexible & Accurate: Filters**

Use a texel filter either on the texture on the CPU side, or if you are using programmable pipeline OpenGL, directly in the fragment shader.

The idea of a filter is simply that you run through a 2D loop to process every texel. If it is white, then you run through an inner 2D loop for each of its surrounding pixels in some radius, and adapt accordingly. This is also known as a box filter, though if you include the radius check, it is really a circular filter -- which avoids axis-al artifacting.

A faster way to do this is to precalculate the set of offsets from each central pixel that you check; this way, you needn't run a square root for every pixel surrounding a given pixel. You want to keep complexity down to \`O(texWidth\*texHeight) rather than O(texWidth\*texHeight\*filterRadius\*filterRadius), in other words.

**Easy: Multiple renders**

Another way to achieve the effect would be not to scale the text, but instead to render your red outline at each of eight (or more) directions, each slightly offset from the original in that direction:

```
 \|/
--+--
 /|\

```

By offsetting each of the red versions like this, you would get a fairly uniform outer edge around your original text. Bear in mind that when shifting diagonally, you should use the same vector magnitude as when you shift horizontally or vertically, rather than simply offsetting by the same x and y values (which leads to a approximatlely 1.4x further length -- basic trig).

**FYI**

This sort of effect is known as dilation, and is sometimes performed via Minkowski Summation, which is the vector-based (continuous) approach to the pixel-based (quantised) box filter I described above.
> 7 votes

# Answer
This feature is implemented directly in FTGL but it is only available in the `ExtrudeFont` class. You simply define an outset for the font:

```
font = new FTExtrudeFont(...);
font->FaceSize(80);
font->Depth(0);
font->Outset(0, 5);

```

Then you can use a different colour for the two render modes:

```
glColor3f(1.0, 1.0, 1.0); /* White inside */
font->Render("Hello", FTPoint(), FTPoint(), FTGL::RENDER_FRONT);
glColor3f(1.0, 0.0, 0.0); /* Red outline */
font->Render("Hello", FTPoint(), FTPoint(), FTGL::RENDER_SIDE);

```

Here is the result, with antialiasing toggled off and on:
> 6 votes

# Answer
Not related to FTGL but there's a great article from Valve about glyph rendering. It provides high quality rendering with small memory requirement, and effects like outlines or shadows can be simply implemented.
> 2 votes

---
Tags: c++, opengl, gui, fonts
---


# Question
Title: How should I set up UDK with Git and CruiseControl?
For a new project in UDK, I'd like to set up a Git repository for version control and a CruiseControl.NET-based continuous integration solution. The good news is that he first part seems easy enough and CruiseControl.NET can work off Git repositories. The bad news is that according to my searches, nobody has ever tried to do this.

Ideally, I'm looking for a step-by-step guide on how to set up such a development environment assuming more than one development computer, one central repository for the "master" branch, and one machine for building and packaging the binaries via CruiseControl.NET.

---

Related:

# Answer
In order to set up continuous integration (e.g. CruiseControl.NET) with a project, you need to be able to build the project from the command line.

From this page:

> Alternatively use the command line ***UDK make*** in the Binaries\Win32 directory.

So, it looks like you could set up your CruiseControl.NET server to execute the "UDK make" command and parse the output for success or failure (and package/archive the binaries, and any other post-processing).
> 2 votes

# Answer
It's possible to setup a continuous integration system with a batch script. See this build.bat file that is used for one of my own projects. The script is triggered by a post-commit hook in the master git repository.

```
call Binaries\Win32\UDK.com make -full -unattended -stripsource -nullrhi
call Binaries\Win32\UDK.com CookPackages -full -platform=PC -nullrhi
call Binaries\UnSetup.exe -GameCreateManifest
call Binaries\UnSetup.exe -BuildGameInstaller

```

This does a complete build and outputs to a zip file in the project root. It includes all the game files that would normally be extracted by the installer generated by UnrealFrontend.

Note that to install UDK on a server, the server has to have DirectX installed, and the UDK installer has to be run with the `-progressonly` argument. See this blog post for details.
> 0 votes

---
Tags: udk, version-control
---


# Question
Title: Game Development at iOS+Android Platform : Template Engine for UI
We have broken down our game development process to

* UI Programming
* Core Game Programming
* Particle Effect Programming

UI will be created by a group of programmers and those UI will be used at Core Game Programming.

For example, at web applications, there are several template engine available, for example `Smarty`.

* Is there any Template engine for UI for Game Development

# Answer
> 1 votes
I don't think there's such a thing as a "Game UI Tempalte-Only Engine". Really your best bet for getting IOS and Android dev in one go + out of the box UI widgets (such as text , buttons, etc) is Unity. I find it a lot easier than the run of the mill "Open GL Text libraries" and such:

http://docs.unity3d.com/Documentation/Components/gui-Basics.html

# Answer
> 0 votes
I honestly don't know what you mean by "Template engine for UI for Game Development" but I think CocosBuilder + cocos2d-x/cocos2d-JavaScript bindings is a free yet capable alternative for cross platform game GUI development. It is trivial to make menus, text, backgrounds, menu animations... etc with CocosBuilder.

---
Tags: android, xcode
---


title: Finding cubes in frustum

text:
# Question
Title: Finding cubes in frustum
Working with an infinite set of cubes, is there a way of detecting which cubes exist within a frustum?

Most frustum culling seems to work along the lines of running through all objects and seeing if they intersect - this is ok with a finite set of objects, or something like Octrees.

I'm currently finding all cubes within the frustum's bounding box - but that's far more than I really need.

I could then test these all against it, but I was wondering if I could skip a step.

# Answer
> 1 votes
With an infinite set of cubes, even the frustum has an infinite number of them. If someone has a better idea I am very interested to hear it. However, the octrees that you mention have worked wonderfully for me in the past. Basically any hierarchical structure will let you quickly eliminate huge number of objects. Then you can chose, depending on the complexity of the objects, whether you want to process all objects within an octtree node, or do you want to do finer detection which objects are within the frustum.

When you talk about cubes, I have a feeling you are talking about some kind of Minecraft like or voxel terrain. The frustum test is an important step, however do notice that in terrain case (and some others) you will have a great deal of objects (cubes) hidden "under" the visible ones. Finding a way to cull those efficiently will be of great importance. My point is that you should not spend every last CPU cycle frustum culling. If you can spend 20% of the time to frustum cull 80%, and then another 20% to cull 80% of hidden ones, it will be bigger improvement then to perform perfect frustum cull.

There are several ways of dealing with an infinite terrain.

1) If the terrain starts simple or small, but then grows, the octree should be balancing. This means that as you add more nodes into the tree, when a particular subtree grows beyond some threshold, one or more children should be pushed up or to the neighbouring tree. The idea is to try at all times have the (roughly) same number of subnodes in each subtree. This is a complex task, so you should definitely look for libraries rather then reinventing it yourself. It is worth noting that in most cases you do not need this complexity as it can be avoided using next method.

2) The easiest way to deal with seemingly "infinite" scene is to use two methods. A higher level structure that basically divides a terrain into a grid. Each grid location, chunk or area is a cube comrised of say 1000x1000x1000 of your cubes. Then use an octree to organize these 1024x1024x1024 area. Since you know the geometry of the large cube, it is easy to organize the octree. When rendering, you can use simple math to come up with several (10-is) large grid chunks that are in the frustum, and then process each one as a separate octree.

# Answer
> 0 votes
You're a bit confused. (Axis-aligned) Bounding box checks are there *to make things cheaper*.

They exist as a broadphase attempt to see whether a given voxel (volume or point) is *likely* to be within the frustum (containing volume) or not. In other words, they explicitly exist as an "early fail" mechanism. This sort of tiered elimination approach is common in graphics and collision detection, and in practice is computationally much more efficient than going straight for the final step -- which in your case is testing specifically to see whether each and every voxel in your world or zone is exactly inside or outside the frustum. It's costly to test every voxel in your world against exact frustum bounds, but it's much, much cheaper to test all of those against AABB bounds.

So don't skip a step. Listen to what the early warning system tells you. Let your axis-aligned bounding box serve its intended purpose -- cheap, early elimination. *Then* you do the expensive "on-which-side-of-each-of-6-arbitrarily-oriented-frustum-planes-is-this-voxel" tests *only* on that subset that you've found to lie within the bounding volume.

# Answer
> 0 votes
I'd go with recursive subdivision of a cuboid that is axis aligned and contains the frustum, which should be straightforward to construct based on the location of the corners of the frustum.

Firstly mark all small cubes as not intersecting the frustum.

Then test to see which case you have for the current cuboid, and apply the appropriate action:

1. Not intersecting the frustum - do nothing they are already marked correctly.
2. Completely inside the frustum - mark all small cubes within the big cube as inside the frustum.
3. It intersects the frustum - If it contains more than one cube then subdivide into two smaller cuboids (splitting on the longest axis), and apply the same test recursively to each one. If it can't be subdivided mark it as intersecting.

At the end of the process all cubes should be marked appropriately.

Note that instead of actually setting a flag on each small cube you may want to collect a list of the intersecting ones in some other way, or the mark them all as outside step will take forever.

---
Tags: voxels, frustum
---


title: Pygame - Change sprite collision Rect

text:
# Question
Title: Pygame - Change sprite collision Rect
I'm making a platformer in Pygame. One of the sprites I'm using is a flag, and I want to detect if the player collides with the flagpole (just like in Super Mario Bros). The problem is that the image is wider than the flagpole, because of the flag itself. I build the Rect for every sprite based on their image, just like so:

```
def initialize_rect(self, pos, correction = 0):
    self.rect = self.image.get_rect(topleft = pos)

```

Doing this, a collision is detected when the player touches the leftmost part of the image, which is a long way from the pole, so it looks terribly wrong.

I'm trying to figure out a way to change the collision box of the sprite, but nothing I try seems to work properly. I've tried the Rect.inflate() method, but that yielded no success. It shrinks the Rect from right to left, and if I then try to change the location of the Rect, the image changes its position too.

I could just make another sprite to detect collisions and somehow link it to the flag, but that would force me to change my design.

Is there a way to change the collision boxes of sprites directly in Pygame?

# Answer
I came up with a solution myself for this that did not have too big an impact in my design. When checking for collisions, instead of using the Rect associated with the sprite I use a new method called get\_hit\_box(), which calculates and returns a new Rect. So instead of

```
if player.rect.colliderect(flag.rect):

```

I have

```
if player.rect.colliderect(flag.get_hit_box()):

```

The method get\_hit\_box() returns a Rect which has the same center as the Rect of the image but different dimensions. This allows me to define the collision Rect I want, regardless of what the image is. To prevent having to change too much code, the get\_hit\_box() method in the parent class of all sprites just returns the unchanged Rect of the image, self.image.get\_rect(). Every sprite now has that method, and I redefine it only in those sprites where special collision behavior is needed.

Hope this helps someone else.
> 2 votes

---
Tags: collision-detection, python, pygame
---


# Question
Title: How can I produce heatmaps based off of player reported data?
For a really good example of what I'm talking about, see how the developer of Replica Island does it based off of Player deaths: http://www.youtube.com/watch?v=7-62tRHLcHk&feature=player\_embedded#t=37m

How can I easily produce heatmaps based off of data that I pass in?

Halo 3 is another good example of heatmap usage in game data reporting: http://www.bungie.net/Online/Heatmaps.aspx

# Answer
> 9 votes
Assuming you have the data set you want to plot already, and the map you want to plot it to, you can start by creating an intensity map: a grid of floating point values that is proportional in bounds to the final map (if the maps are small enough, 1:1 is probably fine). Initialize the entire array to 0.

Then you walk through each point you want to plot, map it into the coordinate space of the intensity map (which should be a simple scale operation, normally), and then plot a "blip" in the intensity map centered at that position.

A basic "blip" might just consist of increasing the intensity at the blip point plus some radius by a small amount. More complex implementations could read the existing intensity, and use a bigger falloff radius the more intense the blip point already is. You can experiment with the blip plotter to find an implementation you like the look of.

Once you have an intensity map you can use the intensity at each individual point as a 1D look-up into a color gradient, which will allow you to achieve the desired visual impact (this is how you can get the multi-colored results that are most commonly seen). You should do this color lookup as you transfer the intensity map to your final plot (rescaling, obviously, as necessary to account for size differences in the intensity map versus the final image).

This should be enough for a basic implementation, but there is room for optimization. For example, the intensity map will not be normalized, so you may need to renormalize it (probably slow) or keep track of the maximum intensity as you plot each blip, so that you can perform the renormalization of an individual intensity at the same time you are doing the recolorization. Additionally, it's possible that the distribution of your values is such that it is not memory-efficient to be storing the entire coordinate space of the map, and you may want to use an alternative solution that doesn't involve preallocating a large chunk of memory that will be mostly-empty.

If you have enough data beforehand to query the minimum and maximum intensities you expect to see in the data set you can avoid having to renormalize at all -- basically if you have some map between (X,Y,Z) to the number of "hits" of the plotted data that occurred at that point -- that's something you can build in to the system that *collects* the data which will help you optimize the mapping portion.

Since the intensity map is just, essentially, a grayscale image a really easy way to prototype this kind of system to use a bitmap for the intensity map and your drawing API of choice (for example, `System.Drawing` in C#) to plot partially-transparent circles to produce an intensity map. It doesn't look the best, but its functional.

# Answer
> 3 votes
**Echo Chamber is a free logging and visualization tool specifically made for games.**

> Visualize SQL based data files that contain information generated by a c++ application. Information can be log statements, function calls, screenshots, or parameter lists.
>
> View 2D and 3D game metrics such as death positions, which weapons are used most often, and memory usage over different parts of the level.

The logging system has a C++ interface (which is like a printf() that outputs to an SQL database, optionally across a network), but Echo Chamber should be able to visualize any SQL database (or it should be simple to create a database in the format Echo Chamber expects). The web site navigation is a bit obtuse; relevant Echo Chamber manual and associated Raknet logging function.

Unfortunately there is no screen shot of the heat maps in action, but Echo Chamber definitely supports heat maps:

# Answer
> 2 votes
For example, get coordinates on a designated event in the game. For example when player dies, you get coordinates in your scenegraph where player died.

So once you have values you need in your database, enumerate each coordinate how many times it appears in your list/database. You'll have a list something like:

* 15: 1,5
* 10: 6.15
* 3: 27,58

or whatever your values are. You'll have a frequency paired with coordinate like a key-\>value pair. You can then quantify key scale to a color. For example key of 0 is black and maximum key you have in your key-value list is red, and everything between is a gradient between black, mid point yellow and max point red. Quantify each result to a color and there you have it.

# Answer
> 2 votes
I'm not sure if you're looking for some sort of app or an algorithm for this one. I've actually had the pleasure of building custom heat map visualization software and it's a lot of fun.

A quick Google search revealed HeatMap API which could be an appropriate solution if you don't want to roll your own.

Maybe if you explain exactly what you're looking for (application-wise or programming-wise) we can help you better?

# Answer
> 0 votes
Something else you could do is just output the relevant data to a CSV file or something, then import it with statistical software (like Microsoft Excel, LibreOffice Calc, R, or GNUPlot) and have it spit out a graph. If you know a little bit of shell scripting (or Batch if you use Windows), you could probably automate the whole thing.

---
Tags: visualization
---


# Question
Title: Custom VertexDeclaration for Color, Texture, Normal
What is the best way to create a VertexDeclaration, that makes it able to render a Shape consisting of vertices and also be able to store a color for the shape (in case the texture can't be rendered - or in case we want color instead of a texture) - instead of having both a VertexPositionNormalTexture and a VertexPositionColor struct in the same class/struct.

I'm trying this approach:

```
public interface IShape : IVertexType { }

public struct ShapeFace
{
    public int Count { get; set; }
    public Color Color { get; set; }
    public Vector3 Position { get; set; }
    public Vector2 TextureCoordinates { get; set; }
    public Vector3 Normal { get; set; }
    public Vector3[] Vertices { get; set; }

    // Perhaps I need this?
    // public int[] Indexs { get; set; }
}

public struct Shape : IShape
{
    public ShapeFace[] Faces { get; set; }

    /* Need to implement VertexDeclaration here */
}

```

How do I implement the VertexDeclaration to understand what I want to do?

A shape contains faces, each face can have it's own texture OR color, normal mapping, texture coordinates, etc.

**Example** A cube has 6 faces, each face needs 2 triangles, each triangle has 3 points. 6 * 2 * 3 = 36 vertices. This way I can create a cube with 6 faces instead of 36 vertices, and render it in color or with a texture.

I really want to simplify it so that I can create some kind of struct that works this way.

# Answer
First, a handy link from Riemers XNA tutorial.

I did this, in what seems a similar goal to you, in the process of making my voxel-based game. The link above was extremely handy (as well as a few other articles on that site).

I solved this myself without an interface, instead creating my own direct descendant of IVertexType, called VertexPositionColorNormal, as I wanted colors as well as lighting. I will later be adding texture details, as well as using a normal map rather than a single face value. The code I used is here:

```
public struct VertexPositionColorNormal : IVertexType
{
    public Vector3 Position;
    public Color Color;
    public Vector3 Normal;

    public readonly static VertexDeclaration VertexDeclaration
        = new VertexDeclaration(
            new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
            new VertexElement(sizeof(float) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0),
            new VertexElement(sizeof(float) * 3 + 4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0)
            );

    public VertexPositionColorNormal(Vector3 pos, Color c, Vector3 n)
    {
        Position = pos;
        Color = c;
        Normal = n;
    }

    VertexDeclaration IVertexType.VertexDeclaration
    {
        get { return VertexDeclaration; }
    }
}

```

The important thing to note is that the VertexDeclaration has to give, very explicitly, the exact size in bytes of each vertex that you are going to send the hardware. If it doesn't, you'll get XNA whining over and over about how there is size mismatches or unexpected end of vertex data, or all sorts of other issues.

That is ALL the VertexType and VertexDeclaration should be doing, defining a vertex. Any management of a collection of vertices to make a box or any other model should be done in a different class that manages a collection of these Vertices in order to define a shape.

I keep the Struct for the VertexType/Declaration in my Chunk class file, but it could realistically go anywhere, it just makes sense for me to keep it here, as it is the highest level that deals directly with the vertices. Each Block contains an array of the 8 vertices that make it up, and the chunk class is responsible for combining these into single meshes in order to speed up rendering.

Another useful link is this one which details how (in OpenGL + C++, unfortunately) how to assemble the VertexBuffer with all these wonderful vertex types. Luckily for us, XNA handles a good portion of material in this regard, so it is very easy to maintain a list/array of the custom Vertices and send this data as a single buffer to the video card.
> 4 votes

---
Tags: xna, rendering
---


# Question
Title: How to execute AI in Cocos2d (replacing the Update method)
What is the best way to run AI in Cocos2d?

I already have my AI implementations. Normally I would execute AI in my game loop by checking how much time has elapsed since last AI execution and whether I can execute it in the current situation, then finally execute it.

From my understanding, Cocos2d removes the concept of the GameLoop and replaces it with Actions, which is great, but I'm not sure how best to employ them to take over in this AI execution. My current workaround is to create a ccSequence that 1) Executes AI, 2) Executes another ccSequence that does the same thing (essentially make an Action loop). What I don't like about this is that Actions all have to be timing needs to be precise in Actions... but I can work with that.

Another thing I don't like is that while this is good for AI... what about rendering actions. I can easily render the result of my Action for me, but what about the result of another AI's action? Such as another AI killed me. I have to wait for my Action Sequence to execute before I can check if anything happened to me, but what if my action was 10 seconds long... do I stand there before I realise I should be dead?

I'm thinking now that I could have multiple Action sequences set up. One for my AI. One for general updates to me. But before I go too far down this path, are Action Sequences really a good replacement for ye olde Update methods?

# Answer
I'm making an assumption that this is the Cocos2d-iphone branch.

Cocos2d allows you to schedule an update that happens every frame, just like a game loop. If you schedule this update on your scene or some base layer/node that always exists, you can carefully execute your AI actions first, then check/update your game state. I find this to be a really good place to manage AI and game states.

Alternatively, you can schedule updates at specific intervals instead of every frame, and you can also specify the priority of the update callback, so you can make sure that your update method runs before or after everything else during the current frame and before rendering.

See the documentation on scheduling updates/selectors.

Personally, I do all my game logic and AI in the scheduled updates, not actions (with a few exceptions, like changing status after an action completes). True, you can manage a collection of actions and stop them prematurely if necessary, but it does get a little painful sometimes and the smoothness of your game can suffer. For myself, I often use custom actions that perform relative movements/changes, instead of absolutes, so they could be combined and canceled without messing up the visuals.
> 2 votes

---
Tags: cocos2d
---


title: Applying Forces to Box2D Bodies

text:
# Question
Title: Applying Forces to Box2D Bodies
In full disclosure, I am VERY new to box2D let alone the Java version of it.

I have a box (here of type Hero) that I am trying to move. I did this by trying to apply a force as follows...

```
private void itterate() {
  Vec2 vec = hero.getPosition();
  hero.applyForce(new Vec2(0, 100), hero.getPosition());
  Vec2 vec2 = hero.getPosition();
  String test = "TEst";
}

```

The problem I am seeing is this doesn't change the poistion so vec == vec2. I also tried this....

```
private void itterate() {
  Vec2 vec = hero.getPosition();
  hero.applyForce(new Vec2(0, 100), hero.getWorldCenter());
  Vec2 vec2 = hero.getPosition();
  String test = "TEst";
}

```

Neither seemed to do what I am wanting. How can I "push" the object toward the bottom of the screen (Increase y)?

UPDATE I tried this as well...

```
private void itterate(int count) {
    Vec2 vec = hero.getPosition();
    Vec2 vec1 = hero.getLinearVelocity();

    int velocityIterations = 6;
    int positionIterations = 2;

    world.setContinuousPhysics(true);

    hero.applyForce(new Vec2(0, 10000), hero.getWorldCenter());
    world.step(timeStep, velocityIterations, positionIterations);
    Vec2 vec2 = hero.getPosition();
    String test = "TEst";
}

```

# Answer
What you have here is a misunderstanding of how physics engines work.

When a force is applied, it is merely set as some state indicating that the force was applied. The actual movement does not yet happen. The physics engine needs to integrate the physics with a time step, do collision checks, and then resolve those collisions (which can apply more impulses to the objects, causing them to move in other ways), and it does this a few to try to get the physics simulation to stabilize as best as possible.

Short version: physics engines don't apply forces immediately, they integrate them in whole when the simulation is advanced.

In Box2D, this is done with the Step method on the World object. (I'm assuming the class and methods names in jbox2d are identical or very similar to those in the main C++ Box2D.)

http://www.box2d.org/manual.html#\_Toc258082976
> 3 votes

# Answer
Using the previous answer here is what I came up with to get it to work (In Java)....

```
...
Vec2 gravity = new Vec2(0, 0f);
world = new World(gravity, true);
world.setContactListener(this);
groundBody = world.createBody(new BodyDef());
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC;
bodyDef.position.set(10f, 20f);
bodyDef.angle = 0;
test = world.createBody(bodyDef);
PolygonShape dynamicBox = new PolygonShape();
dynamicBox.setAsBox(5,  5);
FixtureDef fd = new FixtureDef();
fd.shape = dynamicBox;
fd.density = 20f;
fd.restitution = 0;
return test.createFixture(fd);

...
Inside Loop
...

float timeStep = 1.0f / 60.0f;
int velocityIterations = 6;
int positionIterations = 2;
test..setLinearVelocity(new Vec2(0, 100));
world.step(timeStep, velocityIterations, positionIterations);

```

This seemed to work well for me
> 0 votes

---
Tags: java, box2d, jbox2d
---


# Question
Title: What existing engines can do open-world games?
I'm looking for a 3D engine that would allow me to do open-world games. Basically: \- the game is looks like one big "map" of several km wide where you can walk from one point to another \- there would be a possibility to fly so I can't compute in advance how much of the terrain is visible (you can fly up and see a lot of things around you) \- should handle a day/night cycle (so I can't really pre-compute a general lightning since it would change)

I don't really need something that would be very performant because I don't plan on havings lots and lots of models etc (I'm not doing a AAA game), I'm mainly looking for a solution that is scalable, ie not something where I just load all the game assets in memory for the whole world and then not display most of it.

Do you know any engines (possibly free and open source) who can currently handle this? I tried looking at how to do this with Ogre but I don't think it's really possible

# Answer
> 1 votes
Every engine can do it, you just need to know how to do it. Make enough big map, with all features what you wanna to have. After that, code/script everything. Then you can add features to the game, new models,maps and etc.

---
Tags: open-world
---


# Question
Title: Why are some objects not rendering properly?
Here's a button I exported from Blender into a .x format:

Now here it is in the game with BasicEffect applied to everything:

And now with my custom shader:

And there's the problem. While the surrrounding environment is much brighter (I will get around to doing something about that btw), the button isn't. I'm using the vertex shader to do the lighting calculations. Sharp-eyed observers will notice that the texture is still slightly visible, but that's just ambient lighting. I have no specular lighting, just ambient + diffuse. So I guessed if lighting = ambient, then diffuse must be 0.

Here's my diffuse code:

```
float4 CombineDiffuseLights(float3 Normal, float3 Position3D)
{
    float4 lightColour = (0,0,0,0);
    for (int i = 0; i < NumberOfLights; i++)
    {
        float3 LightDirection = normalize(LightPosition[i] - Position3D);
        float DiffuseIntensity = saturate(dot(LightDirection, Normal));  //Where I suspect the problem lies
        lightColour += DiffuseIntensity * DiffuseColour * AttenuationPerLight(Position3D, LightPosition[i]);
    }
    lightColour.a = 1;
    return lightColour;
}

```

For the record:

* `Normal = mul(input.Normal, World);`
* `Position3D = mul(input.Position, World);`
* `DiffuseColour = (1,1,1,1);`
* Everything in the environment is using the same (vertex) shader
* All normals are the right way around (`CULLMODE = CCW;`)
* All LightPositions are going in with correct values

I've also noticed that if I manually set `DiffuseIntensity = 1;` this happens:

Besides the retina-searing brightness, it's proportionally the right shade compared to the environment, but there's no depth (duh, it's all 1). So why on earth is `DiffuseIntensity = saturate(dot(LightDirection, Normal));` giving me problems? It's a pretty standard way of finding a diffuse value isn't it? Is it doing something that I'm not aware of or is it a case of 'HLSL: You're doing it wrong!'? Normally I'd have some clue but I am totally stuck on this one.

# Answer
Found it. After days of debugging with PIX, looking through assembly code and reviewing all of my old code samples, it turned out that it wasn't anything in my diffuse code that was wrong, just one of the parameters I passed through. I said I was using:

```
Normal = mul(input.Normal, World);

```

but I was assuming that I hadn't non-uniformly scaled anything. As it turns out I should have used:

```
Normal = mul(input.Normal, WorldInverseTranspose);

```

It took me a couple of minutes to work it out, but I eventally found that I *was* using non-uniform scaling, and I was using it on the exact objects that were screwing up. At least now I know what a non-uniformly scaled object looks like without `Matrix.Inverse(Matrix.Transpose(objectWorldMatrix))` applied to it.

It's always the little things isn't it...
> 4 votes

---
Tags: xna, directx, shaders, hlsl
---


title: enemy shooting towards FPS

text:
# Question
Title: enemy shooting towards FPS
WELL first of all I want you to see my game (its deployed on heroku cloud) :

http://still-escarpment-3701.herokuapp.com

(It takes almost 10 sec to load so please wait for couple of sec)

I have successfully implemented fps shooting .but same logic are not working for enemy to fps shooting ..:(

THE PROBLEM IS THAT :

> Bullets gets saturated just after the shooting function is called ..i need enemy to shoot the bullets after some suitable delay just like its happening with fps shooting ...

```
       bulletTempEnemy = new J3D.Transform();

       bulletTempEnemy.geometry = J3D.Primitive.Sphere(0.5, 4, 4);
       bulletTempEnemy.renderer = J3D.BuiltinShaders.fetch("Normal2Color");

       bulletHolderEnemy = new J3D.Transform();

    engine.scene.add(bulletHolderEnemy);

function EnemyShooting(){

     bulletHolderEnemy.position.x =swat2.position.x;
     bulletHolderEnemy.position.y =swat2.position.y;
     bulletHolderEnemy.position.z =swat2.position.z;

    var b = bulletTempEnemy.clone();

var f =v3.sub(first_person_controller.position,swat2.position).norm();
b.direction = new v3();
b.direction=f;

    b.position.fromArray(f);
    b.progress = 0;
    b.ttl = 50;

    b.animate = function() {
    b.position = b.direction.cp().mult(1 + b.progress);
    b.progress += 1;
    b.ttl--;

                if(b.ttl == 0) {
                    bulletHolderEnemy.remove(b);
                                 }
            }

            bulletHolderEnemy.add(b);

```

}

and then code below was called in the game loop function draw()

```
 var zdis= Math.abs(Math.abs(Math.abs(swat2.position.z) -  Math.abs(first_person_controller.position.z)));
 var xdis= Math.abs(Math.abs(Math.abs(swat2.position.x) - Math.abs(first_person_controller.position.x)));

if(xdis < 80)
{
setInterval(EnemyShooting(), 90000);

}

   for(var i = 0; i < bulletHolderEnemy.numChildren; i++) {
   bulletHolderEnemy.childAt(i).animate();
  }

```

library used :J3D (https://github.com/drojdjou/J3D)

any help would be appreciated to resolve this saturation probLem of shooting bullets ....:|

# Answer
> 1 votes
Something that I have used for delays: Have a counter that increments by dt each frame. If it is above the required delay, don't continue to increment it. Then, if it is above the required delay AND the firing condition is true, have it fire the bullet and set the counter back to zero.

Pseudo-code here (in game loop):

```
if (firingcounter <= firingdelay){
    firingcounter += dt
}
if (firebulletcondition == true and firingcounter > firingdelay){
    firebullet()
    firingcounter = 0
}

```

# Answer
> -1 votes
thankx alot garan my problem is resolved :)

var firingdelay=1000;

var dt=50;

if (xdis \< 80 && firingcounter \> firingdelay){ EnemyShooting(); firingcounter = 0 }

if (firingcounter \<= firingdelay){ firingcounter += dt }

---
Tags: 3d, javascript, vector, first-person-shooter, webgl
---


# Question
Title: Are there game engines like Unity but for 2D?
I really like the convenience of unity3d. The ability to edit the level and see my results in real time are great. My problem is the idea I want to implement is 2d and uses 2d sprites. Scaling sprites appears to be a problem for me and all advice I receive says to purchase 150 dollars addons for unity. I love the physics components and the rapid prototyping but I figured that maybe unity is not the tool for the job for this 2d game.

Is there any 2d game engine like unity but for 2d games that would work on the PC and Android? Or is this something most people code themselves and make? To me the most important features of Unity3d were its ease to see what was edited and then have it apply instantly.

Thank you. Most searches seemed to give me frameworks and not a large engine suite.

# Answer
Flashpunk is a free library for Flex which provides a lot of functionality for 2D games. It doesn't have real time level editing, but there are tile based editors you can use to easily produce levels such as the Ogmo Editor.
> 5 votes

# Answer
How about Unity itself? I know Desktop Dungeons went down that route.

Setup your sprites as flat planes in X and Y, and then use Z as your depth (greater values of z will render behind lower ones).

Use an orthographic camera to eliminate true perspective, as you're better off faking this with paralax or whatever.

You may have to build your own collision detection / physics, but in 2D they're trivial.
> 2 votes

# Answer
Cocos2d Javascript bindings help you develop crossplatform mobile/browser games. Their vision is one code base accross mobile platforms and browsers. They say Mac support is there, while Windows Phone 8 support is on the way. Windows is not supported natively, though cocos2d-x project anounced that they support Windows 8 Metro. With cocos2d-html5 backend support, cocos2d-JS can be quite a portable platform.

Also there is a promising world/user interface editor called CocosBuilder. With a dedicated developer, who is employed by an industry giant, this tool has been under heavy development lately and progressing nicely.

Here is the wiki page for cocos2d-JS: https://github.com/cocos2d/cocos2d-iphone/wiki/cocos2d-and-JavaScript

Whatever you do, unless you have very good reasons and plenty of resources (work force, money, and time), don't write your own engine.
> 0 votes

---
Tags: unity, 2d, android
---


# Question
Title: How to create Button/Switch-Like Tile where you can step on it and change its value?
If the player steps on a Button-Tile when its true, it becomes false. If the player steps on a Button-Tile when it is false, it becomes true.

The problem is, when the player stands on (intersects) the Button-Tile, it will keep updating the condition. So, from true, it becomes false. Because its false and the player intersects it, it becomes true again. True-false-true-false and so on.

I use ElapsedGameTime to make the updating process slower, and the player can have a chance to change the Button to true or false.

However, it's not the solution I was looking for. Is there any other way to make it keep in False/True condition while the Player is standing on the Button tile?

# Answer
> 1 votes
You may just want another bool value to act as a mark saying whether or not the button can be pressed again.

One route could be to start with a bool we'll call:

```
bool buttonCanBePressed = true;

```

in the part of your code where you are checking if the player is on the button you could say:

```
if (playerIsOnButton && buttonCanBePressed)
{
buttonCanBePressed= false; //or buttonCanBePressed= !buttonCanBePressed;

// do button specific logic here
}

```

You would then have a check to see if player is still on the button

```
if (!playerIsOnButton)
buttonCanBePressed = true;

```

This way the player can only activate the button once until he has left the button then returns.

# Answer
> 0 votes
A more generic version of Dialock's answer which does not require extra state for every triggerable tile is to simply only check the button press state when the player's primary tile position has changed. Something like:

```
Vec2 old_tile_pos = player.GetTilePos();
player.UpdatePosition();
Vec2 tile_pos = player.GetTilePos();
if (tile_pos != old_tile_pos)
  ProcessTileEffect(tile_pos);

```

That all assumes that you have a clear definition of the primary tile the player is on. In games where the player moves one whole tile at a time, that's pretty obvious. In games where the player can smoothly move, it could just be the the under the player's center position.

If you want a smoothly moving player and want tiles to be triggered when the player is only partially standing on them, you'll need to extend the logic above to check multiple tile positions. Get the list of all tiles the player is colliding with, move the player, then get the new tile collision list. Any tile in the first but not in the second list is one the player stepped off of. Swap that around and you've got the tiles the player stepped onto.

---
Tags: xna, xna-4.0
---


# Question
Title: UDP + digital signature vs TCP vs other solutions to guarantee message authenticity
TCP guarantees message authenticity rather reliably using packet sequence number. Other option would be going with UDP and using digital signatures to make the message authentic. What could be my other options (basically are there any I missed)? Maybe there is some sort of framework which I could use which would allow me to plug into a game engine without writing all authentication logic(each time using tcp i would need that clients login into my system, with udp i would rely on client public signatures inside my db).

TY

# Answer
> 3 votes
TCP does not guarantee message authenticity, it only guarantees that all messages are received and that they are received in the order they were sent.

If you want to be sure the messages originate from the source you expected you can use Diffie-Hellman key exchange to establish a key. You can then use that key to encrypt all further messages using AES or another encryption algorithm. When you implement these algorithms correctly they are secure. (That is the only known way to crack it is by brute-forcing the key). Anyway implementing these algorithms correctly is very hard so it would be best if you would try to find a library that has already implemented these algorithms.

A popular networking library for games is LIDGREN which includes AES encryption, however I'm not sure if it has also implemented D-H key exchange but it should be easy to add this on top.

---
Tags: authentication
---


# Question
Title: OpenGL ES 2.0 - How to batch draw particles that have unique translations, rotations, scales, and alphas?
I've combined all of my vertex data for many particles into a single array. How would I batch draw all of those particles in a manner that preserves their unique translations?

Any code examples would be greatly appreciated.

# Answer
> I've combined all of my vertex data for many particles into a single array.

How did you do this exactly? Details?

You could "secretly contain" the transformation matrix for each particle's vertex in 4 texture coordinates.

So, you'd have a vertex format like:

```
vec4 position
vec4 color
vec4 matTexcoord0
vec4 matTexcoord1
vec4 matTexcoord2
vec4 matTexcoord3
vec4 texturingTexcoord

```

Little does the shader know that `matTexcoord0-matTexcoord3` are not actually texture coordinates. No. They are a *transformation matrix in disguise*.

Da da da dah!!

Effectively a `mat4x4` is passed using 4 `vec4`'s. So you apply the transformation matrix contained in `matTexcoord0-3` in the shader as a kind of `world` transform. If you use point sprites this can be very efficient.
> 2 votes

# Answer
Perform the translation in your vertex shader. You must either have a parallel array which contains the translations for each vertex, or store the translations in a texture which you lookup in using some attribute of each particle.

(Note: Answering as if for WebGL; I have no actual GL ES experience.)
> 0 votes

# Answer
Each particle needs it's own transformation matrix, so a parallel array or third element to the array of a unique tranform matrix is needed. Then before you draw a particle, multiply the current Modelview matrix by the particle's transform matrix.
> 0 votes

---
Tags: shaders, opengl-es, opengl-es2, particles, vertex-arrays
---