title: Entity System with C++ templates

text:
# Question
Title: Entity System with C++ templates
I've been getting interested in the Entity/Component style of game programming, and I've come up with a design in C++ which I'd like a critique of.

I decided to go with a fairly pure Entity system, where entities are simply an ID number. Components are stored in a series of vectors - one for each Component type.

However, I didn't want to have to add boilerplate code for every new Component type I added to the game. Nor did I want to use macros to do this, which frankly scare me. So I've come up with a system based on templates and type hinting. But there are some potential issues I'd like to check before I spend ages writing this (I'm a slow coder!)

All Components derive from a `Component` base class. This base class has a protected constructor, that takes a string parameter. When you write a new derived Component class, you must initialise the base with the name of your new class in a string. When you first instantiate a new `DerivedComponent`, it adds the string to a static hashmap inside Component mapped to a unique integer id. When you subsequently instantiate more Components of the same type, no action is taken. The result (I think) should be a static hashmap with the name of each class derived from Component that you instantiate at least once, mapped to a unique id, which can by obtained with the static method `Component::getTypeId ("DerivedComponent")`. Phew.

The next important part is `TypedComponentList<typename PropertyType>`. This is basically just a wrapper to an `std::vector<typename PropertyType>` with some useful methods. It also contains a hashmap of entity ID numbers to slots in the array so we can find Components by their entity owner. Crucially `TypedComponentList<>` is derived from the non-template class `ComponentList`.

This allows me to maintain a list of pointers to `ComponentList` in my main ComponentManager, which actually point to `TypedComponentList`s with different template parameters (sneaky).

The Component manager has template functions such as:

```
template <typename ComponentType>
void addProperty (ComponentType& component, int componentTypeId, int entityId)

```

and:

```
template <typename ComponentType>
TypedComponentList<ComponentType>* getComponentList (int componentTypeId)

```

which deal with casting from ComponentList to the correct TypedComponentList for you.

So to get a list of a particular type of Component you call:

```
TypedComponentList<MyComponent>* list =  componentManager.getComponentList<MyComponent> (Component::getTypeId("MyComponent"));

```

Which I'll admit looks pretty ugly.

## Bad points of the design:

* If a user of the code writes a new Component class but supplies the wrong string to the base constructor, the whole system will fail.
* Each time a new Component is instantiated, we must check a hashed string to see if that component type has bee instantiated before.
* Will probably generate a lot of assembly because of the extensive use of templates. I don't know how well the compiler will be able to minimise this.
* You could consider the whole system a bit complex - perhaps premature optimisation? But I want to use this code again and again, so I want it to be performant.

## Good points of the design:

* Components are stored in typed vectors but they can also be found by using their entity owner id as a hash. This means we can iterate them fast, and minimise cache misses, but also skip straight to the component we need if necessary.
* We can freely add Components of different types to the system without having to add and manage new Component vectors by hand.

What do you think? Do the good points outweigh the bad?

# Answer
I think it is a good first implementation but may I point out some things.

```
Component::getTypeId ("DerivedComponent")

```

The above piece of code worries me for a few reasons.

1. It is prone to bugs and even if we assume you never make any obvious mistakes like naming it the same as another component type, it is hell for maintainability. What I did in my system was have a static function which returns the typdef

```
typedef std::size_t ComponentType;

```
2. Performance. It becomes a nightmare to think about how you can maximise performance, even with your string hashing scheme. Suddenly you will have to pass a string everywhere you want to get a component type, which can easily end up taking much of your frame time, even utilising const&.

Now, this may seem like a 'hack' to you but I have many dozens of components and I can attest to it working well:

```
static const ComponentType GetType()
{
    static char uniqueVariable = 0;
    return reinterpret_cast<ComponentType>(&uniqueVariable);
}

```

It should be clear that the type will be unique (thereabouts) for each type. Strictly speaking, I have at times wondered whether some edge case of memory allocation could break the system but I haven't had any problems with it so far.

Even further, I know there is a big concerted effort against the use of macros, but any experienced programmer worth their salt will tell you that in some cases they are the lesser evil. I think that is the case here. I wrapped the above method inside of a macro so that I may simply define classes.

```
#define COMPONENT_TYPE_INFORMATION static const ComponentType GetType() { static char uniqueVariable = 0; return reinterpret_cast<ComponentType>(&uniqueVariable); }

```

If you're worried about macros then consider reading this in order to protect yourself as much as possible from bugs. The macro shown above is just for illustration purposes.

Here is an example of a component and usage:

```
class Component
{
public:
    virtual ComponentType GetType() = NULL;
    //etc etc
}

class DerivedComponent : public Component
{
public:
    DerivedComponent(/*pass some arguments here perhaps*/) { }

    void MyMethod() { } //do something

    int MyAccessor() { return 1; }

    COMPONENT_TYPE_INFORMATION
private:
};

//ComponentList stores a list of pointers to Component for the inheritance goodness

template<typename T>
bool DoesComponentMatchExist(ComponentList list)
{
    for(std::size_t i = 0; i < list.size(); i++)
    {
        if(list[i]->GetType() == T::GetType())
            return true;
    }

    return false;
}

```

Note that T::GetType() will conveniently return a compiler error if it does not implement GetType as specified by the pure virtual component base class.

Regarding the rest of your post, while I solved the problem with pools of memory, your approach seems fine to me, though passing around a component manager constantly may end up being a hassle. It is up to you though, there are advantages and disadvantages to doing it that way.

One thing I would mention, though, is you may want to have lists of components within entities seperate from others, rather than having a single super list. Behind the scenes, you can still store the components in one memory pool, but you should probably think about supporting it. Passing the list of the parent object into the constructor of each component is really quite powerful. You could do something like:

```
MyComponent::MyComponent(ComponentList parentContainer)
{
    //we check whether another component exists in the container.
    //in this way we can have dependencies on components
    //without grouping together unnecessary functionality
    //for instance, you may want a renderable to require a graphics core component
}

```
> 3 votes

---
Tags: c++, entity-system
---


title: Kinect for Windows Commercial License

text:
# Question
Title: Kinect for Windows Commercial License
Kinect for Windows SDK 1.6 is available for users to download. What I enquire is: Can I publish a commercial game with it? Do I have to apply for anything?

I've searched through the Microsoft's Kinect documentation about the subject but failed to find the information I'm looking for. It is impossible to publish a game for XBOX using Kinect, I know that. But what about Windows?

# Answer
Probably even if you wanted to make games for IOS, Microsoft/Bill Gates would not get upset as those apps require the Kinect Sensor which they produce... But from what I've read kinect is also available for Windows applications as the Kinect for Windows, it is about 20% more expensive but it is legal to use it on your pc. You can make any application you want. But you are not allowed to encourage people to use the Xbox Kinect sensor on your Windows apps, instead they should require a Windows Kinect sensor. http://www.microsoft.com/en-us/kinectforwindows/purchase/

http://www.microsoft.com/en-us/kinectforwindows/develop/sdk-eula.aspx

Paragraph 1) b. of the end user license agreement has the answer to your question.

> Restricted Use with the Kinect for Xbox 360 Sensor. The Kinect for Xbox 360 sensor is sold subject to the terms of a Limited Warranty and Software License Agreement that permits use of the device solely in connection with an Xbox 360 or Xbox 360 S console. Notwithstanding this restriction in the Kinect for Xbox 360 sensor Limited Warranty and Software License Agreement, you may use an unmodified Kinect for Xbox 360 sensor to assist in the design, development, and testing of your Kinect for Windows Applications, subject to the terms and conditions of this agreement. All of the other terms of the Kinect for Xbox 360 Limited Warranty and Software License Agreement remain unchanged. You agree that end users of Kinect for Windows Applications are not licensed to use Kinect for Xbox 360 sensors in connection with such Kinect for Windows Applications, and that you and your distributors will not directly or indirectly assist, encourage, or enable Kinect for Windows Application end users to do so.

You can: 1) Make apps both for Windows and Xbox.

2) Keep in mind that the Windows apps require a Windows Kinect sensor, and Xbox applications require an Xbox Kinect sensor. If you make apps for Windows Kinect you will need the Windows Kinect sensor, otherwise your SDK might make some problems.

3) Go to http://www.microsoft.com/en-us/kinectforwindows/ and download Kinect for Windows SDK 1.7 as there is a newer version - FREE
> 1 votes

# Answer
The Kinect for Windows runtime versions 1.0, 1.5, 1.6, and 1.7, allow you to develop commercial applications. Check the licensing documents for any specific terms, the legacy SDK did not allow you to develop commercial applications.

Be aware that the Windows runtime versions do not support the Kinect for Xbox 360 device.

You can find the specific information I'm referencing in the Kinect FAQ under the heading

> "What are the guidelines for using Kinect for Windows sensors for development and deployment?"
> 1 votes

---
Tags: windows, licensing, kinect
---


title: Creating a 2D perspective in 3D game

text:
# Question
Title: Creating a 2D perspective in 3D game
I'm new to XNA and 3D game development in general.

I'm creating a puzzle game kind of similar to tetris, built with blocks. I decided to build the game in 3D since I can do some cool animations and transitions when using 3D blocks with physics etc.

However, I really do want the game to look "2D". My blocks are made up of 3D models, but I don't want that to be visible when they're not animating.

I have followed some XNA tutorials and set up my scene like this:

```
this.view = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
            this.aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
            this.projection = Matrix.CreatePerspectiveFieldOfView(
                        MathHelper.ToRadians(45.0f), aspectRatio,
                        1.0f, 10000.0f);

```

... and it gives me a very 3D-ish look. For example, the blocks in the center of the screen looks exactly how I want them, but closer to the edges of the screen I can see the rotation and sides of them.

My guess is that I'm not after a perspective field of view, but any help on which field of view/settings to use to get a "flat" look when the blocks aren't rotated would be great!

# Answer
In your supplied code, notice that you use the following to create your projection:

this.projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f);

The first value is your field of view, in this case, 45 degrees. You can modify this value to be something that gives you what you're looking for. The documentation is here.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.matrix.createperspectivefieldofview.aspx

If you want a truly 2D effect, you'll will need to set your projection to orthographic using CreateOrthographic. You mention that you want something that still shows "some depth", in which case you might have more luck with CreateOrthographicOffCenter in which your camera is off to one side (perhaps try altering your left and right values by a 0.2 offset.)

http://msdn.microsoft.com/en-us/library/bb195659.aspx
> 1 votes

