title: 2D Polygon Triangulation

text:
# Question
Title: 2D Polygon Triangulation
I am creating a game engine using the JBox2D physics engine. It only allows you to create polygon fixtures up to 8 vertices, To create a body with more than 8 vertices, you need to create multiple fixtures for the body.

My question is, How can I split the polygons a user creates into smaller polygons for JBox2D?

Also, what topology should I use when splitting the polygons and why? (If JBox2D can have up to 8 vertices, why not split polygons into 8 per polygon)

# Answer
This simple algorithm assumes you're working with a **convex** polygon (in the case of physics engines you definitely should be):

Loop over the polygon with two indices, one called next and one called last. This is also known as a format called "Triangle Fan". Here's a demo image:

You set up these two indices and loop something like this:

```
TriVertexList TriangleFan( int vCount, Vec2[] v )
{
  int start = 0;
  int last = 1;
  int prev = 0;
  TriVertexList out;

  while(start != last)
  {
    out.push( v[start], v[last], v[prev] );
    prev = last;
    last = last + 1 == vCount ? 0 : last + 1;
  }

  return out;
}

```

This algorithm can easily be extended to 3D (which I currently use to triangulate my 3D meshes).
> 5 votes

---
Tags: java, physics, graphics, lwjgl, jbox2d
---


title: How to implement scripted events?

text:
# Question
Title: How to implement scripted events?
I'm building a game in C++ (using SDL) for a college project, I'm trying to figure out how to script events that happens when a player does something, or some time passes etc.

I have a and idea of how to do it but I don't want to go against how it's commonly done.

---

Right now I have a class called Obj from where enemies, items and the player are child classes, my idea is to add 3 public variables to it like this:

```
class Obj{
    int eventDeath,eventTouch,eventTalk,eventMeet;
}

```

Then I could create an Obj with eventDeath=1 and when it died it would fire event(1). event() would be something like this:

```
void event(int n){
   switch(n){
   case 1:
      dialog("I'm dying");
      break;
   }
}

```

I could also add invisible "Obj" in specific places for when a player walks over a certain place. I don't know if this is a good idea but I can't think of other means to do it. How is it commonly done? Also how do I keep track of events that already happened?

# Answer
> 2 votes
Then I'd recommend creating a new class for each type of message (with a common `Message` base), since different messages will typically need different bits of data in them. You can then use over-loading of methods to make delivery of events simple and easy. Something like:

```
// messages.h
class Object;

struct IMessage {
  virtual void dispatch(Object& obj) const = 0;
};

struct DeathMessage : public IMessage {
  void dispatch(Object& obj) const;
};

/* more messages */

// object.h
#include "messages.h"

class Object {
public:
  virtual void onDeath(const DeathMessage&) { }
  /* other handles here */

  void onMessage(const IMessage& msg) { msg.dispatch(*this); }

// messages.cpp
#include "messages.h"

void DeathMessage::dispatch(Object& obj) {
  obj.onDeath(*this);
}

```

Now your `Object` subclasses can override `onDeath` or `onCreate` or `onDamage` or whatever as desired. Different messages can have additional data, e.g `DamageMessage` can include how much damage was caused, what type of damage, who the source of the damage is, etc.

So far as making events trigger once, just add a boolean to the class. The first time you process the message, set it to true. Ignore repeats if it's not false.

You can generalize the system further once you have more experience with the language and programming concepts.

---
Tags: c++, sdl, scripting, dialogue-tree
---


title: box2d raycast filter category

text:
# Question
Title: box2d raycast filter category
I am trying to filter a category in my ray casting (jBox2D within libGDX), which should return the closest object that **does not** belong to the category `LEVEL0`. I've tried a plethora of approaches, but none of them seem to work.

This post, for example, instructed me to do so:

```
private static class RayCast implements RayCastCallback {
    Fixture f;
    Vector2 point;
    float fraction;

    public RayCast() {
       this.fraction = 1f;
    }

    @Override
    public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
       if (fixture.getFilterData().categoryBits == Corpo.LEVEL0)
          return 1f;

       if (fraction <= this.fraction) {
           this.f = fixture;
           this.point = point;
           this.fraction = fraction;
       }
       return 1f;
    }
}

```

Yet, it ignores the `LEVEL0` bodies only sometimes, and sometimes ignores other bodies as well (though it seems to work on most cases, it fails frequently enough to be unacceptable). I've tried a few other solutions, including: returning -1 in the first if (which should mean ignore this collision), return `this.fraction` always, instead of 1, but nothing works - this, in fact, seems to be a very common problem, as the internet is filled with a variety of workarounds, none of them working for me.

I think my library is updated, or at least is the version that is included in the latest libGDX (which, according to my quick research, is the actual latest).

I've posted this same question here, but I'm not sure about the official forum's activity, so I decided to ask here too, just in case. Whichever website gives the answer first, I shall copy it to the other.

# Answer
*(I haven't got enough rep to comment)*

Unless there's a bug in the LibGDX Box2D, the only thing I can think if is your condition - are you sure `categoryBits` is going to be exclusively `LEVEL0`? Or do you need to do a bitwise AND:

`if ((...categoryBits & Corpo.LEVEL0) == 0) { ... }` ?

Are you always setting the `categoryBits` for every fixture?

Can you step through the callback in a debugger to check what is coming through it?
> 3 votes

---
Tags: box2d, libgdx, raycasting
---


# Question
Title: How to draw a rotatable and zoomable sphere?
My game is a sort of business simulation game of Earth, and I want the main interface to be just like a google earth view. Is there a way to do this with built in OpenGL features or do I have to implement the engine myself.

# Answer
> 2 votes
You can do this by creating the vertices for a sphere using one of the algorithms from this question, then you can orbit around it using the strategy described here.

If you should use an engine or not isn't really something we can answer here. It depends on how long you want to spend creating the required functionality yourself. Typically, it's recommended to use an existing engine instead of creating your own.

As an aside, you might want to consider a divide and conquer strategy for some of your problems, like this one. Breaking the problem down into more generalized components will often make it easier to find answers and solve your problems faster.

---
Tags: opengl, rotation, windows
---


# Question
Title: 2d array to calculate height for player in heightmap?
I'm trying to work out how to do so my player position takes into the account of the floor so if I generate a floor that is hilly when I walk I won't walk through the heel. The problem is that I'm not sure how to do it.

I can do basic collision detection for walls. However, this isn't collision detection. I need the add the height of the terrain to the player.

So as you see the terrain is really a grid with 4 points making a face. So I can get the 4 points and work out. I can probably work this out on myself, but I was wondering if I should store say the heigh at (x,z) in a 2d array or do I just work out the height again everytime I move?

It just I use simplexnoise and I worry that this will be expensive to do every turn.

```
 import java.util.ArrayList;

    public class VoxelLevel
    {
    Mesh mesh;
    Material material;
    Transform transform;
    Shader shader;

    VoxelLevel(String textureName)
    {
        material = new Material(new Texture(textureName));
        transform = new Transform();

        shader = BasicShader.getInstance();

        generateLevel();

    }

    private void generateLevel()
    {
        ArrayList<Vertex> vertices = new ArrayList<Vertex>();
        ArrayList<Integer> indices = new ArrayList<Integer>();

        int sizeX = 10;
        int sizeZ = 10;
        int freq = 25;

        for(int x=-300; x<300; x+= sizeX)
        {
            for(int z=-300; z<300; z+=sizeZ)
            {
                indices.add(vertices.size()+0);
                indices.add(vertices.size()+3);
                indices.add(vertices.size()+2);
                indices.add(vertices.size()+0);
                indices.add(vertices.size()+1);
                indices.add(vertices.size()+3);

                vertices.add(new Vertex(new Vector3f(x,50+25*(float)(SimplexNoise.noise(x/freq, z/freq) + 0.25 * SimplexNoise.noise(2*x/freq, 2*z/freq)),z), new Vector2f(0.75f,0.75f)));
                vertices.add(new Vertex(new Vector3f(x+sizeX,50+25*(float)(SimplexNoise.noise((x+sizeX)/freq, z/freq) + 0.25 * SimplexNoise.noise(2*(x+sizeX)/freq, 2*z/freq)),z), new Vector2f(0.75f,1.0f)));
                vertices.add(new Vertex(new Vector3f(x,50+25*(float)(SimplexNoise.noise(x/freq, (z+sizeZ)/freq)+ 0.25 * SimplexNoise.noise(2*x/freq, 2*(z+sizeZ)/freq)), z+sizeZ), new Vector2f(1.0f,0.75f)));
                vertices.add(new Vertex(new Vector3f(x+sizeX,50+25*(float)(SimplexNoise.noise((x+sizeX)/freq, (z+sizeZ)/freq)+ 0.25 * SimplexNoise.noise(2*(x+sizeX)/freq, 2*(z+sizeZ)/freq)),z+sizeZ), new Vector2f(1.0f,1.0f)));
            }
        }

        Vertex[] vertArray = new Vertex[vertices.size()];
        Integer[] intArray = new Integer[indices.size()];

        vertices.toArray(vertArray);
        indices.toArray(intArray);

        mesh = new Mesh(vertArray, Util.toIntArray(intArray));
    }

    public void input()
    {

    }

    public void update()
    {
        //SimplexNoise.noise(0.25, 0.25);
        //SimplexNoise.noise(0.35, 0.65);
        //SimplexNoise.noise(0.254, 0.225);
        //SimplexNoise.noise(0.254, 0.215);
    }

    public void render()
    {
        shader.bind();
        shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), material);
        mesh.draw();
    }

}

```

# Answer
> 0 votes
Getting the height from your terrain at any x/z point is super fast so there's no reason to store and manage a cache, it just adds complexity.

---
Tags: java, heightmap
---


# Question
Title: What are reasons for input polling vs. input events?
I noticed people use both - but is there any empirical evidence when it's better to use one over the other?

This is related but not quite a 'why use either' or even 'why use both': Polling vs event driven input

# Answer
Behind the scenes, typically input is polled anyway, just by the os behind your back ;)

Regardless, even if you poll you're going to need to package state changes up in some way in order to use that information elsewhere in your game. And odds on you're going to package that up in an event.

So realistically, going straight to events is going to save you the headache of state management and get you to where you need to go faster.

Be aware, that you dont want to be sending "button down!" or "user pressed A" events into your game, you want to re-interpret those using your keymapping and translate them into actual things like "the user jumped" or "start the game".

