# Question
Title: How to get drawn Image width/height on the screen with openGL ES on Android?
I need to know how to get drawn image length and width.

I have this code so far where I draw Radar in left top corner with hard-coded coordinates:

```
int _SRC = R.drawable._item;

...

float vertices[] = {
            0f,  0f,  0.0f,
            0f,  2.0f,0.0f,
            2.0f,0f,  0.0f,
            2.0f,2.0f,0.0f
    };
...

addRadarToView(0,240);

...

public void addRadarToView(float x, float y) {
    this.x = x;
    this.y = y;
}

 ...

private void updateScreenData(float screenWidth, float screenHeight){
    // takes screen Height and Width
    this.mScreenWidth = (screenWidth > 0) ? screenWidth : 1f;
    this.mScreenHeight = screenHeight;
    wRatio = 10f/mScreenWidth;
    hRatio = mScreenHeight/10f;
}

 @Override
public void loadTextures(GL10 gl) {
    Log.e(LOG_TAG, "loadTextures");

    InputStream is;

    is = mContext.getResources().openRawResource(_SRC);

    Bitmap bitmap = BitmapFactory.decodeStream(is);

    try {
        is.close();
        is = null;
    } catch (IOException e) {
    }

    gl.glGenTextures(TEXTURE_COUNT, textures, 0);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    bitmap.recycle();

}

 protected void drawRadar(GL10 gl){
    gl.glPushMatrix();
    try {
        float transx =  (wRatio * (x));
        float transy =  (mScreenHeight*wRatio) - (wRatio * (y)) - 1/hRatio;
        // Log.e(LOG_TAG, "transx: " + transx + "; transy: " + transy + "; sprite.x: "+  sprite.x + "; sprite.y: " + sprite.y);

        gl.glTranslatef(transx, transy, 0.0f);

        //###########  draw ##############

        gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, floatBufferArray[mFrame]);

        //update();

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
        gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        //###############################

    } catch (NullPointerException e) {
    }
    gl.glPopMatrix();
}

```

I used `addRadarToView(0,240);` to set x=0 and y= 240;

So as I see `x` represents left border of vertices. When 240 is `y` that represents bottom border. Strange.

**\[EDIT\]**

In canvas i used something like:

```
 int srcX = currentFrame * width;

Rect  src = new Rect(srcX, 0, srcX+width, height);
Rect  dst = new Rect(x, y, x+width, y+height);
canvas.drawBitmap(bitmap, src, dst, null);

```

Where `width` and `height` are:

```
bitmap.getWidth();
bitmap.getHeight();

```

Please, help me to sort it out.

Thanks,

# Answer
> 2 votes
This is one of the great things about openGL over canvas. OpenGL and android will handle the scaling of the image for you. Depending on how you build your renderer class will determine exactly how you specify your vertices location, but generally if you follow a how to guide you will always be working in a plane from -1 to +1 for 2D games. This means that if you declare a bitmap within this plane you can simply use translatef() to move the image where it needs to be.

After looking at your code I believe the problems you are having is because you are attempting to use pixels to determine an amount to translate your image by. It is important to use raw measurements from a 1.0 dpi device to get your base pixel location, otherwise it will not scale properly.

This is how I did it here and here

To summarize I believe your confusion is coming from the fact that openGL does not use pixels to determine location but instead uses a vertices that are translated during run.

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


title: Copyright issues in games

text:
# Question
Title: Copyright issues in games
I have developed an android game which is a puzzle type game. since I am a fan of iron man myself and want to use its wallpapers in my gaming area background so my question is can I use it in my game without violations of copyright issues because I have seen some apps on playstore which uses iron man content like this https://play.google.com/store/apps/details?id=com.celfishmedia.ironman3

thanks in advance

# Answer
> 3 votes
Short answer, no. That isn't how copyright works. If you use someone else's copyrighted material without an agreement with the copyright holder, you are in violation of their copyright and they can tell you to remove the infringing parts of your work.

Long answer, ask a lawyer, because I'm not one. But in general, here's how it is:

Some companies are very laid back about fan-made content/use of copyrighted material and won't enforce their copyright unless you're doing something really bad that they'd rather not have their work associated with, or if you're profiting from it. Others will send out cease-and-desist letters for just about everything that would be considered infringing.

If you do choose to include those wallpapers, the worst that will happen at first is that you'll receive a cease-and-desist letter kindly asking you to remove the wallpapers or face legal action. If for some very stupid reason you choose to keep them, you will be faced with a lawsuit, and you will lose. Hands down. This question alone is enough evidence to show that you knew you were infringing on some copyrights.

---

As for the example, if you look at the other apps Cellfish has released, you'll see they have a bunch of company logos front and center, and all their apps describe themselves as the "official" app of that kind for that company/IP.

With those kinds of download numbers, they'd have the pants sued off of them by now were they not properly licensing the copyrighted material.

Some quick Googling revealed that Cellfish does way more than just make a few apps and that they were probably hired to make those apps by the copyright holders.

> Marvel is pleased to continue extending its digital offerings, now to Android wallpapers, with our new partners at Cellfish. It adds a lot of value for Avengers fans worldwide." said Peter Phillips, Senior Vice President and General Manager of Marvel Digital Media Group.

From this press release.

---
Tags: android
---


# Question
Title: What's the best way to compare blocks in a matching game that can be multiple colors?
I have a match 3-4 game and the blocks can be one of 7 colors. There are an addition 7 blocks that are a mix of the original 7 colors so for example there is a red and blue block and there is also a red/blue block which can be matched with either the red or the blue. My original thought is just to use binary operations so.

```
int red     = 0x000000001;
int blue    = 0x000000010;
int redblue = 0x000000011;

```

Then just do an & operation so see if they match. Does this sound like a decent plan or am I over complicating it?

edit:

Better yet so it's more readable.

```
int red = 1;
int blue = 2;
int red_blue = 3;
int yellow = 4;
int red_yellow = 5;

```

maybe as defines or static vars?

# Answer
This is probably the easiest way to do it - not overcomplicating it at all. However, I'd work with constants rather than variables (assuming those are available in your chosen language).

```
const int COLOR_ALL      = 0xffff; // or just -1
const int COLOR_RED      = 0x0001;
const int COLOR_BLUE     = 0x0002;
const int COLOR_YELLOW   = 0x0004;
const int COLOR_RED_BLUE = COLOR_RED | COLOR_BLUE; // saves you doing the math yourself (error prone)

```

Then, to verify the colors match you can simply do something like this:

```
// Assumption: picked_blocks is an array with the colors of the selected blocks

int check = COLOR_ALL;
for (int i = 0; i < num_picked_blocks && check; i++) // Whether "&& check" is worth it, really depends on the maximum number of blocks to check
    check &= picked_blocks[i]; // This will essentially remove all colors from check that aren't in this block

if (check)
    ; // Choice is valid.
else
    ; // Choice is invalid.

```
> 1 votes

---
Tags: logic
---


# Question
Title: How to develop a real-time game server for html5 web app?
I'm contemplating a graduate project proposal of developing a rather complex HTML5 game that requires real-time server communication. The premise of the actual game play is simple: 10 players battle it out with one another. Many pieces of information will be tracked, such as: player health, each players X/Y position on the screen, items in inventory, etc. The server structure for all of these potential changes, however, is not so simple.

My goal is to develop a scalable environment that can theoretically maintain 50,000 concurrent players in 5,000 separate game instances while all running reliably with less than 1 second latency. My comfort skill set is mostly in web technologies. For a small scale app, I would use PHP/MySQL. But for an app this large, I am confident HTTP requests will not be even a short term solution.

I don't really know how to approach this situation.

* Should I develop my own server, if so, what language should I use? I do not want to use NODE.JS. Is Python viable?
* Is a single, high-performance server capable of maintaining this type of load, or will I need to look into developing a cloud/cluster?
* What type of database read/write would be optimal for this situation? How would I scale beyond 50,000 players? How would this scale with a cloud/cluster?

# Answer
This is too broad, you need to work out some things.

* What do you call a high-performance server. You can get some very powerful servers with 4 CPU sockets and such. But it is likely 4 servers with a single socket may be cheaper.
* Real time (meaning each game instance must be processed all the time at some frequency) or turn based (meaning you just need to process whatever a player did on their turn)
* How complex is the game logic? 3D world? Physics? Advanced AI?
* Are the game instances like a single short match (I am guessing this for 10 players), and the the player joins another, or a persistent world?

Assuming you are trying to get somthing fairly demanding, but with each game being a single match, the generally direction I would go is:

* Carry on using PHP/SQL for the general website, registration, logins, any persistent stuff like player stats, any items/skills/etc they have, etc.
* Write the actual game as a separate thing, possibly almost without any database stuff. Just have the game instance load in whatever the 10 players needs from the DB at the start. At the end of the match it can save stuff back to the DB. Avoiding in game DB access for general game logic avoids the DB scaling issues.
* The game instance could be its own process (but 5,000 might not scale well). You can alternatively run the instances in there own like server process with some maximum per process, possibly then split down further with some number running on each thread. The downside is if you crash a process or have some other glitch you effect multiple games. Either way this is scalable, you can put these game servers on multiple machines.
* The game instances would be written as if you were doing a PC client-server game or similar. The main logic would not really care about the client being on a web browser. You will need something like a GameInstance.Update method that you can run x times per second, and reads anything from the client sockets, processes an update step and sends stuff back to the clients.
* The game server instances could use HTTP for communication with the browser client. You could also try out WebSockets which give a more raw TCP connection.
* The game server could use node.js which is useful if you want to share common code with the client and server. Another option to do that would be to use something like C/C++ with emscripten to compile to Javascript for the client and use native C/C++ on the server. There might be some other languages you can do similar things with, but those are the ones I have used.
> 6 votes

---
Tags: html5, browser-based-games, websocket, webapp
---