# Answer
I guess you are looking for Orthographic projections. I don't know about XNA in detail, but this link could be a starting point.
> 1 votes

---
Tags: xna, graphics, camera, matrix, perspective
---


# Question
Title: Loading images in XNA 4.0; "Cannot Open File" Problems
Okay, I'm writing a game in C#/XNA 4.0 and am utterly stumped at my current juncture: Sprite animation. I understand how it works and have all the code in place, but my ContentLoader won't open my file...

Basically, my directory looks like this:

```
    //WindowsGame1
      - "Game1.cs"
      - //Classes
          - "NPC.cs"
      - Content Reference
          - //Images
              - "Monster.png"

```

Inside my NPC class, I have all the essential drawing functions, i.e. LoadContent, Draw, Update. And I can get the game to find the correct file and attempt to open it, but when it tries, it throws an exception and tells me it can't open the file. This is how my code in my NPC class looks:

```
    Texture2D NPCImage;
    Vector2 NPCPosition;
    Animation NPCAnimation = new Animation();

    public void Initialize()
    {
        NPCAnimation.Initialize(NPCPosition, new Vector2(4, 4));
    }

    public void LoadContent(ContentManager Content)
    {
        NPCImage = Content.Load<Texture2D>("_InsertImageFilePathHere_");
        NPCAnimation.AnimationImage = NPCImage;
    }

```

The rest of the code is irrelevant at this point because I can't even get the image to load. I think it might have to do with a directory problem, but I also know little to nothing about spriting or working with images or animations in my code. Any help is appreciated. Not sure if I provided enough information here, so let me know if more is needed! Also, what would be the correct way to direct that Content.Load to Monster.png given the current directory situation? Right now I just have it using the full path from the C:// drive. Thanks in advance!

# Answer
> 1 votes
Make sure you include the path to the image (relative to the content folder) and do not include ".png" XNA will convert the .png to a .xnb (XNA binary) as part of the content pipeline, so you don't want to reference the .png portion of the file in your code.

On rare occasions I've also seen people with problems because of their PNG was corrupt. If the above doesn't fix the problem, try another png file... something simple you find from a quick google search.

---
Tags: xna, c#, xna-4.0, animation, sprites
---


# Question
Title: Effective way to check if an Entity/Player enters a region/trigger
I was wondering how multiplayer games detect if you enter a special region. Let's assume there is a huge map that is so big that simply checking it would become a huge performance issue.

I've seen bukkit (a modding API for Minecraft servers) firing an Event on every single move. I don't think that larger games do the same because even if you have only a few coordinates you are interested in, you have to loop through a few trigger zone to see if the player is inside your region - for every player. This seems like an extremely CPU-intense operation to me even though I've never developed something like that.

Is there a special algorithm that is used by larger games to accomplish this? The only thing I could imagine is to split up the world into multiple parts and to register the event not on the movement itself but on all the parts that are covered by your area and only check for areas that are registered in the current part.

And another thing I would like to know: How could you detect when someone must have entered a trigger but you never saw him directly in it since his client only sent you an move packet shortly before entering and after leaving the trigger area. Drawing a line and calculate all colliding parts seems rather CPU intensive if you have to perform it every time.

# Answer
This is just another category of collision detection. Your server needs to be able to tell if two bounding shapes are colliding for any number of reasons and this needs to be efficient; there are many ways to achieve this. The world is then capable of having thousands of entities (including triggers) and information about which ones are currently in contact are cheaply calculated. Then idea you mention is a very rudimentary form of *spatial partitioning*. More complicated and dynamic methods such as *kd-trees*, *bsp trees*, *octrees*, *spatial hashiing* and *dynamic bounding volume hierarchies* are typically used in real games.

Games like Minecraft use a form of fixed-size chunks that act somewhat like a spatial hash. In Bukkit, presumably it limits checks to chunks - if you are in chunk `(1,4)` and a trigger covers chunks `(19,45)`-`(21,47)` then there is obviously no need to even consider testing your avatar against the trigger. The game will only compare your avatar to triggers that it already knows coincide with the chunk you're in. I think this is what you said your idea was, though it's hard to tell exactly what you meant.

The case of a player entering and leaving a trigger area in one update cycle doesn't really happen. The server uses *discrete* updates in most cases, meaning that it looks at the player's position at specific time intervals. In the general case, it checks the position after each movement. The player is simply not allowed to move fast enough - nor are triggers allowed to be small enough - that the player is able to enter and leave a trigger with a single position update.

In Minecraft again, assuming we cared about triggers as small as a single block, the player is simple not capable of moving by a whole block or more in a single iteration of the game's physics cycle. More generally, entities can only move at a smallish fraction of the block size per update cycle. Mechanics like pistons can break these rules but then there are a lot of potential bugs with such mechanics. The game can also special-case some updates or use a smaller update cycle than normal (e.g., if the player moves 1 whole block at a time, the game checks the player's original position, the ending position, and position halfway between).

More generally, especially for MMOS and even an increasing number of action games, the client does not send position updates to the server. The client sends input commands to the server such as "move forward." The server then calculates the player's new position, does whatever post-movement checks are necessary, and then sends the result back to the client. The client may have also processed the move (to hide network latency and make the game feel smoother) so the client is then responsible for *lag compensation* and *prediction correction*, handling any discrepancies in its predicted movement and the server authoritative movement its received afterward.
> 4 votes

# Answer
A method I use for dividing scenes up, is to create a zone, which is essentially just an invisible cube, within this cube you can have sub-zones which are children to the parent zone. Depending on the environment you are rendering, you can optimize in relation to how you partition your world with these zones.

If you have an internal environment, you can make the building a parent zone, each room a zone and then create a portal in the doorway of each zone. Essentially, the portal checks to see if it is within your view volume and if so, renders the geometry on the other side of the portal. If you have several doorways in view, this means you can see each portal, and the contents of each room rendered visibly, but this is a local optimization, however this does relate.

In an external environment, you can register the players within zones and the players that are visible and of immediate effect to them. Once they enter this zone, the agents and players visible to the player are of high priority, so you prioritize the amount of data you process in relation to their actions over agents and players of a greater distance (or not at all if they are in a separate zone).

A quick method is a AABB collision detection with the zone, or use four points(like you're catching them in a net) and do your localized data streaming for that area as previously mentioned.

You do not need to fire an event constantly to check if they have left/entered a zone, as it is network based, you can check against child objects in the zone after so much movement has been detected, in relation to the size of the environment and then increase your checks as they draw closer to the zone limits, but this only works if zones are connected.

If you have "layers" of zone sizes, you can quickly isolate the location of an agent or player, then recursively traverse the relevant zones that are contained within each other, to find the player. This saves you traversing all zones in the environment to find them, and you can do checks in relation to what you need. If you need their rough location, find a "top layer" zone, one of the largest, but if you need their exact location, traverse down to the "bottom layer" zones, that pin point them in relation to objects.

So:

1. Register player location in zone, check zone verts, approximate player location in relation to objects (cache data, only upate if change occurs), you now have cached data you can use to locate/reference.
2. Traverse zone tree starting from top, checking if depth of information is enough(do we need their rough location in an area, or their exact transform, acceleration and velocity), traverse tree.
3. Register other players in zone, reference those from primarily player, prioritize data packet size over closer players, approximate players further away, ignore external zones (or high approximation depending on environment)
4. Do other checking here(this will validate what information we need). Check player location in relation to objects (are we leaving the zone?) if not, 2, else 1.
> 2 votes

# Answer
What you are looking for is called collision detection, and there are a ton of solutions to this.

First off, collision detect can sometimes be built into a physics engine. But it can also be its own separate system often referred to as a collision layer. A game can have multiple layers so some object sets only collide with other object sets.

Collision detection is often a multistep processes, especially objects are irregularly shaped polygons. Here are two decent articles over collision detection: http://www.gamasutra.com/view/feature/3190/advanced\_collision\_detection\_.php http://www.wildbunny.co.uk/blog/2011/04/20/collision-detection-for-dummies/

To sum them, up collision detection can be separated into two main steps, rough and fine. Rough is where each object has a radius equal to the distance from the center to the farthest point. Then distance is calculated between two object centers. If that distance is less than their two radii, then the objects may be colliding. This is a very simple calculation, and for some applications is enough. After rough collision, fine collision is calculated. There are many algorithms used for fine collision and they are a trade off between speed and accuracy. Some games, like physic puzzles, require extremely accurate collisions, but others may sacrifice some accuracy for speed. Some fine collision calculations include:

1. More circles. Place small circles on each point around the border of the object and then calculate distance again.
2. Overlap. There are multiple ways to calculate overlap, and if two polygons are overlapping then they are colliding.
3. Penetration depth. Some engines might not care about the exact moment when the objects collide, but how far they collide with each other.

Now calculating collision between every object every frame gets expensive fast. Often objects are grouped together to trim down the number of calculations. (Two objects far apart are not colliding and don't need to be checked.) The most common method for grouping is using a quadtree for 2D or octtree for 3D. This involves separating the game space into sub regions, placing all of the objects in those regions. The sub regions may be further subdivided based on the quadtree implementation. Then collision is only checked between objects in a particular region and possibly adjacent regions. This vastly reduces the number of needed calculations. Check out this article about quadtrees and collision: http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space/

If you decide to use a framework for you game (XNA, Lbigdx, Unity, etc) you might be able to use their collision system. This can be a deciding factor on what framework to use, as some are better than others at collision. If you are writing a game from scratch then there are many libraries than can be imported to do collision detection. Box2D has implementations in most languages, and is a decent choice for both collision and physics.
> 1 votes

---
Tags: movement, events, entity
---


title: Jumping with a player Matrix

text:
# Question
Title: Jumping with a player Matrix
My players position is stored in a world matrix and I want to make him jump. Can I do this just by creating a translation from the matrix? I want the player to be able to jump while moving in a direction also. I've looked on google but didn't find any tutorials on jumping with a matrix

# Answer
> 2 votes
Simply adding or removing a vector to the translation will be insufficient on its own. You don't want to press jump and then instantly be 10 pixels higher.

You need to apply some very basic form of physics. At the simplest, you can use *velocity* and nothing else. When the player jumps, add a decent upward velocity, say `(0,10,0)`. This velocity is in *units/second*. That is, each frame, take the elapsed time `dt` and multiply it with the velocity to get a change in position, e.g.

```
velocity = (0,10,0)
dt = 1/60 // whatever your frame time is if you're not using a fixed timestep
position = dt * velocity

```

You can then set the velocity back to a negative amount after detecting that some fixed amount of time has passed or that a certain height has been achieved in the jump. Set it back to zero once the player contacts the ground.

Having only velocity will give you linear movement. It will look "wrong" and feel bad to players. To make it "right," you need to include some form of acceleration, which will make the player's movement have more "curve" to it (this is all in terms of continuity, curvature, and other topics you would have learned in Calculus I). Velocity is the first derivative with respect to time of position. Acceleration is the first derivative with respect to time of velocity, and hence the second derivative of position with respect to time.

The simplest form of acceleration to use is to just add gravity. Each frame, before applying velocity to position, first apply acceleration using much the same formula. Let's say that the best gravity for your game is `(0,-10,0)`

```
gravity = (0,-10,0)
velocity += dt * gravity;
position += dt * velocity;

```

Note that this is a very simplistic form of *Euler numeric integration*. You may want to use a better (and more complex) form of integration in your game, though the simple methods works perfectly fine for many.

Now you jump and get that initial high upward velocity. The player shoots upward but slows down automatically, eventually falling back downward. Zero out the vertical velocity while in contact with the floor.

Another benefit of gravity is that it makes falling automatic and smooth. If a player walks off a ledge he'll accelerate downward until landing. You can use the magnitude of the velocity when landing to determine damage from falling, too, if that's part of your game.

This jumping will still not feel super smooth. Getting really good jumping requires acceleration when going upward and lots of other small tweaks to "feel right." It's somewhat common to want to apply a constant upward velocity for a small amount of time (unaffected by gravity) before letting gravity kick in to feel better. Getting a "perfect jump feel" can be somewhat difficult and depends on your specific game.

You can do further from just acceleration and model force or even impulses as well. These are typically less useful for standard platformers, though.

Note that horizontal movement can benefit from velocity and acceleration as well. It can feel a bit nicer and more "Mario-like" if the player accelerates to and from rest when moving horizontally, giving a very slight slide effect when stopping and a very small "start" effect when starting to move. In these cases, you'll want to model horizontal movement with a velocity (which is capped at your maximum horizontal speed), an acceleration from input (+/-X for right/left respectively), and a *damping* effect to remove horizontal movement over time. For example,

```
damping = 0.1
velocity.x -= velocity.x * damping * dt
velocity += acceleration * dt
clamp(velocity.x, -max_speed, +max_speed)

```

That formula removes 1/10th of the horizontal velocity every second. You can play with the numbers to find the right values for your game.

# Answer
> 0 votes
The world matrix is just a convenient way to store position and orientation. Within the matrix will be your x,y,z translation values (distance from the origin).

You really have two options when it comes to jumping:

1) Use or create a physics system in which you have velocity and acceleration values. Your position (stored in the world matrix) is modified by those values for each physics update. To initiate a jump, provide an initial velocity in the Y direction, which will eventually be overcome by acceleration due to gravity in the -Y direction. A simple psuedo-code would look something like this:

On Update: velocity += (acceleration * timeStep); position += (velocity * timeStep);

In each of these cases you can use a translation matrix to store your positions (or you can just use a Vector3).

But this means you have to know when to stop jumping (as in, the player has collided with the floor). Assuming there are no other objects in the game, a simple solution is to limit prevent the y-value from going below zero. As in:

if (position.y \< 0) position.y = 0;

Anything beyond this simple example, you'll need to start thinking about using a more robust physics engine.

2) A second really simple solution to the jump problem is to just create a second matrix that is a "jump offset". During the "jump" have the offset move from 0 to jumpHeight and back to 0. You could even do this using a SIN value if you wanted something that looked more fluid. Your calculated position will always be:

realPosition.Y = groundPosition.Y + jumpOffset;

Or if you're instead using matrices, you'll write something like:

playerTransform = playerMatrix * jumpOffsetMatrix;

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


# Question
Title: Cocos2d sprite's parent not reflecting true scale value
I am encountering issues with determining a CCSprite's parent node's scale value.

In my game I have a class that extends CCLayer and scales itself based on game triggers. Certain child sprites of this CCLayer have mathematical calculations that become inaccurate once I scale the parent CCLayer. For instance, I have a tank sprite that needs to determine its firing point within the parent node.

Whenever I scale the layer and ask the layer for its scale values, they are accurate. However, when I poll the sprites contained within the layer for their parent's scale values, they always appear as one.

```
// From within the sprite
CCLOG(@"ChildSprite-> Parent's scale values are scaleX: %f, scaleY: %f",
      self.parent.scaleX, self.parent.scaleY); // Outputs 1.0,1.0

// From within the layer
CCLOG(@"Layer-> ScaleX : %f, ScaleY: %f , SCALE: %f",
      self.scaleX, self.scaleY,     self.scale); // Output is 0.80,0.80

```

Could anyone explain to me why this is the case? I don't understand why these values are different. Maybe I don't understand the inner design of Cocos2d fully. Any help is appreciated.

# Answer
Going to answer my own question... This is the code I am using to insert a sprite into the layer

```
EarthTank * earthTank = [[EarthTank alloc] initWithWorld:self->world
atLocation:spawnPointRight withID:pid];
earthTank.tankShaft = shaft;
[earthTank createInitialArsenal:tempPlayer];
[earthTank addAndAlignTankShaft];
[spriteBatchNode addChild:earthTank z:2];

```

So the problem is self.parent (called within sprite) references the SpriteBatchNode and not the layer itself. If you change the call to self.parent.parent you can find the Layer's true scale values.

Moral of the story: If you use a spriteBatchNode the parent of a sprite is not the layer, but the spriteBatchNode.
> 0 votes

# Answer
I believe this is related to the scene graph and parent/child relations. As the child's transformation matrices are computed against the parent, the parent is the world origin of transformation.

The child is perceiving up the scene graph tree as an individual node, they see the parent as a transform reference and if the parent is always uniformly scaled, as this is their world transform.