This will let you swap out controllers/input schemes/etc
> 4 votes

# Answer
**Polling mechanism**

The software check for a condition repeated times until something is ready.

E.g. Childs in a car:

> Child: Did we arrived yet?
> Mom: No;
> Child: Did we arrived yet?
> Mom: No;
> .... (repeat many times)
> Child: Did we arrived yet?
> Mom: Yes

**Events**

The condition itself is able to inform the software when it is ready.

E.g. Childs in a car:

> Mom: I will tell you when we arrive
> Child: Ok, I am going to read in the while
> ... (child reading silently)
> Mom: We arrived!
> Child: Great!

Events mechanism is superior to polling: due to several reasons:

* The CPU does not spend time in checking the condition
* The CPU can do something else in the while
* The latency between the moment when the condition has changed and the software reaction is shorter: in the polling, the worse case is the delay between polling, while in the event mechanism, the minimum latency could theoretically become close to zero.

There are a few benefits for the poll mechanism:

* Require much simpler hardware, which is not a concern in Gaming.
* The software does not require event loop, which is simpler.

**Summary**: As all game platforms have support for events, you should use them always.

**Why to use both**

I do not know about any real situation in which polling is recommended in game development.

Obviously, polling is extremely important in other fields, for example signal sampling.
> 5 votes

# Answer
The issue of input events versus input polling is a matter of fidelity in most situations, and indeed, the reality is that one is simply a layer of abstraction built on top of another. Using input API's to directly read memory from a particular device gives you the option to control precisely how often you are reading input from a particular device, and in situations where you are attempting to simulate an analog/continuous function (driving/flying for instance) this is quite important. On the other hand, events tend to simulate discrete actions, and they work better for on/off type behaviors. Many systems use combinations of the two, based on their needs.
> 0 votes

---
Tags: input, keyboard
---


# Question
Title: How to change the default UDK game folder?
How can I change the default UDK game folder, the folder where it takes config files from?
Looking at the engine configuration files, it is taking it from `%GAME%Game/`, and when that's `UDK`, it loads from `UDKGame`, but how do I change the `%GAME%`?

# Answer
Without license you cannnot. I have tried a few months ago but got an error at compile and cooking time.

Others with the same issue:

http://forums.epicgames.com/threads/841042-How-to-set-up-a-game-project-in-the-root-UDK-directory-outside-of-UDKGame
> 1 votes

---
Tags: udk
---


# Question
Title: Error on running exe, build using SharpDX
I have developed a windows application to read gamepad using SharpDx (XInput) and C# (VS 2008). The application is running smoothly in my development environment. But when i move to some other machine (Windows 7), its giving me error "Unable to load dll 'xinput1\_3.dll' ". My question is is it mandatory to have directx runtime environment in clint machine also to run the exe ? Because i was thinking it will make use of dll "XInput9\_1\_0.dll" which is a part of windows 7.

# Answer
Yes. SharpDX is simply a wrapper over the DirectX DLLs. The SharpDX files do not include the DirectX DLLs, and therefore you must redistribute them with your application if you want it to run on other computers.

Note that some DLLs are included in some versions of Windows, but apart from the very basic files, like d3d9.dll, you should not suppose that any DirectX DLLs are going to be available in the target computer. This is especially true for the newer DirectX components, such as XInput, XACT or XAudio2.

That said, simply copying the DLLs with your application won't work in most cases (the d3dx9 files being an important exception). DirectX components are based on COM, and therefore must be registered.

Microsoft recommends you use the redistributable package installer to install the DirectX components required by your application.

If you use this approach (which I recommend as well), you don't have to distribute every DirectX file. You just need to include:

* `dxsetup.exe`
* `dsetup32.dll`
* `dsetup.dll`
* `dxupdate.cab`

as well as the specific DLLs required by your application. These files can be found in `Program Files\DirectX SDK\Redist\` if you have the DirectX SDK installed in your computer.

If you do this, you can then call `dxsetup.exe` (preferably with the `/silent` switch) to install the required DirectX components in the target computer.

This can all be automatically performed by a Visual Studio Setup project. You just have to include these files, and have `dxsetup.exe /silent` called from a custom action.

To test your setup, I recommend you setup a virtual machine (I prefer VirtualBox), save the disk image as soon as the base OS is installed, and try your installer. If you have a problem, you can revert to the freshly installed disk image, and try again with a new installer.

Note that since you're writing your program in C#, you also need the .NET framework to be installed in the target machine for your program to run. More information on how to do this can be found here.
> 2 votes

# Answer
This really depends on which DirectX SDK was used to build the binaries. If someone uses for example the SDK released in month X of year Y, you'll most likely also need the DirectX version that has been up to date at that time. Unfortunately Microsoft ditched most versioning stuff starting with DirectX 9.0c. There are tons and tons of hidden subversions, all being backwards compatible, but adding additional support libraries. In a similar way there are different "sub versions" of DirectX 10 and 11 as well.

Easiest way to ensure your programs works, would be either bundling (or providing a download URL) to Microsoft's DirectX Runtime Web Installer. It's essentially a downloader that will always install the correct and latest runtime files for the system it's run on.
> 1 votes

# Answer
The target machine is missing the .dll files, either you install the redistributable or just copy the needed .dll files to the executable folder. The first option is the one that most professional in my opinion.
> 0 votes

---
Tags: c#, directx, sharpdx
---


# Question
Title: calculating occlusion in cube voxel engine
This is more a conceptional (approach) question then the search for an implemented solution, since I was unable to find proper hints via google or similar.

The problem is as follows:

Given you have a 3D world that is encoded as voxels. So basically you have your 3D matrix were each position in the matrix is either solid or void ( for simplicity ). Now you look with your camera onto this cloud form a given ( in my case fixed for an isometric perspective ) angle. For each non void coordiante I draw an isometric projected block ( due to my choosen fixed camera angle ), while leaving void coordinates empty.

Of corse I want ot omit to draw coordiantes that are not vissible, so I alread exclude coordiantes that the camera would not see. But I also want to omit coordinates that would be hidden by other blocks, which are in the perspective closer to the camera.

I currently solve this by choosing a specifc camera angle that ensures that a block at coordiantes 0,0,0 would occlde a block at -1,-1,-1; -2,-2,-2; -3,-3,-3; and so on ( is that clear enought or should I add an image to explain? ). This is a rather cheap trick but it works and makes rendering faster as I have only to do a trace for each visible coordiante on the screen and draw the first non void coordinate in that trace. I saw this solution also used in Gnomoria for instance.

But I am wondering, if anyone has some keywords or hints if there is a more general approach to solve this occlusion problem without falling back using cheap camera tricks.

# Answer
> 3 votes
3D DDA is the algorithm used for this. It is similar to the method used for lighting occlusion in roguelikes.

---
Tags: isometric, voxels, occlusion
---


title: Spell classes and inheritance

text:
# Question
Title: Spell classes and inheritance
I'm currently developing a small game, that includes spell casting. My class structure looks like this:

**AbstractSpell**

**AbstractDamageSpell**

**AbstractClickableSpell**

**AbstractClickableDamageSpell**

"Clickable" means that the user has to hit a key followed by a mouse click. Some spells don't need that extra mouse click (like Windwalk). As you can see, **AbstractDamageSpell** and **AbstractClickableDamageSpell** have the same properties and methods. Is there a better way of extending these classes? Any hints in general?

# Answer
> 6 votes
Several suggestions come to mind.

I feel you may have gone a little inheritance happy. While inheritance is a great tool, sometimes all you need is a little more customization of a single object.

First, a component system seems to jump out as a good candidate. Then you'd just have a `Spell` class (or perhaps something even more broad, but that's not necessary to explain the process), and components that you attach to it, like `DamageComponent` or `ClickableComponent`. When the spell is cast, the manager responsible for it would cycle through the components to determine how to interact with it.

If you're not too familiar with components, or feel like you'd like an approach in between a standard OO approach and this, you can give your `Spell` members like `m_pDamageComponent` and `m_pClickableComponent` and have the value `NULL` indicate that they aren't relevant, and use the object it's pointing to otherwise. Actually, if the behavior is simple and consistent, there's no reason it needs to be encapsulated. Those can just be booleans.

I can elaborate on any of these suggestions if necessary.

---
Tags: java, inheritance
---


title: How to rotate two scaled objects

text:
# Question
Title: How to rotate two scaled objects
I have two objects. The head and tail of a future "grapple". The head and tail always point in the same direction. However, when I tried using scaled rectangles (that were bigger/smaller than the source rectangles) the rotations no longer worked, as in, the drawn head was no longer "attached" to the tail. (Without scaling them, this worked fine.)

The red sprites are without any rotation (Code below). The others are rotated about their respective "lower" origins (bottom center) (Rotation = 0)

So, the non-red sprites should be touching head to tail (the same way the red sprites are).

I have been fiddling with the code for a while... here is what I think you will need to see to help:

```
Initialization()
{
    Rectangle headSize = new Rectangle(0,0, 29, 100);
        Rectangle linkSize = new Rectangle(0,0, 29, 67);
        Rectangle tailSize = new Rectangle(0,0, 29, 53);

        Rectangle headSource = new Rectangle(0, 0, 29, 53);
        Rectangle linkSource = new Rectangle(0, 53, 29, 67);
        Rectangle tailSource = new Rectangle(0, 120, 29, 53);

        this.headSize = headSize;
        this.linkSize = linkSize;
        this.tailSize = tailSize;

        headSource = headsource;
        linkSource = linksource;
        tailSource = tailsource;

        chainHandle = new Link(new Rectangle((int)position.X,
                (int)position.Y,
                tailSize.Width,
                tailSize.Height),
                tailSource,
                0);

        chainHead = new Link(new Rectangle((int)position.X + tailSize.Width / 2 - headSize.Width / 2,
            (int)position.Y - headSize.Height,
            headSize.Width,
            headSize.Height),
            headSource,
            0);

}

    public Link(Rectangle rectangle, Rectangle sourceRect, float rotation)
    {
        TruePosition.X = rectangle.X;
        TruePosition.Y = rectangle.Y;

        Position = TruePosition;
        Rotation = rotation;

        scaledUpperOrigin = new Vector2(rectangle.Width / 2, 0);
        scaledLowerOrigin = new Vector2(rectangle.Width / 2, rectangle.Height);
        scaledCenterOrigin = new Vector2(rectangle.Width / 2, rectangle.Height / 2);

        upperOrigin = new Vector2(sourceRect.Width / 2, 0);
        lowerOrigin = new Vector2(sourceRect.Width / 2, sourceRect.Height);
        centerOrigin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);

        dims = new Vector2(rectangle.Width, rectangle.Height);
    }

    public void Draw(SpriteBatch sb)
    {
        //debug purposes
        sb.Draw(chainAtlas, chainHead.GetRect(), headSource, Color.Red);
        sb.Draw(chainAtlas, chainHandle.GetRect(), tailSource, Color.Red);

        sb.Draw(
            chainAtlas,
            chainHead.GetRect(),
            headSource,
            Color.White,
            MathHelper.ToRadians(chainHead.Rotation),
            chainHandle.scaledLowerOrigin,
            SpriteEffects.None, 1);

        sb.Draw(
    chainAtlas,
        chainHandle.GetRect(),
            tailSource,
            Color.White,
            MathHelper.ToRadians(chainHandle.Rotation),
            chainHandle.scaledLowerOrigin,
            SpriteEffects.None,
            1);
}