title: OBB vs OBB Collision Detection

text:
# Question
Title: OBB vs OBB Collision Detection
Say you have two Bounding Box Objects each of them storing the current vertices of the box in a vector with all the vertices of the object rotated and translated relative to a common axis.

Here is an image to illustrate my problem:

How can I work out if the two OBB's are overlapping any links to help explain the solution to the problem would be welcome. Nothing too convoluted please...

# Answer
> 26 votes
An OBB is a convex hull. A convex hull is a 3D shape that has no "crannies" on its surface. Every "bump" (vertex) on the convex hull *protrudes outward*, never inward. If you slice a plane through a convex hull you will get (only one) convex polygon. If you are inside a convex hull and fire a laser pointing outward you will only punch through the hull's surface *once* (never twice).

The Separating Axis Theorem test can be used to detect collision of convex hulls. The SAT test is simple. It works in 2D and 3D. Although the pictures below will be in 2D, they could just as easily be applied to 3D.

# Concept

This is the key concept you're using with SAT:

* Two shapes only intersect if **they have overlap when "projected" onto every normal axis of both shapes**.

"Projection" of a shape onto a 1D vector looks like this (what I call "crushing")

A shape with red verts, and an axis

"Projecting the shape to the axis" means dropping a perpendicular from each point on the shape just to land on the axis. You can think of this as "crushing" the points by a hand that gathers everything and perpendicularly crushes it down to the axis.

What you're left with: Points on an axis

# SAT says:

For 2 convex hulls to intersect, they have to overlap on **every axis** (where *every* normal on either shape counts as an axis we must check).

Take these 2 shapes:

You see they don't intersect, so lets try a few axes to show were an overlap *doesn't* happen.

Trying the top normal of the pentagon:

These are the extents. They do overlap.

Try left side of the rectangle. Now they do not overlap in this axis, therefore NO INTERSECTION.

# Algorithm:

For each *face normal* on both shapes:

* Find the minimum and maximum extents (largest and smallest value) of the projection of **all the vertex corner points** of both shapes onto that axis
* If they don't overlap, **no intersection**.

And that's really it. The code to make SAT work is very short and simple.

Here is some code that demonstrates how to do an SAT axis projection:

```
void SATtest( const Vector3f& axis, const vector<Vector3f>& ptSet, float& minAlong, float& maxAlong )
{
  minAlong=HUGE, maxAlong=-HUGE;
  for( int i = 0 ; i < ptSet.size() ; i++ )
  {
    // just dot it to get the min/max along this axis.
    float dotVal = ptSet[i].dot( axis ) ;
    if( dotVal < minAlong )  minAlong=dotVal;
    if( dotVal > maxAlong )  maxAlong=dotVal;
  }
}

```

Calling code:

```
// Shape1 and Shape2 must be CONVEX HULLS
bool intersects( Shape shape1, Shape shape2 )
{
  // Get the normals for one of the shapes,
  for( int i = 0 ; i < shape1.normals.size() ; i++ )
  {
    float shape1Min, shape1Max, shape2Min, shape2Max ;
    SATtest( normals[i], shape1.corners, shape1Min, shape1Max ) ;
    SATtest( normals[i], shape2.corners, shape2Min, shape2Max ) ;
    if( !overlaps( shape1Min, shape1Max, shape2Min, shape2Max ) )
    {
      return 0 ; // NO INTERSECTION
    }

    // otherwise, go on with the next test
  }

  // TEST SHAPE2.normals as well

  // if overlap occurred in ALL AXES, then they do intersect
  return 1 ;
}

bool overlaps( float min1, float max1, float min2, float max2 )
{
  return isBetweenOrdered( min2, min1, max1 ) || isBetweenOrdered( min1, min2, max2 ) ;
}

inline bool isBetweenOrdered( float val, float lowerBound, float upperBound ) {
  return lowerBound <= val && val <= upperBound ;
}

```

# Answer
> 7 votes
You should definitely look up **Separating Axis Theorem**. It's for convex objects. There is a rule: "If two convex objects don't intersect, then there is a plane where the projection of these two objects will not intersect".

You can find some examples on the wiki. But it's a little more complicated than for your case.

Something more suitable for your problem can be found here (two cars colliding).

# Answer
> 2 votes
More **SAT** articles.

The last article on this site comes with complete code, i think it's in FLASH, i've no idea, but i had exactly 0 issues converting it to C++ when i had to use SAT for the first time, shouldn't be hard to do the same for other languages. The only thing you'll have to add is storing of the displacement vector on each calculation (if it's the smallest, ofcourse, you'll understand this when you learn about SAT), the code in this tutorial doesn't do it, so you end up with the last calculated vector.

http://rocketmandevelopment.com/tag/separation-axis-theorem/

Good, old N-Game tutorials. Best SAT theory on the web.

http://www.metanetsoftware.com/technique/tutorialA.html

---
Tags: collision-detection, bounding-boxes
---


title: Draw quad with OpenGL VBO using OpenTK

text:
# Question
Title: Draw quad with OpenGL VBO using OpenTK
I'm trying to learn how to use VBO (Vertex Buffer Objects) by putting together a simple program that draws a quad to the screen using OpenTK (C# OpenGL bindings).

Unfortunately I'm not seeing anything on screen. If I draw the same quad in immediate mode it shows up fine.

Since it wasn't working I tried adding Color Data too (in case this was the problem) but it didn't help.

Any help would be greatly appreciated!

```
    private uint indexBufferId;
    private uint vertexBufferId;
    private uint colorBufferId;

    private void InitialiseData()
    {

        // Set-up index buffer:
        ushort[] indices = new ushort[] { 0, 1, 2, 3 };

        GL.GenBuffers(1, out indexBufferId);
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBufferId);
        GL.BufferData(
            BufferTarget.ElementArrayBuffer,
            (IntPtr)(indices.Length * sizeof(ushort)),
            indices,
            BufferUsageHint.StaticDraw);

        // Set-up vertex buffer:
        float[] vertexData = new float[] {
            50.0f, 50.0f,
            100.0f, 50.0f,
            100.0f, 100.0f,
            50.0f, 100.0f };

        GL.GenBuffers(1, out vertexBufferId);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferId);
        GL.BufferData(
            BufferTarget.ArrayBuffer,
            (IntPtr)(vertexData.Length * sizeof(float)),
            vertexData,
            BufferUsageHint.StaticDraw);

        // Set-up color buffer:
        float[] colorData = new float[] {
            1.0f, 1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f, 1.0f
        };

        GL.GenBuffers(1, out colorBufferId);
        GL.BindBuffer(BufferTarget.ArrayBuffer, colorBufferId);
        GL.BufferData(
            BufferTarget.ArrayBuffer,
            (IntPtr)(colorData.Length * sizeof(float)),
            colorData,
            BufferUsageHint.StaticDraw);

    }

    protected override void OnRenderFrame(FrameEventArgs e)
    {

        base.OnRenderFrame(e);

        GL.Clear(ClearBufferMask.ColorBufferBit);

        // Bind vertex buffer:
        GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferId);
        GL.EnableClientState(ArrayCap.VertexArray);
        GL.VertexPointer(2, VertexPointerType.Float, 0, IntPtr.Zero);

        // Bind color buffer:
        GL.BindBuffer(BufferTarget.ArrayBuffer, colorBufferId);
        GL.EnableClientState(ArrayCap.ColorArray);
        GL.ColorPointer(4, ColorPointerType.Float, 0, IntPtr.Zero);

        // Bind index buffer:
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBufferId);

        // Draw:
        GL.DrawElements(
            BeginMode.Quads,
            1,
            DrawElementsType.UnsignedShort,
            IntPtr.Zero);

        // Disable:
        GL.DisableClientState(ArrayCap.VertexArray);
        GL.DisableClientState(ArrayCap.ColorArray);

        SwapBuffers();

    }

```

# Answer
> 2 votes
In the glDrawElements call:

```
void glDrawElements(GLenum mode,  GLsizei count,  GLenum type,  const GLvoid * indices);

```

The second parameter count refers to number of vertices, not number of primitives.

Therefore the correct version of the above should be (using the OpenTK API):

```
GL.DrawElements( BeginMode.Quads, 4, DrawElementsType.UnsignedShort, IntPtr.Zero)

```

---
Tags: opengl, vbo, opentk
---


# Question
Title: gamemaker getting a ball to bounce 90 degrees off of a 45 angle
I am trying to get a circle to bounce off a 45 degree diamond shap using Gamemaker Studio. I would like the ball to bounce in straight lines so my directions would be 0, 90, 180, or 270 degrees, depending on which side of the diamond the collision takes place. Precise bouncing is giving me all sorts of results so I think I would have to do it in code.

I tried saying:

> if (direction \>=0 && direction \<=90) { direction = 90 }

And doing this for all the angles, but this did not work.

Has anyone encountered this before?

# Answer
> 0 votes
So for each triangle rotation assign it a type. and then depending on the angle you approach from change the angle then check it's type using other.type during a collision (or whatever variable you store the other object as when you check for a collision so if you do q = collision(??) which returns the object you collided at then you'd do q.type instead)

For example from the example below lets say the top left one is assigned type = 1 at creation

so

```
if(other.type == 1)
{
  if     (direction ==  0){direction = 90}
  else if(direction == 90){direction =270}
  else if(direction ==180){direction =  0}
  else                    {direction =180}
// no need to compare anything since only one left is direction == 270
// by process of elimination for the else statement
}

```

the others would be 2 3 4 respectively and it's up to you to keep track of which is which.

https://www.dropbox.com/s/bqaqapbr0fiv50m/triangles.png

there is probably a better way which would be to give one triangle object a direction which it would rotate it's image by when it's drawn and be given the direction at creation

and then that direction would be used in the calculations instead of checking type