Try experimenting with non-uniform scale values of the parent and see how this is reflected from the child's perspective. From this you can create a scaling percentage offset that the child can use in it's own calculations(You can't extract the exact location, but you can extract the offset from the world origin of the parent).
> 0 votes

---
Tags: cocos2d, objective-c
---


# Question
Title: Scripting a sophisticated RTS AI with Lua
I'm planning to develop a somewhat sophisticated RTS AI (eg see BWAPI). have experience programming, but none in game development, so it seems easiest to start by scripting the AI of an existing game I've played, Warhammer 40k: Dawn of War (2004). As far as I can tell, the game AI is scripted with some variant of Lua (by the file extension .ai or .scar). The online documentation is sparse and the community isn't active anymore.

I'd like to get some idea of the difficulty of this undertaking. Is it practical with a scripting language like Lua to develop a RTS AI that includes FSMs, decision trees, case-based reasoning, and transposition tables?

If someone has any experience scripting Dawn of War, that would also help.

# Answer
> 4 votes
LUA would work fine for programming an AI.

Here is a basic article over making a FSM in LUA

http://lua-users.org/wiki/FiniteStateMachine

Here is a basic set of classes to make a desicion tree in LUA

http://gamecode4.googlecode.com/svn/trunk/Assets/Scripts/DecisionTreeBrain.lua

LUA overall is an extremely powerful language. Any scripting language would have the ability to program an AI.

---
Tags: ai, scripting, lua
---


# Question
Title: Should I make the Cells in a Tiledmap as null when my player hits it
I am making a Tile Based game using Libgdx. I took the idea from SuperKoalio platformer demo by Mario Zencher. When I wanted to implement Collectables in my game , I simply draw the coins using Tiled Map Editor. When my player hits that, I use to set that cell as null.

Someday on this site suggested me not to do so... never use null. I agreed. What can be any other way. If I am using layer.setCell(x,y) to set the cell to any other cell... even if an transparent one .. my player seems to be stopped by an invisible object/hurdle.

This is my code:

```
for (Rectangle tile : tiles)
                {
                    if (koalaRect.overlaps(tile))
                    {
                        TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(1);
                        try{
                            type = layer.getCell((int) tile.x, (int) tile.y).getTile().getProperties().get("tileType").toString();
                            }
                            catch(Exception e){
                                System.out.print("Exception in Tiles Property"+e);
                                type="nonbreakable";
                            }

                        //Let us destroy this cell
                        if(("award".equals(type))){
                        layer.setCell((int) tile.x, (int) tile.y, null);
                        listener.coin();
                        score+=100;
                        test = ""+layer.getCell(0, 0).getTile().getProperties().get("tileType");
                        }

                        //DOING THIS GIVES A BAD EFFECT
                        if(("killer".equals(type))){
                            //player.health--;
                            //layer.setCell((int) tile.x, (int) tile.y, layer.getCell(20,0));
                        }

                        // we actually reset the player y-position here
                        // so it is just below/above the tile we collided with
                        // this removes bouncing :)
                        if (player.velocity.y > 0)
                        {
                            player.position.y = (tile.y - Player.height);

                        }

```

Is this a right approach? OR I should create separate Sprite Class called Coin.

# Answer
> 1 votes
You should create a separate Sprite class for Coin. You don't necessarily have to do this, but it will make it much easier to create other collectables, or over other kinds of tiles, whereas it sounds like the way you are doing it now, you will have to create a different tile whenever the terrain changes, such as coin-over-grass, coin-over-sand etc.

Your tiles will now have a member, that is a reference, which tracks what kind of collectible is on it, if any. It will be a reference to a collectable, which could be a Coin. If there is no collectable, you could set it to `null` or maybe a special NullCollectable singleton.

```
interface Collectable {
    void collectBy(Listener listener);
}

class Coin implements Collectable {
    public void collectBy(Listener listener) {
        listener.coin();
    }
}

class Tile {
    private Collectable collectable;
    public stepOnBy(Listener listener) {
        if (collectable != null) {
            collectable.collectBy(listener);
            collectable = null;
        }
    }
}

```

You may have heard "never use null", but it's important to know the reason behind such statements. The reason is that null forces you to check for null every time you use that type, because not doing so will trigger `NullPointerException`s, which tend to be useless because they often do not show you the source of the problem - where the object became null. People often use null as either a sentinel value or a placeholder for activating default behaviour. A good pattern to use instead is the Null Object Pattern, where you put your default behaviour in a single class and use that instead of null.

For example, instead of checking null in `Tile.stepOnBy()`, I can use a `NothingCollectable` instead:

```
class NothingCollectable implements Collectable {
    private static final NothingCollectable instance = new NothingCollectable();
    public static NothingCollectable getInstance() {
        return instance;
    }
    public void collectBy(Listener listener) {
        // do nothing
    }
}

class Tile {
    private Collectable collectable;
    public stepOnBy(Listener listener) {
        collectable.collectBy(listener);
        collectable = NothingCollectable.getInstance();
    }
}

```

---
Tags: tiles, libgdx, tilemap
---


# Question
Title: Allocating Entities within an Entity System
I'm quite unsure how I should allocate/resemble my entities within my entity system. I have various options, but most of them seem to have cons associated with them. In all cases entities are resembled by an ID (integer), and possibly has a wrapper class associated with it. This wrapper class has methods to add/remove components to/from the entity.

Before I mention the options, here is the basic structure of my entity system:

* Entity
    + An object that describes an object within the game
* Component
    + Used to store data for the entity
* System
    + Contains entities with specific components
    + Used to update entities with specific components
* World
    + Contains entities and systems for the entity system
    + Can create/destroy entites and have systems added/removed from/to it

Here are my options, that I have thought of:

## Option 1:

Do not store the Entity wrapper classes, and just store the next ID/deleted IDs. In other words, entities will be returned by value, like so:

```
Entity entity = world.createEntity();

```

This is much like entityx, except I see some flaws in this design.

## Cons

* There can be duplicate entity wrapper classes (as the copy-ctor has to be implemented, and systems need to contain entities)
* If an Entity is destroyed, the duplicate entity wrapper classes will not have an updated value

## Option 2:

Store the entity wrapper classes within an object pool. i.e. Entities will be return by pointer/reference, like so:

```
Entity& e = world.createEntity();

```

# Cons

* If there is duplicate entities, then when an entity is destroyed, the same entity object may be re-used to allocate another entity.

# Option 3:

Use raw IDs, and forget about the wrapper entity classes. The downfall to this, I think, is the syntax that will be required for it. I'm thinking about doing thisas it seems the most simple & easy to implement it. I'm quite unsure about it, because of the syntax.

i.e. To add a component with this design, it would look like:

```
Entity e = world.createEntity();
world.addComponent<Position>(e, 0, 3);

```

As apposed to this:

```
Entity e = world.createEntity();
e.addComponent<Position>(0, 3);

```

# Cons

* Syntax
* Duplicate IDs

# Answer
Your IDs should be a mixture of *index* and *version*. This will allow you to reuse IDs efficiently, use the ID to quickly find components, and makes your "option 2" much easier to implement (though option 3 can be made much more palatable with some work).

```
struct entity {
  uint16 version;
  /* and other crap that doesn't belong in components */
};

std::vector<entity> pool;
std::vector<uint16> freelist;
typedef uint32 entity_id; /* this shoudl be a wrapper class */

entity_id createEntity()
{
  uint16 index;
  if (!freelist.empty())
  {
    pool.push_back(entity());
    freelist.push_back(pool.size() - 1);
  }
  index = freelist.pop_back();

  return (pool[id].version << 16) | index;
}

void deleteEntity(entity_id id)
{
   uint16 index = id & 0xFFFF;
   ++pool[index].version;
   freelist.push_back(index);
}

entity* getEntity(entity_id id)
{
  uint16 index = id & 0xFFFF;
  uint16 version = id >> 16;
  if (index < pool.size() && pool[index].version == version)
    return &pool[index];
  else
    return NULL;
 }

```

That will allocate a new 32-bit integer which is a combination of a unique index (which is unique amongst all live objects) and a version tag (which will be unique for all objects that ever occupied that index).

When deleting an entity, you increment the version. Now if you have any references to that id floating around, it will no longer have the same version tag as the entity occupying that spot in the pool. Any attempts to call `getEntity` (or a `isEntityValid` or whatever you prefer) will fail. If you allocate a new object at that position the old IDs will still fail.

You can use something like this for your "option 2" to ensure it just works without worries about old entity references. Note that you must *never* store an `entity*` since they might move (`pool.push_back()` could reallocate and move the whole pool!) and only use `entity_id` for long-term references instead. Use `getEntity` to retrieve a faster-to-access object only in local code. You could also use a `std::deque` or similar to avoid pointer invalidation if you wish.

Your "option 3" is a perfectly valid choice. There's nothing inherently wrong with using `world.foo(e)` instead of `e.foo()`, especially since you probably want the reference to `world` anyway and it's not necessarily better (though not necessarily worse) to store that reference in the entity itself.

If you really want the `e.foo()` syntax to stick around, consider a "smart pointer" that handles this for you. Building off the example code I gave up above, you could have something like:

```
class entity_ptr {
  world* _world;
  entity_id _id;

public:
  entity_ptr() : _id(0) { }
  entity_ptr(world& world, entity_id id) : _world(&world), _id(id) { }

  bool empty() const { return _world != NULL && _world->getEntity(_id) != NULL; }
  void clear() { _world = NULL; _id = 0; }
  entity* get() { assert(!empty()); return _world->getEntity(_id); }
  entity* operator->() { return get(); }
  entity& operator*() { return *get(); }
  // add const method where appropriate
};

```

Now you have a way to store a reference to an entity which uses a unique ID and which can use the `->` operator to access the `entity` class (and any method you create on it) quite naturally. The `_world` member could be a singleton or global, too, if you'd prefer.

Your code just uses an `entity_ptr` in place of any other entity references and goes. You could even add automatic reference counting to the class if you'd like (somewhat more reliable if you update all that code to C++11 and use move semantics and rvalue references) so that you can just use `entity_ptr` everywhere and no longer think heavily about references and ownership. Or, and this is what I prefer, make a separate `owning_entity` and `weak_entity` types with only the former managing reference counts so you can use the type system to differentiate between handles that keep an entity alive and those which just reference it until it is destroyed.

Note that the overhead is very low. The bit manipulation is cheap. The extra lookup into pool is not a real cost if you access other fields in `entity` soon after anyway. If your entities are truly just ids and *nothing* else then there might be a bit of extra overhead. Personally, the idea of an ECS where entities are just IDs and nothing else seems a bit... academic to me. There's at least a few flags you'll want to store on the general entity, and larger games will probably want a collection of the entity's components of some kind (inlined linked list if nothing else) for tools and serialization support.

As a rather final note, I intentionally did not initialize `entity::version`. It doesn't matter. No matter what the initial version is, so long as we increment it each time we're fine. If it ends up close to `2^16` then it'll just wrap around. If you end up wrapping around in ways that make old IDs stay valid, switch to larger versions (and 64-bit IDs if you need). To be safe, you should probably clear out entity\_ptr any time you check it and it is empty. You could make `empty()` do this for you with a mutable `_world_` and `_id`, just be careful with threading.
> 13 votes

# Answer
I'm actually working on something similiar right now, and have been using a solution that's closest to your number 1.

I have `EntityHandle` instances returned from the `World`. Each `EntityHandle` has a pointer to the `World` (in my case, I just call it `EntityManager`), and the data manipulation/retrieval methods in the `EntityHandle` are actually calls to the `World`: e.g. to add a `Component` to an entity, you can call `EntityHandle.addComponent(component)`, which will in turn call `World.addComponent(this, component)`.

This way the `Entity` wrapper classes are not stored, and you avoid the extra overhead in syntax you'd get with your option 3. It also avoids the issue of "If an Entity is destroyed, the duplicate entity wrapper classes will not have an updated value", because they all point to the same data.
> 0 votes

---
Tags: c++, architecture, entity-system, oop
---


# Question
Title: What are the pro/cons of Unity3D as a choice to make games?
We are doing our school project with Unity3d, since they were using Shiva the previous year (which seems horrible to me), and I wanted to know your point of view for this tool.

Pros:

* multi platform, I even heard Google is going to implement it in Chrome
* everything you need is here
* scripting languages makes it a good choice for people who are not programming gurus

Cons:

* multiplayer ?
* proprietary, you are totally dependent of unity and its limit and can't extend it
* it's less "making a game from scratch"
* C++ would have been a cool thing

I really think this kind of tool is interesting, but is it worth it to use at school for a project that involves more than 3 programming persons ? What do we really learn in term of programming from using this kind of tool (I'm ok with python and js, but I hate C#) ? We could have use Ogre instead, even if we were learning direct x starting january...

# Answer
The main "pro" of Uinty3D is that it's crazy fast. I'm not talking about performance here, but about development speed. You have:

* Unified asset pipeline. No need to spend time on resource subsystem at all, no buggy import routines to write and fix: just drop a file into folder, and it works.
* Integrated level editor. No need to spend time on level tools: just get straight to business.
* Great tweaking and debugging support: all your gameplay variables are shown right as you play, and can be changed on the fly too - and all this without writing a single line of code. Pause the game anytime, or step through code one statement at a time.
* Quite comprehesive library of ready-made components. Rendering, sound, physics, controls - a lot of "boilerplate" code is already written.
* Mono as a script host. While one can argue about merits of C# as a language, Mono's base class library offers a wealth of functions. Collections, I/O, multithreading, and insanely expressive LINQ all speed up development considerably.

Also, Unity3d is really good on multiple platforms. Of course, you can't create, say, a windows .exe game and then magically have it "just work" on the iPhone; but Unity gets pretty close to that. What is required is "tweaking" more than "porting".

Of course, in some cases Unity3D is not ideal. Network multiplayer integrated in Unity is OK for some LAN peer-to-peer play, but anything that requires central server pretty much requires you write all network code from scratch. Unity's GUI system is quite quirky and slow, so making complex in-game GUIs is a pain. However, all *other* game GUI systems I've seen are painful too, so Unity's one is not that bad overall.

And, of course, Unity3D is a little less flexible than "game engines" like OGRE, that offer only a library/source code. Its performance is not exactly top-notch, and since you only have a scripting sandbox, you can't use some clever low-level hacks to improve it. For example, if Unity's built-in tree renderer doesn't satisfy you for some reason, you can't write your own one (well, you could, but it would be working through scripts and most probably be too slow and too much hassle). Still, it's possible to do just about anything with Unity so long as you don't mind losing a bit of performance.

The biggest "con" of Unity3D, though, is source control. As already mentioned, Unity's own Asset Server costs a pretty penny. And it sucks, really, really hard. It doesn't even have branching. While Unity3D theoretically supports 3rd-party SCM systems, using them is wrought with peril too. I've seen import settings "magically" change after SVN commit, or all objects' parameters disappear after using Perforce. All these can be worked around, but anyway, Unity3D + Source control = pain.

So, to actually answer your question. I believe Unity3D is one of the best, if not *the* best, choice of game engine for a "little" game. Especially in prototype stage.

That said, if we're talking about an educational project, I' recommend against it. To learn how games work it's better to write one on as low level as possible. Game engines are a great tool; but to use it for maximum gains, it's necessary to understand how they work, and *why* they work that way. And the best way to learn this is write your own game engine - even if it turns out crappy in the end.
> 67 votes

# Answer
I'll start by commenting on your list:

* Scripting is not just a benefit to non-programmers. Being a (good) programmer is more than just knowing a language, it's knowing how to deconstruct problems and think in a particular way. Scripting languages can allow a programmer to leverage those higher-order critical thinking skills in order to produce more powerful, more interesting results in less time than he or she might need to produce equivalent results while also worrying about lower level details that some languages (C++ comes to mind) force into the picture.
* Multiplayer support (or lack thereof) is only an issue one way or another if your project needs it.
* I fail to see how "proprietary" is a con. If this is a school project you're probably not going to want to be spending time hacking on the source of the framework you use, or anything. Besides, DirectX is proprietary too.
* There is absolutely nothing wrong with using higher-level frameworks or tools like Unity. "Making a game from scratch" is a non-achievement -- what exactly do you consider "from scratch?" You're still going to be using somebody else's graphics API. Somebody else's runtime (even C requires a runtime library). "Making a game" is what earns respect, not "making a game without using any useful tools."
* C++ being a "cool" thing is a bit subjective. The language is used very often by professionals in the industry, but probably not for the reasons you would think. As a language, it's starting to show its age and can be extremely cumbersome compared to more modern options. In any cases, languages are just tools and a good programmer should be able to pick up new ones with relative ease.

The big advantage to using Unity for your school project is that it's a high level framework with a lot of infrastructural work already in place for you -- this will allow you to focus on your *game* and not on building a foundation. You have, presumably, a relatively limited window in which to produce this game so the more you can leverage existing tools, the more time you'll have to produce logic or assets that are specific to your game and will make your game look and feel more complete -- there's a learning curve for Unity, but you end up with much more at your disposal much quicker.

A disadvantage is that you're potentially sinking time into learning a specific tool that involves knowledge that *might* not be transferrable, especially if you decide that Unity's workflow and environment just aren't for you and you don't ever want to use it again. Also, Unity doesn't have the most obvious *2D* workflow -- it's very focused on 3D games, which all the overhead in art assets that tends to involve. But I think that, for a school project like you're describing, Unity is a pretty good choice.
> 28 votes

# Answer
One major problem with Unity is the source control. If you're not working in a team this isn't going to matter as much (arguably), but that's pretty likely not going to be the case.

You can use Unity Asset Server, but that requires 1) Unity Pro ($1500), and 2) a per-seat Asset Server License ($500). I'm assuming you can get some kind of educational discount, but it isn't free.