```

Any ideas on how to fix this? I have tried using both original sized origins and scaled origins to no avail, as well as different points of origins.

If you have read this far, thank you for your time! Let me know if you see a fix.

# Answer
> 1 votes
I'll be honest, I don't fully understand what's happening here, but I'll focus on what I *think* the problem is.

It appears as though you are scaling objects separately, when you want to be scaling them as one. More to the point, you need to be scaling from a **common** origin.

```
scaledLowerOrigin = new Vector2(rectangle.Width / 2, rectangle.Height);

```

Each object passed in will have an origin equal to the bottom of itself. What I think you need to do, is specify a point that all objects (in the 'Grappling Hook') are scaled and rotated about.

I'm sorry I can't give you code, I'm sure google can help, but as far as I'm concerned, you need a common point to scale/rotate multiple objects.

**EDIT**

I belive, even if you used the code as is, there should be somewhere in there that you scale the position, which I don't see. If you scale two objects to be %50 (0.5) smaller, it would follow that they need to be %50 closer to each other to maintain their original distance (touching in this case). So while a common point might be needed for rotation, a common 'scale factor' would be needed for scaling, and all values (width,height,position) would be multiplied by that factor.

---
Tags: xna, rotation, scale
---


# Question
Title: What alternatives to large arrays do I have for level data?
So I'm going to store my levels in int\[\] arrays.

Most levels are going to be 300\*300\*300. However, there will be about 24 levels and so that is 24 int arrays of size 300\*300\*300. However, that would mean I need about 2.5GB just to hold the information. Was wondering is there ways around this.

It just the nature of the game I need this many things. I can possible go down to 100\*100\*100 levels, but then I would still need about 17 at minimum.

I just can't get around using large arrays.

# Answer
As mentioned in PeterT's comment, you don't need to load all of your levels at once; instead you just load the current level and when the player transitions from that to a new one, you unload the current and load the new.

That gets you down to about 100mb (the raw per-level cost), but we can go lower still.

Consider a cube; right now you're defining each cube as 8 vertices with 3 ints in each - that's 24 ints total. Instead of that, look at the data you actually need to define a cube. You need the midpoint, and you need the size of the cube; since it's a cube the size is going to be the same in all 6 directions, so that's down from 24 ints to 4.

You'll probably also want rotation, so let's add either an axis/angle or quaternion representation, which is 4 floats (you could alternatively use Euler angles for 3 floats), and - assuming on the platforms that you're interested in - a float is the same size as an int, you're looking at the equivalent of 8 ints.

And what if it's not a cube? Simple enough; you still just need the midpoint, but this time you need 3 sizes; that's 2 extra so our final cost is going to be the equivalent of either 4, 6, 8 or 10 ints - worst case of less than half what you currently have. I'm going to assume cubes for the rest of this, for simplicity, but the same principles will apply if you don't have cubes.

So, we're now at 33mb per level, or 16mb if you don't need rotation. That's quite comfortable, even for 6 or 7 year-old hardware.

So you want to draw it efficiently? You can still do so, even without storing the full vertex data. The midpoint and size is perfectly sufficient to store in a VBO (I'm assuming OpenGL here), and you can use either instancing or a geometry shader to expand that to a full cube. If you need to rotate it, you can convert your axis/angle or quaternion to a matrix in the same shader code and just perform an additional matrix multiply.

And that should resolve your memory problems and yet still get you pretty decent performance (just make sure that you've a reasonably good culling algorithm in place), without even needing to go near any kind of funky compression (or streaming, for that matter) scheme that doesn't translate well to graphics hardware.
> 7 votes

# Answer
If you truly have 300^3\*24 unique uncorrelated integer values representing your game, there's no way around the storage requirements. If, however, there are correlations between values (e.g. large volumes of the same value, gradients, or repeating patterns), you can use compression to store the level data, decompressing each level as it is needed. For a typical minecraft-ey volume data set, you should be able to compress 2.4GB down to around 100MB \[citation needed\].
> 1 votes

---
Tags: java, data-structure, memory-efficiency
---


# Question
Title: Separating game data/logic from rendering
I'm writing a game using C++ and OpenGL 2.1. I was thinking how could I separate the data/logic from rendering. At the moment I use a base class 'Renderable' that gives a pure virtual method to implement drawing. But every object has so specialized code, only the object knows how to properly set shader uniforms and organize vertex array buffer data. I end up with a lot of gl\* function calls all over my code. Is there any generic way to draw the objects?

# Answer
An idea is to use the Visitor design pattern. You need a Renderer implementation that knows how to render props. Every object can call the renderer instance to handle the render job.

In a few lines of pseudocode:

```
class Renderer {
public:
    void render( const ObjectA & obj );
    void render( const ObjectB & obj );
};

class ObjectA{
public:
    void draw( Renderer & r ){ r.render( *this ) };
}

class ObjectB{
public:
    void draw( Renderer & r ){ r.render( *this ) };
}

```

The gl\* stuff is implemented by the renderer's methods, and the objects only store the data needed to be rendered, position, texture type, size ...etc.

Also, you can setup different renderers (debugRenderer, hqRenderer, ...etc) and use these dynamically, without changing the objects.

This also can be easy combined with Entity/Component systems.
> 21 votes

# Answer
Build a rendering-command system. A high-level object, which has access to both the `OpenGLRenderer` and the scenegraph/gameobjects, will iterate the scene graph or gameobjects and build a batch of `RenderCmds`, which will then be submitted to the `OpenGLRenderer` which will draw each in turn, and thereby containing all OpenGL related code therein.

There are more advantages to this than just abstraction; eventually as your rendering complexity grows you can sort and group each render command by texture or shader for example in `Render()` to eliminate many bottlenecks in the draw calls which can make a huge difference in performance.

```
class OpenGLRenderer
{
public:
    typedef GLuint GeometryBuffer;
    typedef GLuint TextureID;
    typedef std::vector<RenderCmd> RenderBatch;

    void Render(const RenderBatch& renderBatch);   // set shaders, set active textures, draw geometry, ...

    MeshID CreateGeometryBuffer(...);
    TextureID CreateTexture(...);

    // ....
}

struct RenderCmd
{
    GeometryBuffer mGeometryBuffer;
    TextureID mTexture;
    Mat4& mWorldMatrix;
    bool mLightingEnabled;
    // .....
}

std::vector<GameObject> gYourGameObjects;
RenderBatch BuildRenderBatch()
{
    RenderBatch ret;

    for (GameObject& object : gYourGameObjects)
    {
        // ....
    }

    return ret;
}

```
> 5 votes

# Answer
I know you've already accepted Zhen's answer but I'd like to put another out there just in case it helps anyone else.

To reiterate the problem, the OP wants the ability to keep the rendering code separate from the logic and data.

My solution is to use a different class all together to render the component, which is separate from the `Renderer` and the logic class. There first needs to be a `Renderable` interface that has a function `bool render(Renderer& renderer);` and the `Renderer` class uses the visitor pattern to retrieve all `Renderable` instances, given the list of `GameObject`s and renders those objects that have a `Renderable` instance. This way, Renderer doesn't need to know of each every object-type out there and it's still the responsibility of each object-type to inform it's `Renderable` via the `getRenderable()` function. Or alternatively, you could create a `RenderableVisitor` class that visits all GameObjects and based on individual `GameObject` condition they can choose to add/not-to-add their renderable to the visitor. Either way, the main gist is that the `gl_*` calls are all outside of the object itself and reside in a class that knows intimate details of the object itself, instead of that being part of `Renderer`.

**DISCLAIMER**: I hand-wrote these classes in the editor so there's a good chance that I've missed something in code, but hopefully, you'll get the idea.

To show a (partial) example:

`Renderable` interface

```
class Renderable {
public:
    Renderable(){}
    virtual ~Renderable(){}
    virtual void render(Renderer& renderer) const = 0;
};

```

`GameObject` class:

```
class GameObject {
public:
    GameObject()
        : mVisible(true)
        , mMarkedForDelete(false) {}

    virtual ~GameObject(){}

    virtual Renderable* getRenderable() {
        // By default, all GameObjects are missing their Renderable
        return NULL;
    }

    void setVisible(bool visible) {
        mVisible = visible;
    }

    bool isVisible() const {
        return getRenderable() != null && !isMarkedForDeletion() && mVisible;
    }

    void markForDeletion() {
        mMarkedForDelete = true;
    }

    bool isMarkedForDeletion() const {
        return mMarkedForDelete;
    }

    // More GameObject functions

private:
    bool mVisible;
    bool mMarkedForDelete;
};

```

(Partial) `Renderer` class.

```
class Renderer {
public:
    void renderObjects(std::vector<GameObject>& gameObjects) {
        // If you want to do something fancy with the renderable GameObjects,
        // create a visitor class to return the list of GameObjects that
        // are visible instead of rendering them straight-away
        std::list<GameObject>::iterator itr = gameObjects.begin(), end = gameObjects.end();
        while (itr != end) {
            GameObject* gameObject = *itr++;
            if (gameObject == null || !gameObject->isVisible()) {
                continue;
            }
            gameObject->getRenderable()->render(*this);
        }
    }

};

```

`RenderableObject` class:

```
template <typename T>
class RenderableObject : public Renderable {
public:
    RenderableObject(T& object)
        :mObject(object) {}
    virtual ~RenderableObject(){}