```
  if     (direction ==  0){direction = 90 - other.direction}
  else if(direction == 90){direction =270 - other.direction}
  else if(direction ==180){direction =  0 - other.direction}
  else                    {direction =180 - other.direction}
// no need to compare anything since only one left is direction == 270
// by process of elimination for the else statement

```

so if the top left one is direction == 0 then the bottom left one would be direction == 90 and as you can see subtracting 90 from the end result creates the same desired effects.

---
Tags: physics, collision-resolution, game-maker, angles
---


# Question
Title: How to get the angle to an object from angle you are facing
I am making an creature simulator where the creatures have a neural net for a brain.

One of the inputs to the net is the angle it has to travel to go to be facing the nearest piece of food. I can get the nearest piece of food, but I need a way of getting the angle it needs to travel to be facing the piece of food.

For example, if it was facing the food, it would be zero, and if it was facing away it would be 180. I got the creatures angle, if it is facing up it would be 0 degrees, and if its facing right its 90 degrees.

# Answer
look up dot product on wikipedia. You need to calculate the dot product of the normalized direction vector you are facing and the normal vector of the surface. something like x1\*x2+y1\*y2. To get the angle between the two vectors you have to use the acos function.
> 0 votes

---
Tags: mathematics, python, pygame
---


# Question
Title: What does Skyrim Creation Kit's NPC class do?
I'm trying to change it with the setclass console command Based on the UESP wiki it looks like it just governs stat gain for leveling, but based on the Elder Scrolls wiki it seems to only control their combat AI.

Obviously it does at least one or both of those - what does it actually do, and does it do anything else? \__ Ex: if change Lydia from warrior1handed to vigilantcombat1h with the console command 000A2C94.setclass 0010bfef will it have any unintended side effects that aren't immediately apparent other than letting her use the alteration and healing spells I just gave her with console and setting her stats in a way that works for that?

Will it do something weird like mess with her factions or ability to join as my follower? Or mess with her health scaling as she levels? Something hard to notice until alot of time went by?

@desaivv\* I was trying to do it with 000A2C94.setclass 0010bfef wasn't sure if it'd cause hidden issues only showing after hours of play or if i made a new character with the same bat file. but the creation kit sounds like an idea too, i'll have to see how complicated it is. it might just show what it'd do or have some easier way to change her behavior to add spells. I'll try it and see if anything obvious shows up short term just wasn't sure if it had known long term problems

# Answer
> 1 votes
I'd like to point out that the "class" is a remnant from the old Elder Scrolls system, in which it defines what skills cause you to level up (and those would start at a higher level at the beginning of the game). I also once saw in the Strategy Guide that it has guidelines for different "class" builds. It sounds like this is the sort of thing "class" is referring to in this context.

# Answer
> -1 votes
Here is the Wikipedia definition of a Class

http://en.wikipedia.org/wiki/Class\_(computer\_programming)

> In object-oriented programming, a class is a construct that is used to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable its instances to have state and behavior.\[1\] Data field members (member variables or instance variables) enable a class instance to maintain state. Other kinds of members, especially methods, enable the behavior of class instances. Classes define the type of their instances.\[2\] A class usually represents a noun, such as a person, place or thing, or something nominalized. For example, a "Banana" class would represent the properties and functionality of bananas in general. A single, particular banana would be an instance of the "Banana" class, an object of the type "Banana".

**Here you will find basics on classes in the Creationkit** http://www.creationkit.com/Class

> The Class Form, used on the Actor Stats Tab, allows you to specify how an Actor will distribute the attribute and skill bonuses they gain based on their level. It also affects a few other systems, such as Bleedout for Essential Actors and skill training for Trainers. Class is only applicable to NPCs. It has no meaning for the player.

**Data Fields X-- X-- X--X-- X-- X--X-- X-- X--X-- X-- X--X-- X-- X--**

**1. ID:** The Form ID of the object.

**2. Full Name:** A label to identify the class. Not displayed in game.

**3. Auto-Calc Other:**

**3.1 Recharge:** Not used.

**3.2 Training:** If checked, this NPC is a Skill Trainer, and can train the player in the selected skill to the selected maximum value.

**4. Bleedout Default:** If the Actor is Essential or Protected, and their health falls below this ratio, they enter the Bleedout state and drop to one knee until their health recovers. This is typically set to 0.1, which means that Bleedout occurs when the Actor's health falls below 10%.

**5. Voice Points:** The pool of 'Voice Points' the Actor has for Shouts. Has no effect if the Actor has no Shouts.

**6. Description:** Not displayed in the game.

**7. Menu Image:** Not used.

> XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

**Here you will find the info that governs stat gaining etc.** http://www.creationkit.com/Stats\_Tab

---
Tags: modding, skyrim-modding
---


title: How to draw texture to screen in Unity?

text:
# Question
Title: How to draw texture to screen in Unity?
I'm looking for a way to draw textures to screen in Unity in a similar fashion to XNA's `SpriteBatch.Draw` method. Ideally, I'd like to write a few helper methods to make all my XNA code work in Unity. This is the first issue I've faced on this seemingly long journey.

I guess I could *just* use quads, but I'm not so sure it's the least expensive way performance-wise. I could do that stuff in XNA anyway, but they made `SpriteBatch` not without a reason, I believe.

So I see there is some sort of GUI notation in Unity. Maybe I could efficiently draw everything using it?

# Answer
Unity has an offical Wiki page on just this - a full blown SpriteManager. It does a lot more than just "draw textures" but it'll do what you want with batching. And it'll give quite a bit of flexibility. Give it a try.
> 5 votes

# Answer
As already mentioned by Vaughan the most popular free 2D framework for Unity is SpriteManager. However another widely used 2D graphics framework is 2D Toolkit; that's the one my company is using. It costs money, but it's not much and the framework has more features than SpriteManager, like tools to generate sprite atlases.

ADDITION: I just successfully displayed images loaded from the web, here's the code

```
  StartCoroutine(DownloadImage());
  ...

private IEnumerator DownloadImage() {
  WWW www = new WWW("http://www.server.com/image.png");
  yield return www;

  GameObject sprite = tk2dSprite.CreateFromTexture(www.texture, tk2dRuntime.SpriteCollectionSize.ForTk2dCamera(), new Rect(0, 0, 300, 150), Vector2.zero);
  sprite.transform.position = new Vector3(50, 500, -1000);
}

```