Alternatively, you can use something like SVN with Unity. To properly support it you still need Unity Pro.

You can't really just check a non-pro version of Unity into SVN and expect it to work flawlessly. Their mechanism for binding GUIDs to assets and so forth isn't exactly SCM-safe.

---

Multiplayer functionality is pretty decent, although to be honest I haven't shipped a game with it. In theory you just attach network views to things and tell it what you want to serialize to set up replication properly. From there it's some UI work to connect to other peers and set up. It's mostly peer-to-peer, though. You might be able to do client/server programming running unity in headless mode, but I haven't messed with it. But just getting person A to run around on person B's screen is pretty easy and fast to do.

Also C# is a *positive* as far as I'm concerned. LINQ is super expressive. It has proper exception handling and garbage collection. It has much more modern paradigms like delegates, lambdas, interfaces and better generic support than C++. (*Edit*: this is obviously controversial. My point is that C# is hardly a *bad* language. I don't want to get into a long debate about the pros and cons of the language vs. C++.)

The biggest positive of using Unity, though, is probably the art pipeline. You can take a PSD or Max file (assuming you have 3ds max installed) in the folder and it gets imported.
> 9 votes

# Answer
Update: Unity now provides all of these features even in the free version, so please disregard the answer below.

---

Something worth noting- if you are using the free version of Unity3D you will be unable to use several effects, including post-processing shaders (like bloom) and, much more importantly, dynamic shadows. These obviously will not have much of an effect on the workflow for the project, but they do place constraints on what can be achieved for free with the engine.
> 6 votes

# Answer
Nevermind's answer covers things pretty thoroughly, but just to pitch in on the source control side of things, it's actually not that terrible once you learn to look out for a handful of gotchas:

* First off, yes Asset Server is expensive, and quite horrible for all but basic use. It's major benefit is being integrated into Unity, and while that is valuable for ease of use and worth it on simpler projects, for anything larger (which would typically be the projects with budget for AS) it just isn't flexible enough.
* Moving on to external version control, it's important to realize that Meta Files have to be treated like any other asset and always added to/updated in version control. Not doing this is likely what happened in Nevermind's scenario of settings vanishing.
* Finally, working with any version control system in Unity (including Asset Server), team communication becomes essential when working with binary assets to avoid stomping on each others' work.

In case you want more detail on these points, I posted a while ago on using git with Unity based on my experience on some fairly large Unity projects: http://goo.gl/ivJVR
> 3 votes

# Answer
Actually. Multiplayer is supported. It simply a matter of choosing a server that you want to run your game.

The hot one on the market now is "SmartFox Server" they offer a few different packages, all of which are free (to an extent). It's only free if you plan on having a certain amount of players, as each package allows a certain amount of players for "free".

If you chose to upgrade, the price is pretty steep for an indie developer. So... In the long run, if you have a lot of players on your server than you will have to charge for your game rather than uploading it on sites like Download.com as a free full game. This may not be an issue for some, but most of us can't afford $2,500 out of pocket for a server.

For Example - SmartFox pro allows 20 players for free. If you want to upgrade it will cost you 500 Euros, which is a bit more in US, around 600-700, and that allows for 100 connections.

The next upgrade is for max amount of players of 500, and it is 1000 Euros, but... You don't have to pay the 1000, you pay the difference.

So you will have to pay only 500 more Euros, rather than the whole 1000. The last upgrades supports unlimited amount of connections, for 2,000 Euros. Which is almost $3,000 US.

So if you upgrade from the 500 connections, you pay 1000 Euros, if you upgrade from 100 connections you pay 1,5000 Euros, and of course, 2,000 Euros to upgrade from free.

Also, this server is very easy to setup with Unity and there are numerous tutorial videos of how to do it exactly on Youtube.
> 2 votes

---
Tags: unity
---


# Question
Title: stretch images when window is re-sized in XNA
Is there a way to re-size all the images inside the view port in a XNA project. At the moment when I re-size the view port the background stays at the same size of the image when I want it to re-size, this is the same for the different sprites. I have looked at different sources and I have not been able to find anything that has helped.

# Answer
So effectively what you're illustrating in your question is that when you re size the viewport, all your sprites stay the same size, in the same location. It is imperative that you do not implicitly scale and position sprites with direct positions such as (0, -10) and scales such as (0.3f, 0.3f).

Instead you must take a scaling and positioning offset that is relational to the viewport size and scale. The reason for doing this is when you translate the application to another desktop resolution, the sprites will scale and position relative to this resolution.

A great example of the application of this is building a game on the iPhone and then finding all the sprites and UI break when ported to the iPad.

Position your sprites such as:

```
vec2 objPos = vec2(width*0.5f, height*0.5f);

```

Scale your sprites such as:

```
vec2 objScale = vec2(width*(0.2f*scaleWidthTuning)), height*(0.2f*scaleHeightTuning));

```
> 1 votes

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


# Question
Title: Path Finding for an Arena based map in 3D using NavMesh
I have a 3D arena map (consider a small island surrounded by water on all sides) for a multiplayer Tank fight game. The moveable areas are marked using a Navigation Mesh made by the Arena designer.

My question is what would be the best way for navigation in such an environment ? Specially considering the case when there is a Bridge at the center of the arena and you could walk under it or even above it ?

If suppose the enemy is standing at the top of the Bridge and my AI is at one of the edges of the map ? How can it know whether the enemy is above or below the bridge and how can it navigate till it ?

# Answer
> 1 votes
There is a lot to nav mesh generation, navigation and agent steering. However, it is one of those subjects whereby you decide "how deep the rabbit hole goes", it is an interesting subject and the more you learn from it, the easier it will be for you to implement/hack.

I found these resources helpful and might get you on the right track:

https://en.wikipedia.org/wiki/Johnson%27s\_algorithm \- Check all the pairs of the shortest paths

http://www.red3d.com/cwr/steer/ \- Solutions and concepts on navigation intelligent agents.

http://www.ai-blog.net/archives/000152.html \- Examples and applications of nav meshes and steering.

---
Tags: algorithm, ai, path-finding, 3d-meshes
---


title: How to generate portal zones?

text:
# Question
Title: How to generate portal zones?
I'm developing a portal-based scene manager. Basically all it does is to check the portals against the camera frustum, and render their associated portal zones accordingly. Is there any way my editor can generate portal zones automatically with the user having to set the portals themselves only? For example, the Max Payne 1/2 engine ("Max-FX") only required to set the portal quads, unlike the C4 engine where you also have to explicitly set the portal zones.

# Answer
> 3 votes
It is entirely dependent how you implement and construct your portals in your code, it sounds like you currently rely on the user to physically create a portal from a rectangular shape or poly and transform this into the correct position, which is an editor design consideration.

You can however modify how you verify the placement and use of portals in your code to reflect geometry in your environment and what constitutes as a portal. Say you have a door in an internal environment, within the frame of the door, you can tag the planes of the door frame and check to see if the tagged frames create a loop, then check for a zone on either side of the door. From this, a portal can be automatically generated, but is limited by the shapes of doors.

Define an abstract concept of what a portal is, it is essentially a shape with a location. With this concept, you can create sub-elements that modify the portal concept, but allow more complex definitions, enabling you to portal external environments, but always remember they need defined parameters: a zone either side of the portal and the portal to be a shape and have a transform.

With the data from this concept, now link it to geometry within the environment as I previously mentioned (tagging a door frame to create a loop for example), that automatically generates the portal. The portal will check either side of its faces for the placement of the zone and then add it as a reference within itself, linking it to the frustum culling portion of your code.