    virtual void render(Renderer& renderer) {
        return render(renderer, mObject);
    }

protected:
    virtual void render(Renderer& renderer, T& object) = 0;
};

```

`ObjectA` class:

```
// Forward delcare ObjectARenderable and make sure the constructor
// definition in the CPP file where ObjectARenderable gets included
class ObjectARenderable;

class ObjectA : public GameObject {
public:
    ObjectA()
        : mRenderable(new ObjectARenderable(*this)) {}

    // All data/logic

    Renderable* getRenderable() {
        return mRenderable.get();
    }

protected:
    // boost or std shared_ptr to make sure that the renderable instance is
    // cleaned up with the destruction of this object.
    shared_ptr<Renderable> mRenderable;
};

```

`ObjectARenderable` class:

```
#include "ObjectA.h"

class ObjectARenderable : public RenderableObject<ObjectA> {
public:
    ObjectARenderable(ObjectA& instance) {
        : RenderableObject<ObjectA>(instance) {}

protected:
    virtual void render(Renderer& renderer, T& object) {
        // gl_* class to render ObjectA
    }
};

```
> 4 votes

# Answer
It completely depends on whether you can make assumptions about what's common for all renderable entities or not. In my engine, all objects are rendered the same way, so the just need to provide vbos, textures and transformations. Then the renderer fetches all of them, thus no OpenGL functions calls are needed in the different objects at all.
> 3 votes

# Answer
Definitely put rendering code and game logic in different classes. Composition (as teodron suggested) is probably the best way to do this; each Entity in the game world will have its own Renderable -- or perhaps a set of them.

You might still have multiple subclasses of Renderable, for example to handle skeletal animation, particle emitters, and complex shaders, in addition to your basic textured-and-lit shader. The Renderable class and its subclasses should only contain information needed for rendering: geometry, textures, and shaders.

Further, you should separate an instance of a given mesh from the mesh itself. Say you've got a hundred trees on screen, each using the same mesh. You only want to store the geometry once, but you'll need separate location & rotation matrices for each tree. More complex objects, such as animated humanoids, will also have additional state information (such as a skeleton, the set of currently applied animations, etc).

To render, the naive approach is to iterate over every game entity and tell it to render itself. Alternately, each entity (when it spawns) can insert its renderable object(s) into a scene object. Then, your render function tells the scene to render. This allows the scene to do complex render-related things without embedding that code into either game entities or a specific renderable subclass.
> 2 votes

# Answer
This advice isn't really specific to rendering but should help come up with a system that keeps things largely separate. Firstly try and keep the 'GameObject' data separate from the position information.

It's worth noting that simple XYZ positional information might not be so simple. If you are using a physics engine then you position data could be stored within in the 3rd party engine. You would either need to synchronize between them (which would involve a lot of pointless memory copying) or query the information directly from the engine. But not all objects need physics, some will be fixed in place so a simple set of floats works fine there. Some might even be attached to other objects, so their position is actually an offset of another position. In an advanced setup you might have position stored only on the GPU the only time it would be needed computer side is for scripting, storage and network replication. So you will likely have several possible choices for your positional data. Here it makes sense to use inheritance.

Rather than an object owning it's position, instead that object should itself be owned by a indexing data structure. For example a 'Level' might have an Octree, or maybe a physics engine 'scene'. When you want to render (or setup a rendering scene), you query your special structure for objects that are visible to the camera.

This also helps give good memory management. This way an object that isn't actually in an area doesn't even have a position which makes sense rather than returning 0.0 coords or the coords that it had when it was last in an area.

If you no longer keep the coordinates in the object, instead of object.getX() you would end up having level.getX(object). The problem with that is looking up the object in the level will likely be a slow operation since it will have to look through all it's objects and match the one your querying.

To avoid that I would probably create a special 'link' class. One that binds between a level and an object. I call it a "Location". This would contain the xyz coordinates as well as the handle to the level and a handle to the object. This link class would be stored in the spacial structure/level and the object would have a weak reference to it (if the level/location is destroyed the objects refrence needs to be updated to null. It might also be worth having the Location class actually 'own' the object, that way if a level is deleted, so is the special index structure, the locations it contains and its Objects.

```
typedef std::tuple<Level, Object, PositionXYZ> Location;

```

Now the position information is stored only in the one place. Not duplicated between the Object, the Spacial indexing structure, renderer and so on.

Spacial data structures like Octrees often don't even need to have the coordinates of the objects they store. There position is stored in the relative location of the nodes in the structure itself (it could be thought of as a kind of like lossy compression, sacrificing accuracy for fast lookup times). With the location object in the Octree then the actual coordinates are found inside it once the query is done.

Or if you are using a physics engine to manage your object locations or a mixture between the two, the Location class should handle that transparently while keeping all your code in the one place.

Another advantage is now the position and refrence to the level is stored in the same location. You could implement object.TeleportTo(other\_object) and have it work across levels. Similarly AI path-finding could follow something into a different area.

With regards to rendering. Your render can have a similar binding to the Location. Except it would have the rendering specific stuff in there. You probably don't need the 'Object' or 'Level' to be stored in this structure. The Object could be useful if you are trying to do something like colour picking, or rendering a hitbar floating above it and so on but otherwise the renderer only cares about the mesh and such. RenderableStuff would be a Mesh, could also have bounding boxes and so on.

```
typedef std::pair<RenderableStuff, PositionXYZ> RenderThing;

renderer.render(level, camera);
renderer: object = level.getVisibleObjects(camera);
level: physics.getObjectsInArea(physics.getCameraFrustrum(camera));
for(object in objects) {
    //This could be depth sorted, meshes could be broken up and sorted by material for batch rendering or whatever
    rendering_que.addObjectToRender(object);
}

```

You might not need to do this every frame, you could ensure you take a bigger region than the camera currently shows. Cache it, track object movements to see if there bounding box comes within range, track camera movement and so on. But don't start messing with that kind of stuff until you have benchmarked it.

You physics engine itself might have a similar abstraction, since it also doesn't need the Object data, just the collision mesh and physics properties.

All your core object data would contain would be the name of the mesh the object uses. The game engine can then go ahead and load this in whatever format it likes without burdening your object class with a bunch of render specific things (which might be specific to your rendering API, ie DirectX vs OpenGL).

It also keeps different components separate. This makes it easy to do things like replace your physics engine since that stuff is mostly self contained in the one location. It also makes unittesting much easier. You can test things like physics queries without having to have any actual fake objects setup since all you need is the Location class. You can also optimize stuff easier. It makes it more obvious what queries you need to perform on what classes and single locations to optimize them (for example the above level.getVisibleObject would be where you could cache things if the camera doesn't move to much).
> 2 votes

---
Tags: c++, opengl, rendering, logic, data
---


title: Does C# affect performance in Unity?

text:
# Question
Title: Does C# affect performance in Unity?
similar question :How does Unity use C# as a scripting language? In Unity , some functions like Update , run per object , per frame. so , is .Net framework involved at runtime ? could it affect performance?

# Answer
Compared to what? In what case?

Compared to Boo or UnityScript, scripting Unity in C# can be faster, but the difference will probably be quite marginal.

Compared to C/C++, C# may be slower in many cases, but since the languages operate at different levels, making a useful comparison is very difficult. As Unity cannot be scripted in C/C++, you would get more substantial performance differences because of the engine switch, rather than the language switch.

**However**, in the vast majority of programming, algorithmic choices have much more impact in performance than language choices: for arbitrarily big random arrays, BubbleSort in ultra-optimized assembly will *always* lose to QuickSort, even if written in Brainfuck.

**However**, when writing software, ease of writing, simplicity, clarity and understandability are usually much more important than performance. Basing your language choice exclusively on performance issues is not usually a wise idea.

So, if this is your first time using Unity, I would like to recommend you use the language you're most comfortable with, and if you find any specific performance problems you can detect by profiling, you should focus on fixing that specific problem, first by trying a better algorithm, and only as a last resort, by doing it in a different language which you know will give you better performance in that specific problem.
> 2 votes

---
Tags: c#, unity
---


# Question
Title: How to get a job in the game industry if you live in a country where there are no game companies?
You know not everyone of us is living in the US/Europe where there is potentially many more employers/opportunities than other countries, I live in a country where there is literally zero game companies (aside from a couple of companies that make HTML games), but I am sure there are many other people with the same situation, I am making some prototype games that will/might help.

But the real question is there any better way to get noticed (at least get an interview) by international companies, or given you are living far away will diminish their interest in hiring you?

-This question might be considered subjective or even a duplicate, but I feel am addressing an issue that might not have been addressed.

# Answer
The answer to your question is this:

1) Have skills that the industry needs.

2) Have a strong portfolio that you can show off demonstrating the skills from #1.

3) Make contacts in the industry. This means being active on social media networks that folks in the industry care about.

4) Collaborate on small projects with others to prove that you can work independently, with others, and still get things done.
> 3 votes

# Answer
This is my experience and opinions, and some people might disagree with me. Do not read this as hard facts, but more or less as a guide. I also know this is not exactly the answer for what you asked in your question. Instead it is one of the many answers for the question "how to get employed in the gaming industry" in the title.

Why don't you start your own business? Running a business is fairly easy, at least it is here in Finland. The business part is easy enough in the beginning, and when the company gets bigger you can always hire help to do the business stuff for you if you prefer to just create the games. The only real challenge is to get the customers, but that's so easy on gaming industry nowdays when compared to other software industries, or any other industry. Why do I say that? Well.. There's so much publishing platforms nowdays. Steam Greenlight, gog.com, indie royale and Totalbiscuit to say at least, and most likely a lot more stuff I do not know about.

You said you are making some prototypes. That's really all these publishing platforms need. Just try to get a green light for your game prototype in steam, and after that you are much better off to take the risk and get a loan from bank to hire some help with the areas of expertise you might not be good at, like graphics or sounds or programming. You also might try out some of these cheap contract-based work websites like fiverr.

I am not saying it won't be hard road to travel. But if you succeed, you will be more than satisfied.
> -1 votes

---
Tags: game-industry, career, hiring
---


# Question
Title: Move background with the player location
I want to move background with player location in ios . I have implemented the infinite parallax background by using the CCParallax class but i don't need it. I want to do something similar to this game http://www.youtube.com/watch?v=fNRNlLzrKmc.

my game level is large want to parallax up when player will move up. How will i do that please explain me. will i have to use CCCamera or i can do this by using CCParallax class.

Thanks,

# Answer
Your example shows parallax movement, it's just in two dimensions. Commonly parallax movement is only displayed for the X axis.

You simply need to extend your existing parallax code to apply to the Y axis in addition to the X axis.
> 1 votes

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


# Question
Title: Can I use a translate function to implement a viewport?
I read this great question and its accompanying great answer about rendering a viewport in a top down 2D game:

> As for actually drawing the objects the camera can "see", you now draw all objects relative to the camera's world coordinates. To compute an object's screen position relative to the camera, simply do:

```
int screenX, screenY; //screen position of the object being drawn

screenX = object.x-camera.x;
screenY = object.y-camera.y;

```

After thinking about this, it would be really invasive to change every place I render to run this `object.coord - camera.coord` equation first.

I'm wondering if this could be accomplished in one non-invasive step that translates the coordinate system first. I'm rendering on the html5 canvas and this translate function says:

> Moves the origin point of the context to (x, y).

I'm having trouble visualizing this though. Does this mean I simply plug `(-camera.x, -camera.y)` into the function? *Should* I use a translate function to render a viewport or is there a good reason to apply the equation on every thing I render?

# Answer
> 2 votes
Yes you can, that's what I'd do.

Each frame you need to reset the transformation by calling ctx.setTransform with an identity matrix. Then you need to do whatever transformations you want (e.g. translate).

Note that you'll still need to do culling unless you want to draw every item in the universe on each frame.

# Answer
> 0 votes
The equations you've quoted are translations. A single `translate()` to move the entire viewport is may appear as a more efficient one-step solution, but it performs the same calculations for every object to be drawn. The algorithm required for moving a 2D camera is so straightforward, there are no real shortcuts or detours at play. Every sensible method will function and perform similarly.

# Answer
> 0 votes
logically speaking, even if you use a translate function, at the bottom line, it does calculate the equation whenever you use the function. In my experience with Unity3D, I can simply switch between world-position and local-position. Under the hood, they are implementing the equations anyway. Its always nice to have separate functions for translating in context of world model or local model. IMHO, I would recommend against using direct hard codded implementations.

---
Tags: game-design, architecture, camera, html-canvas, viewport
---


title: Separating components and logic

text:
# Question
Title: Separating components and logic
I've been working on how to build some of my game systems using components and systems. I'm having a little trouble following the approach that components should just be bags of data and systems should implement the logic. It'd seem for this to be true you have to limit the complexity of the components or somehow make the system aware of all possible complexity.

For example, I have equipment in my game that characters can equip. Equipment has an "Item" component that has an item name, description, value etc. and allows me to identify it as an item for the purpose of character inventory, etc. That's simple enough.

Here's my problem though. Equipment also needs to be "equippable". Originally, I implemented it as something like this:

```
class EquipComponent : public Component
{
public:
     virtual bool equip(Entity* character) = 0;
     virtual bool unequip(Entity* character) = 0;
};

```

then I'd export this class to my scripting engine, and I'm free to have equip/unequip do whatever I want to the character they're being equipped too.

When I try to implement this component as just a bag of data, it just seems so limited. If I want the equipment to increase stats, I can add an array of stat adders/multipliers. If I want to have equipment add status effect resistances, I can add a table for that. If a piece of equipment has different effects for different weatrers, now I have to add data on a per user basis. Suddenly my simple bag of data has gotten massive. I could split it into seperate components, but now my system needs to be aware of every possible component that can change how an item is equipped.

I can see problems like this popping up in a lot of potential components/systems, so I was wondering how one can decouple the components and systems? Am I thinking too rigidly that most component logic should be handled by systems? As much as this is a learning experience, I would like to have something I can use for more than one project and that has good scalability.

Any insight or advice would be appreciated!

# Answer
> 5 votes
There are several potential problems here.

First, not all components need the idea of systems as from "entity component systems." Much simpler and more obvious designs are both quite possible and more "real-world" (I've seen major AAA engines using the simpler approaches; I've never in my life seen a real engine using pure ECS). Components can be regular objects with methods and behavior and event handlers and all the other stuff you'd expect. There are places where an ECS-like approach makes sense, but those are not everywhere. I'd even argue that they are never needed as most of the performance-sensitive systems in the game have parallel hierarchies

Second, you should avoid making tons of components that are tied together functionally. If every item is equippable and every equippable is an item, there is zero purpose to making them separate components. Just merge the interfaces/features. Experience across a number of significant games with component-based engines has led me at least to lean towards coarser components rather than granular components (obviously it's a balancing act).

Third, the problem you're running into is not directly a problem with your ECS-based design. Things like equipment can have data that describes effects and then the system can use that data to apply it to characters. This is one of the more awkward areas of pure-ECS since you end up with a system that depends on its own components and then depends on another system/component (which somewhat eliminates the data-oriented nature of ECS). You could also implement equipment with events. E.g., the item triggers an "Add 10 Strength" event and pushes that into an event queue. Then the character system processes that event queue. For more detail on how such an event system might work, see the article series starting at this BitSquid blog entry. Yes, you can add "an array of stat modifiers" but you can take this a step further to include an array of effects in a bytecode-like data layout, very efficient to apply (but you'll need more complicated tools to edit and visualize the data).

I really would just recommend dropping the whole systems approach and using a simpler component model. Development gets easier and faster and it's unlikely that any loss of performance is going to hurt you noticeably (and if by some off chance you're working at DICE on Battlefield 5 or something, you can get most of the data-oriented benefits in the areas most needing it without using a pure ECS everywhere).

---
Tags: c++, architecture, component-based
---


# Question
Title: How to determine the point of intersection of two lines?
I have two lines say P1( 0, -1, 0, -1 ) and P2( -1, 0, 0, -1 ). Since I'm working in 2D, there is no Z component. The x,y,z components are normals and the w component is the distance from origin. I am not given the origin or any points on the line.

What method should I use to programmatically determine the point of intersection for these two lines?

# Answer
> 4 votes
This *is* a plane intersection problem. You have two plane definitions in the point-normal form. The normal is given, and the point is the distance value `w` multiplied by the normal.

Wikipedia says:

> a point `P` with position vector `r` is in the plane if and only if the vector drawn from `P_0` to `P` is perpendicular to (normal vector) `n`.

(`P_0` is your plane's point, `n` is its normal)

If two vectors are perpendicular, their dot product is zero. Your solution is point `P`. So you have this equation twice, once for each plane:

```
n.x * (P.x - P_0.x) + n.y * (P.y - P_0.y) + n.z * (P.z - P_0.z) = 0;

```

So that leaves you with 3 unknowns and two equations. But lucky you, you happen to know that `P.z` is zero. Solve the remaining portion of the system of equations and you are done.

# Answer
> 1 votes
From https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect

Suppose you have 2 lines : (p,p+r) and (q,q+s). Now, these 2 lines intersect if we can find t and u such that: p + t r = q + u s. Solving both sides, we get t = (q − p) × s / (r × s). if rxs is 0, they are parallel. Visit the above link to understand briefly.

---
Tags: c++, geometry
---


title: Easing equations with moving end points

text:
# Question
Title: Easing equations with moving end points
Usually easing equations have 4 parameters:

* time
* duration
* begin point
* end point

For example:

```
public static float EaseOutQuad(float currTime, float begin, float end, float duration)
{
    currTime /= duration;

    return -end * currTime * (currTime - 2f) + begin;
}

```

Now afaik `begin` and `end` point are fixed values. In my game I have an object oscillating between 2 points on its local X axis. I'm interpolating its position using easing equations, but I would like to be able to modify the end point dynamically avoiding discontinous or abrupt changes.

Is it possible to do this using easing equations or something similar? Any suggestion?

# Answer
> 1 votes
If you parameterize the movement on time elapsed since the beginning (i.e. you don't compute the position incrementally, but fully every frame), and the end point also moves smoothly, you should get smooth movement without much problems.

Something like this:

```
start_x = 0
end_x = 100
total_time = 5  // 100 pixels in 5 seconds
t = 0
while t < total_time:
    t = min(t + delta_t, total_time)
    p = t / total_time
    x = start_x + p*(end_x - start_x)
    draw at x

```

is a simple linear interpolation between start\_x and end\_x. Note that `x` is a function of the parameter `p`, and it doesn't depend at all on the previous value of `x`.

So if you want the end point to move smoothly, it's just like this:

```
start_x = 0
end_x = 100
total_time = 5  // 100 pixels in 5 seconds
t = 0
while t < total_time:
    t = min(t + delta_t, total_time)
    p = t / total_time
    end_x += delta_t * speed_of_endx  // <----------
    x = start_x + p*(end_x - start_x)
    draw at x

```

That should work fine. Of course, the computation of the position of `end_x` will probably be decoupled from the computation of `x`; this is just an example.

# Answer
> 3 votes
A common scheme is simply lerping the new and old functions

```
Blend(oldBegin, oldEnd, oldT, newBegin, newEnd, newT, blendT) {
  oldPos = OldCurve(oldBegin, oldEnd, oldT);
  newPos = NewCurve(newBegin, newEnd, newT);
  return Lerp(oldPos, newPos, blendT);
}

```

There are decisions and bookkeeping to keep track of and decide when and how fast to transition from the old to the new curves. Specifically if i'm going from point A to B from time 0 to 1, then at time T decide i need to go to point C instead you have the choices:

```
// migrate curves with a blend time.  smoothest, but can be have high speed variance if B and C are far apart.
Blend(time) = {
  oldPos = Curve(A, B, time);
  newPos = Curve(A, C, time);
  return lerp(oldPos, newPos, (time - T) / BLEND_DURATION);
}

```

or maybe

```
// start new curve from current position.  lower speed variance
Blend(time) = {
  oldPos = Curve(A, B, time);
  newPos = Curve(oldPos, C, (time - T));
  return lerp(oldPos, newPos, (time - T) / BLEND_DURATION);
}

```

or something else that suits your use case better. For the best results, a good grasp of the underlying calculus (of both the curves as well as the externals causing the end point changes) can go a long way to crafting a formula to produce the desired effect.

---
Tags: interpolation, easing
---


# Question
Title: Mobile (bluetooth) connection to wiimote/controller
Looking to make a game for cross-platform mobile game. (Android, iOS, Win8)

Playing with a controller is a pretty important feature. Bluetooth connecting with a Wiimote works, but there are a few other bluetooth controllers I'd like to support as well. I can do this on a PC, because the bluetooth serial/connection is solvable.

Ideally, it'd be write-once.

Maybe a plugin for Unity3d? Maybe some other engine? I'm willing to use pretty much any engine that lets me write custom shaders.

At this point, trying to find examples of programs that can successfully connect, even to the wiimote, using bluetooth on a non-rooted android device is not going well.

# Answer
There is a wiimote plugin for unity. I have never used it, so I can´t tell you how much customization it needed to make it work with Android, ios and wp8. I guess you could get some help from the unity community but nevertheless this would be something for experineced unity users.

At least for WP8 I know about a bluetooth api, which may be used to connect to the wiimote, while you need to write most of the logical mapping by yourself.
> 0 votes

---
Tags: android, ios, mobile, windows-phone-8, bluetooth
---


title: Filling in a shape from vertices

text:
# Question
Title: Filling in a shape from vertices
What I'm trying to do is set a bunch of points to create a shape and then fill everything in within those points. It needs to be done in 3D becasue this is being used as a way to generate a texture for another shader I'm working on so the other shader knows what to highlight and what to not highlight.

Right now what I have a camera setup and I have it drawing a simple square with line lists. Eventually this will be extended upon to be more than just a simple square.

What is the best way to go about filling this shape in with a color, keeping in mind that it won't be a square later on.

# Answer
Sounds like you are asking for a convex hull, this is sortof like "gift wrapping" all your vertices. (Otherwise, if the shape can be concave you cannot imply it by the vertices alone)

Wikipedia has a good list of techniques here: http://en.wikipedia.org/wiki/Convex\_hull\_algorithms

And google code even has an implementation (I haven't tested this): http://code.google.com/p/stanhull/
> 1 votes

# Answer
**Triangulation**

If the shape is defined by a series of vertices/points which are listed linearly to create a outline/membrane then what you want is polygon triangulation.

By breaking the shape down into a list of triangles it will be possible to render like any other mesh in XNA (or opengl/directX). If you don't already know how to do this there are a plethora of triangle rendering tutorials out there for xna or pretty much any other system.

***Note:*** If the system generating the shape can guarantee that it is monotonic (convex) then you will probably be able to get away with rendering it as a triangle fan where the center (first point) is simply the average of all points making up the shape membrane.
> 0 votes

---
Tags: xna, color
---


title: How to move a rectangle properly?

text:
# Question
Title: How to move a rectangle properly?
I recently started to learn OpenGL. Right now I finished the first chapter of the *"OpenGL SuperBible"*. There were two examples. The first had the complete code and showed how to draw a simple triangle. The second example is supposed to show how to move a rectangle using SpecialKeys. The only code provided for this example was the SpecialKeys method. I still tried to implement it but I had two problems.

1. In the previous example I declared and instaciated *vVerts* in the *SetupRC()* method. Now as it is also used in the *SpecialKeys()* method, I moved the declaration and instantiation to the top of the code. Is this proper c++ practice?
2. I copied the part where vertex positions are recalculated from the book, but I had to pick the vertices for the rectangle on my own. So now every time I press a key for the first time the rectangle's upper left vertex is moved to (-0,5:-0.5). This ok because of

GLfloat blockX = vVerts\[0\]; //Upper left X

GLfloat blockY = vVerts\[7\]; // Upper left Y

But I also think that this is the reason why my rectangle is shifted in the beginning. After the first time a key was pressed everything works just fine. Here is my complete code I hope you can help me on those two points.

```
GLBatch squareBatch;
GLShaderManager shaderManager;
//Load up a triangle
GLfloat vVerts[] = {-0.5f,0.5f,0.0f,
                    0.5f,0.5f,0.0f,
                    0.5f,-0.5f,0.0f,
                    -0.5f,-0.5f,0.0f};

//Window has changed size, or has just been created.
//We need to use the window dimensions to set the viewport and the projection matrix.
void ChangeSize(int w, int h)
{
    glViewport(0,0,w,h);
}

//Called to draw the scene.
void RenderScene(void)
{
    //Clear the window with the current clearing color
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);

