title: Is there any Shaders Directory?

text:
# Question
Title: Is there any Shaders Directory?
There are many tutorials to learn GLSL, Cg, HLSL... with classical samples as bump mapping, toon-shading...

But is there a shaders directory?

* a website where i can share my shaders
* search shader by name, description and implementation

# Answer
Maybe NVIDIA Shader library can help you, but it's not large shader library.
> 3 votes

# Answer
While not a website, the ShaderX series of books (7 at present) is a good reference about common shader effects.

Some are available for free download at http://tog.acm.org/resources/shaderx/
> 2 votes

# Answer
Yup; there's definitely not enough of these! In addition to the above, the samples that come with RenderMonkey have definitely been helpful for me.
> 2 votes

# Answer
There are are few online locations that allow you to visualize on the fly the shader you're typing ; they often based on WebGL.
One of them is called the "Shader Toy" (http://www.iquilezles.org/apps/shadertoy/).
An other one is called the "GLSL Sandbox" (http://glsl.heroku.com/), and it seems that you can save and share your creations there (I am not 100% sure however).
> 0 votes

---
Tags: web, shaders
---


# Question
Title: How to make a gui button follow a path after a touch?
I would like a button in my gui menu to follow a specific path if we selected it, I am wondering how I could do it: if we touch the button, then it can only move on the specific path, it is an arc such as this path :

Would you know how to achieve this? I am using Unity, but I think the theory should be the same for other software/language ?

Thanks for your help

\__

EDIT:

here is the code for the bezier curve in unity : Where should I put the script?

```
using UnityEngine;
using System.Collections;

public class DrawBezierHandle extends Editor {

    public Transform startT;
    public Transform endT;

    function Start(){
        startT = GameObject.Find("start").GetComponent("Transform") as Transform;
        endT = GameObject.Find("end").GetComponent("Transform") as Transform;
    }

    function OnSceneGUI() {

        var width : float = HandleUtility.GetHandleSize(Vector3.zero) * 0.1;
        Handles.DrawBezier(startT.position,
                        endT.position,
                        startT.position * 5 * Vector.up,
                        endT.position * 5 * Vector.up,
                        Color.red,
                        null,
                        width);
    }
}

```

# Answer
Well, first of all you need a way to descrive such path.

I would use some spline curves like Bezier curves or Hermite Splines to describe the path, and let the button follow that path once pressed. Unfortunately these curves are not available as is, you need to implement them. If you are interested here you can find 2 nice Herman Tulleken's articles(fundamentals and some algorithms), that contains a basic bezier spline implementation for Unity3D too:

If you want to go another way you can define some points the button should pass through and interpolate position (and eventually orientation) of the object while updating its position. You can interpolate `Vector3` position using Lerp or Slerp methods.

---

EDIT

If you attach your script you should be able to see the Bezier curve drawn. (Pay attention that your control and tangent points are coincident, so it will be always a straight line). Unity just let you draw such parametric curves, you have to evaluate it on your own.

The article I linked to you gives you the code. For example:

```
Vector3 CalculateBezierPoint(float t,
  Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3)
{
  float u = 1 – t;
  float tt = t*t;
  float uu = u*u;
  float uuu = uu * u;
  float ttt = tt * t;

  Vector3 p = uuu * p0; //first term
  p += 3 * uu * t * p1; //second term
  p += 3 * u * tt * p2; //third term
  p += ttt * p3; //fourth term

  return p;
}

```

You can move a GameObject along the curve you can varying `t` parameter inside your Update function. For example:

```
float time = 0f;
void Update()
{

   if (time < 1f)
   {
     time += Time.deltaTime;

     transform .position = CalculateBezierPoint(time,startP, startT, endT, endP );

   }
}

```

> how could I clamp the coordinates so that the button only slide on the curve, exactly where the touch is (without any delay)? I thought about creating a list of 50 Vector2, and compare the x/y with the touch pos, but it might be too heavy... Would you have any idea about that?

Well, the curve parameter domain is \[0,1\]. You could for example start recording a gesture when a touch is detected near the start control point. Supposing you gesture length is \[0,N\], what you can to is to map the gesture interval domain to the curve one.
> 5 votes

# Answer
Just for what concern GUI you can use UIToolkit. It's free and opensource and already have the methods that you need for doing simple gui movement (you can call the delegate with the Action onTouchUpInside). There are also a demo scene that reproduce what you want to do, and with this library you can make all your GUI's element with a single draw call (pretty useful if you play to make a game runnable also in mobile).

I know that there are also excellent substitutes of UIToolkit (search in Assets Store for more info), but i've experience just with that for now :)
> 1 votes

---
Tags: unity, path-finding, gui, curves, beziers
---


title: How to make bird to fly using box2d

text:
# Question
Title: How to make bird to fly using box2d
I am new to Box2D, I have set gravity to 10. How to make an object fly in space even though the gravity is 10. What are the properties I need to set to make object fly? Is there any different approach?

# Answer
> 4 votes
It sounds like you essentially want to have specific objects ignore gravity, is that correct? Since gravity is a property of the world object, it looks like the way to do this is to either

1. Disable gravity entirely, and then manually apply gravity to every object you want to have it (ignoring the objects you don't want to be affected by gravity), or
2. Apply a force that counteracts the force of gravity every frame to the objects you want to appear to be unaffected by gravity.

You also may be able to use a `b2_kinematicBody` instead of `b2_dynamicBody` if you don't need your "flying" objects to respond to any forces whatsoever. This may or may not be appropriate for your needs.

# Answer
> 1 votes
In general, the best way is to make your object dynamic and add a force to it in every frame, to the left or to the right. What I mean is that you can determine your path and calculate the force by considering the weight and gravity, which is why you apply the force to the bird. I think it's the best way, and also the most realistic.

---
Tags: physics, box2d, cocos2d-iphone
---


title: Change opacity of a texture in XNA 4.0

text:
# Question
Title: Change opacity of a texture in XNA 4.0
I have created a terrain using VertexPositionNormalTexture in XNA 4.0, but now I would like to allow the user changing the opacity of the terrain (from 0%, totally opaque, to 100%, totally transparent), so that user can see through it. Is there a simple way to do that?

I would also like to know how to do that if I use VertexPositionColor instead of VertexPositionNormalTexture (i.e., creating a colored terrain)

Thank you very much in advance.

# Answer
Changing the colours of a vertex buffer is relatively expensive. You'd have to use something like `VertexPositionColor` and then modify every vertex every time you want to change transparency!

It would be **much** easier, and faster, to add transparency using a shader (pixel or vertex). Fortunately `BasicEffect` does exactly what you need - it even has an appropriate `Alpha` member. Here's the code:

```
GraphicsDevice.BlendState = BlendState.AlphaBlend;
basicEffect.Alpha = 0.5f; // <- however opaque you want it

```

The other built-in effects also have `Alpha` members.

If you're writing your own shaders - just pass in a colour (with appropriate transparency) as a shader parameter. Then somewhere in your vertex or pixel shader, multiply by that colour before output.
> 4 votes

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


# Question
Title: I'm having trouble with collision detection in XNA
I've written a tile editor and game in XNA, with velocities and gravity, and am having trouble with some of my collision detection things. It works okay, but seems to glitch between just inside and outside the tile the player is on. Here's my collision detection function and the other functions it uses:

```
void SolveCollisions(List<Tile> tiles, Vector2 screensize)
    {
        if (position.X < 0)
        {
            position.X = 0;
        }
        if (position.X + 32 > screensize.X)
        {
            position.X = screensize.X - 32;
        }
        if (position.Y < 0)
        {
            position.Y = 0;
        }
        if (position.Y + 32 > screensize.Y)
        {
            position.Y = screensize.Y - 32;
        }

        foreach (Tile t in tiles)
        {
            if (absTilePos(position.X) == absTilePos(t.position.X))
            {
                if (intersect(position.Y, t.position.Y, 32, 32))
                {
                    if (position.Y > 0)
                    {
                        velocity.Y = 0;
                        position.Y = tilePos(position.Y);
                    }

                    if (position.Y < 0)
                    {
                        velocity.Y = 0;
                        position.Y = tilePos(position.Y) + 32;
                    }
                }
            }

            if (absTilePos(position.Y) == absTilePos(t.position.Y))
            {
                if (intersect(position.X, t.position.X, 32, 32))
                {
                    if (position.X > 0)
                    {
                        velocity.X = 0;
                        position.X = tilePos(position.X);
                    }
                    if (position.X < 0)
                    {
                        velocity.X = 0;
                        position.X = tilePos(position.X) + 32;
                    }
                }
            }
        }
    }

    bool intersect(float p1, float p2, float s1, float s2)
    {
        if (p1 < p2 && p1 + s1 > p2)
        {
            return true;
        }
        if (p2 < p1 && p2 + s2 > p1)
        {
            return true;
        }

        return false;
    }

    float tilePos(float f)
    {
        int i = (int)f;
        i /= 32;
        i *= 32;
        return (float)i;
    }

    float absTilePos(float f)
    {
        int i = (int)f;
        i /= 32;
        return (float)i;
    }

```

The player also glitches into blocks on it's top and right ( http://puu.sh/2cVQf ) when it hits them instead of bouncing off them - it just goes straight into them.

Does anyone know how to remedy this? Thanks!

# Answer
Here's how I would solve this problem. The code written below is written out of memory, not tested - you will obviously have to make it legal C# code and adapt it to your project.

```
class AABB // make your game objects have an AABB
{
    Vector2 position, size; // position is the top-left position
    float getLeft() { return position.X; }
    float getRight() { return position.X + size.X; }
    float getTop() { return position.Y; }
    float getBottom() { return position.Y + size.Y; }

    bool isIntersecting(AABB other)
    {
        return getRight() > other.getLeft() &&
        getLeft() < other.getRight() &&
        (getBottom() > other.getTop() &&
        getTop() < other.getBottom());
    }
}

void SolveCollisions(AABB aabb, List<Tile> tiles, Vector2 screensize)
{
    if (aabb.getLeft() < 0) aabb.position.X = 0;
    if (aabb.getRight() > screensize.X) aabb.position.X = screensize.X - aabb.size.X;
    if (aabb.getTop() < 0) aabb.position.Y = 0;
    if (aabb.getBottom() > screensize.Y) aabb.position.Y = screensize.Y - aabb.size.Y;

    foreach (Tile t in tiles)
    {
        AABB other = t.getAABB(); // getAABB() would return the tile's axis aligned bounding box

        if (!aabb.isIntersecting(other)) continue; // no collision with this tile, check the next one

        // let's find the shortest distance to "push out" the object and resolve collision

        float left = other.getLeft() - aabb.getRight();
        float right = other.getRight() - aabb.getLeft();
        float minXPush = Math.Abs(left) < Math.Abs(right) ? left : right;

        float top = other.getTop() - aabb.getBottom();
        float bottom = other.getBottom() - aabb.getTop();
        float minYPush = Math.Abs(top) < Math.Abs(bottom) ? top : bottom;

        if(Math.Abs(minXPush) < Math.Abs(minYPush)) // x pushing distance is minor than y
        {
            aabb.position.X += minXPush;
        }
        else
        {
            aabb.position.Y += minYPush;
        }

        // collision should be resolved now
    }
}

```

This solution is the most basic one, and has many problems. I wrote some articles about 2D collision I advise you to read:

http://veegamedev.wordpress.com/2012/08/14/getting-2d-collisions-right-part-one/ http://veegamedev.wordpress.com/2012/08/14/getting-2d-collisions-right-part-two/
> 0 votes

---
Tags: xna, c#, collision-detection
---


# Question
Title: Why don't C++ Game Developers use the boost library?
So if you spend any time viewing / answering questions over on Stack Overflow under the C++ tag, you will quickly notice that just about *everybody* uses the boost library; some would even say that if you aren't using it, you're not writing "real' C++ (I disagree, but that's not the point).

But then there is the game industry, which is well known for using C++ and *not* using boost. I can't help but wonder why that is. I don't care to use boost because I write games (now) as a hobby, and part of that hobby is implementing what I need when I am able to and using off-the-shelf libraries when I can't. But that is just me.

Why don't game developers, in general, use the boost library? Is it performance or memory concerns? Style? Something Else?

I was about to ask this on stack overflow, but I figured the question is better asked here.

EDIT :

I realize I can't speak for all game programmers and I haven't seen all game projects, so I can't say game developers *never* use boost; this is simply my experience.

Allow me to edit my question to also ask, if you do use boost, why did you choose to use it?

# Answer
> 43 votes
Some developers do, some developers don't (in games and elsewhere). It depends on what the needs/requirements of those developers are, and what existing technology they have to leverage.

C++'s standard library is often given the same treatment, and people often wonder the same thing you are wondering about *it*, too. Most of the reasons are similar, for example:

* A developer may already have an in-house library of functionality that provides the same services that the standard library or Boost provides. Such in-house libraries were often written long ago, when implementation support for the standard library was weak and Boost was basically non-existent, so they more-or-less *had* to be written. In this scenario, it's usually not really worth transitioning away from the in-house functionality -- it would be a major porting effort that would destabilize a lot of code, and provide almost no benefit.
* A developer may be working on platforms where compiler support for the advanced C++ techniques leveraged by Boost are not well supported, such that the Boost code doesn't compile at all or performs quite poorly. This applies to the standard library as well, although much less so these days.
* Boost and the language's standard library are general purpose, and while that is fine and good for most applications, sometimes a developer has specific needs that can be better addressed by more specialized containers.

I think the above are two reasonable reasons, although there are certainly others. You have to be careful though because many reasons for avoiding Boost, the standard libraries, or whatever boil down to "not invented here" syndrome, which *can* be an indication that the reason isn't very well grounded in practical realities.

Also remember that the needs of a large-ish studio are usually very different from the needs of an individual developer. For example, an individual developer probably has less legacy code floating around to maintain and so perhaps porting from a home-grown version of the Boost or standard library functionality will not be as big of a time sink and will save that developer from having to maintain that code as extensively in the future -- thus invalidating my first bullet point.

In the end, it is all about evaluating your requirements and time investiture against your desired goal and determining which option meets your needs the best. Developers who aren't using Boost or the standard library have usually done so and reached that conclusion -- perhaps you will too, and perhaps not.

# Answer
> 32 votes
**Edit Coming Back to This Question After A Few Years**
Having continued to use more and more boost libraries, I thought I'd update this question to give a solid case for why you should use boost when the description of the product matches your desired functionality. This will convince even nay-sayers. Download openSSL, try to make a client and server application with it. Now try and make that work on every platform. Then, download and use boost::asio::ssl to make the same application. If you're not convinced that boost is the right place to look for clean, well optimized, peer reviewed, cross-platform code, this simple exercise will convert you.

**Tl;dr version:**

In my opinion, you don't see a ton of indie or small to mid size development firms using boost because it's a massive and powerful wild beast that isn't easy to tame and you're basically on your own when trying to learn how to use it. The documentation is lacking in a few ways (see long version) and "the community" around the project either seems to be missing, scattered or inactive (compared to other projects).

**Very Long Winded Version:**
I realize there is already an accepted answer but as someone who actually uses boost in nearly every project I do, I thought I'd post an answer.

I remember when I first got poking around in boost and honestly I had no frigging idea what was happening. Boost is not very well documented at all. People might disagree with me on that I'm sure because there are tons of snippets of example code and a comments and such, but it is all very cold and vague as well as difficult to navigate.

Also it seems difficult to find any place where you feel like you've found "the community" around the project. In fact the community seems non-existent, or nomadic. Unfortunately even their mailing list has been trolled by so many leech sites that you can go down this rabbit hole always looping back around to where you started.

These two factors make learning to use boost libraries a rather daunting task. Even if the technicalities of using boost aren't excessively complex, it is a massive set of libraries and staring it down when all you're armed with is a few code snippets and scattered pieces of the mailing list from the darkest corners of the internet... well you get the idea.

I got into tinkering with boost around version 1.45 and it's only now in version 1.52/1.53 that I feel comfortable enough to use it in production. There are so many things to get used to and remember, even simple things like how you've configured boost and remembering that configuration, because how the libraries are built and function can vary wildly based on your preferences at compile time due to how customizable things are.

*However*, **make no mistake**, once you can wield boost, you've gained a powerful weapon for rapidly building solid, cross-platform programs. Just take `boost::asio` for example. You can write an immensely powerful, scalable and rock solid cross platform asynchronous web server in just a couple hundred lines. I've written multiple clients, servers, proxies etc over the years with just a few hundred lines of code each that have yet to fail me, and can port them from platform to platform in minutes.

As others have pointed out, larger companies are usually stuck with legacy stuff or like to roll their own which I completely understand. There is also this really silly thing I've heard of and encountered where dev leads and or project managers forbid using boost because it's "too big". My guess is that they believe that boost is 1 single library or they've never heard of BCP.

**As for WHY I choose to use boost**

I'd say I use it because as you imply in your question, it's "the" C++ library. Boost is viewed in the C++ world as the swiss army knife of things that eventually you're going to need to use. So the idea is that if there is a need, there should be a highly performant, and portable version of it in boost. Big companies contribute to boost, very educated people with impressive resumes contribute and maintain it, and when a new standard of C++ is being developed, people usually look to boost to see what parts of it should become ISO standardized C++.

So if I need to add some functionality that there is probably an existing library for, the first place I'll look is boost just because I'm pretty safe in betting that it's pretty well optimized, portable, it will be supported and maintained for a very long time and bugs will be found and dealt with. In the open source world those qualities can be very difficult to come by.

# Answer
> 22 votes
We used a bit of Boost back at our old workplace. The main reasons for mostly avoiding it and limiting its use were:

* compile times - some of it is very slow to compile, and you end up being reluctant to have boost #includes in any of your headers
* complexity - it's not well known by most game developers and so makes for unreadable code
* performance - some of the concepts perform slowly by default, eg. shared\_ptr

# Answer
> 16 votes
Same thing is (was?) being said for the "more standard" STL. This article talks about EASTL, an in-house rewrite of (parts of) STL by Electronic Arts to accomodate the needs of game development which are rather different than those of "more generic" application development.

So, maybe, someone somewhere is re-writing (parts of) *boost* to accomodate their needs in game development!

# Answer
> 7 votes
I hang out at StackOverflow and don't use boost. I will add my reason, because it is one not mentioned yet.

Boost has many great ideas, really. I like to look at what they have done and try out new things and ideas. They are great, because it is breeding ground for many C++ improvements.

But the boost is a very unwieldy beast for many reasons. One of the reason is that they need (want to) to be compatible on virtually any compiler with any quirks. As a result they need to employ many tricks, such as MPL to pull it off. For example (a long time ago) I wanted to use their shared\_ptr, getting it to run meant I need the sources and libraries of what felt like 90% of boost. I ended up writing my own; 50 readable lines of code. (My requirements where stricter, like no weak\_ptr or thread safety.)

Often you need a really small subset of boost, but integrating the entirety of boost is just not worth the hassle.

**Edit**:

Just to make is clear, since it appears not to have come over clearly (i.e. downvote). I use **do** use third party libraries. But in most cases, all things being equal, integrating a third party library or boost, the other third party library is quicker and cleaner. The remaining is done in "2h" finger exercise. I do take a very hard look in the build it or buy question.

# Answer
> 6 votes
Who says they don't use boost? I've known one or two C++ engines that have used boost. I've never directly worked with them; but, that's mostly 'cause my experience lies in Unreal.

As for reasons I've encountered for not using boost, and these are subjective:

* We like rolling our own data structures specific to the platforms we're deploying to
* We like limiting the amount of non-internally developed code we have to use in our projects, especially when that external code is reliant on other externally developed libraries.

It basically boils down to: a general solution isn't always the "right fit."

I'm sure someone who's actually worked with the library could comment better.

# Answer
> 4 votes
In our case (not games), we have a great reason for not using boost (nor std): We have a lot of code that dates back a decade. According to the seniors, std and boost were either incomplete, full of bugs or just too slow for the high-performance things we require. So some base classes were implemented, using the same concepts (such as iterators) and often optimized for our algorithms. Nowadays, all three libraries (ours, std and boost) are very similar.

But do we want to port over all our code? Not really. I assume many other companies face the same dilemma. Either rewrite a lot of tested and working code or not use std/boost.

# Answer
> 2 votes
I don't personally use boost or any other general purpose code when making games, because games are not generally general purpose. The kind of code you might need to implement a game is usually specific to game development, not always but like 98% (random figure) of the time. You can tack on that last few bits of code from boost or some other lib, but its probably better just to write out those little part you need here and there.

On a side note, I think that it is rather fun to write out your own code in c++, which is why I have never use boost or anything like it.

# Answer
> 0 votes
legacy in house libraries is not a factor... the main reason why anyone shouldn't use boost u other general purpose library is because they're not optimized speed and memory, tho i have to mention that Cryengine uses the STL but they compile it agianst an open source version called STLPort, so dont be afraid of using the STL, just implement your custom allocators and you'll fine. dont use boost tho.

---
Tags: c++
---


# Question
Title: web based quizz game database design, how do I store results?
I'm building a very basic quizz type of php/mysql/ajax game.

At this stage I'm thinking about the DB design, and specifically how to score results, I've two options in my mind. But cannot decide which one is better (being self taught. mostly by doing things, I have no idea what are best practices or what can be useful or not.)

So, I've 3 tables:

1. Users -\> contains: user\_id, user\_name, user\_pass, user\_score
2. Quizz -\> contains: quizz\_id, quizz\_answer, quizz\_question, quizz\_value
3. Results -\> this is the one I'm debating. Should I keep user results in a separate table and have it like: result\_id, result\_user\_id, result\_quizz\_id, result\_score Or simply include results for user inside users table under user\_results and save it as array of answered quizz\_ids

I'm debating if it is good practice to have separate results table or not. If I've it separately it means 10K users can easily create 10K\*100 results rows. On the other hand array in user\_results can become to contain 100 keys.

Performance wise, and taking into consideration good practices, which way is better?

Can mysql handle 10K\*100 row lookups constantly on the bases of user\_ID? Or is it wiser to just explode array from user\_results column?

# Answer
Let my explain, why you should definitely add your results as a separate relation-table and why having a string of IDs inside the user table is "wrong":

First of all, try to look at the database as a separate sub-system. The sub-system should be self-contained. So if you have a table `Users` and `Quizz` and there's a relation between the two (eg. user have multiple or one results per quiz), then this should be reflected in your database design.

Why? Most importantly, it allows you to work with the Database *outside* of your application code. If you leave it up to your application to make the relation between `Users` and `Quizz`, then you're severely limiting the usefulness of the database itself. You won't be able to use any other tool (eg. directly querying your database for these relations) without re-implementing or re-applying that logic you used in your application.

Having your `Results` stored in the `Users` table can also limit performance if you have to implement DB locking (which might be necessary with lots of concurrent users).

Also be aware that you're about to perform premature optimization. Databases are already heavily optimized and can handle thousands and millions of rows. Without identifying the database as a bottle-neck, there's no reason to deviate from good practice. I highly doubt that querying the user table, splitting the IDs to an array and then querying the `Quizz` table with these IDs individually is going to be any faster than what the DB would do for you with some simple `JOIN` statements.

If you're interested in the topic, you might want to read up on Database normalization. There's another candidate in your design that might be off, which is the `user_score` column in your `Users` table. I suspect that this is a running total of all result scores? If yes, you should get that with a query from your results instead:

```
SELECT SUM(result_score) FROM Results WHERE result_user_id = <yourUserID>

```
> 3 votes

# Answer
If I remember my database design 101; **long tables** are always preferable to **wide tables**.

Essentially, a million rows isn't really anything even close to a big deal for a relational database; even 10 million shouldn't really make MySQL sweat.

This also comes back to design: the results shouldn't be on the user table, because they are not part of the user, but a property of the user.
> 2 votes

---
Tags: databases
---


# Question
Title: How to force a line break before the last word of a line reach the edge?
I'm printing a sliding text by adding each letter after a short period of time. My problem is that when the text multilines, the last word of a line starts on the current line and jumps to the next when it grows too big to fit, making for an ugly effect.

So I guess I need to determine the word where the line would break and replace the previous space with line break to force the break before the word reach the edge. I'm failing to see how to do that. In addition, if there is any way to make the libgdx `BitmapFont` calculate that I would love to learn.

# Answer
> 6 votes
Basically, the algorithm is as follows:

1. Set `maxBreak` to the wrap length.
2. If string is shorter than max break, return string.
3. Set `nextBreak` to `maxBreak` and `newString` to `""`and `lastBreak` to `0`
4. Check if char at `nextBreak` is a break char (space, new line, etc.)
5. If char is not a break char, subtract one from `nextBreak` and repeat step 4
6. If char none of the chars are break chars, you must split the string, so do so at wrap length, so set `nextBreak` to wrap length
7. Add substring from `lastBreak` -\> `nextBreak` and a new line char to `newString`
8. Set `lastBreak` = `nextBreak` and add wrap length to `nextBreak`
9. Go back to step 4 until `nextBreak` is larger than the original string length.

**In fewer words.** You want to start at the maximum wrap length and work backwards until you find a break point. When you find it, insert a newline character. Repeat that until you've reached then end of your original string.

Now, in code:

```
public static String wrapString(String string, int charWrap) {
    int lastBreak = 0;
    int nextBreak = charWrap;
    if (string.length() > charWrap) {
        String setString = "";
        do {
            while (string.charAt(nextBreak) != ' ' && nextBreak > lastBreak) {
                nextBreak--;
            }
            if (nextBreak == lastBreak) {
                nextBreak = lastBreak + charWrap;
            }
            setString += string.substring(lastBreak, nextBreak).trim() + "\n";
            lastBreak = nextBreak;
            nextBreak += charWrap;

        } while (nextBreak < string.length());
        setString += string.substring(lastBreak).trim();
        return setString;
    } else {
        return string;
    }
}

```

Where `string` is the string you want to break and `charWrap` is the maximum number of characters allowed per line.

To find out what `charWrap` should be, you'll likely want to find the average width in pixels of your characters, then see how many you can fit in the space you have available.

---
Tags: java, libgdx
---


# Question
Title: Obj Blender Export Recommendation for OpenGL C++
I have been modelling some objects inside blender, like a light bulb. I finished the light bulb, and I got a question at the time of export it.

I want to export the light bulb in the wavefront format (.obj), but the light bulb is formed by different meshes, I mean, It's not joined in one mesh. If I export the obj that will be as different meshes inside the .obj

My final question is, for import it in the OpenGL C++ side, it's better to join all the meshes (vertexes) inside one or leave them as separated objects? There will not be any trouble on translating... resizing... etc, if they are not joined?

# Answer
> 4 votes
## Definitions:

* Mesh: Any amount of triangles which are positioned to appear as one object.

For example, a cube, it looks like one object and contains 12 triangles. I would call this a mesh.

> I'd like to note that this definition is not at all correct, but I will be using it, so it's best to know what I mean.

* Blender Object: An object in blender which, in object mode, can only be selected as a whole.

For example:

Notice how there is only one object which I can only select as a whole. This is a blender object.

> When you export as a .obj file, it exports the whole blender object, including all meshes.

## The .obj format:

A .obj file has simple statements. In their simplest form (vertices and faces, no normals) they look like this:

```
v 1.0 5.0 1.0
v -1.0 2.4673 -12.06

```

or

```
f 1 5 3
f 5 1 5

```

The `v` stands for `vertex` it describes a vertex.

The `f` stands for `face` it describes a triangle, the example:

```
f 1 5 3

```

Means: That there is triangle made of vertex 1, vertex 5, and vertex 3

The order is the same order they are declared in the file

```
v 1.0 -1.0 -1.0  # 1st vertex
v 1.0 -1.0 1.0   # 2nd vertex
v -1.0 -1.0 1.0  # 3rd vertex
v -1.0 -1.0 -1.0 # hmm...

```

The important thing to realize is that the concept of a 'mesh' as I call it, does not exist in OpenGL, nor does it exist in the .obj file. It is a special concept and above that, it is Blender's doing.

Therefore, loading this data into a proper parser should come out with the right result, merely because OpenGL doesn't require each vertex array to be only one mesh, because to do so, would be an incredible speed reduction and a crap time for the developer.

Therefore, a blender object, as defined before, can be exported to a .obj file. Once this said file is loaded into your program and read, if properly done, should produce exactly what you expect. Multiple meshes that is.

Hopes this helps, if not I'll try to explain further.

---
Tags: c++, opengl, blender
---


title: How to implement armor?

text:
# Question
Title: How to implement armor?
I am a newbie in Python, I am very bad at math too and I need some help. Also close/move this post if you feel this isn't the right place for it.

```
Hero1 = 5000   # His HP is 5k.
Hero1dmg = 200 # damage output

```

How can I subtract some value (let's say 20%) from Hero1's damage output?

# Answer
A very basic formula would be:

```
damageAfterArmorCalc = damageAmt*(1-armorReductionPercent)

```

`damageAmt` Is the original amount of damage to be done.

`armorReductionPercent` is the percent of damage the armor negates, this percentage should be a value from 0 to 1, so the 20% in your example would be `.2`. If we're doing 100 damage initially, we can look at some examples for what that does.

So what's happening here, if the armor does not negate any damage, then we get:

`100 * (1 - 0) = 100*1 = 100`

As you know, any number multiplied by one is still that number. Now if the armor negates 100% of damage, we would get

`100 * (1 - 1) = 100*0 = 0`

Since any number multiplied by zero is zero. Now we know it works for both extremes, how about the inbetween values? Say it negates 20% of damage as in your example. , we can see how that looks:

`100 * (1 - .2) = 100*.8 = 80`

We know that 20% of 100 is 20, and that 100 minus 20 is 80. So it looks like this works just fine.

I suggest you look into some basic math tutorials and get the basics down. Khan academy is a great resource for this.
> 8 votes

# Answer
To subtract 20% off his damage output, multiply by .8 (20% = 0.2, so multiply by 1 - .2 = 0.8). That makes the new damage 160.
> 1 votes

---
Tags: mathematics, python
---


# Question
Title: Compare Mouse X,Y with Grid X,Y to find the closest grid position
**EDIT: From two very good answers I have decided to use isometric projection instead of my silly grid of cordinates.**

I am doing a game entirely in canvas, and I find it quite troublesome right now.

I felt silly trying to post the grid. Here is the code with the grid on hastebin.com

Hastebin Link

Since I have all the grid cordinates, I am iterating the 2D array and turn each iteration into a vertex that I compare to the mouse vertex. My goal is to find the vertex closest to the mouse vertex. Instead all I am returning right now is (17,0) every time, no matter where I click. Do you have any idea why?

```
function mouse_click(ev) {
    var x = ev.clientX - c.offsetLeft;
    var y = ev.clientY - c.offsetTop;
    // Run click_grid
    alert(click_grid(x,y));

}

// Find the grid that is nearest the clicked cordinates.
function click_grid(xx,yy){
    var result = [];
    var result2 = [];
    var best = [0,0];
    var lastNode = [];
    var currentNode = 9000;
    for(var y = 0;y < 18; y++){
        for(var x = 0; x < 18; x++){
            // Distance = |P-E| = |(3,3)-(1,2)| = |(2,1)| = sqrt(2'2+1'2) = sqrt(5) = 2.23
            result = [grid.grid_x[y][x] - yy,grid.grid_y[y][x] - xx];
            result2 = [result[0] * result[0], result[1] * result[1]];
            currentNode = Math.sqrt(result2[0] + result2[1]);
            if(currentNode < lastNode){
                best = [y,x];
            }
            lastNode = currentNode;
        }
    }
    return([best]);
}

```

# Answer
> 1 votes
Judging from your grid, this is a simple isometric projection. Typically, we use linear algebra to figure out the coordinates, rather than iterating over all the grid coordinates.

For example: we know, based on your data, that the transformation looks something like this.

```
map (0,0) <-> screen (340,0)
map (0,1) <-> screen (360,10)
map (1,0) <-> screen (320,10)

```

We can derive the formula:

```
mapcoordinates = [-x/40+y/20+8.5, x/40+y/20-8.5 ]

```

for example, if you try out this code, it should alert the same results (sans bounds checking) I flipped x and y because of the choice of coordinates labels is reversed, and I added 0.5 and then converted to integer (`>>0`) to handle rounding to the "nearest" coordinate:

```
function click_grid(x,y) {
   return [-y/40+x/20+9>>0,y/40+x/20-8>>0];
}

```

# Answer
> 2 votes
I think you want to move `lastNode = currentNode;` inside the `if` like:

```
        if(currentNode < lastNode){
            best = [y,x];
            lastNode = currentNode;
        }

```

---
Tags: javascript
---


# Question
Title: Application design for specific points on image
Hi guys I am starting a simple hobby app in Unity, its a 2D app, which have some alphabets like A,B,C..Z (images) . There ll be specific paths where user touch one by one to complete drawing the alphabet, like image below. Now I have some solutions for it in my mind:

1. Make a grid of small boxes/planes with colliders on complete alphabet character, and enable some of its planes, like in image the "red" line ll have small planes behind it with colliders enabled (planes with colliders on "yellow" and "blue" line ll be disabled) "red" plane colliders are triggered with some texture when user clicks/touches on that plane wo show some color on touch point. Thats how complete alphabets can be done with one grid.
2. Create mesh colliders for every alphabet in 3dsMax or any other modeling tool and enable them one by one. For e.g first enable "red" line collider then "yellow", then "blue". But this ll require to make collider for every curve and changing design ll require re work.
3. Picking specific pixel set on the image, e.g to first pick red area pixels, if user touching on these pixels then true else false.

I would like if some can have a better solution of it ? may be any optimized way, may be some variation of custom colliders, bounds, line renderes, curves etc.

# Answer
Why not create a path under the alphabet that you can use as the drawing guide?

I don't know much about meshes, colliders or 3D models, but in Cocoa Touch or Core Graphics you could create a `UIBezierPath` of `CGPath` which and lay it underneath the image (whether you want it visible or not) and you could track the user's touch and drag along the path.

This would also allow you to easily create segments, lines and curves along the path in the order you wish them to be enabled/highlighted/shown. You could further overlay a colour on the path as the user is dragging over it. You could also bundle the paths inside the application with the images if you want.

Creating models in 3dsmax as well as the colliders and meshes seem like a waste of energy, but that's just my $0.02.
> 2 votes

---
Tags: 2d, collision-detection, architecture, touch, pixel
---


# Question
Title: Optimising out tiles outside of viewport
I am playing around with the HTML5 canvas and have begun implementing a tile engine.

However, it's currently very inefficient: I have a 100x100 2D array and my code loops through the whole thing every frame. (Very bad, I know.) I'd like to optimise the rendering loop by using a viewport or camera to determine which parts of the area are view.

Here is an example. I haven’t added the camera offset yet because I’m not sure how:

```
for (var y = 0; y < state.map_data.length; y++) {
    col = state.map_data[y];
    for (var x = 0; x < col.length; x++) {
        color = (state.map_data[y][x]==1)?'#fff':'#000';
        self._draw({
            type:'rec',
            x: x * state.tile_width,
            y: y * state.tile_height,
            width: state.tile_width,
            height: state.tile_height,
            fill: color,
            visible: true
        },self.ctx);
    };
};

```

Here is a link to the game as it is.

How can I make this more efficient?

# Answer
> 4 votes
From my understanding you just read the camera bounds and use that as your index reference of your tile grid. Draw from the first tile in the top left corner of your current screen, relative to the cameras position, to the last tile of your bottom right corner index. This way you only draw tiles that are within camera bounds.

For example the first would be something like so:

```
int indexX = topleftXBound/ tileSize;
int indexY = topleftYBound/ tileSize;

```

Then calculate the right bottom bound. You can use these indexes to determine what starting point and limit you should use for your forloop. Instead of drawing 100x100 tiles. You only a few in comparison.

You could represent your camera as a simple rectangle that you move around. Have the center, the width and height.

---
Tags: javascript, html5, camera, optimization
---


# Question
Title: Models with more than one mesh in JMonkeyEngine
I’m a new jmonkey engine developer and I’m beginning to import models. I tried to import simple models and no problems appeared, but when I export some obj models having more than one mesh in the OgreXML format, Blender saves multiple meshes with their own materials (e.g. one mesh for face, another for body etc). Can I export all the meshes in one? I’ve tried to join all the meshes to a major one with blender (face joins body), but when I export the model and then create the Spatial in jme(loading the path of the “merged” mesh), all the meshes that are joined to the major doesn’t have their materials!

I give a more clear example:

I have an .obj model with 3 meshes and I export it. I have :

*mesh1.mesh.xml , mesh2.mesh.xml , mesh3.mesh.xml* and their materials

*mesh1.material, mesh2.material mesh3.material*

so I import the folder in *Assets/Models/Test* and now I have to create something like:

```
Spatial head = assetManager.loadModel( [path] );
Spatial face = assetManager.loadModel( [path] )

```

one for each mesh and than attach them to a common node. I think there is a way to merge those mesh maintaining their materials! What do you think? Thanks

# Answer
you can import this blender model file directly into the jmonkeyengine sdk-- it will convert the blend file to a j3o. when loading the model into jme during runtime, the node or spatial will have the children attached.
> 2 votes

---
Tags: models, blender, 3d-meshes, assets, jmonkeyengine
---


# Question
Title: How to implement collision detection of portals?
For example, take this scenario (excuse my horrible drawing skills):

This is based on "Portal", where the stickman is going through the blue portal (which is linked to the red portal), but there is a wall stopping him on the red portal. Therefore he cannot go completely through the portal.

So my question is this: How do I do the physics/collision detection with them? Do I slice the player? Is there a way to link them? Are there any physics engines that support doing this? If not, how would I make one?

# Answer
The *Portal* game has a nice way by which they solved this problem:

The player sticks through the source portal (blue) and is seen sticking out of the target portal (orange). The player is copied to the target portal and seen stepping through it. The game renders the image you see when looking through the source portal by using a second camera and render-to-texture.

However, the copy of the player at the target location *does not* interact with the physics. It is only there for rendering purposes. Instead, they make virtual collision objects on the other side of the source portal, and make the player collide with that instead. This keeps the physics simple.

You only need those virtual objects for as far as the player can reach without going fully through the portal. As soon as the player passes fully through the portal, the situation is reversed.

**An image to illustrate**: The blue portal is the source portal, the orange portal the target portal. The dashed white box is the virtual collision object, whereas the real box is the rendered object. The player (with the red dot) only interacts with the objects directly around it. The objects at the orange portal are completely ignored.
> 7 votes

# Answer
Here's how I'd try and do it.

While you're inside a portal there would be two copies of the player in the physics engine. Each copy ignores all collisions that are on the opposite side of the portal, and you then combine the results and apply the simulation results to both models.

Ideally you'd apply gravity separately for each half of the player, but you might be able to get away with just applying it for the side of the portal the player's centre of mass is on.

To ignore those collisions you need to set up an appropriate volume, and test if a point is within it. A cylinder (possibly stretched vertically) would seem to be a good option. The test is then something like `if (!collisionPoint.InsideCylinder(portal)) ProcessCollision(); else IgnoreCollision();`

I believe most physics engines have a system for filtering what an object can collide with, so it should be possible using a standard physics engine. For example http://bulletphysics.org/mediawiki-1.5.8/index.php/Collision\_Filtering#Custom\_collision\_filtering

To combine the results the simplest option would probably be to add some kind of inflexible constraint between the two, and let the physics engine handle it.
> 6 votes

# Answer
> How would I calculate how far the player goes down?

Why would you want to? You don't need to calculate how far a player goes "down"; you'll find out how far down it goes as the object goes through the simulation.

> How would I even connect the portals?

A portal, from a purely in-game perspective, is little more than an elaborate teleporter that messes with collision to turn collidable objects into non-collidable ones. When an object touches the portal, it starts potentially colliding with things on the other side. When the object passes "far enough" though the portal, you effectively teleport it to the other one, instantaneously changing its position and orientation.

Physics simply proceeds as normal.
> 4 votes

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


title: Map state in XNA on WP8

text:
# Question
Title: Map state in XNA on WP8
I am developing an RPG for Windows Phone 8 using XNA. I have a map screen and a fight screen. I want to use XNA for both to utilize the graphics helpers and because XNA is awesome. My question is, how do I save the map state between the two screens? That is , how do I save the location of the PC and the enemies when I travel back and forth between the two screens?

# Answer
> 0 votes
If you're using some kind of State Management this will just happen automatically. You'd have two states or screens in the case of the Microsoft XNA sample.

**GameplayScreen**

We can call this your gameplay screen state which would compromise of a few things but for your case you could just have the map on this screen and other things like input for moving around the map and logic for updating entities on this map. You wouldn't include things that aren't related to your "overworld" or "map" display. Things like a mini-map may go here but the decision is yours on how you separate your logic. Ideally, a menu would be another state but that's another discussion. However, **what you should take away from this is no combat takes place inside of this state.**

**FightScreen**

Now, when you need to transit to a battle switch the **ActiveScreen** but don't dispose of the underlying screen. Your **StateManager** should have a mechanism for disabling sending input to screens that are not active and not drawing them (optional; maybe you can enable drawing if you need overlay screens). However, the point is your state is preserved.

See this stack:

Now, when the fight is over you would simply pop the **FightScreen** off the stack and your GameplayScreen would automatically resume!

If you have any other questions, comment and I advise you also check out the RPG Sample for more tips and a working sample that deploys this strategy.

---
Tags: xna, c#
---


# Question
Title: How to setup Authentication Database and Game Database?
I'm playing around with creating a game in C# using the XNA Framework. I've decided to use technologies that I'm pretty much familiar with and create things from scratch. There are probably frameworks out there that would take away all of the difficulties that I'm encountering but I find it fun to dive into these challenges and over come them manually if you will.

My current issue is that when I play MMO type games I know the general setup. I must login (authenticate) and then select a server to begin playing on. Once I log into the server I'm generally met with a Character Select screen of some sort before I actually "log in to the game".

With that said, my initial attempt at developing a database system was this:

1. Authentication Database - table for user information, table for server information
2. Game Database - table for characters, table for inventories, items, etc...

After I created these I noticed a key missing problem. Users are linked to characters and characters are linked to a server. I currently have these pieces of information spread over 2 databases. I thought to myself, maybe this isn't a good idea?

I guess I could: Game Client can store the reference to the account identifier in the code once login was successful, but doesn't that sound like a security issue?

Anyone have thoughts or suggestions? Or a good book recommendation for development in this area?

**Note** I'm not trying to develop an absolute perfect system that I can release and make money off of. I'm more doing this for experience, fun and enjoyment so my solution doesn't have to be perfect, but I don't want it to be the worst possible solution either :)

# Answer
This is fine if you use a multi-process setup that involves a gateway daemon and an actual world server daemon (which can be further split into other sub daemons for processing of data in the world; but this is a whole other story on its own...)

To use the setup you have, you just setup some communication between the two servers. The servers initially connect to the gateway server login, process and do all the work through that vein. Then, when everything is confirmed the player sends a packet and the gateway daemon sends an OK and passes the OK to the client and the internal world server. The client is given a token which is then sent to the world server to prove who they are - then the world server takes the data the gateway daemon gave it and constructs the player and everything needed from the shard specific data.

There's a lot of topics on this, so see:

Information on seamless MMO server architecture Loadbalancing Questions Should I keep login server apart from game server?
> 0 votes

---
Tags: xna, c#, server, databases, storage
---


# Question
Title: My ClanLib based Keyboard Manager not working
I created a simple Keyboard manager to detect whether buttons are currently pressed, or if where pressed in that frame. It seems like it should work, yet it seems to not read anything. Here is my class:

```
KeyboardManager.h file

class KeyboardManager
{
public:
    KeyboardManager(CL_DisplayWindow*);
    ~KeyboardManager(void);

    void Update();

    bool isPressed(int code);
    bool isReleased(int code);
    bool wasJustPressed(int code);

private:
    bool currState[0xffff];
    bool prevState[0xffff];
    CL_InputDevice *input;
};

KeyboardManager.cpp file

KeyboardManager::KeyboardManager(CL_DisplayWindow* window)
{
    input = &window->get_ic().get_keyboard();
    for(int i = 0; i < 0xFFFF; i++)
    {
        currState[i] = false;
        prevState[i] = false;
    }
}

KeyboardManager::~KeyboardManager(void)
{

}

void KeyboardManager::Update()
{
    for(int i = 0; i < 0xFFFF; i++)
    {
        prevState[i] = currState[i];
        currState[i] = input->get_keycode(i);
    }
}

bool KeyboardManager::isPressed(int code) { return currState[code]; }
bool KeyboardManager::isReleased(int code) { return !currState[code]; }
bool KeyboardManager::wasJustPressed(int code) { return currState[code] && !prevState[code]; }

```

As you can see, I ommited the includes. My question is, why does it not work! BTW. I based the keys array size on this page http://www.cl.cam.ac.uk/~mgk25/ucs/keysymdef.h . It seems like the Clanlib input is based on it. Also, it does not cover all the posible chars, but I only put enough for the ones I use, the basic keyboard letters, numbers, control, shift, arrow keys, etc.

This souldn't be important, but I'm using VS 2010

EDIT: I updated th keyboard manager and added the game logic as a whole here:

```
Game.h

class Game
{
public:
    Game();
    ~Game();

    void setName(string);

    static int main(const vector<CL_String>&);
    void run();
    void OnWindowClose();
    void quitGame();

    void setWidth(int);
    void setHeight(int);

private:
    bool quit;
    string name;

    int width;
    int height;
};

Game.cpp

Game::Game()
{

}

Game::~Game()
{

}

void Game::setWidth(int newWidth)
{
    width = newWidth;
}

void Game::setHeight(int newHeight)
{
    height = newHeight;
}

void Game::OnWindowClose()
{
    quit = true;
}

void Game::quitGame()
{
    quit = true;
}

void Game::setName(string newName) { name = newName; }

void Game::run()
{
    int x = 0;

    setWidth(800);
    setHeight(600);
    setName("Game");
    quit = false;

    CL_DisplayWindow window(name, width, height);

    CL_Slot slot_quit = window.sig_window_close().connect(this, &Game::OnWindowClose);

    CL_GraphicContext gc = window.get_gc();
    KeyboardManager keyboard(&window);
    CL_InputDevice mouse = window.get_ic().get_mouse();

    CL_ResourceManager resources("resources.xml");
    CL_Sprite* sprite = new CL_Sprite(gc, "WalkingBlankPonyRight", &resources);

    while (!quit)
    {
        if(keyboard.isPressed(CL_KEY_ESCAPE))
            quit = true;

        sprite->update();

        if(keyboard.isPressed(CL_KEY_D))
            x++;
        else if(keyboard.isPressed(CL_KEY_A))
            x--;

        CL_Draw::fill(gc, CL_Rectf(0, 0, 1024, 720), CL_Colorf::cornflowerblue);
        sprite->draw(gc, x, 200);

        window.flip();
        CL_KeepAlive::process();

        CL_System::sleep(10);
    }
}

int Game::main(const std::vector<CL_String> &args)
{
    CL_SetupCore setup_core;
    CL_SetupDisplay setup_display;
    CL_SetupGL setup_gl;

    try
    {
        Game* game = new Game;
        game->run();
    }
    catch(CL_Exception &exception)
    {
        // Create a console window for text-output if not available
        CL_ConsoleWindow console("Console", 80, 160);
        CL_Console::write_line("Error: " + exception.get_message_and_stack_trace());

        console.display_close_message();

        return -1;
    }

    return 0;
}

CL_ClanApplication app(&Game::main);

```

# Answer
Your code:

```
KeyboardManager::KeyboardManager(CL_DisplayWindow window)
{
    input = &window.get_ic().get_keyboard();
    for(int i = 0; i < 0xFFFF; i++)
    {
        currState[i] = false;
        prevState[i] = false;
    }
 }

```

input = &localVariable

You pass "window" by value. When "window" goes out of scope, using "input" will cause undefined bahaviour, it points at something that "might" not be in there anymore. Pass a pointer to "window" instead.
> 1 votes

---
Tags: c++, 2d, input, keyboard
---


# Question
Title: Moving an object toward another object on sphere knowing their quaternions
I have a sphere centered in world origin. On the sphere surface I have two objects and I know their quaternions (rotation around sphere).

Currently my movement works on Vector2 inputs (cannot change distance from sphere surface) concatenating the current movement quaternion to existing quaternion:

```
 RotationQuaternion *= Quaternion.CreateFromRotationMatrix(
        Matrix.CreateRotationX(-_movementDirection.Y * Speed * deltaSeconds) *
        Matrix.CreateRotationY(_movementDirection.X * Speed * deltaSeconds));

```

How would I move one object toward another? I have looked into quaternion lerping functionality, but this does not really help, as what I would ideally want is movement direction and apply my own speed and acceleration to it.

Thanks for any help - geometry is not my strongest suite!

# Answer
On a sphere, the distance between two points is a product of the angular distance between them (ie: the angle between the vectors pointing from the sphere's center to those two points) and the radius of the sphere. The distance around a circle, the circumference is `2 * pi * r`, where `r` is the radius. We can therefore divide the circumference by the ratio of the angle and 2pi (assuming angles in radians). So given the angle between two points on a circle, the distance between them is:

```
d = (angle / (2pi)) * (2pi * r)
d = angle * r

```

Once you have the distance between them, you can now pick any speed you want. With the distance, you can convert this into an *angle*; This angle represents the distance you want the object to move this frame. Given a speed of `s` and a frame time delta `t`, the distance you want to move is `s * t`. Therefore, the delta angle that represents this distance is:

```
d = angle * r
s * t = angle * r
angle = (s * t) / r

```

We now have an angle, but we need an axis to rotate around. That's easy too: it's the (normalized) cross-product between the two vectors. The *order* of the cross product is important. Use the right-hand rule: to go from P to Q, you want `P x Q`, not `Q x P`.

Given an angle and an axis, simply compute a quaternion from them with the usual means. Multiply that by your current quaternion to get the new one.
> 3 votes

---
Tags: xna, 3d, rotation, geometry, quaternion
---


# Question
Title: Vertical vs horizontal hex grids, pros and cons
With hex grids, you can choose to arrange the tiles with the pointy sides up, so that you can move along the west-east axis, or you can arrange them with an edge up, so that you can move along the north-south axis.

Horizontal or pointy-side-up hex grid:

Vertical or flat-side-up hex grid:

According to **this page**, the vertical alignment is "by far the most popular" in pen-and-paper RPGs, but it doesn't explain why. **This blog post** also mentions both varieties, but again gives no reason to use one or the other.

And if you look at some PC games using hexes, it seems both have their adherents:

* **Horizontal:** Heroes of Might and Magic series (except V), Civilization V...
* **Vertical:** Panzer General and many similar wargames, Battle for Wesnoth...

But what are the main reasons for choosing a vertical or a horizontal layout of hex grids?

I'm looking for objective advantages and disadvantages in terms of data structures, graphics, gameplay, etc, not personal preferences. Or is it really inconsequential which orientation you choose?

# Answer
> 37 votes
I have been able to come up with a few reasons myself, but I'd really like to hear more.

1. Horizontal layout matches the layout of the keyboard. You could use WEADZX for movement, similar to WASD on square grids. On the other hand, I have also found suggestions that QWEASD is a natural fit for vertical hexes.
2. Horizontal hexes seem to be better suited for 3D/isometric perspective, where the bottom row is closest and the top row is farthest. In this layout, high sprites won't obscure the center of the tile behind it, but just the edges. This would possibly make the vertical hex arrangement better suited for top-down views.
Compare to square vs diamond ("isometric") grid, as in Simcity Classic vs Simcity 2000.
3. For an NxN grid, the horizontal layout results in a grid that is wider than it is tall, just like PC monitors. In other words, with horizontal hexes the view of the map that fits on your widescreen has a slightly more equal row/column ratio. Depending on the display area available and the size of the map, this could give the player a better view, and it might require less scrolling.

# Answer
> 27 votes
I would go with vertical layout if you are using any sort of bird's eye perspective, as in the image above.

Why? Because **more walls will be visible.** If you use horizontal layout, and you have walls that run along the vertical lines, you will not be able to make out details on them very well (such as doors or gates). Furthermore, if you are using the aforementioned perspective type, your hexes will look a lot better, because you will probably have to squash them half way. If you squash a horizontal hex halfway, it has very low slope on its points (roughly 1/8) vs a 1/2 slope for a squashed vertical hex. In other words, if you are simulating bird's eye perspective and/or using pixel art, vertical tiles will give you a better look.

# Answer
> 21 votes
Sounds like you're leaning toward horizontal as having more advantage. For what it's worth, bees agree with you when they build their honeycombs:

> The axes of honeycomb cells are always quasi-horizontal, and the nonangled rows of honeycomb cells are always horizontally (not vertically) aligned. Thus, each cell has two vertical walls, with "floors" and "ceilings" composed of two angled walls(disparity with image "Honeycomb-Process"). The cells slope slightly upwards, between 9 and 14 degrees, towards the open ends.

Try as I might, I couldn't find a theory as to why bees do it this way. (Don't get me wrong, there are various theories as to why they use the hexagonal geometry, but that doesn't appear to explain why horizontal rather than vertical.)

Anyway, thought I'd add to the list of horizontal advantages/disadvantages: "It's how bees do it." If your game is some kind of bumble-bee sim, that would be a persuasive reason to go with horizontal hex.

---

Alternate benefit of the horizontal approach: By using a horizontal (or pointy-side up) alignment for the hex-grid, you make your grid conform to the instructions for setting up a tent.

# Answer
> 17 votes
If you are building a strategy game, the game requirements and design itself should dictate which orientation you choose. Note that defensive lines are more easily held with the grain than against it, so your choice of grid orientation relative to map orientation will affect game play. To emphasize defence, such as in WWI, align the hex grid with the natural defensive lines; to emphasize offense as in WWII, do the opposite.

# Answer
> 16 votes
Your hex orientation will influence both your general aesthetics and your asset production.

If you choose vertical tiles, you can make your hexes twice as wide as they are tall and have pixel-perfect accuracy. Here are some 64x32 hexes.

Note that the diagonal edges are at 45 degree angles, making them easier to render in pixels.

The narrow height of the hexes relative to their widths can suggest depth, especially when you pace objects on them that can overlap with hexes behind them.

Another example of how the hex orientation can affect your asset production is with objects placed on horizontal tiles. On horizontal tiles you can only go roughly left or right. You can not go directly up or down. (Similarly, you can only go roughly up or down on vertical tiles). You could therefore possibly get away with only using a single side-facing image for objects on horizontal tiles.

With vertical tiles you'd have to make dedicated front and back images for the objects at the very least if you want different orientations, while on horizontal tiles you can use a single image that gets flipped.

# Answer
> 14 votes
From a technical and programming perspective, there should be no fundamental difference in data structure between the two orientations - any reasonable scheme should be easily modifiable to work well with either setup.

Design-wise, in the end it *will* come down to preference — as you've noted, there are multiple games using either scheme, which is pretty clear evidence that neither is technically superior. One thing that's worth noting is that Western text flows horizontally rather than vertically; because of this, Western players are likely to latch on to the horizontal elements of a design more quickly and more strongly than the vertical elements, because they're wired to look for horizontal structure. In the case of hexes, this means what you're calling the horizontal hex grid will draw attention to its horizontal straight lines more readily than the vertical hex grid draws attention to its vertical straight lines, and so if you want to emphasize the straight-line movement then the horizontal grid is likely to do a better job of that.

Contrariwise, though, if you want to *de*-emphasize the straight lines in the grid (which is one good reason for choosing a hex grid over a square one in the first place!) then you may want to use the vertical hex grid over the horizontal, since the lighter weight given to vertical lines will minimize the overall sense of straight lines in the grid for players.

One caution, though: note that this *is* a culturally-trained trait, not an inherent one, and that if you want to introduce your game into Japanese or other markets then you may want to reevaluate the decision, since the natural flow in those cultures is often vertical rather than horizontal (compare, for instance, Japanese *4-koma* vs. American comic strips).

---
Tags: maps, hexagonal-grid
---


# Question
Title: Calculating transform of arrow model pointing at some point in 3D space
I'm working on a 3D flight game and I'd like to implement a simple "navigation arrow" pointing at the next waypoint in world which the player has to fly to.

I have position of both airplane (=camera) and the target and also orientation of the airplane (in form of quaternion). But sadly I can't figure out correct way to use them to get the arrow pointing at the target regardless the airplane yaw/pitch/roll.

The arrow was already working once, but only when the airplane was in horizontal orientation. But when the airplane was tilted, the tilt was not reflected in the arrow transform.

Here's my code (it might not be accurate, as I'm desperately trying anything that could help) to get the arrow rotation

```
Vector3 target = ...;
target.subtract(airplane.position);
target.normalize();

Vector3 dir = new Vector3(0, 0, -1); // initial airplane direction
dir.rotateBy(airplaneQuat); // current airplane direction

double angle = Math.acos(target.dot(dir));
Vector3 axis = target.cross(dir);

```

I think my problem is the fact that the airplane can fly upside down and in other riddiculous orientations, and I just cannot visualize all the transforms in my head. I'll be happy for any help.

---

**UPDATE:** Based on Cong's answer I came up with working solution. Here's the pseudocode. It could be improved, but the arrow behaves sufficiently accurate by now, just the way I indended.

```
Vector3 dir = target.position;
dir.subtract(airplane.position);
dir.normalize();

Quaternion q = airplane.orientation;
q = q.conjugate();
dir.rotateBy(q);

Vector3 up = Vector3(0, 1, 0);
Matrix4 mat = Matrix4.createLookAt(dir, up);

Matrix4 transform = Matrix4(); // identity
transform.translate(0, -0.85, 0); // move to the bottom of the screen
transform.mul(mat);
transform.scale(0.2); // just scaling the model

```

# Answer
> 4 votes
What you are looking for is the LookAt algorithm. OpenGL already has that in a nice function: `gluLookAt`, although it multiplies the current matrix instead of returning it to you so you may need some push/pop trickery to get at it.

If you want to do it yourself, there are two ways; by constructing a transformation matrix, or by using quaternions. Here's the abridged version of this tutorial:

```
void LookAt(Matrix4& orient, const vec3& target, const vec3& Up)
{
    vec3 ZAxis = target - orient.WAxis();
    ZAxis.normalize();
    vec3 XAxis = CrossProduct(Up, ZAxis);
    XAxis.normalize();
    vec3 YAxis = CrossProduct(ZAxis, XAxis);
    YAxis.normalize();
    orient.XAxis(XAxis);
    orient.YAxis(YAxis);
    orient.ZAxis(ZAxis);
}

```

Where `orient` is your arrow's transform matrix (position and rotation), `target` is where you want it to point at, and `Up` is a suitable "up" direction.

Here's another link which may be useful: https://stackoverflow.com/questions/349050/calculating-a-lookat-matrix

# Answer
> 0 votes
The "gluLookAt" function (as mentioned by Cong Xu, is definitely useful, but I find this to be even better:

http://renderdan.blogspot.com/2006/05/rotation-matrix-from-axis-vectors.html

It is really the same thing as a lookAt matrix, but gives you a deeper understanding of its functionality.

Using tangent space vectors, you can easily rotate an object into a given position. It is actually really important to understand how this works (I think) if you want a firm understanding of 3D vector math, but you can just as well use it without digging too deep.

---
Tags: opengl, quaternion, transformation
---


title: Libgdx Animation Timing

text:
# Question
Title: Libgdx Animation Timing
I'm having a small issue with libgdx animation.

I'm using getKeyFrame() to get the current frame of the animation and I'm updating the state time by adding on deltaTime in my update function for the object. The animation is not looping.

My problem is that the animation seems to play at different speeds depending on the frame rate. On my phone this animation plays particularly slow. My thinking was that the stateTime would cause it to skip a few frames when it's going slow, but this doesn't seem to be happening.

Here is the code;

```
        sprite = Animation.getKeyFrame(stateTime, false);
        sprite.setRotation(angle);
        sprite.setPosition(position.x, position.y);
        sprite.draw(batch);

```

Has anyone else experience this issue.

# Answer
I;ve tested it and it seems to work ok on libgdx 0.9.3... Can it be some problem with the way you generate "stateTime"? I would also look in the frameDuration argument that the Animation constructor get.
> 1 votes

# Answer
Check this: getKeyFrame

```
sprite = Animation.getKeyFrame(stateTime, true);

```

Animation seems to play at different speeds depending on the frame rate. Can you verify if your game runs at 60fps or 30fps? I also recommend you look for information about "frame skip".
> 0 votes

---
Tags: android, animation, rendering, libgdx
---


# Question
Title: How to build a math module and simulate a system?
For example, in the classical game SimCity:

* an economic model to simulate the supply and demand of the city, then calculate how many people live in each building, how many people work there.
* a traffic model to simulate the commute time of the citizens,
* in another game, there'd be a whole stock market, where the player and sim-citizens can buy and sell.

Obviously, we cannot simulate every single citizen, every single car, every single trader in the market, we need some math modules and formulas.

I'm making a fake SimCity and almost finished the graphics parts. Now I'd like to know how to do the math parts, or how to build such math modules.

# Answer
I will speak about the economic part. In a game I want to develop I want to introduce real economics subjects as well.

There are two ways you can do that.

You can actually use macroeconomics mathematical models to describe the world (description of people behaviour at aggregate level). There are models on stock exchanges (on why and when people prefer stocks to bonds and viceversa), on commodity international exchange as well. There are also models on migration between countries. The subject is called "international economics" and "monetary economics". I suggest you to google that and study starting from the trivial models.

But I thought I can do even something better. I asked myself the following question: exactly why I cannot simulate each single person to describe their behaviour in the economy and then aggregate it? This by starting from microeconomics principles! Well because of execution time in my game. So my idea is this one, and I will try to implement it in the near future. If you want to simulate 100.000 people behaviour with microeconomics decisions, just create a different thread that will run in another core, so that I will not affect the real time of the game. Than every second I will compute the behaviour and choises of 2000 people, so that in less every 60 seconds all the behaviour of my 100.000 will be assessed and taken into account. Every second the game will incorporate the decision of the people that have already decided what to do and then the economy will evolve by people that keep deciding through out the game. This will move prices of financial assets and commodities, will make people migrate from countries... in short will simulate all the economical world from a microeconomics prospective rather than a macroeconomics one.

Hope I will be able to implement this and hope I gave you at least a nice idea.
> 3 votes

# Answer
I agree with Bogdan Marginean that you wouldn't always want to focus on a single person. In case of SimCity it's the group that matters (be it citizens of a neighbourhood). They have a similar problem with commuting, sewage , similar happiness level etc.

However, the flyweight pattern isn't actually applicable here. The common part is immutable. Instead of creating entities that very just a bit it will be better to consider a group as a primary unit.
> 0 votes

---
Tags: mathematics, algorithm, simulations
---


title: Problem with sensor in box2d

text:
# Question
Title: Problem with sensor in box2d
I have two bodies: one green static sensor (spikes) and one orange dynamic body (brick).

I have bullet and it's a dynamic body too, but with bullet flag set.

My problem is that when the bullet is moving left to right, it sometimes hits the orange brick instead of the spikes and it flies away. There is code to remove the bullet when it hits spikes. How can I make sure it hits the spikes first?

# Answer
> 1 votes
It might caused by the "high speed". Remember, most of the in-game movements are not continuous like in real life. The bullet might be fast enough to just pass your spike layer in one frame.

It can be pretty tricky to solve this problem... Please check this: Continuous Physics Engine's Collision Detection Techniques

# Answer
> 0 votes
You will need to set the moving body's definition as a bullet body. Are you still having the problem of skipping the sensor? If so, adjust the scale of the world or frequency of the simulation.

---
Tags: box2d, physics
---


# Question
Title: What is the price to license EA's GlassBox game engine?
*"SimCity 5"* is powered by the GlassBox engine. If we want to use the engine for building our own simulations, what is the price for a license?

# Answer
The company I work for are in talking with EA about using the engine, they are not interested in anyone using it until the release of the game. I'd imagine it will be a per-case basis on which they sell a "license" to use it, and probably some sort of royalty contract too.
> 6 votes

# Answer
I don't think EA will sell/license the GlassBox engine to anyone. Having created an engine for your own game, for internal use is something totally different from creating an engine for other people to use. I haven't heard of EA making GlassBox to sell it and having finished an engine doesn't mean you can just start selling it:

The tools have to be polished a lot more, internally you can learn everyone to work around a few quircks but when you release it you are expected to have polished them out. You have to create extra documentation, maybe even set up a few introduction lessons, take care of managing customer relations, provide support for problems, etc.. etc... This is usually not worth it unless you expect a lot of interest from other developers. (Of course EA is likely to use the Engine on other projects of their own studios but that is a lot easier since people still expect internal tools and the people who can solve your problems are always next door)

This is why only a few big companies license there engines, and they usually create the engine specifically for this purpose. For example look at Epic with their Unreal Engines. Usually ID also releases their (tools for their) engine, but look at their latest game, RAGE where they (still?) haven't released the tools, even though they initially planned so, because they were only good enough for internal use.
> 5 votes

# Answer
We can just assume and I'd say only EA can tell... haven't seen any public offer or anything like that. Plus the question is whether they'd want to share it with a possible contender. :)
> 1 votes

# Answer
I'm not aware of any indication from EA or Maxis that they would be interested in licensing this engine to anyone for any purpose.

RoyT's comments about tools and the engine's readiness for external use are 100% correct.

From experience with other popular engines, the licensing seems to start at about $100k and go up from there, and can include a % of revenue.

However, I also know that every single engine license agreement can be negotiated and almost always are negotiated to take into account the specifics of that developer and their plans or expectations.

IF you can make a genuinely compelling *business* case for them licensing the engine to you, it is certainly possible. It really can't hurt to ask, at least. But I would expect the answer to be a polite 'no' regardless of the nature of your proposal.

That's actually good news because I believe it would be a mistake. The other well-known engines like Unreal and CryEngine are ready to go right now. You can download them and be actually writing code *today*. There is already masses of documentation and tutorial videos, there are thousands of people who already have years of experience using these things.

Most of all, the content tools are very mature and reliable and have already churned out thousands and thousands of levels, models, scripted events, and other game assets.

The benefits of all this stuff *far* outweighs the possible benefits of the SimCity engine already being targeted toward simulation.

What's more, I can promise you that you will find the simulation-specific parts of the SimCity engine will turn out to be useless for your purposes for any one of a hundred different reasons. I say this, not because I know your requirements and the engine's abilities (obviously I know nothing of either), but after 25+ years in the software business this is a pattern of events I've watched unfold too many times to count.

Go with the known quantities that are already industry standards and have a ready pool of talent, information, and tools. Delivering a finished game is already very difficult but trying to use the SimCity engine would make it much more difficult than the alternatives, even if EA was willing to do it.
> 1 votes

---
Tags: simulations
---


# Question
Title: What tools should I consider if my aim is to make a game available to as many platforms as possible?
We're planning on developing a 2D, grid-based puzzle game, and although it's still very early in the planning stages, we'd like to make our decisions well from the beginning.

Our strategy will be to make the game available to as many platforms as possible, for example PCs (Windows, Mac and/or Linux), mobile phones (iPhone and/or Android based phones), game consoles (XBLA and/or PSN) PC will have an emphasis, but I believe that's the most flexible platform so that shouldn't be a problem.

So, what programming language, game engine, frameworks and all around tools would be best suited for our goal?

P.S.: I'm betting a set of tools won't cover ALL of them, and that there will still be some kind of "translating" effort for some platforms, but we'd like to know what the most far reaching are.

# Answer
> 12 votes
We have a thick C++ framework on top of a thin platform layer, also C++. Porting a game to a new platform is a matter of implementing a new platform layer, which because it's quite thin, it's quite fast to do.

Also, all of our dependencies are open source and cross platform libs, such as SDL, Ogg, LibPNG, etc.

For example, we have a Win32/DirectX platform, a SDL/OpenGL platform for Linux and Mac, working on an iOS platform for iPhone/iPad, and an android port would also be possible. For some time we had a Playground platform, meaning our framework ran on top of PlayFirst's Playground engine. This layered approach allows you to leverage whatever interface you have to the underlying hardware/OS, as long as you can draw a textured quad, get some input and play a sound, you're pretty much set.

I'll get flamed for this, but C++ is probably the most cross-platform language there is. Every architecture and OS most likely has a C++ compiler or gcc can be ported to it.

# Answer
> 9 votes
Just use Unity

# Answer
> 6 votes
I've just found out about NME a few days ago in another question and thought it might be worth spreading the word. On the subject of multi-platform support, the frontpage states the following:

> Choosing NME opens almost endless opportunities. Create one application and publish to Facebook, the iOS App Store, the webOS App Catalog, the Android Market, the Mac App Store, the Ubuntu Marketplace, NOOK Apps, the Chrome App Store, Steam and other marketplaces without writing specific code for each platform.

I haven't personally tested it yet, but it did strke me as being interesting for many reasons:

* The API is *very* **similar to Flash**, which a lot of people are already familiar with. I've personally done many games in Flash / AS3 before and it's quite **easy to learn** and to work with.
* It uses a language called Haxe which is apperently very similar to ActionScript 3, but **can be compiled into a multitude of formats**, including native C++.
* The above, combined with a few intelligent pipelines set up for you by NME, allows it to be extremely multi-platform. On the **PC** you can target Windows, OS X and Linux, and on **mobile** you can target iOS, Android and webOS (while still getting native performance by using C++ with OpenGL ES under the hood). Finally it also allows **web** game development using either Flash or HTML5 canvas.
* It's **completely free**.

I don't have much time to try it at the moment, so if someone does, it would be helpful if you could leave some feedback about it.

# Answer
> 1 votes
Well that depends, can you programming in C/C++, Obj-C and C#?

Unity3D is the best 1 size fits all but 2D games in it can be abit tricky (for a 2D game anyway).

If you are targeting the Xbox with XNA (aka the indie store) then you have to use C#. But you cant really use C# with iOS (except with unity). While you can use C/C++ for iOS you still need to use a little bit of Obj-C unless you use some sort of middle ware.

If you don't use an engine, I think the best thing to-do is write your own layer of abstraction. So that any calls to your library have to go through this middle layer, so when it comes time to port you just need to change the implementation of the abstraction layer and your game code is more or less intact.

# Answer
> 1 votes
Other answers have covered tools and languages pretty well, but on the graphics side of things, I'd definitely recommend making your (2D) graphics in a vector format and ensuring that they look good at small and large sizes. Too much detail scales down poorly, too little detail scales up poorly.

# Answer
> 1 votes
Moai SDK is an open source framework and currently is able to publish to android, IOS and chrome. Moai would be able to be extended to cover hosts such as game consoles, depending on your skill and knowledge in those areas.

# Answer
> 0 votes
I would say your best language choice would be c#. You can use it to develop in Unity for a number of platforms. c# is also the language used in MonoTouch (for developing for iOS) and MondoDroid (not out yet but will let you target Android platforms). And, of course, c# can be used in XNA which lets you target XBOX 360 and Windows Phones.

That pretty much covers everything. There will still be work to do in the fact that you will be using different tools for manipulating game content, but your core game logic shouldn't need to change if it's all in c#.

oh and of course c# is used in Silverlight which would let you target the web also.

# Answer
> 0 votes
Step one should probably be to make the game, at least a decent prototype, using your favourite tools/tech, for a single platform (or small number of platforms).

It's very easy to get bogged down in cross-platform tools/tech development. Focusing too much on cross-platformness before having a game is kind of like premature optimization. It's certainly worth thinking about early on, but don't spend all your time on it until you've actually got a game.

Trying to support every platform before knowing whether the game will be a success sounds like a high-risk strategy - especially if it's a simple low-budget game (where the cost of developing cross-platform systems could massively outweigh the cost of developing the game itself?).

Wouldn't it make sense to launch it on a small number of platforms, see how well it does, and determine if it's worth supporting the more challenging platforms (e.g. less powerful systems, those with arkward input devices, or those that require a complete port to C# or Java)

# Answer
> 0 votes
I know it's unpopular, but AS3 with Starling might be your answer for mobile, desktop and web. It's STUNNING and performs in ways that are surprising. I made and iOS kinect game that also ran on windows and android. There was nothing else that could handle the computational needs and was that cross platform. Also - you can hook in any Arduino projects seamlessly. Most people just have not noticed what Adobe has done to the flash / flash builder tools as of late....

# Answer
> -3 votes
Flash and Java have very widespread support; they work on all PCs (more or less) and many mobile devices (more or less), and I'm sure they're about as easy to port to a console as any other project with a PC influence.

---
Tags: software-engineering, tools, cross-platform
---


# Question
Title: Choosing a correct collisionshape for a voxel engine
I am building a voxel engine on Ogre with bullet as a physics engine.

I separated my blocks into chunks to help batch together render calls.

At the moment, each chunk's physics is handled by a btBvhTriangleMeshShape that is constructed through the vertices and indices.

Each time the user breaks a voxel, I modify the vertex and index array and construct a new btBvhTriangleMeshShape.

Unfortunately, because btBvhTriangleMeshShape has to recreate an optimizedBVH each time it is created, this becomes quite slow, taking several seconds each time the user breaks a block.

I've alternatively tried using a btConvexTriangleMeshShape, but the broadphase collision detection now becomes very low performance dropping the fps to single digits if the player is near the blocks.

What is the proper collisionshape to choose?

# Answer
Ive decided to use compoundshape and construct boxcollisionshapes for each block. I've done some optimization to only build collisionshapes for visible blocks.

As requested, here's some more information:

1. For each Chunk I create a `OgreBulletCollisions::CompoundCollisionShape`
2. For each visible Block inside each Chunk I construct a `OgreBulletCollisions::BoxCollisionShape` of the proper size.
3. Next I call `CompoundCollisionShape`'s `addChildShape` function to add the `BoxCollisionShape` to the `CompoundCollisionShape`.
4. When all the box shapes are added I create a `RigidBody` out of the `CompoundCollisionShape`

As for the optimization:

1. I build the chunk with Ogre3d's `ManualObject`
2. I iterate through every block inside a chunk and then iterate through all of the 6 sides of the block
3. For each side, I check if there's a block adjacent to that side. If so, that means the side is obscured and do not need to be rendered.
4. If all 6 sides of a block are all obscured, then the block need not have a collision shape attached to it.
5. Recalculate as necessary if chunks are modified.
> 1 votes

# Answer
So couple of things to keep in mind here, typically physics engines are built with the assumption that objects are not added/removed as much as would happen with voxel engines. Not only do you have to update when they change the terrain, but you are going to be constantly removing/adding chunks as they walk around the world. The other thing to consider is that the physics engine keeps it's own copy of all the shapes in an oct-tree. Meaning you're going to have two copies of all the geometry floating around in memory, which can be expensive.

Also, with all the adding and removing you'll be doing, you have to consider that octtrees are not so great at the adding and removing part. They are great for spatial lookups, but slower to update. Now it's perfectly possible to still do all of this, but these are some good things to keep in mind.
> 1 votes

---
Tags: ogre, bullet-physics, voxels
---


title: Client Server Multiplayer Project

text:
# Question
Title: Client Server Multiplayer Project
I have reviewed the relevant WinForms/XNA samples here and here.

However, my requirements are slightly different.

Given the following:

* I am developing a multiplayer (Client - Server) game
* There will be three projects in the solution, one for Client and Server respectively, plus an additional one containing the core game/engine
* The instances will share common code from this engine project (core Game Engine functionality)
* I require the Server instance to also allow management of the server (e.g. connection list etc.) via a Windows Form
* Finally, and importantly, I am proposing to use the Dependency Injection pattern on initialisation of the client/server instances to inject the relevant network management class as required - similar to the approach here

What is the best way to achieve this? Specifically, are there any flaws with organising the projects in the solution the way I have proposed above? For the Server project, do I start it as an XNA project and then call the Winform, or vice versa?

Thank you for any advice you can spare.

**Edit - a brief example of the "dependency injection" style pattern I plan to use. Forgive me if this is not an example of "pure" / full / traditional DI!**

```
// Create the server
using (var game = new ExampleGame(new ServerNetworkManager()))
{
    game.Run();
}

// Create the client
using (var game = new ExampleGame(new ClientNetworkManager()))
{
    game.Run();
}

```

# Answer
OK, so after the positive reception of my design idea, I have gone ahead and implemented a prototype. For completeness, I'll describe the structure of my project below. Most importantly, it builds and runs, and the DI works great.

**Solution Structure (in VS2010)**

* Solution Root:
    + *Client*. Console Application. Startup Project.
    + *Server*. Console Application. Startup Project.
    + *XNAGame*. Windows XNA Project. No entry point (Program.cs removed). Output Type: Class Library. No Startup Object.
    + *XNA Game Content*. Standard XNA content project.

**Client/Server Projects**
Reference the XNAGame project and Microsoft.Xna namespace. Both contain a *Program.cs* with a `static void main()` method as expected. This method invokes the XNA game, considering Dependency Injection, as follows:

```
// Network Manager type injected as appropriate.
using (XNAGame game = new XNAGame(new ClientNetworkManager()))
{
    game.Run();
}

```

**XNAGame Project**
Contains all the usual XNA structure (class with Update/Draw methods, etc.) but with one fundamental difference: there is a Windows Form in this project.

The RTTI features in C# allow this class instance to ascertain whether it has been instantiated as a Client or a Server. Obviously, the relevant Network Manager classes should have been created that implement a common interface for the polymorphism to work. For example:

```
// Constructor accepts the "injected" type as below.
public XnaGame(INetworkManager networkManager)
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";

    this.networkManager = networkManager;
}

// RTTI / Polymorphism. Determine if this instance is a Server or a Client.
public bool IsServer()
{
    return this.networkManager is ServerNetworkManager ? true : false;
}

// The Windows form within this project can then be run as follows.
protected override void Initialize()
{
    // TODO: Add your initialization logic here

    // If this is the server, we need to create and show the management form.
    if (this.IsServer() == true)
    {
        Form = new MainServerForm();
        Form.Show();
    }

    base.Initialize();
}

```
> 1 votes

---
Tags: networking, multiplayer, xna-4.0, windows-forms, dependency-injection
---


# Question
Title: Deep copying or cloning in actionscript 3
I would like to make a mirror reflection of an entity in Flashpunk. So I would like to copy a spritemap from one Entity to another (`reflectionEntity`). If i use something like this

```
reflectionEntity.sprite = otherEntity.sprite;

reflectionEntity.sprite.scaleY=-1; // to reflect

```

then the graphic of the original entity is also scaled.

Is there a simple way out of this? I have been searching for the solution for more than an hour and have not found a suitable one.

# Answer
> 2 votes
I'm assuming that `reflectionEntity.sprite` is an instance of `Image` or `TiledSpriteMap`. In the constructor for Image there's a `souce:*` parameter where you specify where the image comes from. This is the data you want to share.

Copying `reflectionEntity.sprite` (again, assuming that this is something like `Image`, or any subclass of `Graphic` really) just copies the references to that, which is why your changes propagate.

Flashpunk keeps an internal reference to the source, as seen here, but has it marked `protected` for whatever weird reason.

Keep the reference to whatever object you use to load your image, and pass that into a new instance like so:

```
[however the embed statement is written goes here, I forget]
var yourSpriteSource:Class; // Class, assuming you're doing resource embedding
/*
...
*/
otherEntity.sprite = new Image(yourSpriteSource);
reflectionEntity.sprite = new Image(yourSpriteSource);

```

Another alternative is to subclass each Graphic class you're interested in and expose the `source()` function. Another alternative to that (which is likely what *I* would do on a project), is fork Flashpunk and make the `source()` function public. But that's a bit extreme.

Think of `Graphic` subclasses as bits of data that know how to render the *real* graphics data, which is the `source` parameter you pass into their constructor.

---
Tags: software-engineering, flash
---