If you wish to make it even easier in your editor, you can essentially "paint portals" over doorways, have a widget of a rectangular shape, click over the door frame, it automatically tags the door frame and creates the portal in that shape, that location and references both zones.

---
Tags: c++, 3d, algorithm, optimization, scene
---


# Question
Title: Rotate an image and get back to its original position - opengles glkit
I need to rotate an image in opengles GLkit and get it back to its original position in GLkit.

```
rotation += 5;
_modelViewMatrix = GLKMatrix4Rotate( _modelViewMatrix, GLKMathDegreesToRadians(5), 1, 0, 0);
_modelViewMatrix = GLKMatrix4Rotate( _modelViewMatrix, GLKMathDegreesToRadians(rotation), 1,0,0);

```

I need to move it in x axis for certain amount and getting back to its original position from where it started. How should i do it?

# Answer
> 1 votes
Here's some very crude code to roughly illustrate a potential solution:

```
 if(object.grabStart){
   vec3 startRot = object.transform.rotation;
   object.startRotReference = startRot;
}

rotation += 5;

object.RotateXYZ(rotation,0,0);

if(object.transform.rotation.x >= object.targetRotX)
  object.RotateToStartRot();

```

---
Tags: opengl, iphone, ios, opengl-es, objective-c
---


# Question
Title: Multiplayer in a game. How to design it object wise?
I was suggested on StackOverflow to ask this question here.

I'm working on a simple game and I was thinking of adding multiplayer feature but I'm a bit stuck. I'm not sure what approach should I take, keeping in mind good programming practices.

I have a Player object which is created for each player but then I have many other classes that would have to be able to access them. The thing is, if I initialise them in, let's say my main method, then I can't relate to different instances of player class from other classes. The only solution to my problem that comes to my mind is using some form of global objects but afaik using anything globally in apps is usually not a good practice. Any suggestions/ideas?

# Answer
> 1 votes
You are only presenting a very narrow view on your whole object hierarchy, but usually you have one object, let's call its class GameState, which in turn is a composite of all other objects that are currently found in the game, like the enemies, bullets and players.

---
Tags: java, multiplayer, oop
---


# Question
Title: How would you implement chromatic aberration?
How would you implement the effect of chromatic aberration with shaders?

Would rendering of the world with different focus distances for each color solve the problem (maybe with the usage of only one depth rendering pass)?

# Answer
> 23 votes
Chromatic aberration is caused when a lens can't focus every color to the same focal point. A simple way to fake this effect, and render it as a quick full-screen post-process, is to apply an offset to each color channel in a fragment shader.

By using a different offset for each channel, you can achieve a reasonable facsimile of the desired effect. An example of this technique can be found here; the fragment shader would look something like this:

```
void main () {
    // Previously, you'd have rendered your complete scene into a texture
    // bound to "fullScreenTexture."
    vec4 rValue = texture2D(fullscreenTexture, gl_TexCoords[0] - rOffset);
    vec4 gValue = texture2D(fullscreenTexture, gl_TexCoords[0] - gOffset);
    vec4 bValue = texture2D(fullscreenTexture, gl_TexCoords[0] - bOffset);

    // Combine the offset colors.
    gl_FragColor = vec4(rValue.r, gValue.g, bValue.b, 1.0);
}

```

This simple hack doesn't really take into account the fact that chromatic aberration is a lens effect, though: to get a better simulation, you'd actually want to render something to act as the lens. This is similar to how you render objects that are reflective or refractive. Consequently, a typical reflection/refraction shader can be the basis for implementing chromatic aberration.

Normally, you'd compute a single refraction vector based on a view vector and some defined index of refraction, using GLSL's refract function in a vertex shader:

```
void main () {
    // ...

    // RefractionVector is a varying vec3.
    // 'ratio' is the ratio of the two indices of refraction.
    RefractionVector = refract(incidentVector, normalVector, ratio);

    // ...
}

```

Then you'd use that vector in a fragment shader to perform an cube texture lookup (into an environment map). Typically this is done alongside a reflection effect as well, and combined used a computed Fresnel term.

To simulate chromatic aberration, then, you can perform *three different* refraction vector computations, each one slightly offset via differing indices of refraction, in the vertex shader:

```
void main () {
    // ...

    // RefractionVector is a varying vec3, as above.
    // 'ratioR,' et cetera, is the ratio of indices of refraction for
    // the red, green and blue components respectively.
    RedRefractionVector = refract(incidentVector, normalVector, ratioR);
    GreenRefractionVector = refract(incidentVector, normalVector, ratioG);
    BlueRefractionVector = refract(incidentVector, normalVector, ratioB);

    // ...
}

```

Those three different vectors can be used to perform three different cube map lookups, which can be mixed together similar to how the colors were mixed in the simple example:

```
void main () {
    vec3 color;
    color.r = vec3(textureCube(EnvironmentMap, RedRefractionVector)).r;
    color.g = vec3(textureCube(EnvironmentMap, GreenRefractionVector)).g;
    color.b = vec3(textureCube(EnvironmentMap, BlueRefractionVector)).b;

    gl_FragColor = vec4(color, 1.0);
}

```

For more details, the OpenGL Orange Book is available and contains an example of the basic reflection and refraction effects, as well as an example of the chromatic aberration effect.

---
Tags: opengl
---


title: How to modify VBO data

text:
# Question
Title: How to modify VBO data
I am learning LWJGL so i can start working on my game. In order to learn LWJGL I got the idea to implement the map builder so I can get comfortable with graphics programming. Now, for the map creation tool I need to draw new elements or draw the old one's with different coordinates.

*Let me explain this:*

My game will be a 2D scroller. The map will be consisting of multiple rectangles ( 2 strip triangles). When I click my left-mouse button i want to start the rectangle and when I release it I want to stop the rectangle bottom-right at that position.

As I want to use VBOs I want to know how to modify data inside the VBO based on user input. Should i have a copy of a vertex array and then add the whole array to the VBO at each user input? How is usually implemented the VBO update?

# Answer
> 10 votes
For small data like this, you want glBufferSubData, sweet and simple :)

Later on you probably should look into glMapBuffer though, as it is how you work with data larger than a few kilobytes quickly.

---
Tags: opengl, java, lwjgl, vbo
---


title: Using name of real products in games

text:
# Question
Title: Using name of real products in games
My friend and I are creating a Computer Tycoon game. We're using graphics cards and other real CPUs in the game. So can we use names like GeForce\_210 in the game without issues?

Also, if the above doesn't work, can we just change a little bit in the name like LeForce and will that work?

# Answer
If you change the name, it isn't violating trademark.

The creators of the Simpsons twisted the Apple into a Mapple. Everyone knew it was the parody of Apple. No copyright infridgements.

Rockstar used car models, that were taken from the real world, only to change to logo and the company name. There are cars nearly identical to the ones in real life.

> http://gta.wikia.com/Yakuza\_Stinger

The horror game "Drea D Out" featured an irisphone, which looked like an iphone.

Contact an IP law advisor, that is the only thing you can actually rely on in the matter.

As for the "GEFORCE"\_210, **don't do it, unless you have written permission from the Nvidia corporation**, the word Geforce itself is a trademark. It would be illegal to create a browser named Google-it because it contains the phrase google.
> 2 votes

---
Tags: legal
---


title: Win32 strange exception

text:
# Question
Title: Win32 strange exception
When creating 2500 objects, I get a strange windows exception. It says the operation copmleted successfully at my constructor line. The program doesn't run or anything. I'm assuming it has something to do with memory. Each object has 32 indices and 8 vertices, so that 640,000 bytes or whatever vertices and indices are stored as. Any idea on how to fix this? Creating 25 objects works fine\

```
    System.ComponentModel.Win32Exception was unhandled
    Message=The operation completed successfully
    Source=System.Drawing
    ErrorCode=-2147467259
    NativeErrorCode=0
    StackTrace:
   at System.Drawing.Icon.Initialize(Int32 width, Int32 height)
   at System.Drawing.Icon..ctor(Type type, String resource)
   at Microsoft.Xna.Framework.WindowsGameWindow.GetDefaultIcon()
   at Microsoft.Xna.Framework.WindowsGameWindow..ctor()
   at Microsoft.Xna.Framework.WindowsGameHost..ctor(Game game)
   at Microsoft.Xna.Framework.Game.EnsureHost()
   at Microsoft.Xna.Framework.Game..ctor()
   at Cube_Chaser.Cube..ctor(GraphicsDevice graphicsDevice, Vector3 Position, Color Color) in C:\Users\daj\Desktop\Cube Chaser after removal of cubedrawable - Copy\Cube Chaser\Cube Chaser\Cube.cs:line 31
   at Cube_Chaser.Cube.CreateMap() in C:\Users\user\Desktop\Cube Chaser after removal of cubedrawable - Copy\Cube Chaser\Cube Chaser\Cube.cs:line 247
   at Cube_Chaser.Game1.LoadContent() in C:\Users\daj\Desktop\Cube Chaser after removal of cubedrawable - Copy\Cube Chaser\Cube Chaser\Game1.cs:line 86
   at Microsoft.Xna.Framework.Game.Initialize()
   at Cube_Chaser.Game1.Initialize() in C:\Users\daj\Desktop\Cube Chaser after removal of cubedrawable - Copy\Cube Chaser\Cube Chaser\Game1.cs:line 77
   at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
   at Microsoft.Xna.Framework.Game.Run()
   at Cube_Chaser.Program.Main(String[] args) in C:\Users\user\Desktop\Cube Chaser after removal of cubedrawable - Copy\Cube Chaser\Cube Chaser\Program.cs:line 15
  InnerException:

```

# Answer
By changing my `Cube` class so it did not inherit from `Microsoft.Framework.Xna.Game` I was able to make this work.
> 0 votes

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


# Question
Title: Why does clipping take place after illumination?
Can you explain why clipping takes place after the illumination process in the rendering pipeline? Would it be not cheaper to clip first and do then the illumination?

# Answer
It wouldn't actually be faster, and it would be mean a much more complex pipeline with less control and flexibility over the final image.

Conceptually, clipping creates extra vertices. When you clip a triangle, you end up with a polygon, and that means you'll need at least one extra vertex in order to turn everything into triangles again.

While many lighting computations are done now at the per-pixel level, some per-vertex setup is often necessary or desirable. It is useful to look at what reality would be if you *did* clip before you did any other per-vertex attribute computations needed for eventual per-vertex lighting.