    GLfloat vRed[] = {1.0f,0.0f,0.0f,1.0f};

    shaderManager.UseStockShader(GLT_SHADER_IDENTITY,vRed);
    squareBatch.Draw();

    //perform the buffer swap to display the back buffer
    glutSwapBuffers();
}

//This function does any needed initialization on the rendering context.
//This is the first opportunity to do any OpenGL related Tasks.
void SetupRC()
{
    //Blue Background
    glClearColor(0.0f,0.0f,1.0f,1.0f);

    shaderManager.InitializeStockShaders();

    squareBatch.Begin(GL_QUADS,4);
    squareBatch.CopyVertexData3f(vVerts);
    squareBatch.End();

}

//Respond to arrow keys by moving the camera frame of reference
void SpecialKeys(int key,int x,int y)
{
    GLfloat stepSize = 0.025f;
    GLfloat blockSize = 0.5f;
    GLfloat blockX = vVerts[0]; //Upper left X
    GLfloat blockY = vVerts[7]; // Upper left Y

    if(key == GLUT_KEY_UP)
    {
        blockY += stepSize;
    }

    if(key == GLUT_KEY_DOWN){blockY -= stepSize;}

    if(key == GLUT_KEY_LEFT){blockX -= stepSize;}

    if(key == GLUT_KEY_RIGHT){blockX += stepSize;}

    //Recalculate vertex positions
    vVerts[0] = blockX;
    vVerts[1] = blockY - blockSize*2;

    vVerts[3] = blockX + blockSize * 2;
    vVerts[4] = blockY - blockSize *2;

    vVerts[6] = blockX+blockSize*2;
    vVerts[7] = blockY;

    vVerts[9] = blockX;
    vVerts[10] = blockY;

    squareBatch.CopyVertexData3f(vVerts);

    glutPostRedisplay();
}