(because I had an older version of 2D Toolkit installed I had to do this in order for this to work; I believe the latest versions don't have this issue)
> 2 votes

---
Tags: xna, 2d, unity
---


# Question
Title: Implementations of task-based parallelism in game engines_
I'm looking for implementations of this because I'm having an especially hard time understanding how data is usually handled. As I understand it, simply using critical sections and locking code regions where modification of shared resources happens is a no-go, because locking and unlocking imposes quite severe performance penalties on the program.

So another approach would be to simply copy all relevant data when I create the task and pass it to a thread and overwrite the original data at the end or at the beginning of the following frame with whatever the worker thread returns to me... which results in the problem that if two tasks modify the same resource... it's unclear to me how to meaningfully resolve that "result collision".

I guess it's theoretically possible to apply only deltas of incoming changes: Let's say each entity, at the beginning of a frame, checks the messaging system for modifications to itself. If there are n modifications to the entities component e, then the new e would probably just be the old e plus the sum of all "old\_e - new\_e" for each n. But that seems kind of ugly and I'm not sure if it even works for things which are not just simple changes to single numbers.

Are there any open source examples which implement this system that I could actually look at?

# Answer
"Result collisions", as you put it, need to be handled with some type of synchronization. That can be locks, it can be atomics where possible (a good choice for simple things like adding up numbers, since there's often hardware support for atomic memory operations), or it can be some type of transactional approach. But no matter which solution you use, if you have high contention (many tasks needing to update the same memory), you will run into performance problems.

The short answer to dealing with contention is: don't do things that cause contention. :) Task-parallel systems need to be designed *not* to have result collisions at all, as much as possible.

For example, in some cases it's possible to switch to a gather model rather than a scatter one, where you have exactly one task for each result item and it pulls in whatever input data it needs. GPU shaders work this way, for instance; you have one shader thread for each output vertex, pixel, etc. and the shader reads buffers, samples textures etc. to get its inputs.

Another possibility, when all the output data really does need to end up merged together in one container, is to use the map-reduce pattern. You run independent "map" tasks, each of which has its own separate output buffer that it writes its results into. Then you run a collection of "reduce" tasks, whose job is to merge together two or more of those individual output buffers into a larger one. By structuring the reduce tasks as a tree, you can run several of them in parallel as well, merging larger result sets together at each step until you get down to just one. An example of this is mipmap generation.

All this was rather abstract, but for a look at a real task-parallel system, you might check out Fabian Giesen's Optimizing Software Occlusion Culling series, particularly the two "Care and feeding of worker threads" articles. This is about a software rasterizer, which you probably don't have in your game, but the principles apply in general.
> 1 votes

---
Tags: multithreading
---


# Question
Title: How to correctly represent a bone system?
I'm currently representing my bone system as follows, in pseudocode:

```
root = {}
root.rot = v3(0,0,0)
root.pos = v3(0,0,0)

function create_child(parent,rot,length):
    child_bone = {}
    child_bone.rot = parent.rot + rot
    child_bone.pos = parent.pos + v3(0,0,bone.length).rotate(child_bone.rot)

```

This works for most situations, but sometimes I get weird occasions where rotating a parent bone makes the child bones rotate wildly. What is the proper mathematical representation of a bone system?

# Answer
Heres basically the idea of how to find a bones location:

You start in the bones local space, where the root is on the origin and the tip has a distance equal to the bone lenght along one of the axis from it, you use the z-axis as far as i can tell from your code, i used x in my images, i will refer to it as z-axis from now on since you use it that way(image1).

To go to the parents local space you have to do a rotation followed by translation. the rotation is the bone´s rotation relative to it´s parent, now the tip of the parent bone (green bone in image) is at the origin, we have to do the translation along the z-axis for the lenght of the parent bone to get to the local space of the green bone where the root is in the origin. (image 3)

We repeat these steps to get to local space of the red bone (image 4 & 5)

The last rotation is to get from the red bones local space to the armatures local space.(image 6) Note how all rotations are rotationg around diffrent pivot-points(allways the origin of the current system, but since you do translations in between they change), which is one of the problems in the code you posted.

You might have to apply another set of transformations to get to world-space if neccesary, if your armatures local space is not translated nor rotated relative to world space these steps aren´t required.

In my opinion there are 2 good ways of applying these transformations, one is by using matrices, the other by using quaternions.

> The 4 points p0, p1, p2 and p3 are the 4 points you see in image 6, they are in order: red root, green root, blue root, blue tip.
>
> len0 is red´s lenght, len1 is green´s lenght and len2 is blue´s lenght.
>
> Rotations used are 30 for red (r0, q0), -30 for green (r1, q1) and 60 for blue (r2, q2). All relative to parent.
>
> Matrices have Column-vectors and post-multiplied because of that, so the transformations are applied from right to left.
>
> **Matrices:**
>
> ```
> //rotate creates a rotation matrix represented by an angle and an axis
> //translate creates a translation matrix along the specified vector
>
> mat4 r0 = rotate(30,vec3(1,0,0)) * translate(vec3(0,0,len0));
> mat4 r1 = rotate(-30,vec3(1,0,0)) * translate(vec3(0,0,len1));
> mat4 r2 = rotate(60,vec3(1,0,0)) * translate(vec3(0,0,len2));
>
>
> p0 = glm::vec4(0,0,0,1);
> p1 = r0 * p0;
> p2 = r0 * r1 * p0;
> p3 = r0 * r1 * r2 * p0;
>
> ```
>
> **Quaternions:**
>
> ```
> //angleAxis creates a Quaternion based on the angle and an axis
>
> quat q0 = angleAxis(30,vec3(1,0,0));
> quat q1 = angleAxis(-30,vec3(1,0,0));
> quat q2 = angleAxis(60,vec3(1,0,0));
>
> p0 = vec3(0,0,0);
> p1 = q0 * vec3(0,0,len0);
> p2 = q0 * ( (q1 * vec3(0,0,len1) ) + vec3(0,0,len0) );
> p3 = q0 * (q1 * ( (q2 * vec3(0,0,len2) ) + vec3(0,0,len1) ) + vec3(0,0,len0) );
>
> ```

The code is basically applying all the transformations as described in the beginning. THe matrices are basically doing the translation and rotation for a single bone in one step, whereas the quaternions can only store rotation and you have to translate them in an extra step.

You can calculate the positions you need as described here. You can´t calculate a rotation the way you do it in your sample, since there is simly no rotation existing. The problem is that all the diffrent rotations applied are rotation around diffrent pivot-points and need to have translations in between. You can either store the rotation relative to the parent the way i did or you can use Matrices which can store translations and rotations in the same matrix to do something like this, then you won´t need the position anymore.

Hope this helps, feel free to ask questions.
> 1 votes

---
Tags: 3d, animation, vector, linear-algebra
---


# Question
Title: Scaling a game world both for realism and for mechanics
I am currently working on a turn-based 4X game, and one of the things I quickly ran into was a question of scaling. On one hand, I want things like realistic sizes (having some idea of what each tile represents in terms of area), but on the other hand, doing so would limit me in terms of certain mechanics I want to implement (the size of a realistic city would not even occupy a tile, let alone multiple tiles, a mechanic I want to use).

How would I go about scaling the world so that I can have both realistic scaling AND the mechanics I want?

Some things I have considered:

Changing the size of the world. Nothing says that I have to have this take place on an Earth clone (especially with randomly generated terrain). Smaller worlds might allow the detailing I'd need for the cities without having unrealistic tile sizes.

Foregoing the realism: Something that came up while I was researching was that ancient cities were tiny by today's standards. Ancient Rome (the part encompassed by the Aurelian Walls) was only 5.3 square miles (for comparison, Manhattan is 22.96 square miles- enough to fit four Romes). I could forgo the realistic sizes of cities and make them the size I want for my mechanics.

Not including the entire world: Depending on the time-period I end up basing this off of, it may be pointless to include areas that effectively did not exist.

What is the best way to balance realism and mechanics for the scaling of a game world?

# Answer
Gameplay is always more important than realism. Realism is a tool to make the game more accessible and easier to understand. When game features work like the player expects them to work in real-life (note: the players expectations are not necessarily realistic), it makes it easier for the player to learn the game. But that's it.

As soon as realism starts to make the game less interesting to play, it has to go.

A good example for this is the Civilization series. It has plenty of acceptable breaks of reality. In the beginning it takes *decades* for a unit to travel to a neighboring city, to name just one. Is this a flaw? Looking at the huge success of the series, it isn't.

So forget about what would be a *realistic* scale for your game world, think about what would be a *fun* scale.

* You want players to have some room to expand, but have them meet and get into conflict with other players quite soon.
* You don't want players to manage too many units, cities and other entities at the same time, because this will be tedious.
* You want players to make meaningful decisions, and not force them to do too much micro-management, especially when it has little or no importance.

To reach these goals, you have to compress the world (move meainingful locations closer together).
> 7 votes

---
Tags: game-mechanics, world-design, scale
---


# Question
Title: How to find monitor resolution with glfw3?
For a while now, I have been playing around with making a game using OpenGL, and glfw3. I have been perfectly happy to create windows at my native resolution of 1920x1080. I'm getting to the point where I want to share it with other developers, so I cannot keep hard coding the screen resolution in. I went looking for ways to find the maximum resolution of the available monitor, which glfw provides using the function `glfwGetVideoModes(GLFWwindow*, int);`. It supposedly finds all available displays for a monitor (resolution, color depth, refresh rate), and returns them as an array of possibilities.

```
void GetMaxMonitorResolution(int* w, int* h)
{
    int count;
    const GLFWvidmode* modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &count);

    int maxWidth = 0;
    int maxHeight = 0;
    for (int i = 0; i < count; i++)
    {
        if (modes[i].width > maxWidth)
            maxWidth = modes[i].width;
        if (modes[i].height > maxHeight)
            maxHeight = modes[i].height;
    }

    *w = maxWidth;
    *h = maxHeight;
}

```

The problem is, even though my monitor supports 1920x1080, it keeps creating a window at 800x600, the smallest resolution possible on my monitor. I am relatively new to C++, so I am only 80% sure how pointers work, especially pointers to arrays and the such. So if I am somehow messing up the pointers, or if it truly is a problem with glfw, I would appreciate any help.

EDIT: The documentation for glfw3 monitors is here and here, in case anyone was wondering.

# Answer
Your code works perfectly on my computer.

What happens if you simply use `glfwGetVideoMode` instead? For example,

```
void get_resolution() {
    const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor());

    window_width = mode->width;
    window_height = mode->height;
}

```

That should give you the user's desktop resolution, which is probably what you want. If the above doesn't work either, I'm going to guess that it is a bug in the build of GLFW that you are using.
> 9 votes

---
Tags: c++, opengl, resolution, glfw
---


title: Create a fly camera with lookAt

text:
# Question
Title: Create a fly camera with lookAt
I want to create a free cam with the lookAt matrix in OpenGL. I just made the control with W, A, S and D so you can move around. But now I nee to **look** around. I thought doing that with sine and cosine on the target of `lookAt`, and it's partially working. But the problem is the input. I just don't know how to use the mouse coordinates(btw the mouse is fixed) to move the target or how to prepare the coordinates for sine and cosine.

Is there any example of what I'm looking for?

# Answer
As my previous answer got a downvote because it was too code-heavy I'll explain a little more:

For a camera which is not locked to any target point you should not use `lookAt` but rather compute the camera transformation matrix yourself.

You will need a camera position (x,y,z) and at least two rotation angles (i.e. pitch and yaw). To get the full tranformation matrix you multiply a translation matrix and one rotation matrix for each angle together, but as matrix multiplication is not commutative the order is important here. You can either first rotate and then translate, or the other way around, which yields totally different results. To understand the behavior I suggest just messing around with the order, but for a typical first person camera you will want to translate first and then rotate.

To achieve the correct movement of the camera you need to do two things:

* First you need to capture the mouse delta, i.e. the mouse movement since the last time you checked for mouse movement and add these up to your rotation angles. Additionally you may want to incorporate some kind of mouse speed multiplier here.
* Second you need to apply movement to the camera position correctly. This gets a little tricky as soon as the angles are not zero anymore, because movement is not along any of the axis. You will need to calculate the correct movement direction using the current rotation angles and some trigonometry. Here you may want to add some movement speed multiplier.

I hope that cleared things up a bit, and gives more insight into what my code actually does.

### Previous answer:

I would suggest not using `lookAt` and just creating the transformation matrix yourself. I did that a while ago in C# using DirectX, but I think it's self-explanatory what happens here:

```
public void ApplyFreeLookCamera(Context ctx)
{
    if (Enabled)
    {
        HandleInput(ctx);
    }
    Vector3 transPos = GetPosition();
    transPos.Multiply(-1);
    Matrix view = Matrix.Translation(transPos);
    view *= Matrix.RotationY(Yaw);      // left-right rotation
    view *= Matrix.RotationX(Pitch);    // up-down rotation
    view *= Matrix.RotationZ(Roll);     // ah snake, snaaake!
    ctx.Graphics.Transform.View = view;
}

```

And to handle input something like that:

```
private void HandleInput(Context ctx)
{
    // calculate movement direction
    var distance = MovementSpeed * ctx.FrameSeconds;
    var dx = (float)Math.Sin(Yaw) * distance;
    var dz = (float)Math.Cos(Yaw) * distance;
    //float dy = (float)Math.Sin(Pitch) * distance;
    var movement = new Vector3();
    // check keys
    if (ctx.Input.KeyPressed(Constants.CameraForward))
    {
        movement.X -= dx;
        movement.Z += dz;
    }
    if (ctx.Input.KeyPressed(Constants.CameraBackward))
    {
        movement.X += dx;
        movement.Z -= dz;
    }
    if (ctx.Input.KeyPressed(Constants.CameraLeft))
    {
        movement.X -= dz;
        movement.Z -= dx;
    }
    if (ctx.Input.KeyPressed(Constants.CameraRight))
    {
        movement.X += dz;
        movement.Z += dx;
    }
    if (ctx.Input.KeyPressed(Constants.CameraUp))
    {
        movement.Y += distance;
    }
    if (ctx.Input.KeyPressed(Constants.CameraDown))
    {
        movement.Y -= distance;
    }
    Position.Add(movement);
    // view direction
    var mouseDelta = ctx.Input.GetMouseDelta();
    if (ctx.Input.MouseButtonPressed(Constants.CameraMouseButton))
    {
        Yaw -= mouseDelta.X * MouseSpeed;
        Pitch -= mouseDelta.Y * MouseSpeed;
        ctx.Input.CenterMouseInWindow();
    }
}

```
> 6 votes

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


# Question
Title: What's the minimum viable product to present a game to a publisher?
I am currently working on a puzzle game. I am aiming in the future to ask a publisher to publish it. What do you think could be the minimum viable product to reach before sending it. I am talking about the completeness of the work (number of levels, graphic details etc)

# Answer
> 10 votes
The completeness of the work depends on the publisher, the game, you and the relationship you have with that publisher.

Each publisher will have their own standards for what's complete enough. Further, those standards could be tighter or less restrictive depending on the relationship you have with them. If you've never spoken to them, and they don't know you, it's likely you'll need something a bit more complete than if you were taking another game to them after you'd already had one success with them.

And it depends on the game. If it's mostly complete, but critical/technically challenging components are missing, that's more risk to the publisher. The genre is also important, if your puzzle game is mostly complete, but adding additional levels is very difficult or has the potential to break other things, that's more risk to the publisher.

Additionally, it depends on you and what you've produced before. If you have a portfolio of completed games, the publisher may feel more comfortable accepting something that isn't entirely complete, because they "know you're good for it".

This situation is like a job interview. If you can convince them you can do the job, and you'll do it well, they're more likely to hire you.

Your job is to convince them that the risk of taking your game is low. You can do that either by proving that the game is complete enough to be of very low risk on its own, or that the work that still needs to be done can be completed easily by you.

Your sales skills will come into play here. **You need to sell yourself along with the game. If the game is incomplete, this increases the importance of selling yourself. If the game is totally done, this reduces the importance of selling yourself.** It's up to you to decide how well you'll sell, and therefore how complete the game needs to be.

# Answer
> 2 votes
Depends on the publisher, really. Some of them want to see polished almost finished products, others want to be involved as early as possible in the process.

You can probably just ask them. It's possible that they may take a look at your early demo and give you some feedback or advice "for free" (e.g. without you having to make a commitment to publish with them, for example).

---
Tags: publishing
---


# Question
Title: Target a specific Entity in a Component-Entity design
I'm starting to work on a game with Entity-Component Model Architecture (Artemis in C#). I'm beginning with something pretty simple, entities which are living things, with `HealthComponent`, `PositionComponent`, `SpriteComponent`, `MoveComponent`. I want them to be able to target other entities (for example other Living things or even other entities of the game (like say inerts objects)) for them to move to them and grab them or be able to do other actions with them.

I can find which entity they will target by going through the mechanic of searching through all entities having the good components (`PositionComponent`, `TargetableComponent`) but i don't see how I can store the information of the target except by saving somewhere the ID of the entity.

So I would have a `TargetComponent` which is basically the ID of an entity that has for exemple a `PositionComponent`

That does not seem right, does it?

# Answer
> 6 votes
It sounds right to me. There are some benefits to doing it this way:

* You're not duplicating data.
* The information about the entity is always up-to-date (i.e. using the entity ID to get the position of the entity will always return the current position of the entity).

Those two essentially mean the same thing. If you were to store the position of the target entity, you'd have to update it every time the target moved. Further, you'd have to still store some kind of entity ID to know which entity you were targeting so you could perform other operations like attacks that alter the `HealthComponent` of the target entity.

There are some things you need to consider, but aren't significant problems.

1. You have to ensure the target entity has a position component. This is a simple check you can perform when assigning the target. It's pretty likely that the entity will have a position, otherwise it wouldn't make sense to be targeting it. But, it's just a simple check to make sure it has a position before assigning it as a target.
2. When saving and loading the game state, you need to ensure that entity IDs are assigned in the same way they were before. You don't want to save the game targeting one entity, and load the game with a totally different target.

Overall, if you find something that works for you, it's right (at least it's right enough). Don't worry about straying from the entity-component system or breaking any rules. Just make your game, and don't sweat the little things.

# Answer
> 1 votes
You need to ask yourself what are the requirements an entity must satisfy for it to be "targetable". Saying, "it must have the `TargetableComponent`" isn't useful. You are really trying to answer, "what additional information and behavior is required for an entity to be considered targetable?"

If all the information you need out of a targeting system is a back-reference to the owning entity from which you can access the position, maybe you're better off putting together a list of `PositionComponent`s for your targeting system. No really new information is being added, and the `TargetableComponent` is just being used as a "marker component." That is, it exists solely to add a single bit of information to an entity: whether or not it is targetable. Marker components aren't inherently bad, but in most cases seeing them seems like a case of "to a hammer, everything looks like a nail."

In this case, I would have some sort of flag/tag system (a \[Flags\] enum could work well for this, you can have 64 different flags if you type it as a long), and arrange it such that I could quickly query an area of the game world for objects for which the following is true: `(entity.Flags & EntityFlags.Targetable) == EntityFlags.Targetable`. If you need more than 64 tag/flag/whatevs, then that's what lists of tag IDs are for (they could just be hashes of the string name).

I'm assuming you need much more than one bit of information for your `TargetableComponent` though. Maybe you need to send events when an entity becomes targeted, need to know how many other entities are targeting this entity, and all sorts of stuff. In which case, don't feel guilty for using this `TargetableComponent` pattern.

Whether or not it's better to use marker components versus some sort of tagging depends completely on how you're planning to use it in your game. Do you want to dynamically check for the presence of `TargetableComponent` on entities? How frequently are you doing that? If it's as frequent as every few frames, is that an expensive operation in your system (ie: Unity)? Are you pre-populating a list of targetable entities by scanning all entities at level load for those who have `TargetableComponent`? Or does `TargetableComponent` itself maintain a static fast-access list?

Bottom line: Keep doing what you're doing so you can make progress and better define your problem. If necessary, you can redesign this system later to better handle your requirements.

---
Tags: c#, component-based, entity-system
---


# Question
Title: Recommended aspect ratio for android / smartphones?
I'm making a game for android and would do it in 720p, but the phones got all different aspect ratios. Also thinking about a ios and windows phone port later.

When the aspect ratio does not match, pretty much all I can do is making black borders, stretch it, or leave the part which does not make it out on the screen. The game would be not as good when not the entire screen is visible, for example you see an enemy spawning later.

Which aspect ratio should I choose? On the techniques I stated above, maybe I just let the user decide, they are very easy to implement and they can choose the handicap which is at least annoying for them.

On 16:9 they will be only borders on the top and bottom, but at some aspect ratio somewhere in between, some would have them on the left and right.

Resolution itself is not important, trying to scale down with drawing to a renderTarget first.

# Answer
Depending on game type and graphical choices, showing a larger environment when the screen is larger than minimum size can range from harmless and good-looking (e.g. the same playfield with more audience around it in a team sport simulation, the same view of the car and the road with more sky and clouds above it in first-person 3D racing) to unacceptable (e.g. seeing more players in a team sport simulation, seeing incoming enemies earlier in a RTS or seeing a larger portion of the road from a different perspective in racing).

Letterboxing might not be exciting, but it surely beats stretching aspect ratio or damaging the balance of your game.
> 0 votes

---
Tags: c#, android, monogame, resolution, aspect-ratio
---


# Question
Title: Using an FSM, how do you clean up state related attributes that may be used from several states?
I'm making a game that plays a bit like Diablo, but you can harvest resources like in an RTS.

I have the following states in my FSM: `IdleState`, `ApproachingTargetCoordinateState`, `ApproachingTargetEntityState`, `CuttingTreeState`.

When a user clicks a tree, `Player.targetEntity` is set to the corresponding `Tree` instance (which inherits from `Entity`) and the player's state is set to `ApproachingTargetEntityState`. When the player reaches the tree, a transition is made to `CuttingTreeState`. Shortly after, the tree is cut down, and state is changed back to `IdleState`.

At this point, I'd like the `Player.targetEntity` reference to be removed because its no longer needed. Where should I put the logic that does this?

I could do this in the `CuttingTreeState#exit()` method but that would only work in situations where everything happens as described above. If for instance the user clicks a random coordinate (not a tree) before the player reaches `CuttingTreeState`, `CuttingTreeState#exit()` is never run and so `Player.targetEntity` is never removed.

I can't put it in `ApproachingTargetEntityState#exit()` either, as that would remove the reference to the tree before we get to `CuttingTreeState`.

Another solution would be to just not care about `Player.targetEntity`. But it just feels wrong to me that the attribute is set for example when the player is in the `IdleState`.

How can I solve this problem? What is usually done?

# Answer
One option is as Nathan's comment, just identify when and where the values need to be cleaned up and do it manually there.

If you implement callback on the *edges* of a FSM rather than just the *nodes*, meaning chunks of code that are run on transition, then you can have a specific implementation of an edge from any of the `Tree` states to `Idle` allowing the idle state itself to be unaware of tree-specific details but allowing code to be reused for all of the possible ways into the idle state.

Another option is to use a hierarchical FSMs. You could have one "parent" state that is the `Tree` state or `Idle` or `Combat` or whatnot, and then a number of sub-states for `Tree` including `Approaching`, `Cutting`, etc. Now the variables are only stored in the `Tree` state so they are cleared/discarded when switching from `Tree` to `Idle`. The substates should have easy access to their parent's shared data.

You can make a base `Targeting` state class/definition that `Tree`/`Combat`/etc derives from which can then allow some common code and even sub-states to be shared between tree cutting, combat, whatever since your targeting is likely going to be common.
> 2 votes

---
Tags: architecture, ai, state, behavior, fsm
---


title: Bullet entry Point around Player Object

text:
# Question
Title: Bullet entry Point around Player Object
I have a player rotating by the mouse and want the bullets line up with the player's gun. Right now they simply come from the point of the player and shoot in the direction of mouse. I just need the bullets to line up with the player's gun as he rotates, rather than at a fixed position. Sorry my math is a little rusty and not sure how to achieve this. I've marked the two spots where I know I need to change.

```
  var player = {
  x: (canvas.width/2),
  y: (canvas.height-60),
  vx: 0,
  vy: 0,
  Bullets: [],
  draw: function() {
    ctx.save();
    ctx.translate(canvas.width/2, canvas.height-60);
    ctx.rotate(Math.atan2(mousePos.x-this.x, this.y-mousePos.y));
    ctx.drawImage(img, 0, 702, 42, 64, -21, -33, 42, 64);
    ctx.restore();
  },
  shoot: function() {
        var angle = Math.atan2(player.x- mousePos.x, player.y - mousePos.y);
        this.Bullets.push(Bullet({
        radian: angle,
        speed: 6,
        x: player.x, //<-- Here
        y: player.y, //<-- And Here
      }));
    }
};

function Bullet(I) {
  I.active = true;
  I.radian = Math.atan2(player.x- mousePos.x, player.y - mousePos.y);
  I.xVelocity = -I.speed * Math.sin(I.radian);
  I.yVelocity = -I.speed * Math.cos(I.radian);
  I.width = 3;
  I.height = 3;
  I.color = "#000";

  I.inBounds = function() {
    return I.x >= 0 && I.x <= canvas.width &&
      I.y >= 0 && I.y <= canvas.height;
  };

  I.draw = function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  };

  I.update = function() {
    I.x += I.xVelocity;
    I.y += I.yVelocity;

    I.active = I.active && I.inBounds();
  };
  return I;
}

```

I have tried using the following,

```
x: Math.cos(mousePos.x- player.x),
y: Math.sin(player.y - mousePos.y),

```

But the bullets only comes from the top left screen (with the mouse click on the bottom right). Would it have to do with the translate that I doing on the player?

# Answer
> 2 votes
You need to set the bullets position to the position of your player and then add a step into the right direction to land on your gun. Like so:

```
shoot: function() {
    var distance = 1; // here you need the distance of the gun from the center of the player
    var angle = Math.atan2(player.x- mousePos.x, player.y - mousePos.y);
    this.Bullets.push(Bullet({
    radian: angle,
    speed: 6,
    x: player.x + distance*Math.sin(angle),
    y: player.y + distance*Math.cos(angle),
  }));
}

```

When you are rendering the player you are restoring the transformation right afterwards, so I don't think it has to do with that.

# Answer
> 3 votes
A common approach to this problem, and many others, is to define "attachment points" (also called "hard points" or "nodes" or a million other things) to your model/sprite definitions. These are artist-defined locations on the model such as "left foot" or "head" or such. They are usually attached to the skeleton or other animation data (each frame for sprites).

You can then locate specific points on your character or items. The gun (or the character If your gun is baked into the model/sprite) can have a "muzzle" location. You can then find the muzzle location to know exactly where the end of the gun's barrel is and not need to hard-code locations; if the art changes or you add new characters or enemies or anything, the code just automatically finds the location the artist declared as the muzzle and everything just works with no further work. You can even add orientation information so you know which way to fire the project based on the model design, frame of animation, etc.

The other points can be used for all kinds of things, too. They can be useful for physics, equipment, visual effects, and so on. In 3D it's common to have the hands defined for a character so you know where to attach a gun model such that you can have a wide variety of characters and guns and they all just work together, and then you can query the gun's muzzle location/orientation in world space (transformed based on how its attached to the character, the pose the character is in, and where the character is).

---
Tags: 2d, javascript, html-canvas, trigonometry
---


# Question
Title: What's the difference between using hardware-accelerated APIs and the OS's drawing API?
On Windows, I can do drawing with the OS API without OpenGL or D3D. The code I am writing will make calls to a device driver and tell the GPU what to do regardless, right?

How is using OpenGL different exactly? Do these libraries have code that will interact with the GPU differently than just the Windows API does?

# Answer
> 2 votes
On a modern OS, where the desktop window compositing system is backed by a hardware-accelerated API like OpenGL or D3D, using the OS's drawing API *will* ultimately involve some calls being made into that underlying hardware-accelerated API. However:

* It is not always the case that the OS is using GPU-based compositing (particularly on older versions).
* You are paying a penalty in the form of the additional abstraction layers between you and the GPU.

In other words, on older versions of Windows, making calls into the GDI API can very well result in completely CPU-side software processing and rendering of the primitives you are drawing.

Even if the above is not the case, you're still calling into GDI, which does a lot of work to transform your input into internal formats, copy data around to buffers, et cetera. Eventually that data is translated to something D3D could comprehend. This usually means the GDI buffers are blit to textures on the CPU (exactly as they would have been in the old days) which is then given to the GPU to render.

In other words, you could do a lot better in terms of efficiency of rendering 2D elements by directly accessing D3D or OpenGL.

Futhermore, if you want to use 3D, the OS level APIs generally provide no facility for that (since they were originally designed to do 2D composition of GUI elements), so you'll do all that 3D geometry transformation on the CPU side in order to transform it to a form you can submit to GDI. You won't be utilizing the GPU hardware effectively at all.

# Answer
> 1 votes
If you're not drawing with Direct3D or OpenGL, you're most likely using GDI+.

There is a vast amount of differences between graphics APIs but all of them work by sending commands to a graphics driver that tells your hardware what to do. Unless you're writing that driver yourself, there's always going to be an API between you and your hardware.

Differences between the APIs include but are not limited to:

* Different rendering pipelines
* Different setup and drawing code
* Higher or lower level of abstraction

In short: no, you're never issuing the rendering hardware commands yourself and yes, different librairies speak to drivers differently (even different OpenGL implementations on the same computer could implement the spec in divergent ways).

More importantly, why does this matter to you? Maybe there's something else we can help with.

# Answer
> 1 votes
I'm not sure, but if you mean GDI/GDI+ or Win32 API in general, all drawing is done via software.

Using OpenGL, for example, you can reduce CPU time spent in graphics and do other stuff. The graphics hardware provide optimized functionality for commonly used operations like vertex transformation, rasterization, etc.

The code that really is executed by calling OpenGL commands, is done by the manufacturer of your hardware. The ones that can use it the best way possible.

If you are interested in learning more, there is a great tutorial here: http://www.arcsynthesis.org/gltut/

---
Tags: graphics
---


title: Get rotate angle using a formula

text:
# Question
Title: Get rotate angle using a formula
I am developing a game that is being played on a board with the top first tile having the coordinates \[0,0\], the next one has \[0,1\], second row has \[1,0\]... and so on (most likely this would be a standard but im not sure...).

When an object is to move around the board, it should first rotate to a specific angle - meaning if it is moving north North - it should point to the default angle 0, NE is 45, E is 90, and so on.

How would I get this angle based on where the object is moving, but using 1 formula?

So if an object is to move NW (up and left), on the grid that would mean the destination is \[y-1, x-1\] in reference to where it is now \[y,x\] ( \[row, column\] ).

I know I could use 8 statements and say if destination == \[y-1, x-1\] then angle = 315, but I was wondering if there is a specific formula for this? Im guessing yes but I never loved trigonometry...

# Answer
> 1 votes
Your movement vector is obtained substracting source position to target position

and the angle usually in radians is

```
  Vector2 V = Target - Source;
  angle = Math.Atan2(V.Y, V.X)

```

---
Tags: mathematics, coordinates, trigonometry
---


# Question
Title: World Bounds - (0, Size) or (-HalfSize, HalfSize)?
When creating a game space in which to move, draw and collide objects, is it better to have the (0,0) point, or the (0,0,0) point, be in the very center of your space, such that the bounds of the worlds are (-halfSize, halfSize), or is it better to have it be at the far corner of your space, so the bounds are (0, size)?

What are the pros and cons of each, and what sort of problems do they each entail? Or does it really just not matter?

It seems like a minor detail, but I wanted to see if there were perhaps major issues I might be overlooking.

# Answer
> 15 votes
It seems to me that having the center of your space be (0, 0, 0) is better. Assuming you are using a signed format to represent positions in space, a center of (0, 0, 0) allows you to use both the negative and positive parts of your format, which can do wonders for **precision** for floats and **range** for signed integers. This may not matter for small scales, but for large scales it can make all the difference, that is, before you have to come up with a new system entirely.

**Just to clarify:** Given that you are creating a game world, which I assume you're rendering, the ultimate format you will convert to will be float, which is as you know, a signed format. In that case, you may get to a situation where (0, Size) cannot be represented, whereas (-HalfSize, HalfSize) can be. If you are not planning to render and can choose an arbitrary format then use either style, though I would still personally prefer the aforementioned style.

# Answer
> 5 votes
It doesn't particularly matter. As long as you're consistent throughout your game.

I believe the more common approach is to have the world bounds centered around `(0,0)`, meaning you'd have your bounds go from `-halfSize, halfSize`. Since most data structures that represent position (Vector2 or Vector3) default to zeros, you know that the default placement for objects is in the center of the world (instead of in the bottom corner).

---
Tags: geometry, coordinates, space-partitioning
---


# Question
Title: Data structure for random outcome from a hit probability table
The basic idea of a hit-table is carried over from pen & paper role playing games. You roll a die or a number of dice representing your ability to attack an opponent. Your opponents defense is relative to your ability to attack: if you can roll higher than their defensive ability, then you hit them; if not, you miss.

Games started out with simple implementations and mechanics got more complicated as (e.g.) later editions of the rulebooks were published and players/customers desired a more realistic combat experience.

So conceptually, a hit table may look something like this:

```
Roll    Outcome
1-5     Miss
5-15    Dodge
16-20   Parry
21-80   Hit
81-100  Critical Hit

```

World of Warcraft calls this an attack table, but I haven't found a good resource which discusses a good data structure for this. The best implementation I have come up with so far is a linear traversal of an ordered list of the relative outcomes, which makes the decision algorithm `O(n)`, where `n` is the number of possible outcomes. The psuedo-code for this comes out to be:

```
var result = randome.next(0, hittable.maxvalue)
foreach outcome in hittable
    if result < outcome.max_value
        return outcome

// Reached the end of the table without finding an outcome
// Probably an error here, but let's fake it
return hittable.last

```

A typical combat in (most) modern games has many, many attacks that go to the hit-table for determination, as well as many possible outcomes. It is not hard to imagine this lookup becoming a serious bottleneck in terms of processing time. I remember the algorithm of a bucket sort from my Comp. Sci. coursework and have been enamored with the idea of finding a datastructure which would allow for a `O(1)` lookup of random number values. What would such a datastructure look like?

I can imagine how it could work with a one-liner query in SQL, but something tells me that would be adding a whole lot of overhead for a not-true `O(1)` solution.

```
SELECT name FROM hittable
WHERE hittable.min_roll < RAND() AND RAND() < hittable.max_roll

```

This is just a notion that popped into my head because "it's a hitTABLE, so why not store it in a table". Note: the above query also would not work because the two calls to rand would return random numbers.

*Edit:* MMORPGS have also implemented something similar for Loot Tables, which determines what you get from winning a battle (by looting the corpse of the defeated foe). This is complicated by having multiple potential outcomes for each random result, e.g.

```
Roll    Outcome
1-5     Nothing
5-15    Some Gold
16-20   An Item
21-80   Some Gold and An Item
81-100  Lots of Gold and TWO Items

```

In a game the size of World of Warcraft, you could have thousands of players looting the same monster in any given second, so again a strong argument can be made for finding the very fastest way to perform lookups of this manner.

# Answer
This is called weighted randomization *(or "discrete distribution selection")*, and there are two good data structures to represent it:

* A partial-sum tree *(my name, as I don't think it has a good name)*
* Walker's Alias Method

Both are described quite nicely in this blog post.

---

If you are coding in C#, I've implemented them both in an easy-to-use weighted randomizer library for C# here. You can find the documentation here.

Using it, your code would look something like this:

```
enum AttackOutcome { Miss, Dodge, Parry, Hit, CriticalHit };
...
//Create the randomizer
IWeightedRandomizer<AttackOutcome> randomizer
    = new StaticWeightedRandomizer<AttackOutcome>();

//Add the items, and their associated weights
randomizer.Add(AttackOutcome.Miss, 5);
randomizer.Add(AttackOutcome.Dodge, 10);
randomizer.Add(AttackOutcome.Parry, 5);
randomizer.Add(AttackOutcome.Hit, 60);
randomizer.Add(AttackOutcome.CriticalHit, 20);

...

//Later, randomly pick an item.  This can be done as many times as you'd
//like; it's O(1), so it's super-fast no matter how many items you add!
AttackOutcome outcome = randomizer.NextWithReplacement();
switch(outcome)
{
    case AttackOutcome.Miss:
        ...etc.
}

```
> 3 votes

# Answer
You're overthinking it. Let's be real for a second here. What you're doing is creating a log flow that is essentially:

```
var result = randome.next(0, hittable.maxvalue)

foreach outcome in hittable
    if result < outcome.max_value
        return outcome

// Reached the end of the table without finding an outcome
// Probably an error here, but let's fake it
return hittable.last

```

This is as simple as it gets and your pseudocode can be directly translated into code. You are simply not going to be able to go do better than one if statement check, which, by the way, is negligible in terms of processor time unless you are telling me you have thousands or even tens of thousands of hit entries?

If you do indeed have ten thousand entries, or, better yet, **you've profiled your code to check that this has become a problem** then you can speed it up somewhat by performing a modified binary search. The only thing you will need to change from the standard algortithm that can be googled is that you want the **first** entry that is more than or equal to your 'roll'. Let me know if you need me to make some pseudocode but it should be pretty trivial to write.
> 8 votes

# Answer
If the tables are stable (don't change), you can get an O(1) sampling via the Alias Method. It almost certainly isn't worth the trouble if the tables are smaller, though.

The basic idea is to split up your range into a series of N buckets of uniform weight, with each bucket containing exactly 2 weighted option. You can select one of the N buckets with the usual uniform random number generation techniques. Then you can pick one of the two items in the chosen bucket with another random number. Two random numbers and you get an answer, fairly accounting for weight, every time.

The trick is a preparation step that makes the buckets. You need to do a pass to find the average weight of all buckets. Then you do a pass to split all your items into small values (items with a weight below average) and large items (at or above average). Then you repeatedly pop one item from each list, put the small item into the next bucket, and then put in the large item such that it fills up the average. Subtract the "used up" amount from the large item. If the new value is below average, add it to the small list, otherwise the large. Each bucket contains the two items in it and the weight of the small item that was added to it.

Say we have:

```
A 0.5
B 1.2
C 0.9
D 1.4

```

The total weight is 4.0, the average is 1.0. We have a small list containing:

```
A 0.5
C 0.9

```

and a large list containing

```
B 1.2
D 1.4

```

We take the first item from each, A and B. We put A in the first bucket, which now has a weight of 0.5. We still need 0.5 to hit the average, so we put in B and subtract that 0.5 remainder from it's weight. We now have a weight of 0.7 for B. This is below the average, so we put B in the small list, giving us:

```
Small
-----
C 0.9
B 0.7

Large
-----
D 1.4

Buckets
-------
A,B  0.5

```

Now we pop one from each list, giving us C and D. We put C in the next bucket, for a total weight of 0.9. We still need 0.1 to hit the average, so we put in D and subtract 0.1 from its weight. That gives us a new weight for D of 1.3. That is over average, so we put D back into the large list. Now we have:

```
Small
-----
B 0.7

Large
-----
D 1.3

Buckets
-------
A,B  0.5
C,D  0.9

```

We take one of each (there only is one of each) and we get B and D. We put B in the third bucket which only has a weight of 0.7 now. We need 0.3 to fill up to average, so we put in D and subtract 0.3 from its weight, giving us 1.0. That's at average so we put it in the large list, giving us:

```
Large
-----
D 1.0

Buckets
-------
A,B  0.5
C,D  0.9
B,D  0.7

```

We now have no more small items. If you are out of small items, then *either* you are also out of large items or you have exactly one large item at a weight equal to average (as in our example). If you don't have one of these two cases, your implementation is wrong. We put this final large remaining item equal to average weight into it's own final bucket. Our buckets are now:

```
Buckets
-------
A,B  0.5
C,D  0.9
B,D  0.7
D,-  1.0

```

That's four buckets. To choose one of our weighted oppions, we get a random number \[0,N) where N is the number of buckets (4). Say we got 2. That's the third bucket containing B,D 0.7. We now get another random number from \[0.0,Avg) where Avg was our average weight (1.0). Say we get 0.465. That's less than the pivot weight of 0.7 in that bucket, so we pick that bucket's small item, which was B.

We can keep doing this over and over and over. Choose two random numbers and get a properly weighted result. No looping or iteration. O(1) lookup for the generated table.

There are variations of the initial processing algorithm to make the table generation much more efficient should you have a situation where the table might change in unpredictable ways during play. If the table changes frequently, you're better off with an O(log(N)) binary search of a sorted running-sum table. In such a table using the above example, you'd have:

```
A   0.5 = 0.0+0.5
B   1.7 = 0.5+1.2
C   2.6 = 1.7+0.9
D   4.0 = 2.6+1.4

```

This table needs a single O(N) pass to generate. You need the sum of weights and that running sum for each item. Choose a random number in \[0,Sum). Do a binary search to find the smallest running sum that is still greater than or equal to the random number. A binary search on four items is unlikely to be faster than a linear search but it scales better for larger tables obviously (not as well as O(1), but the preprocessing step is much cheaper for this method than an alias table).
> 7 votes

# Answer
based on how small these hit table usually are, I guess O(n) won't hurt. I mean how big can N be? in your example it's 5, I mean there are 5 possible outputs, and iterating over them won't take that much time. But strictly speaking about O notation you can reduce it to O(logN). here is the idea:

you can think of hit table as a list of numbers. since all the possible random values are covered exactly with 1 outcome, we can rest assured if we find the smallest number bigger than the input value we can determine the outcome. converting your example we'll have something like this:

1\<--Miss--\>5\<--Dodge--\>15\<--Parry--\>20\<--Hit--\>80\<--Critical Hit--\>100

these numbers (1,5,15...) are very unlikely to change during game play, in fact they usually are determined during game balancing, and set by the game designer. so it can just store them as a sorted list.

The last key to O(logN) algorithm is binary search. Most languages already have it implemented in their core library. so we just pair key values with outcome, and search between the keys for that specific key. What ever key is found, you simply have to return it's respective value.

here is a sample code in C++:

```
std::map<int, std::string> hitTable;

void initializeHitTable()
{
    hitTable[5] = "Miss";
    hitTable[15] = "Dodge";
    hitTable[20] = "Parry";
    hitTable[80] = "Hit";
    hitTable[100] = "Critical";
}

string getHitTableOutCome(int value)
{
    std::map<int, std::string>::iterator searchResult;
    searchResult = hitTable.upperBound(value);
    /*
        upperBound will return the smallest key-value pair in
        the table which is not smaller or equal compared to
        the input value. it means hitTable.upperBound(2) will
        return (5, "Miss"). note that hitTable.upperBound(5)
        results in (15,"Dodge"). also note that std::map always
        stores the keys in ascending order, and upperBound uses
        binary search to find it's result.
    */
    if (value < 1 || searchResult == hitTable.end())
        return "value is out of table);
    /*
        either if our input value is is below 1 or above 99
        we don't have any entry in our hit table to match it.
        the first condition is pretty obvious, and the second
        one means there is no entry larger than value in our
        hitTable
    */
    else
        return searchResult->second;
    /*
        searchResult is a key-value pair. And
        searchResult->second, it the value assign to that
        specific key.
    */
}

```
> 1 votes

# Answer
You can try the following (in Python):

```
# coding: utf-8
hittable = {(1,5): "miss", (6,15):"dodge", (16,20):"parry", (21,80):"hit", (81,100):"critical hit"}
@memoize
def hash(x):
    for i in hittable.keys():
        if x in range(i[0],i[1]+1):
            return i
import random

for i in range(10):
    x = random.randint(1,100)
    print x, hittable[hash(x)]

```

For `@memoize`, use some memoization decorator.

This, however, boils down to just having the mapping of each of the attacks to the outcome (with O(1) access).

Without memoization, you have just slightly more convenient access to the values (with O(n) access), as the looping is hidden in the `hash` function.
> 1 votes

# Answer
What you could do is either use an array of the critical points, and then use an enum for the index that you retrieve based on this. Alternatively, you could use else-if statements chained together. I feel that an enum would be the best final data structure (containing miss, dodge, parry, hit, critical hit) as it can allow you to have stronger typing in the end.
> 0 votes

---
Tags: data-structure, random
---


title: Monogame crashes without any change

text:
# Question
Title: Monogame crashes without any change
I've written a game in MonoGame, which works great on my desktop computer. It's running Windows 8, has a good graphics card and can be assumed to be up to date with everything.

However, when I run on my laptop, it crashes within the starting function game.Run(). I created a new template project, and it still crashes. I've check the obvious places, it's running x86 config, I've installed the openAL, and the dlls are in the right places.

The error is "NullReferenceException" occurred in MonoGame.Framework.dll

I can't post images, but I've changed nothing about the new project. It runs the init and the loadContent functions, then crashes.

The thing that might be important, the laptop has openGL 2.1, Windows 7. I have OpenTK, OpenAL installed. If anyone has even suggestions on things that might be the cause, or want more info, just say.

EDIT: The stack is as follows:

```
at Microsoft.Xna.Framework.Audio.OpenALSoundController.Update()
at Microsoft.Xna.Framework.OpenTKGamePlatform.BeforeUpdate(GameTime gameTime)
at Microsoft.Xna.Framework.Game.DoUpdate(GameTime gameTime)
at Microsoft.Xna.Framework.Game.Tick()
at Microsoft.Xna.Framework.OpenTKGameWindow.OnUpdateFrame(Object sender, FrameEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at OpenTK.GameWindow.OnUpdateFrame(FrameEventArgs e)
at OpenTK.GameWindow.OnUpdateFrameInternal(FrameEventArgs e)
at OpenTK.GameWindow.RaiseUpdateFrame(Stopwatch update_watch, Double& next_update, FrameEventArgs update_args)
at OpenTK.GameWindow.DispatchUpdateAndRenderFrame(Object sender, EventArgs e)
at OpenTK.GameWindow.Run(Double updates_per_second, Double frames_per_second)
at OpenTK.GameWindow.Run(Double updateRate)
at Microsoft.Xna.Framework.OpenTKGamePlatform.RunLoop()
at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior)
at Microsoft.Xna.Framework.Game.Run()
at Mojo.Program.Main(String[] args)

```

Posted as an error report to MonoGame, I'll answer this depending on their response.

# Answer
I had this the other day. After much frustration ("What have I done? Nothing's changed!") I realised that I had unplugged my headphones.

Apparently OpenTK makes some assumptions about using sound drivers - try plugging in your speakers...!

(Notice that in the stack trace it is the sound controller throwing the exception)
> 1 votes

---
Tags: c#, windows, monogame, exceptions
---


# Question
Title: Inheritance Hierarchy and Design -- avoiding multiple inheritance
I am working on a 3D game, and need some advice about how to best design and structure my code so that I achieve what I'm going for without using bad practices like multiple inheritance.

Basically I keep finding myself tempted to implement multiple inheritance with simple interfaces.

For example, I have an abstract base class, `Physical_Object`, and I have an abstract class derived from it, `Controllable`, and I have a class derived from Controllable, `Drone`.

Controllable must implement an update method, which, depending on the state of the controllable, will either call an AI update method, or an update method based on the keyboard/controller state.

A Drone has different segments, of which are interchangeable, and have different abilities.

Some of these segments, as well as some other future game objects will need to be able to target/trace a ray from their origin to where they are aiming. So I thought to make a new abstract class / interface which requires the implementation of `target`.

Currently, I have an abstract `Drone_Segment` class, which helps to allow me to polymorphically manage the Drones interchangeable segments. And these each have hierarchies, like for example, `Drone_Turret_Segment: Physical_Object-->Controllable-->Drone_Segment->Drone_Turret_Segment.`

In essence, given the current structure and design, the quickest and easiest way to add the `target` method to all of the classes which will need it, without multiple inheritance, is to add and implement `target` in the `Controllable` class. But this would have the downside, that Objects that have no logical use for the method would inherit it.

Another option is to make a simple interface and make just objects which need the target method inherit from it, but I cannot figure out how to best do this without multiple inheritance, ie: `Physical_Object-->Controllable-->(Drone_Segment,Targeting_Object)->Drone_Turret_Segment.`

What are some ways to go about this?

# Answer
> 9 votes
Note that there is nothing wrong with multiple inheritance. The diamond inheritance issue is... a problem. Plain multiple inheritance with no common bases is quite useful.

That said, inheritance at all is generally the wrong approach unless you're implementing functional interfaces. Many class hierarchies, including your own, end up looking too much like real-world taxonomies.

Consider aggregation/composition over inheritance. Instead of thinking "a `Drone` *is-a* `Controllable` in behavior" think instead "a `Drone` *has* `Controllable` behavior."

You can do static aggregation or dynamic composition. The latter has a lot of advantages, but the former is quite fine.

The usual article to link with a better-worded explanation is Evolve Your Hierarchy.

# Answer
> 3 votes
Dependency Injection is able to solve this problem.

A top-level object, rather than implementing or overriding a specific process, defines that it requires an object capable of fulfilling it. It also defines *what* that object is supposed to do, i.e. it defines the component's interface. Then smaller, simpler, and independently implemented objects must fulfill that interface. This is backwards from classic polymorphism, where low-level objects define and high-level objects implement, hence the name Dependency Inversion Principle.

For instance, your `Drones` can require an object that implements `Update()` and do their updating via that property. That object is independent of the inheritance chain. The object fulling the interface can work by an AI process, or it could sample player input, or it could follow a script, etc. No code duplication because each implementation is exactly what it needs and no more, but also no unnecessary inheritance in child classes. No multiple inheritance, either.

Note that this architecture's goals are roughly the same as this site's ever-popular Component-Entity architecture. The idea is to remove functional parts from object definitions, make functions modular, and improve the brittle programs created by using inheritance directly.

# Answer
> 1 votes
It really sounds to me like you want to use multiple inheritance to mix together different pockets of functionality to form something new. While dependency injection can be useful in an inheritance hierarchy, a better option would be to form aggregate object compositions.

Using a component based architecture is a simple and natural way to piece together different types of game objects. What you're really doing, on a fundamental level, is creating new things from pre-existing implementations. This is what component based architecture is for: you create objects based off of what they do, instead of using inheritance hierarchies that organize implementation and code based off of abstract naming identifiers.

A component based architecture will allow you to avoid the age old problem of features creeping up your inheritance hierarchy in order to avoid code duplication.

# Answer
> 1 votes
I would look into component design

http://gameprogrammingpatterns.com/component.html http://www.gamasutra.com/blogs/MeganFox/20101208/88590/Game\_Engines\_101\_The\_EntityComponent\_Model.php

It uses wrapper classes and loads them with reusable components. This has several advantages. First is "flattens" out an inheritance tree. Say you have a vehicle superclass with two sub classes: Tires and Treads. Tanks then a sublcass of Treads. But what if you want a tank with tires? Do you inherit from tanks to reuse the gun logic, or do you inherit for tires to get the wheel logic. Or do you inherit from both and get the **dreaded diamond?** With component design you can have a general vehicle class and then components. Propulsion can be one type of components, (sublcassed into tires, wheels, propellers, or wings) and gun can be another type of component. Essentially, component systems are useful if you have a wide array of objects that reuse functionality, but not necessarily inherit from each other.

There are other advantages also. Like you can store all of the same type of components next to each other in memory and update one type of component at a time. You will spend less time pulling random components then, but only worry about this if you need to improve performance.

---
Tags: c++, design-patterns, polymorphism
---