If you were to perform lighting (and other vertex attribute) computations *after* you clipped a triangle, you'd have to have already transformed the position all the way to clip space so you know what and where to clip, and you'd also have to determine values for all attributes of all the new vertices. That means you're going to have to interpolate them, much like varying data is eventually interpolated across the surface of the triangle when fragment shading is performed.

But that means that now you have these extra computations to perform (which you're just going to perform again when you do fragment shading), *and* you have an additional vertex (at least) to run your vertex shader on. So it isn't necessarily true that clipping earlier would be more efficient.

Furthermore, many vertex attributes are specified by hand, and/or may not interpolate well. This is especially true of some of the attributes used to do some of the clever tricks used to make modern effects. That would *significantly* decrease the amount of flexibility available in the graphics pipeline to achieve interesting lighting effects or other such fancy business. Especially so with the modern programmable pipeline. That loss of flexibility would be a huge detriment, optimization or no.

Finally, a somewhat less important issue is that clipping is done in a very unusual coordinate space, and it would be fairly annoying to work in that space all the time (for lighting computations, and whatnot).
> 5 votes

# Answer
Clipping happens after vertex processing, before the pixel processing stage of the graphics pipeline. It has to take place after vertex processing for the trivial reason that clipping needs to know where the vertices are in screen space.

Clipping has nothing in particular to do with illumination. It only takes place after illumination if you do illumination per-vertex. But nowadays, lighting calculations are usually done per-pixel, not per-vertex. Only the pixels within the viewport, i.e. those that survive clipping, will be shaded, so in that case illumination is done after clipping.
> 6 votes

# Answer
It doesn't necessarily do that.

In some models, lighting is per-vertex. The problem is that you can't clip vertices until *after* they're transformed into clip space, since you have absolutely no way to know if a vertex is visible or not (aside from view frustrum clipping, which is not cheap). So you do all per-vertex calculations in one go. Then comes the conversion to clip space where clipping can cheaply and easily be done. Then the clipped triangle is rasterized and the fragment/pixel shader is run.

Many newer rendering pipelines do most or all lighting calculations in the pixel shader, so it actually is done after clipping.

To cut down on the amount of vertex data processed, the application should do some form of culling. Due to the inherent inefficiencies of clipping before hitting clip space, culling is typically by whole objects/meshes. An object which is only partially potentially visible will still have vertex processing done for all its vertices but at least objects which are wholly outside the view frustrum won't be sent to the GPU for processing in the first place.

In simple pseudo-code, the pipeline (including the application-side bits) is something like:

```
for each object:
  if not culled:
    for each vertex:
      run vertex shader
      convert to clip space
    for each triangle in clip space:
      clip triangle // note this is after vertices are processed
      convert to NDC space
      rasterize
    for each fragment of clipped triangles:
      do early depth test
      do early stencil test
      run pixel shader
      do alpha test, depth test, stencil test
      write depth, stencil, and blend outputs

```

Lighting traditionally was done all in vertex shaders because they're much cheaper. A large triangle will have only 3 vertices (maybe more if clipped into a more complex polygon, though most hardware just maps all shapes into multiple trapezoids anyway) but it could have potentially thousands of fragments/pixels (maybe even millions in some cases). Doing the computation in the pixel shader requires significantly more powerful hardware than was available when the classic rendering pipeline was defined.
> 4 votes

---
Tags: graphics, rendering, pipeline, clipping
---


# Question
Title: How to create a rectangle shape in cocos2d-android
I am new to cocos2d-android. I want to create a rectangle shape in the scene .for that i am trying to do something like this.

```
  CGRect rect = CGRect.make(x,y,70,70);

```

But it was not displaying the rectangle so far. could any one help me to do so?

# Answer
> 1 votes
Check out the example file for drawing primitives. You can see an example of drawing a arbitrary polygon there:

```
// closed purple poly
gl.glColor4f(1.0f, 0.0f, 1.0f, 1.0f);
gl.glLineWidth(2);
CCPoint vertices2[] = {CCPoint.ccp(30, 130), CCPoint.ccp(30, 230), CCPoint.ccp(50, 200)};
Primitives.drawPoly(gl, vertices2, 3, true);

```

Just define your rectangle points there.

There are a lot more test examples to be found there that can answer the basic drawing questions like this.

---
Tags: cocos2d
---


title: Can LWJGL support multiple displays

text:
# Question
Title: Can LWJGL support multiple displays
Can LWJGL support multiple displays either as separated windows or as part of an AWT Window?

# Answer
From a bug report about multiple displays in LWJGL:

> This is one of the primary features planned for LWJGL 3.0. You can actually already experiment with multiple windows if you're feeling adventurous and want to try 3.0, see this post for an example.
>
> Do keep in mind that LWJGL 3.0 is at a pre-alpha stage and all APIs may be subject to change.
>
> Closing this issue as there's no plan to implement multiple Displays in LWJGL 2.x.

So, **if you're using version 2.x, no, LWJGL cannot support multiple displays**. While it looks like there might be plans to do so in the future, I wouldn't plan on it for your own game, and I wouldn't start using the alpha for your development either.
> 1 votes

---
Tags: lwjgl
---


# Question
Title: When I shoot from a gun while walking, the bullet is off the center, but when stand still it's fine. (Video Included)
I am making a small project in Unity, and whenever I walk with the gun and shoot at the same time, the bullets seem to curve and shoot off 2-3 CMs from the center. When I stand still this doesn't happen.

This is my main Javascript code:

```
@script RequireComponent(AudioSource);

var projectile : Rigidbody;
var speed = 500;
var ammo = 30;
var fireRate = 0.1;
private var nextFire = 0.0;

function Update() {
    if(Input.GetButton ("Fire1") && Time.time > nextFire) {
        if(ammo != 0) {
            nextFire = Time.time + fireRate;
            var clone = Instantiate(projectile, transform.position, transform.root.rotation);
            clone.velocity = transform.TransformDirection(Vector3 (0, 0, speed));
            ammo = ammo - 1;
            audio.Play();
        } else {

        }
    }
}

```

I assume that these two lines need to be tweaked:

```
var clone = Instantiate(projectile, transform.position, transform.root.rotation);
clone.velocity = transform.TransformDirection(Vector3 (0, 0, speed));

```

I just started Unity, and I might have a difficult time understanding some things.

**EDIT:**

Here is a video - http://www.screenr.com/2pxH

(If there are any more mistakes in my code, feel free to edit it.)

# Answer
> 2 votes
A better way to handle bullets in Unity is have them travel instantaneously through raycasting.

```
var hit : RaycastHit;
if(Physics.Raycast(transform.position, transform.forward, hit)){
    var bullet = Instantiate(projectile, hit.collider.transform.position, transform.root.rotation);
}

```

# Answer
> 4 votes
The issue is that your shooting with the same speed while moving with different speeds.

Imagine you would throw a stone at an angle of 90 degrees to the rails from a moving train. On the train it looks like the stone flies in a straight line from the train, keeping the 90 degrees.

```
 S
 ^
 |
 |
 |
 Train--->

```

An observer standing besides the train sees the stone flying in an angle slightly off the 90 degrees.

```
 O   S
    ^
   |
  |
 |
 Train--->

```

The speed of the train is added to the speed of the flying stone.

This is not what your code is doing. Your bullet always flies at the same speed in the same direction.

The speed of your bullet when firing needs to be its starting speed plus the speed of the player.

This can be done using vectors: Calculate the speed vectors of the player and the bullet and add them to get the correct speed.

You already have the bullet speed vector. So you should be able to do something like this:

```
var bullet_speed = transform.TransformDirection(Vector3 (0, 0, speed));
clone.velocity=bullet_speed + player.velocity;

```

This code snippet is not tested, since I don't have Unity.

# Answer
> 0 votes
the rotation of the projectile might be a little offset from the centre while walking. Try this

```
var clone = Instantiate(projectile, transform.position, Quaternion.identity);

```

---
Tags: unity
---


title: Memory is full with vertex buffer

text:
# Question
Title: Memory is full with vertex buffer
I'm having a pretty strange problem that I didn't think I'd run into. I was able to store a 50x50 grid in one vertex buffer finally, in hopes of better performance. Before I had each cube have an individual vertex buffer and with 4 50x50 grids, this slowed down my game tremendously. But it still ran. With 4 50x50 grids with my new code, that's only 4 vertex buffers. With the 4 vertex buffers, I get a memory error. When I load the game with 1 grid, it takes forever to load and with my previous version, it started up right away. So I don't know if I'm storing chunks wrong or what but it stumped me -.-

Thats how theyre stored. The array I'm reading from is a byte array which defines the coordinates of my map. Now with my old version, I used the same loading from an array so that hasn't changed. The only difference is the one vertex buffer instead of 2500 for a 50x50 grid. cubes is just a normal list that holds all my cubes for the vertex buffer.

Another thing that just came to mind would be my draw calls. If I'm setting an effect for each cube in my cube list, that's probably going to take a lot of memory. How can I avoid doing this? I need the foreach method to set my cubes to the right position

As requested, here's my entire cube class plus the draw method within my main class

```
    public class Cube
{
    BasicEffect effect;
    Texture2D grass;
    Texture2D texture;

    public GraphicsDevice device;

    VertexBuffer vertexBuffer;
    IndexBuffer indexBuffer;

    List<VertexPositionTexture> vertices = new List<VertexPositionTexture>();
    List<short> indices = new List<short>();

    public Vector3 cubePosition { get; set; }

    public List<Cube> cubes = new List<Cube>();

    public int no;

    public Cube(GraphicsDevice graphicsDevice, Vector3 Position, Texture2D Texture)
    {
        device = graphicsDevice;
        Texture = grass ;
        cubePosition = Position;

        effect = new BasicEffect(device);
    }

    public void Draw(BasicEffect effect)
    {
        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            no++;
            pass.Apply();
            device.SetVertexBuffer(vertexBuffer);
            device.Indices = indexBuffer;
            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 12);
        }
    }

    private void SetUpIndices()
    {
        //Front face
        //bottom right triangle
        indices.Add(0);
        indices.Add(2);
        indices.Add(3);

        indices.Add(0);
        indices.Add(1);
        indices.Add(2);

        indices.Add(1);
        indices.Add(5);
        indices.Add(6);

        indices.Add(1);
        indices.Add(6);
        indices.Add(2);

        indices.Add(2);
        indices.Add(6);
        indices.Add(7);

        indices.Add(2);
        indices.Add(7);
        indices.Add(3);

        indices.Add(4);
        indices.Add(7);
        indices.Add(6);

        indices.Add(4);
        indices.Add(6);
        indices.Add(5);

        indices.Add(1);
        indices.Add(4);
        indices.Add(5);

        indices.Add(1);
        indices.Add(0);
        indices.Add(4);

        indices.Add(0);
        indices.Add(7);
        indices.Add(4);

        indices.Add(0);
        indices.Add(3);
        indices.Add(7);
        #region IndicesArray
        /*indicesArray[0] = 0;
        indices[1] = 2;
        indices[2] = 3;
        //top left triangle
        indices[3] = 0;
        indices[4] = 1;
        indices[5] = 2;
        //back face
        //bottom right triangle
        indices[6] = 1;
        indices[7] = 5;
        indices[8] = 6;
        //top left triangle
        indices[9] = 1;
        indices[10] = 6;
        indices[11] = 2;
        //Top face
        //bottom right triangle
        indices[12] = 2;
        indices[13] = 6;
        indices[14] = 7;
        //top left triangle
        indices[15] = 2;
        indices[16] = 7;
        indices[17] = 3;
        //bottom face
        //bottom right triangle
        indices[18] = 4;
        indices[19] = 7;
        indices[20] = 6;
        //top left triangle
        indices[21] = 4;
        indices[22] = 6;
        indices[23] = 5;
        //left face
        //bottom right triangle
        indices[24] = 1;
        indices[25] = 4;
        indices[26] = 5;
        //top left triangle
        indices[27] = 1;
        indices[28] = 0;
        indices[29] = 4;
        //right face
        //bottom right triangle
        indices[30] = 0;
        indices[31] = 7;
        indices[32] = 4;
        //top left triangle
        indices[33] = 0;
        indices[34] = 3;
        indices[35] = 7;
        */
        #endregion IndicesArray

    }

    private void SetUpVertices()
    {
        #region VPNormalTexture
        /*
        //front left bottom corner
        vertices.Add(new VertexPositionNormalTexture(new Vector3(0, 0, 0), new Vector3(0, 0, 0), new Vector2(1, 0)));
        //front left upper corner
        vertices.Add(new VertexPositionNormalTexture(new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector2(0, 0)));
        //front right upper corner
        vertices.Add(new VertexPositionNormalTexture(new Vector3(1, 1, 0), new Vector3(1, 1, 0), new Vector2(0, 1)));
        //front lower right corner
        vertices.Add(new VertexPositionNormalTexture(new Vector3(1, 0, 0), new Vector3(1, 0, 0), new Vector2(1, 1)));
        //back left lower corner
        vertices.Add(new VertexPositionNormalTexture(new Vector3(0, 0, -1), new Vector3(0, 0, -1), new Vector2(1, 0)));
        //back left upper corner
        vertices.Add(new VertexPositionNormalTexture(new Vector3(0, 1, -1), new Vector3(0, 1, -1), new Vector2(0, 0)));
        //back right upper corner
        vertices.Add(new VertexPositionNormalTexture(new Vector3(1, 1, -1), new Vector3(1, 1, -1), new Vector2(0, 1)));
        //back right lower corner
        vertices.Add(new VertexPositionNormalTexture(new Vector3(1, 0, -1), new Vector3(1, 0, -1), new Vector2(1, 1)));
        */
        #endregion VPNormalTexture
        //front left bottom corner
        vertices.Add(new VertexPositionTexture(new Vector3(0, 0, 0), new Vector2(1, 0)));
        //front left upper corner
        vertices.Add(new VertexPositionTexture(new Vector3(0, 1, 0), new Vector2(0, 0)));
        //front right upper corner
        vertices.Add(new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(0, 1)));
        //front lower right corner
        vertices.Add(new VertexPositionTexture(new Vector3(1, 0, 0), new Vector2(1, 1)));
        //back left lower corner
        vertices.Add(new VertexPositionTexture(new Vector3(0, 0, -1), new Vector2(1, 0)));
        //back left upper corner
        vertices.Add(new VertexPositionTexture(new Vector3(0, 1, -1), new Vector2(0, 0)));
        //back right upper corner
        vertices.Add(new VertexPositionTexture(new Vector3(1, 1, -1), new Vector2(0, 1)));
        //back right lower corner
        vertices.Add(new VertexPositionTexture(new Vector3(1, 0, -1), new Vector2(1, 1)));
        #region VPColor
        /*
        //front left bottom corner
        vertices.Add(new VertexPositionColor(new Vector3(0, 0, 0), color));
        //front left upper corner
        vertices.Add(new VertexPositionColor(new Vector3(0, 1, 0), color));
        //front right upper corner
        vertices.Add(new VertexPositionColor(new Vector3(1, 1, 0), color));
        //front lower right corner
        vertices.Add(new VertexPositionColor(new Vector3(1, 0, 0), color));
        //back left lower corner
        vertices.Add(new VertexPositionColor(new Vector3(0, 0, -1), color));
        //back left upper corner
        vertices.Add(new VertexPositionColor(new Vector3(0, 1, -1), color));
        //back right upper corner
        vertices.Add(new VertexPositionColor(new Vector3(1, 1, -1), color));
        //back right lower corner
        vertices.Add(new VertexPositionColor(new Vector3(1, 0, -1), color));
        * */
        #endregion VPColor
    }

    public void CreateMap()
    {

        byte[,] map =
        {
            //imagine a 2d array with 50 rows and columns of zeros. too big to post

        };

        for (int x = 0; x < 50; x++)
        {
            for (int z = 0; z < 50; z++)
            {
                for (int y = 0; y <= map[x, z]; y++)
                {
                    SetUpVertices();
                    SetUpIndices();
                    cubes.Add(new Cube(device, new Vector3(x, map[x, z] - y, z), grass));
                }
            }
        }

        vertexBuffer = new VertexBuffer(device, typeof(VertexPositionTexture), vertices.Count(), BufferUsage.WriteOnly);
        vertexBuffer.SetData<VertexPositionTexture>(vertices.ToArray());

        indexBuffer = new IndexBuffer(device, typeof(short), indices.Count(), BufferUsage.WriteOnly);
        indexBuffer.SetData(indices.ToArray());
    }

    public void LoadContent(ContentManager content)
    {
        grass = content.Load<Texture2D>("grass");
    }
}

```

}