//Main entry point for GLUT based programs
int main(int argc, char** argv)
{
    //Sets the working directory. Not really needed
    gltSetWorkingDirectory(argv[0]);
    //Passes along the command-line parameters and initializes the GLUT library.
    glutInit(&argc,argv);
    //Tells the GLUT library what type of display mode to use, when creating the window.
    //Double buffered window, RGBA-Color mode,depth-buffer as part of our display, stencil buffer also available
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH|GLUT_STENCIL);
    //Window size
    glutInitWindowSize(800,600);
    glutCreateWindow("MoveRect");
    glutReshapeFunc(ChangeSize);
    glutDisplayFunc(RenderScene);
    glutSpecialFunc(SpecialKeys);
    //initialize GLEW library
    GLenum err = glewInit();

    //Check that nothing goes wrong with the driver initialization before we try and do any rendering.
    if(GLEW_OK != err)
    {
        fprintf(stderr,"Glew Error: %s\n",glewGetErrorString);

        return 1;
    }

    SetupRC();

    glutMainLoop();
    return 0;
}

```

# Answer
> 1 votes
If you want to move the rectangle as whole all you need to do is adding an offset to every vertex -which is also equivalent to multiplying each vertex with a translation matrix. What you need to do is simply, given that Vertex and Offset are both of type Vector3 which is something you can easily achieve (and will save a lot of headache

```
struct Vector3
{
  float x;
  float y;
  float z;

  // you also need to overload some arithmetic operators
}

for (int i=0; i < vertexCount; ++i)
   vVerts += offset;

```

and for key hits you only set the offset value,

```
 if(key == GLUT_KEY_DOWN){offset.y -= 1;} // make sure to reset offset on key up

```

Keep in mind that this is not how vertices are usually transformed in OpenGL, eventhough it's acceptable it doesn't give you the advantage of using matrices and shaders.

From your question, it seems you are learning using OpenGL Super Bible 5th/6th which is something I don't recommend for a beginner please check my answer here for the reason, I recommend 4th edition for beginners and then learning the buffers and the more advanced stuff from 5th/6th.

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


title: Bump mapping Problem GLSL

text:
# Question
Title: Bump mapping Problem GLSL
I am having a slight problem with my Bump Mapping project. Although everything works OK (at least from what I know) there is a slight mistake somewhere and I get incorrect shading on the brick wall when the light goes to the one side or the other as seen in the picture below:

The light is on the right side so the shading on the wall should be the other way. I have provided the shaders to help find the issue (I do not have much experience with shaders).

**Shaders:**

```
varying vec3 viewVec;
varying vec3 position;
varying vec3 lightvec;
attribute vec3 tangent;
attribute vec3 binormal;
uniform vec3 lightpos;
uniform mat4 cameraMat;

void main()
{

    gl_TexCoord[0] = gl_MultiTexCoord0;
    gl_Position = ftransform();

    position = vec3(gl_ModelViewMatrix * gl_Vertex);
    lightvec = vec3(cameraMat * vec4(lightpos,1.0)) - position ;

    vec3 eyeVec = vec3(gl_ModelViewMatrix * gl_Vertex);
    viewVec = normalize(-eyeVec);

}

uniform sampler2D colormap;
uniform sampler2D normalmap;

varying vec3 viewVec;
varying vec3 position;
varying vec3 lightvec;

vec3 vv;

uniform float diffuset;
uniform float specularterm;
uniform float ambientterm;

void main() {

    vv=viewVec;

    vec3 normals = normalize(texture2D(normalmap,gl_TexCoord[0].st).rgb * 2.0 - 1.0);

    normals.y = -normals.y;

    //normals = (normals * gl_NormalMatrix).xyz ;

    vec3  distance = lightvec;
    float dist_number =length(distance);
    float final_dist_number = 2.0/pow(dist_number,diffuset);
    vec3  light_dir=normalize(lightvec);
    vec3  Halfvector = normalize(light_dir+vv);
    float angle=max(dot(Halfvector,normals),0.0);
          angle= pow(angle,specularterm);
    vec3 specular=vec3(angle,angle,angle);
    float diffuseterm=max(dot(light_dir,normals),0.0);
    vec3 diffuse = diffuseterm * texture2D(colormap,gl_TexCoord[0].st).rgb;
    vec3 ambient = ambientterm *texture2D(colormap,gl_TexCoord[0].st).rgb;
    vec3 diffusefinal = diffuse * final_dist_number;
    vec3 finalcolor=diffusefinal+specular+ambient;

    gl_FragColor = vec4(finalcolor, 1.0);

}