```
    public void DrawMap(GameTime gameTime)
    {

        foreach (Cube block in cube.cubes)
        {

            effect.VertexColorEnabled = false;
            effect.TextureEnabled = true;

            Matrix center = Matrix.CreateTranslation(new Vector3(-0.5f, -0.5f, -0.5f));
            Matrix scale = Matrix.CreateScale(1f);
            Matrix translate = Matrix.CreateTranslation(block.cubePosition);

            effect.World = center * scale * translate;
            effect.View = cam.view;
            effect.Projection = cam.proj;

            effect.FogEnabled = false;
            effect.FogColor = Color.CornflowerBlue.ToVector3();
            effect.FogStart = 1.0f;
            effect.FogEnd = 50.0f;

            cube.Draw(effect);
            noc++;
        }

```

# Answer
I used my eyes this time and looked at the line that gave me the error. I was creating an effect every time I created a new cube. I don't really need 100,000 instances of basic effect so I deleted that line from my constructor and it worked

```
     effect = new BasicEffect();

```

Now that the game runs fine, I'm getting an incredibly low frame rate. But that is for another question.
> 1 votes

# Answer
Use just one vertex buffer and draw it many times to save memory. Take advantage of hardware instancing to increase performance.
> 0 votes

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


# Question
Title: How to set orthgraphic matrix for a 2d camera with zooming?
I'm using ID3DXSprite to draw my sprites and haven't set any kind of camera projection matrix. How to setup an orthographic projection matrix for camera in DirectX which it would be able to support zoom functionality?

```
    D3DXMATRIX orthographicMatrix;
    D3DXMATRIX identityMatrix;

    D3DXMatrixOrthoLH(&orthographicMatrix, nScreenWidth, nScreenHeight, 0.0f, 1.0f);
    D3DXMatrixIdentity(&identityMatrix);

    device->SetTransform(D3DTS_PROJECTION, &orthographicMatrix);
    device->SetTransform(D3DTS_WORLD, &identityMatrix);
    device->SetTransform(D3DTS_VIEW, &identityMatrix);

```

This code is for initial setup. Then, for zooming I multiply zoom factor in `nScreenWidth` and `nScreenHeight`.

**UPDATE**

This is going to work:

```
    D3DXMATRIX orthographicMatrix;
    D3DXMATRIX identityMatrix;
    D3DXMATRIX viewMatrix = D3DXMATRIX(
        1,      0,      0,      0,
        0,      1,      0,      0,
        0,      0,      1,      0,
        (FLOAT)(-(this->nScreenWidth / 2)), (FLOAT)(-(this->nScreenHeight / 2)),        0,      1
    );

    D3DXMatrixOrthoLH(&orthographicMatrix, (FLOAT)this->nScreenWidth, (FLOAT)-this->nScreenHeight, 0.0f, 1.0f);
    D3DXMatrixIdentity(&identityMatrix);

    this->p_device->SetTransform(D3DTS_PROJECTION, &orthographicMatrix);
    this->p_device->SetTransform(D3DTS_WORLD, &identityMatrix);
    this->p_device->SetTransform(D3DTS_VIEW, &viewMatrix);

```

And put `D3DXSPRITE_OBJECTSPACE` flag next to other flags when you use `ID3DXSprite::Begin()`:

```
if(this->p_sprite->Begin(D3DXSPRITE_ALPHABLEND | ... | D3DXSPRITE_OBJECTSPACE) != D3D_OK) return 0;

```

For zoom functionality you can produce this matrix:

```
D3DXMatrixOrthoLH(&orthographicMatrix, this->nScreenWidth * this->dZoom, -this->nScreenHeight * this->dZoom, 0.0f, 1.0f);

```

# Answer
Since you mentioned `ID3DXSprite`, I assume you're using Direct3D 9. In that case, you can set the projection matrix using

```
pDevice->SetTransform(D3DTS_PROJECTION, projMatrix);

```

The `projMatrix` for a 2D camera with zooming and translation could be constructed as follows:

```
s     0     0  0
0     s     0  0
0     0     1  0
-x*s  -y*s  0  1

```

where `x, y` is the camera position and `s` is the zoom factor. This is the result of a translation by `-x, -y` (centering the view on the camera position) followed by a 2D scale by `s`.
> 1 votes

---
Tags: c++, 2d, camera, directx9
---