```

# Answer
I am flipping y because the bricks were lit on the opposite side, and that fixed it.

I found the problem with the shadow: I had to do `position = cameraMAT *gl_Vertex` instead of `gl_Modelviewmatrixi`.

I do not really know why this fixed the problem though.
> 2 votes

---
Tags: shaders, glsl
---


title: Libgdx InputListenner not working

text:
# Question
Title: Libgdx InputListenner not working
I've added an `InputListener` to my `libgdx` `actor` and I've added the `actor` to the `stage`. The `stage` (and all of its actors) gets drawn just fine.

The problem is my `actor` doesn't seem to be receiving keyboard inputs as nothing happens when I press keys.

```
@Override
public void show() {
 stage = new Stage();
 player = new Player();
 player.setPosition(600, 600);
 stage.setKeyboardFocus(player);
 player.addListener(new InputListener(){
   @Override
   public boolean keyDown(InputEvent event, int keyCode) {
    System.out.println("Key Down");
    return true;
   }
 });
 stage.addActor(player);
}

```

# Answer
> 1 votes
The problem was I hadn't set the `stage` as the `InputProcessor`, so I did that `onShow()`:

```
@Override
public void show(){
 ...
 Gdx.input.setInputProcessor(stage);
}

```

I also set it to null `onHide()` just in case:

```
@Override
public void hide(){
 ...
 Gdx.input.setInputProcessor(null);
}

```

# Answer
> 0 votes
Notice

```
int keyCode

```

Replace it with the key code of the key you want it to listen for.

---
Tags: java, libgdx
---


title: Falling Blocks and complex shapes

text:
# Question
Title: Falling Blocks and complex shapes
I currently have a simple Tetris-like game and have come across a problem I cannot solve.

Unlike Tetris where there is a **single** falling shape, I have multiple, potentially interlocking shapes that need to fall; I need to calculate their final positions. Consider the following:

1. To calculate the final position of the green shape, I simply scan down for every square until I hit another square or the edge of the board. **Done**
2. For multiple, simple shapes I work my way UP the board. Thus the red is found to not need moving, the orange goes down by one, the green down by three. **Done**
3. I don't know how to treat the interlocked green and red shapes. Using the logic of #2 we would end up "stuck" floating mid-air. If I scan down for the green shape, I encounter the red and thus do not move, and vice-versa for the red. The solution might be to treat the two shapes as one.
4. Similar to #3, in this scenario I could also succeed by treating the objects as one.
5. Unlike #3 and #4 I could not treat the shape as one as the orange shape would end up floating one-square too high...
6. Another variation of problem #6.

There could be other scenarios whereby I have many many shapes that interweave in more and more complex scenarios, but I think the above covers the most fundamental parts of the problem.

I feel like there's an elegant solution that I've yet to encounter / think up and would be very grateful at any insight, ideas or resources.

**SOLUTION**

The solution I've come up with is indeed elegant, based on @user35958's answer below, I have created the following recursive function (pseudo code)

```
function stop(square1, square2){
    // Skip if we're already stopped
    if(square1.stopped){
        return;
    }
    // Are we comparing squares?
    if(!square2){
        // We are NOT comparing squares, simply stop.
        square1.stopped = true;
    } else {
        // Stop IF
        // square1 is directly above square2
        // square1 is connected to square2 (part of the same complex shape)
        if(square1.x == square2.x && square1.y == (square2.y+1) || isConnected(square1, square2)){
            square1.stopped = true;
        }
    }
    // If we're now stopped, we must recurse to our neighbours
    stop(square1, squareAbove);
    stop(square1, squareBelow);
    stop(square1, squareRight);
    stop(square1, squareDown);
}

```

**Animated GIF showing each pass of the solution**

To summarise:

* When "stopping" a square, we also stop:
    + ANY square above it. ALWAYS.
    + Neighbouring square that we are connected to (ie the same shape).
* We stop the entire bottom row, and the function recurs up through the squares.
* We repeat until all squares are stopped.
* Then we animate.

# Answer
> 4 votes
Well, you don't exactly need to treat to shapes as one if there's a distinction between shapes that are moving and shapes that are at rest. A shape (A) could detect a shape (B) directly below it and if it's moving, then the B shape could then see if there's anything directly below it, and if there's an resting shape, then A and B are now resting, and if there's nothing, they both move down, but if there is a moving shape, then this new shape will be treated by A and B as A treated B, so it's sort of recursive. Keep in mind that for each step, the lowest shapes need to check for shapes below them first.

So, for problem #6, the green shape is the lowest moving shape, and it would see that the only shape that's directly below it is the red shape, so then the red shape would detect nothing directly below it, and they would move down. Once the green shape is adjacent to the orange shape, it would rest, and the red shape would move down and then detect the resting green shape, and it would rest too.

# Answer
> 3 votes
It seems like the problem with cases #5 and #6 stem from a single root: **you're only performing one pass of movement checks.** You should keep moving things down (lets call it a "gravity pass") until you know nothing moved.

For example, in case 6, this is what would happen if you used multiple passes:

* Orange moves down
* Green moves down
* Orange moves down
* Green moves down
* Orange moves down
* Nothing moves down (done!)

This strategy of multiple gravity passes could solve #5 as well, although it won't help with cases #3 and #4 where it seems you need to treat them like one piece.

To distinguish when two or more pieces should be treated as a single piece, I think the easiest algorithm is to check if there are any "holes" in the combined space of all the pieces. If there are, it can be treated as multiple pieces.

---
Tags: 2d, collision-detection, grid
---


# Question
Title: Making the player fall below the actual map
I have a 2d map of integers

```
0000000000
0200000001
1111100011

0 = sky/empty
1 = ground
2 = player

```

When player falls in a hole/cliff I want the player to go below the map, so it will look like the player had died by falling in the hole/cliff.

Here is what I did:

```
if(player.getY()+player.getHeight() > map.getHeight()){
   //player has fallen in hole/clifff
}

```

The code above will test if the player's feet touch the end of map. But how to move him below the map? Because if I move the player down then the array will be out of bounds.

Is there way without changing the map array?

# Answer
Don't save the player position inside the map, save it external.

You could also lay an simple interface around the raw map access to check for the position where the player is currently. If an access to that position were made you just return a `2`.

The design as an simpified UML:

```
IMap
+ int getObjectAtPosition(int x, int y)
+ Vector2i getSize()

```

Vector2i is a 2d vector with x and y components. Of course the implementation for this interface must have an method for tetting the player position and getObjectAtPosition should do the above mentioned stuff.

To check for the death of the player because he is outside the map you need to check the height against the minimal height of the map *before* an access to the array. If it is below the borders just let the player die or do some other fancy stuff.
> 4 votes

---
Tags: animation, maps
---


# Question
Title: What input and window handler should I learn for complement OpenGL?
I have a good base in C++ programming and I did some 2D games using SDL. Now I want to start making 3D games, but as much as posible, I want to learn following the standars of the profesional industry. I think learning openGL I will have more acuratte skills for programming 3D graphics, so I prefer to study openGL instead of a game engine. But my cuestion is, what library I should choice for complement openGL in the area of the input and windows handler, if posible, following the standars of the industry?

Thanks you in advance for the help! (And sorry for my bad english)

# Answer
SDL Is a fairly good choice. Typically used in cross-platform and Open-Source Projects. Including in professional applications. Not limited to, but including these few SDL applications. Including 3D applications, with it's OpenGL binding ability.

However, a lot of professional game companies will make their own game library/engine. Creating it by learning the target system's API. And they will, in particular, learn how to create a window through that API, including how to bind OpenGL to it.

A list of those APIs for common systems are:

* Windows - WinAPI
* \*nix - X windows
* Mac - cocoa
> 0 votes

---
Tags: opengl, c++, input
---


# Question
Title: Box2d making a body follow the mouse accurately
I am trying to make a box2d `b2Body` follow my mouse position. This is the code I am using at the moment but it is not performing very well:

```
deltaPos = mousePos - body->GetPosition();
deltaPos *= k;
body->ApplyForce(deltaPos, b2Vec2(0, 0));

```

I have tried playing with `k` but the body either lags too far behind the mouse or flies round and round the mouse like crazy. Should I be using an exponentiation there instead of multiplication? I am scared of applying too much force and breaking the sim (I suppose I could use a max).

Is there a more straightforward way to do this?

# Answer
> 2 votes
You can use a Mouse Joint to "attach" the mouse to the body (see http://www.box2d.org/manual.html#\_Toc258082974)

If that doesn't work well for whatever reason, the manual suggests using a kinematic body and adjusting its position manually(http://www.box2d.org/manual.html#\_Toc258082973)

---
Tags: c++, mathematics, physics, box2d
---


# Question
Title: What is the term that describes the "user" of a status ailment
Suppose a Snake performs a skill that inflicts a "poison" status on the Hero, and every minute the Hero receives damage equal to the Snake's skill level.

What is a term that would describe the snake as the object that inflicted the status ailment, that players would recognize or be able to figure out based on context? I imagine there are some standard terminology used in the industry.

Some things I have thought of include "applier" or "inflicter".

# Answer
> 4 votes
http://en.wikipedia.org/wiki/Status\_effect

According to the above, one can glean the following:

1. a positive effect is a Buff
2. a negative effect is a Debuff
3. the recipient of either is the Target
4. the source of either is the Caster

Ergo, the poison effect would be a Debuff with the Snake as the Caster and the Player as the Target

---
Tags: terminology
---


# Question
Title: Movement doesn't look smooth (slight lag)
Currently I'm using a variable time step and when the FPS drops by even a small amount you can easily notice a slight lurch forward of the player. I'm making a platformer and I'm wondering whether I should use a fixed timestep instead, however I'm confused as to why my movement doesn't look smooth, because the various articles I've read all say that a variable timestep is meant to make movement look much smoother.

**So my question:** Is a fixed timestep the better option for a 2D platformer, and why would anyone even use a variable timestep if your sprite appears to jump forward every 2-3 seconds?

```
private static final int UPDATE_RATE = 90;
private static final long UPDATE_PERIOD = 1000000000L / UPDATE_RATE;

private void mainLoop() {
    long beginTime, timeTaken, timeLeft;
    while (state == State.PLAYING) {
        beginTime = System.nanoTime();

        update();
        repaint();

        timeTaken = System.nanoTime() - beginTime;
        timeLeft = (UPDATE_PERIOD - timeTaken) / 1000000L;
        if (timeLeft < 10)
            timeLeft = 10;
        try {
            Thread.sleep(timeLeft);
        } catch (InterruptedException ex) { }
    }
}

```

Delta time is calculated every time repaint is called.

```
long currentTime = System.nanoTime();
        deltaTime = (currentTime - previousTick) / 1000000L;
        previousTick = currentTime;

```

This is how I pass the delta time into the player class.

```
public void move(float deltaTime) {
    if(left && !right)
        xPos -= 250*(deltaTime/1000);
    if(right && !left)
        xPos += 250*(deltaTime/1000);
}

```

# Answer
**Get rid of the Sleep call**.

Sleep is *fine* for reducing CPU usage, but it is *not fine* for controlling framerate, and these two are not the same thing.

* Sleep can have poor precision, in the order of ~16 milliseconds.
* Sleep guarantees that the thread will resume *at some arbitrary time* **after** the Sleep interval has elapsed, not at the exact Sleep interval.

Since this is tagged Java, I'm going to refer you to http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html and quote:

> these sleep times are not guaranteed to be precise ... you cannot assume that invoking sleep will suspend the thread for precisely the time period specified

If nothing else, this is completely messing up your timestep. Given the poor granularity of Sleep calls, if you go even a little above one Sleep interval you're now Sleeping for two intervals - and as I said, a default Sleep interval can have a granularity of ~16 milliseconds.

If you want (or need) to reduce CPU usage, you can keep a count of time elapsed since the previous frame, and if it's not yet time to run a frame, Sleep for *one* millisecond, otherwise run the frame. Combine this with a method of improving the precision of Sleep (I don't know Java so I can't advise what's appropriate here) and your program will be a succession of Sleep (1) calls with the occasional frame interspersed.

But either way, the point remains: **do not use Sleep for controlling framerate**.
> 6 votes

# Answer
deltaTime = (float)(currentTime - previousTick) / 1000000.f

It's a simple floating point bug. When you divide an integer by another integer it returns an integer. This truncates all your decimal detail.
> 2 votes

---
Tags: java, lag, timestep
---


# Question
Title: How to implement trading card game's "special effects cards"?
I am trying to write a kind of a trading card game here, in some way, it is similar to *Magic The Gathering*, or the *Yu-Gi-Oh!* card game.

For those of you who are not familiar with it, basically, in the game, there is a special kind of card (Spell cards/ Trap cards/ etc.), which have special effects that can bend the rules of the game. What I totally have no idea is, how to implement the logic of these cards. I have some idea of storing the card's data with some flags that can signal what kind of ability it has, but that would be very limited in what it can do (only some simple stats modification, maybe).

To give you an idea of what kind of effects these cards can have, here is some example of the spell card effects that are present in the *Yu-Gi-Oh!* card game:

* Revive a creature that has been destroyed
* Take control of the opponent's creature
* Modify stats of the creature based on some conditions (e.g. Number of creature with certain names that have been destroyed)
* Special summon a certain creatures if the some conditions are fulfilled.
* Fuse two or more creatures into a stronger creature.
* Immunity to some of the special cards' effect.

Konami has made several video games of the game, complete with the AI and thousands of cards variety. I don't think it is actually possible to hard-code the entire database, is it?

Now, of course what I am trying to do is in no where as complex as those games, but I am curious, how do they implement these?

# Answer
> 18 votes
There are several open-source projects of this nature, with different approaches to implementing the rules. Here is a blog entry from the creator of one of the more well-known MtG implementations, CardForge. It may not be a complete list, but it contains several open-source projects where you can simply browse the code, or visit the forums for specific questions.

As an actual answer: Your best bet for a robust framework is to strictly employ Object-Oriented Programming. Every Action, every Trigger, every Ability is an object. Zones like Hand, Library are objects too, needless to say. In the Rules engine, never pass around dumb objects like strings or integers to describe game objects, but your objects only.

Every action puts a number of trigger on a stack, where every other ability can check whether or not they care about that particular trigger, and if they do, they fire their own actions, potentially creating new triggers, and so on.

Then you work down those stacks according to the game's rules, until the stack is empty, at which point new actions can be taken etc.

Ideally, if you perfectly implement the game's rules, your rules code does not contain a single hardcoded card. Hardcoding cards can create convenient shortcuts, but in the long run, this will bloat your code and create potential pitfalls, such as when new cards are released that interact with those cards in a novel way. In a game like MtG with over 12,000 unique cards and no end in sight, there are MANY such interactions.

# Answer
> 2 votes
It is quite futile task to try incorporate all that with switches and variables alone. You would have to either hard code functions or, more likely, have a script that you interpret during the runtime. You would expose necessary functions to check status of the board and decks and graveyards to the script and the functions to execute actions, and so on. The script is then just a simple string to store along with the other variables associated with the card.

# Answer
> 1 votes
I also am planning out card game using web languages with mysql db. I am currently going for a very generic setup so it keeps very flexible to new unique cards. For example instead of :

```
reduceHitPoints() { }
reduceMana() { }
reduceSpeed() { }

```

it could easily be:

```
reduce($attacker, $target, $reduceWhat, $amount) { }
massReduce($attacker, Array $targets, $reduceWhat, $amount) { }

```

applying this concept for all actions will simplify classes, allow for new cards to be created by simply adding a single row into your cards table.

All the options and abilities will get defined in the db in that single row.

---
Tags: architecture, game-mechanics, card-game
---


# Question
Title: How can I design lots of different attack types that can be combined?
I'm making a top down 2D game and I want to have a lot of different attack types. I'd like to make the attacks very flexible and combine-able the way The Binding of Isaac works. Here's a list of all the collectibles in the game. To find a good example, lets look at the Spoon Bender item.

> Spoon Bender gives Isaac the ability to shoot homing tears.

If you look at the "synergies" section, you'll see it can be combined with other collectibles for interesting yet intuitive effects. For example, if it combines with The Inner Eye, it "Will enable Isaac to fire multiple homing shots at once". This makes sense, because The Inner Eye

> Gives Isaac a triple shot

What's a good architecture to design things like this? Here's a brute force solution:

```
if not spoon bender and not the inner eye then ...
if spoon bender and not the inner eye then ...
if not spoon bender and the inner eye then ...
if spoon bender and the inner eye then ...

```

But that will get out of hand very fast. What's a better way to design a system like this?

# Answer
You totally don't need to hand-code combinations. You can instead focus on the properties that each item gives you. For instance, *Item A* sets `Projectile=Fireball,Targetting=Homing`. *Item B* sets `FireMode=ArcShot,Count=3`. The `ArcShot` logic is responsible for sending out `Count` number of `Projectile` items in an arc.

These two items can be combined with any other items that modify these (or other) properties freely. If you add a new type of projectile it'll just automatically work with `ArcShot`, and if you add a new firing mode it'll automatically work with `Fireball` projectiles. Likewise, `Targetting` is a property that sets the controller for the projectiles while `FireMode` creates the projectiles, so they can be easily and trivially combined in any combination as makes sense.

You might also set of property dependencies and such. For instance, `ArcShot` requires that you have a provider of `Projectile` (which might just be the default). You might set priorities so that if you have two active items that both provide `Projectile` the code knows which one to use. Or you can provide UI to let the user select which projectile type to use, or simply require the player to unequip high-priority items he doesn't want, or use the most recent item, etc. You can further allow a system of incompatibilities, e.g. such that two items that both just modify `Projectile` cannot both be equipped simultaneously.

In general, when possible, prefer any kind of *data-driven* approach (or *declarative*) over *procedural* approaches (the big if-else messes) when it comes to the objects and such in your game. Higher-level generic logic that is configurable by simple data is much preferable over hard-coded lists of special-cased rules.
> 16 votes

# Answer
If you are using an OOP language, this sounds like a good place to employ the Decorator Pattern. When you want to modify how an attack happens just decorate it with the appropriate augmentation.

Crude c++ Example:

```
class AttackBehaviour
{
    /* other code */
    virtual void Attack(double angle);
};

class TearAttack: public AttackBehaviour
{
    /* other code */
    void Attack(double angle);
};

class TripleAttack: public AttackBehaviour
{
    /* other code */
    AttackBehaviour* baseAttackBehaviour;
    void Attack(double angle);
};

void TripleAttack::Attack(angle)
{
    baseAttackBehaviour->Attack(angle-30);
    baseAttackBehaviour->Attack(angle);
    baseAttackBehaviour->Attack(angle+30);
}

```

This method would be best if you have a very large number of attacks and you need to have them all behave in more or less the same way. If you want to substantially change the way the attack happens with the modifier (e.g. new animation with modifier) then this method is not for you.
> 8 votes

# Answer
As a fan of Binding of Isaac, I too have wondered how to go about something like this. The system in the game is robust enough where emergent behaviors come about from the combination of effects (the one that comes to my mind is getting mirror, spoon bender, and some range boosters results in a swirling, homing tear wall around Isaac, Magneto style). The sheer number of them would make an "if" block impractical.

My conclusion is that Isaac and his tears are two entities in the center of a massive Component-Entity Framework. The entities have some basic stats (movespeed, life, range, damage, sprite, etc) and each component would bring along a stat modifier and a verb.

In code, Isaac and his tears would each have a list that would contain things of an interface. Isaac would have a list of things that subscribe to interface IsaacMutator, and his tears tearMutator. IsaacMutator would have functions to modify Isaacs health, speed, range, looks, and some special verb. TearMutator would be similar. Once per game loop, Isaac would loop through all IsaacMutators that it has, and all living tears would too. To go by your English example, it would read like:

```
Isaac has IsaacMutators:
--spoonbender which gives no stat change and: Tears are made homing
--MeatEater which give +1 health, +1 damage and: nothing
--MagicMirror which gives no stat change and: Tears are made reflecting

Tears have tearMutators:
--(depends on MeatEater) +1 damage and: nothing
--(depends on MagicMirror) no stat change and: +1 vector towards isaac
--(depnds on spoonbender) no stat change and: +1 vector towards enemytype

```

and so on. Because the types are additive, you can stack and add and remove to your hearts content.
> 2 votes

# Answer
I think your way works best. These sort of items each give a condition, if used together they produce a different condition, then you would effectively need all 3 possible conditions defined.

You could also go about it by creating a new type of definition when both items are present, but this actually adds to the convolution:

```
if spoon bender and the inner eye then new spoon bender inner eye

if spoon bender inner eye then ...

```
> -5 votes

---
Tags: game-design, architecture, design-patterns
---